1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
//! From a decoded command to a written reply.
//!
//! This is the layer Y23 exists to keep thin. The wire and the embedded API
//! both have to reach the same code, or there are two implementations of `INCR`
//! and one of them is wrong. So `yo-kv` holds one method per command taking
//! ordinary Rust values, and everything here is about the part that is only
//! true on a socket: which keyword goes where, which combinations a real server
//! refuses, and which of the two protocols the answer is spelled in.
//!
//! # What runs a command
//!
//! [`Server`] holds the databases. [`Session`] holds what one connection has
//! chosen: which database, which name it gave itself, what its id is. The
//! protocol version lives in the [`Out`] because that is what needs it, and
//! `HELLO` changes it there.
//!
//! ```
//! use yo_resp::{Argv, Limits, Out, Proto};
//! use yo_resp::dispatch::{Args, Flow, Server, Session, execute};
//!
//! let mut server = Server::new();
//! let mut session = Session::new(1);
//! let mut out = Out::new(Proto::Resp2);
//!
//! let wire = b"*3\r\n$3\r\nSET\r\n$1\r\nk\r\n$1\r\nv\r\n";
//! let mut argv = Argv::new();
//! argv.decode(wire, &Limits::default())?;
//! let flow = execute(&mut server, &mut session, Args::new(&argv, wire), &mut out);
//!
//! assert_eq!(flow, Flow::Continue);
//! assert_eq!(out.as_slice(), b"+OK\r\n");
//! # Ok::<(), yo_resp::ProtocolError>(())
//! ```
//!
//! # Errors are values until the last moment
//!
//! A command body returns a [`Result`], and this module turns the error into
//! the line that goes on the wire. That is what keeps the same body usable from
//! the embedded API, where an error is a value with a [`Code`] on it and not a
//! sentence to be parsed.
//!
//! The reply buffer is rolled back to where it was before a failing command
//! wrote anything, so a body that checks its arguments halfway through cannot
//! leave half a reply in front of the error.
//!
//! # Nothing here allocates
//!
//! Arguments are slices of the connection's read buffer, keywords are compared
//! in place, numbers are written straight into the reply, and the pairs of
//! `MSET` reach the store as an iterator rather than a `Vec`. The two places
//! that do allocate, an error message and the text of `INFO`, say so and wrap
//! it, because a shard thread that allocates aborts.
mod args;
mod arrays;
mod backup;
mod bits;
mod blocking;
mod bloom;
mod cms;
mod cpu;
mod cuckoo;
mod geo;
mod graph;
mod hashes;
mod himport;
mod hll;
mod json;
mod keyspace;
mod lists;
mod migrate;
mod scan;
mod scripting;
mod server;
mod sets;
mod streams;
mod strings;
pub mod table;
mod tdigest;
mod topk;
mod vectors;
mod vfilter;
mod zsets;
pub use args::Args;
pub use blocking::{Parked, Waiters};
pub use server::parse_memory;
pub use table::{COMMANDS, Spec, arity_ok, lookup};
use crate::reply::Out;
use std::path::{Path, PathBuf};
use yo_common::{Code, Error};
use yo_kv::cold::Blocks;
use yo_kv::{Clock, Keyspace};
/// How many databases a server has.
///
/// Redis's default is sixteen and its `databases` setting can change it. Ours
/// is sixteen and cannot, which is why `CONFIG GET databases` can answer with a
/// constant. Nothing in the design needs the number to be fixed; nothing yet
/// needs it not to be.
pub const DATABASES: usize = 16;
/// Every database's bit in [`Server::dirty`], which is what a fresh server
/// starts on so that the first maintenance turn asks all of them.
///
/// A `u64` holds sixteen bits with room to spare, and the assertion below is
/// what turns raising [`DATABASES`] past sixty four into a build failure rather
/// than a shift that silently drops the databases past the end.
const ALL_DATABASES: u64 = if DATABASES == 64 {
u64::MAX
} else {
(1u64 << DATABASES) - 1
};
const _: () = assert!(DATABASES <= 64);
/// How many keys one command throws away before it leaves the rest to the next.
///
/// A bound and not a loop to the end, because this runs in front of a client
/// that is waiting for its reply, and a server a long way over its limit would
/// otherwise hold that client for as long as it took to walk all the way back
/// under. Sixty four is a batch's worth of commands, so a server that went over
/// by what one batch allocated comes back under in one command, and a server
/// whose limit was just cut in half works through it over the next few thousand
/// rather than in one long stall. Redis bounds the same loop by a time slice
/// instead of a count and hands the rest to a timer; there is no timer here, so
/// the rest goes to the next command that runs.
const EVICT_BUDGET: usize = 64;
/// What a server says to a command that would allocate when it has no room.
///
/// Redis's `shared.oomerr`, word for word including the full stop, because
/// clients match on the `OOM` prefix and people match on the sentence.
const OOM: &[u8] = b"command not allowed when used memory > 'maxmemory'.";
/// What the connection should do after a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flow {
/// Read the next command.
Continue,
/// Write what is buffered and then close, which is what `QUIT` asks for.
Close,
/// Nothing was written and nothing is owed yet.
///
/// The client is on the waiter list and its reply comes when a key it named
/// has something in it or when its deadline passes, whichever happens first.
/// Until then the connection stops reading commands, because a client that
/// is waiting for an answer is not a client that has sent another question.
Block,
}
/// The numbers `INFO` reports that this layer cannot see for itself.
///
/// The reactor owns the sockets, so the reactor is what knows how many clients
/// there are. It writes these directly and nothing here does anything with them
/// except report them.
#[derive(Debug, Clone, Copy, Default)]
pub struct Stats {
/// Connections open right now.
pub clients: u64,
/// Connections accepted since the server started.
pub connections: u64,
/// Commands run since the server started, which this layer counts itself.
pub commands: u64,
}
/// Where the process was started, which is what `dir` defaults to.
///
/// A dot if the working directory cannot be read, which happens when it has
/// been deleted out from under a running process. That is not a reason to
/// refuse to start a server, and it leaves `BACKUP` to fail with the real error
/// from the filesystem if anybody asks for one.
fn working_dir() -> PathBuf {
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}
/// One command's counters, for `INFO commandstats`.
///
/// Three of Redis's five. `usec` and `usec_per_call` are not here because
/// nothing times a command, and timing one means two clock reads around a call
/// that takes tens of nanoseconds to begin with. Redis pays that because Redis
/// has room for it; this does not, and a zero under a name that says microseconds
/// is worse than an absent field, which is the same rule the rest of `INFO`
/// follows.
#[derive(Debug, Clone, Copy, Default)]
pub struct CommandStat {
/// Times the command ran, whatever it answered.
pub calls: u64,
/// Times it was turned away before it ran, which is the wrong number of
/// arguments or no room under `maxmemory`.
pub rejected: u64,
/// Times it ran and answered with an error.
pub failed: u64,
}
impl CommandStat {
/// Whether this command has ever been seen.
///
/// A row that has not is left out of the reply, which is what Redis does and
/// is why the section is a handful of lines on a working server rather than
/// one line per command in the table.
const fn seen(&self) -> bool {
self.calls != 0 || self.rejected != 0 || self.failed != 0
}
}
/// A counter per command, indexed the way [`table::index_of`] says.
///
/// A flat array and not a map, because the dispatcher is already holding the
/// spec and the spec's position in the table is two addresses subtracted. That
/// makes the counting a load, an add and a store on a row the previous command
/// of the same name has already pulled into cache.
struct CommandStats(Box<[CommandStat]>);
impl Default for CommandStats {
fn default() -> CommandStats {
CommandStats(vec![CommandStat::default(); table::count()].into_boxed_slice())
}
}
impl CommandStats {
/// The row for one command.
fn at(&mut self, spec: &'static Spec) -> &mut CommandStat {
&mut self.0[table::index_of(spec)]
}
}
/// Where a database gets its store from, asked by database number.
///
/// `None` means that database cannot have one. The caller owns whatever the
/// stores are cut out of, which for `yodb` is one `.yo` file with a log per
/// database, and this crate never learns what any of that is.
pub type StoreSource = dyn FnMut(usize) -> Option<Box<dyn Blocks>>;
/// Everything a server holds.
///
/// One of these per shard thread, not one per process: the databases inside are
/// not `Sync` and are reached by sending their thread a command. What makes
/// this a server rather than a shard is that it is the whole of what a
/// connection can address.
pub struct Server {
dbs: Vec<Keyspace>,
clock: Clock,
started_ms: u64,
/// Where the next maintenance turn starts looking, so that a database
/// under constant write load cannot hold the other fifteen's space.
next_db: usize,
/// One bit per database, set when a command ran against it.
///
/// The maintenance turn after every batch used to ask all sixteen
/// databases whether they had anything to collect, and asking costs a load
/// and a store in each one. Fifteen of those are cold lines on a server
/// where every client is on database zero, which is every server, and the
/// answer is no every time. This is the cheap half of the question: a
/// database nobody has touched since it last said no cannot have started
/// saying yes.
dirty: u64,
/// What the connections are holding, kept by the engine.
conn_bytes: usize,
/// The `maxmemory` limit in bytes, zero when there is not one.
///
/// Zero is the default and it is the whole reason the check in front of
/// every write is one comparison against a field that is already warm.
maxmemory: u64,
/// Where a database gets a store from the first time it needs one.
///
/// A closure and not a store, because there are sixteen databases and a
/// server that fills memory on database zero should not have opened
/// anything for the other fifteen. Nothing is asked of this until a memory
/// limit is actually reached, so a server that never fills memory never
/// opens a file, and a server that has no file never has one of these.
///
/// `None` from the closure means that database cannot have one, which is
/// how the caller says the file it opened has no more room for logs.
store: Option<Box<StoreSource>>,
/// The `maxstore` limit in bytes, `None` when there is not one.
///
/// The storage limit, and the other half of the inversion `14` section 4.1
/// describes. `maxmemory` is a limit on memory and the right answer to a
/// memory limit on a system with a file under it is to move data to the
/// file, not to delete it. Deleting is the right answer to a limit on the
/// file, and this is that limit.
///
/// Zero is not "no limit" here, which is the one place this reads
/// differently from `maxmemory` and is the difference that makes a drop in
/// cache possible. A storage budget of zero bytes means nothing may live on
/// the file, so migration cannot make room and eviction is the only thing
/// left, which is Redis exactly. `None` is no limit and is the default,
/// which with `noeviction` means the database grows until the disk is full
/// and then writes fail, which is what a database does.
maxstore: Option<u64>,
/// What [`Server::memory_bytes`] said at the last maintenance turn.
///
/// The reading is a walk over every collection in every database and cannot
/// go on a command path, so the command path reads this instead and is at
/// most one batch behind. What that costs is overshoot: a server can end a
/// batch holding one batch's worth of allocation more than its limit before
/// anything notices. A batch is 64 commands, so that is bounded by what 64
/// commands can allocate and not by how long the server runs.
///
/// Only kept up to date when there is a limit to judge it against. A server
/// with no `maxmemory` never reads it and never pays for it.
used: usize,
/// Which database the next eviction draws from.
///
/// Its own cursor and not [`Server::next_db`], because eviction and
/// compaction move at different rates and sharing one would make the
/// database that gets compacted depend on how many keys were evicted.
evict_db: usize,
/// Which database the next active expiry sweep starts at.
///
/// A third cursor for the same reason there is a second one. A sweep runs on
/// every turn of the loop and compaction runs when there is dead space, so
/// sharing a cursor would make which database gets swept depend on which one
/// was last collected.
expire_db: usize,
/// The millisecond the last active expiry sweep ran on, so the next one on
/// the same millisecond does not bother.
expire_ms: u64,
/// Clients parked on a blocking command.
waiters: Waiters,
/// Sockets `MIGRATE` is holding open to the servers it has talked to.
///
/// Empty on a server nobody has migrated a key out of, which is nearly all
/// of them, and it costs a vector's three words to be empty.
peers: migrate::Peers,
/// The numbers the reactor keeps for `INFO`.
pub stats: Stats,
/// A counter per command, for `INFO commandstats`.
cmdstats: CommandStats,
/// Where `BACKUP` puts its files, and where `CONFIG GET dir` points.
///
/// Absolute, and resolved once when the server is built rather than every
/// time somebody asks. `BACKUP LIST` answers absolute paths and a client is
/// entitled to hand one of them to a copy tool, so a relative path that
/// meant something different after a `chdir` would be a path that stops
/// working for reasons nobody could see.
dir: PathBuf,
/// What backup is running, if one is.
///
/// On the server and not on a session, because a backup outlives the
/// connection that asked for it and any other connection can seal it.
backup: backup::State,
/// Set by `SHUTDOWN`, and read by whatever is turning the loop.
///
/// A flag rather than an exit, because the command layer is not what owns
/// the process. It runs inside a batch that has other commands behind it
/// and inside a driver that has a socket file to take away and a file to
/// close, and a server that calls `exit` from a command handler skips all
/// of that. So the command says stop and the driver stops, on the same turn
/// and through the same door a signal uses.
stopping: bool,
}
impl Server {
/// A server with [`DATABASES`] empty databases on the system clock.
#[must_use]
pub fn new() -> Server {
let clock = Clock::system();
Server {
dbs: (0..DATABASES)
.map(|_| Keyspace::with_clock(clock))
.collect(),
clock,
started_ms: clock.now_ms(),
next_db: 0,
dirty: ALL_DATABASES,
conn_bytes: 0,
maxmemory: 0,
store: None,
maxstore: None,
used: 0,
evict_db: 0,
expire_db: 0,
expire_ms: 0,
waiters: Waiters::default(),
peers: migrate::Peers::default(),
stats: Stats::default(),
cmdstats: CommandStats::default(),
dir: working_dir(),
backup: backup::State::default(),
stopping: false,
}
}
/// A server on a clock the caller moves by hand, for tests.
#[must_use]
pub fn with_clock(clock: Clock) -> Server {
Server {
dbs: (0..DATABASES)
.map(|_| Keyspace::with_clock(clock))
.collect(),
clock,
started_ms: clock.now_ms(),
next_db: 0,
dirty: ALL_DATABASES,
conn_bytes: 0,
maxmemory: 0,
store: None,
maxstore: None,
used: 0,
evict_db: 0,
expire_db: 0,
expire_ms: 0,
waiters: Waiters::default(),
peers: migrate::Peers::default(),
stats: Stats::default(),
cmdstats: CommandStats::default(),
dir: working_dir(),
backup: backup::State::default(),
stopping: false,
}
}
/// One database, by index.
///
/// # Panics
///
/// If `i` is not a database. `SELECT` is the only way a client changes the
/// index and it checks, so an index that is out of range here is a bug in
/// the caller and not something a client can ask for.
pub fn db(&mut self, i: usize) -> &mut Keyspace {
// The borrow is mutable, so assume it is used. Anything that only reads
// has [`Server::db_ref`] and does not come through here.
self.dirty |= 1u64 << i;
&mut self.dbs[i]
}
/// Where `BACKUP` writes and what `CONFIG GET dir` answers.
#[must_use]
pub fn dir(&self) -> &Path {
&self.dir
}
/// Point the server at a different directory, which `yodb serve --dir` does.
///
/// Only before it is serving. There is no `CONFIG SET dir` here and there
/// is none on a real server either without turning protected configs on,
/// for the good reason that moving it out from under a running backup would
/// leave files nothing can find again.
pub fn set_dir(&mut self, dir: PathBuf) {
self.dir = dir;
}
/// Drop a sealed backup that has outlived `backup-sealed-ttl`.
///
/// Once per batch, from the same maintenance turn that collects the arena.
/// It reads two fields and returns on a server that has never taken a
/// backup, which is nearly all of them.
pub fn backup_expire(&mut self) {
backup::expire(self);
}
/// Ask for the server to stop, which is what `SHUTDOWN` does.
///
/// It sets a flag and returns. Nothing here closes a socket, flushes a file
/// or ends the process, because none of those belong to this layer, and a
/// batch that is halfway through still has to finish and be written out.
pub fn stop(&mut self) {
self.stopping = true;
}
/// Whether somebody has asked the server to stop.
///
/// Read once per turn by the loop, next to the flag a signal sets. The two
/// mean the same thing and are separate only because one arrives from the
/// operating system and the other from a client.
#[must_use]
pub fn stopping(&self) -> bool {
self.stopping
}
/// One database, by index, without taking it mutably.
///
/// What the prefetch stage needs. It runs for all 64 commands in a batch
/// before any of them executes, so it cannot hold the mutable borrow `run`
/// is about to want, and it does not need one: warming a cache line reads
/// nothing and changes nothing.
///
/// # Panics
///
/// As [`Server::db`].
#[must_use]
pub fn db_ref(&self, i: usize) -> &Keyspace {
&self.dbs[i]
}
/// Take a new clock reading and give it to every database.
///
/// Once per turn of the event loop, which is the only place time moves. A
/// command asking what the time is gets the answer the whole batch got, so
/// two keys written by the same batch expire together (`04` section 3).
pub fn refresh_clock(&mut self) {
self.clock.refresh();
let now = self.clock.now_ms();
for db in &mut self.dbs {
db.clock_mut().set(now);
}
}
/// Move every clock here to `ms` by hand, for tests about expiry.
///
/// A test cannot wait a hundred seconds and a test that waits a hundred
/// milliseconds is a test that fails on a loaded machine, so time moves on
/// request. The system clock underneath will overwrite this on the next
/// [`Server::refresh_clock`], which is why this is only useful in a test
/// that drives commands directly rather than through the event loop.
pub fn set_clock_ms(&mut self, ms: u64) {
self.clock.set(ms);
for db in &mut self.dbs {
db.clock_mut().set(ms);
}
}
/// Seconds since this server was built.
#[must_use]
pub fn uptime_secs(&self) -> u64 {
self.clock.now_ms().saturating_sub(self.started_ms) / 1000
}
/// Bytes held by every database's index and arena, plus the read and reply
/// buffers of every connection.
///
/// The buffers are in here because they are real and because Redis counts
/// its own, so leaving them out would make the one number people compare
/// flattering rather than true. They are not a database, so nothing in the
/// keyspace can change them and the engine has to say when they move.
#[must_use]
pub fn memory_bytes(&self) -> usize {
self.dbs.iter().map(Keyspace::memory_bytes).sum::<usize>() + self.conn_bytes
}
/// What the keyspace itself is holding, live records only.
///
/// `used_memory` minus this is what the store costs to run: the index, the
/// space dead records are sitting in until compaction gets to them, and the
/// connections' buffers.
#[must_use]
pub fn dataset_bytes(&self) -> usize {
self.dbs
.iter()
.map(|db| db.map().arena().live_bytes() as usize)
.sum()
}
/// Bytes the arenas are holding, live and dead together.
#[must_use]
pub fn arena_bytes(&self) -> usize {
self.dbs
.iter()
.map(|db| db.map().arena().reserved_bytes() as usize)
.sum()
}
/// Bytes the indexes are holding.
#[must_use]
pub fn index_bytes(&self) -> usize {
self.dbs
.iter()
.map(|db| db.map().index().memory_bytes())
.sum()
}
/// What arena compaction has cost, across every database.
///
/// The write amplification of value separation, which is invisible from the
/// outside otherwise: a client that writes a megabyte can leave the store
/// copying several more, and the only sign of it without these is that the
/// writes got slower.
#[must_use]
pub fn compaction(&self) -> yo_kv::Compaction {
self.dbs.iter().map(|db| db.map().compaction()).fold(
yo_kv::Compaction::default(),
|a, b| yo_kv::Compaction {
walked: a.walked + b.walked,
moved: a.moved + b.moved,
bytes: a.bytes + b.bytes,
},
)
}
/// Arena segments whose pages are real, across every database.
#[must_use]
pub fn segment_count(&self) -> usize {
self.dbs
.iter()
.map(|db| db.map().arena().resident_segments())
.sum()
}
/// What the connections' read and reply buffers are holding.
#[must_use]
pub const fn conn_bytes(&self) -> usize {
self.conn_bytes
}
/// Note that the connections are holding `delta` bytes more than they were,
/// or fewer when it is negative.
///
/// A delta and not a total because the alternative is a walk over every
/// connection, and the walk would have to happen on a turn of the loop
/// rather than when `INFO` asks, which puts the cost of a report on the
/// command path of a server nobody is asking.
pub fn note_conn_bytes(&mut self, delta: isize) {
self.conn_bytes = self.conn_bytes.saturating_add_signed(delta);
}
/// Keys reclaimed by running into them after their deadline.
#[must_use]
pub fn expired_keys(&self) -> u64 {
self.dbs.iter().map(Keyspace::expired_keys).sum()
}
/// Keys thrown away to make room, which is the other number entirely.
#[must_use]
pub fn evicted_keys(&self) -> u64 {
self.dbs.iter().map(Keyspace::evicted_keys).sum()
}
/// Every command that has been seen, with its counters.
///
/// Only the ones that have. A server reports a handful of lines rather than
/// one per command in the table, which is what Redis does and is the
/// difference between a section a person can read and one they cannot.
pub fn command_stats(&self) -> impl Iterator<Item = (&'static str, CommandStat)> {
self.cmdstats
.0
.iter()
.enumerate()
.filter(|(_, row)| row.seen())
.map(|(at, row)| (table::name_at(at), *row))
}
/// The `maxmemory` limit in bytes, zero when there is not one.
#[must_use]
pub const fn maxmemory(&self) -> u64 {
self.maxmemory
}
/// Set the limit, and take a reading straight away.
///
/// The reading is here rather than left to the next maintenance turn because
/// a client that sets the limit and sends a write in the same batch expects
/// the write to be judged against the limit it just set, and because the
/// cached number is meaningless until the first time there is a limit to
/// compare it with.
///
/// Turning the limit on also turns on the running total every slab keeps of
/// what its collections hold, and turning it off turns that back off, so a
/// server with no limit is not paying to count something nobody reads. The
/// first reading after switching it on is the walk that the total starts
/// from, and it is the only walk.
pub fn set_maxmemory(&mut self, bytes: u64) {
self.maxmemory = bytes;
for db in &mut self.dbs {
db.track_memory(bytes != 0);
}
self.used = self.settled_memory();
}
/// Say where a database should get its store from when it needs one.
///
/// This is what turns the eviction inversion on. Until it is called every
/// database answers a memory limit by evicting, which is Redis, and after it
/// is called a database under memory pressure moves values to whatever the
/// closure hands back instead of throwing keys away.
///
/// Called at most once per database and only under pressure, so a server
/// that is given a file and never fills memory never touches it.
pub fn set_store_source(
&mut self,
source: impl FnMut(usize) -> Option<Box<dyn Blocks>> + 'static,
) {
self.store = Some(Box::new(source));
}
/// Whether this server has been given somewhere to put cold values.
#[must_use]
pub const fn has_store_source(&self) -> bool {
self.store.is_some()
}
/// Open database `at`'s store, if it has not got one and there is one to be
/// had.
///
/// A store that will not open leaves the database where it was, which is
/// evicting, because a memory limit that cannot be answered by moving data
/// still has to be answered.
fn attach_store(&mut self, at: usize) {
if self.dbs[at].store_bytes().is_some() {
return;
}
let Some(source) = self.store.as_mut() else {
return;
};
if let Some(blocks) = source(at) {
self.dbs[at].attach(blocks);
}
}
/// The `maxstore` limit in bytes, `None` when there is not one.
#[must_use]
pub const fn maxstore(&self) -> Option<u64> {
self.maxstore
}
/// Set the storage limit, or clear it with `None`.
///
/// Nothing is read here the way [`Server::set_maxmemory`] reads the memory
/// total, because this limit is compared against a number the store keeps
/// and answers on demand, not against a walk.
pub const fn set_maxstore(&mut self, bytes: Option<u64>) {
self.maxstore = bytes;
}
/// What every attached store is holding, for `INFO memory`.
///
/// Zero on a server with nothing attached, which is not the same as a server
/// whose file is empty, and [`Server::regime`] is the field that tells those
/// two apart.
#[must_use]
pub fn store_bytes(&self) -> u64 {
self.dbs.iter().filter_map(Keyspace::store_bytes).sum()
}
/// What the file has been asked to do, added up over every database.
///
/// Counters and not levels, so they only ever go up and a run is the
/// difference between two readings. G9 is a ratio over these: the faults a
/// run took, divided by the point reads it issued, has to come out at 1.05
/// or less with a working set ten times memory. There is no way to work that
/// out from outside the server, so it is reported rather than inferred.
///
/// A fault is a read that went to the store. Whether it also went to the
/// device depends on the store: a log serves a read out of a resident page
/// without touching anything. At ten times memory almost every fault is a
/// real read, which is why the gate is written against this number, but the
/// two are not the same thing and a run tight against the bar should be
/// checked against what the operating system says.
#[must_use]
pub fn cold_stats(&self) -> yo_kv::tier::Stats {
let mut total = yo_kv::tier::Stats::default();
for db in &self.dbs {
let Some(tier) = db.tier() else { continue };
let s = tier.stats();
total.demoted += s.demoted;
total.promoted += s.promoted;
total.faults += s.faults;
total.served += s.served;
total.bytes_out += s.bytes_out;
total.bytes_in += s.bytes_in;
}
total
}
/// Which way this server answers a memory limit, in one word for `INFO`.
///
/// `evict` is Redis: a memory limit throws keys away. `migrate` is the
/// inversion: a memory limit moves values to the file and nothing stored is
/// lost. A server reports one word rather than leaving an operator to work
/// it out from a limit, a setting and whether a file happens to be open.
#[must_use]
pub fn regime(&self) -> &'static str {
if (0..self.dbs.len()).any(|at| self.migrates(at)) {
"migrate"
} else {
"evict"
}
}
/// Whether database `at` answers a memory limit by moving values to the
/// file rather than by throwing keys away.
///
/// Three things have to hold. There has to be somewhere to move them, which
/// is a store attached to that database or a source that can open one, and
/// on a server that was never given a file this is false everywhere and
/// every database behaves exactly as it did.
/// The storage budget has to be more than nothing, which is what
/// `maxstore 0` says it is not. And the file has to be under that budget,
/// because a full file is a storage limit reached and eviction is the right
/// answer to a storage limit.
fn migrates(&self, at: usize) -> bool {
if self.maxstore == Some(0) {
return false;
}
match self.dbs[at].store_bytes() {
Some(held) => self.maxstore.is_none_or(|cap| held < cap),
// Nothing attached, but somewhere to get one from the moment this
// database needs it, which is what makes the answer yes rather than
// no. Opening it here would mean `INFO` opened files.
None => self.store.is_some(),
}
}
/// Take a fresh memory reading, which the maintenance turn does once a batch.
///
/// Nothing at all when there is no limit, which is the default and is every
/// server that has not asked for one.
pub fn refresh_memory(&mut self) {
if self.maxmemory != 0 {
self.used = self.settled_memory();
}
}
/// [`Server::memory_bytes`], asked the cheap way.
///
/// The same number. The difference is that this asks each database only
/// about the collections that could have moved since the last time, which is
/// what a batch touched rather than what the server holds, so it can be
/// asked once a batch and again on every command that is over the limit.
fn settled_memory(&mut self) -> usize {
self.dbs
.iter_mut()
.map(Keyspace::settled_memory_bytes)
.sum::<usize>()
+ self.conn_bytes
}
/// Make room under the `maxmemory` limit, throwing keys away if that is what
/// it takes. Answers whether there is anything left it could throw away.
///
/// Redis runs the same thing from `processCommand` before every command and
/// so does this: a client that writes has to be judged at the moment it
/// writes, not a batch later, or the limit is a suggestion.
///
/// Three things happen in the loop and all three are needed. Eviction picks
/// a key and drops it. Compaction gives the pages back, because dropping a
/// key marks its record dead and returns nothing on its own, so a loop that
/// only evicted would throw the whole keyspace away and watch the number
/// stay where it was. The reading is taken again each time round, because
/// the two of them together are the only thing that moves it.
///
/// # Why running out of budget is not a no
///
/// `false` means there was nothing left to evict, which is `noeviction`, or
/// a `volatile` policy on a database where nothing has a deadline, or a
/// keyspace that is already empty. It does not mean the server is still over
/// its limit, and that difference is Redis's: `performEvictions` answers
/// `EVICT_FAIL` only when it has run out of things to delete, and
/// `processCommand` refuses the client on that and on nothing else. Running
/// out of time part way through a job it is doing well comes back as
/// `EVICT_RUNNING` and the command goes through, because a server that is
/// evicting steadily and refusing every write while it does it is worse for
/// the client than a little overshoot.
///
/// # What the limit is worth
///
/// Space comes back a segment at a time and a segment is two megabytes, so
/// this holds a server to its limit give or take a segment. A `maxmemory` of
/// a few hundred megabytes gets what it asked for. A `maxmemory` of four
/// megabytes is asking for a precision this store does not have.
pub fn make_room(&mut self) -> bool {
if self.maxmemory == 0 || self.used as u64 <= self.maxmemory {
return true;
}
// The cached reading is a batch old and the batch may have compacted
// since, so take a fresh one before throwing anything away. It is the
// settled reading and not the walk, so what this costs is the handful of
// collections the last batch touched and not the whole database.
self.used = self.settled_memory();
let mut budget = EVICT_BUDGET;
while self.used as u64 > self.maxmemory {
let over = self.used - self.maxmemory as usize;
if !self.relieve_step(over) {
return false;
}
self.compact_hard_step();
self.used = self.settled_memory();
budget -= 1;
if budget == 0 {
break;
}
}
true
}
/// Give back `over` bytes from whichever database can, by moving values to
/// the file where there is one and by throwing keys away where there is not.
///
/// The two answers are the eviction inversion and which one a database gets
/// is [`Server::migrates`]. Answers whether anything was given back at all,
/// and `false` is what refuses the client's write.
///
/// A store that will not take the bytes counts as nothing given back, so the
/// write is refused rather than turned into a deletion. A disk that is
/// misbehaving is a reason to stop accepting writes and it is not a reason
/// to start losing data that was accepted already.
///
/// Round robin from a cursor rather than always starting at database zero,
/// so a server using more than one of them does not empty the first before
/// touching the second. Almost every server is on database zero only, where
/// this is one call that answers and fifteen that say the map is empty.
fn relieve_step(&mut self, over: usize) -> bool {
for turn in 0..self.dbs.len() {
let i = (self.evict_db + turn) % self.dbs.len();
// An empty database has nothing to move and opening a log for one
// would cost a resident page window to find that out.
let gave = if !self.dbs[i].is_empty() && self.migrates(i) {
self.attach_store(i);
// Whether it made room and not whether it moved a key. A round
// that demoted nothing and handed back a segment is a round
// that made room, and reading only the count refuses the write
// that provoked it.
self.dbs[i]
.relieve(over)
.is_ok_and(yo_kv::tier::Relief::made_room)
} else {
self.dbs[i].evict_one()
};
if gave {
self.evict_db = (i + 1) % self.dbs.len();
self.dirty |= 1u64 << i;
return true;
}
}
false
}
/// The sweep the shard loop calls, at most once a millisecond.
///
/// The gate is the whole difference between this and [`Server::expire_step`].
/// A maintenance slice runs on every turn of the loop and a turn is a
/// hundred nanoseconds, so an ungated sweep would draw a fresh sample ten
/// thousand times per millisecond and spend a real share of the shard on
/// looking for keys that cannot have died since the last look. Nothing in a
/// database changes fast enough to be worth asking about more often than the
/// clock can tell the difference, and the clock here is milliseconds.
///
/// A millisecond is also far finer than Redis, whose slow cycle runs at ten
/// hertz, so this is not the thing that decides how promptly memory comes
/// back. What it decides is that an idle server sweeps a thousand times a
/// second rather than a million.
pub fn expire_slice(&mut self, budget: usize) -> usize {
let now = self.clock.now_ms();
if now == self.expire_ms {
return 0;
}
self.expire_ms = now;
self.expire_step(budget)
}
/// Sweep dead keys out of the databases, spending at most `budget` looks.
///
/// Answers what it spent, so the caller can charge its maintenance slice for
/// it. See [`yo_kv::expiry`] for why the budget is in keys looked at.
///
/// Round robin from its own cursor, and every database gets offered whatever
/// is left of the budget rather than a sixteenth of it each, so a server on
/// database zero only, which is nearly every server, spends the whole slice
/// where the keys are. The fifteen empty ones cost a comparison apiece
/// because a database with no key carrying a deadline says so without
/// drawing anything.
///
/// The cursor moves to the database after whichever one did the work, so two
/// busy databases take turns instead of the lower numbered one starving the
/// other.
pub fn expire_step(&mut self, budget: usize) -> usize {
let mut spent = 0;
for turn in 0..self.dbs.len() {
if spent >= budget {
break;
}
let i = (self.expire_db + turn) % self.dbs.len();
let c = self.dbs[i].expire_cycle(budget - spent);
spent += c.examined;
if c.expired > 0 {
self.expire_db = (i + 1) % self.dbs.len();
self.dirty |= 1u64 << i;
}
}
spent
}
/// One slice of compaction for a server that is over its limit.
///
/// Takes the databases in the same order [`Server::compact_step`] does and
/// stops at the first one that had something to move, and it asks with the
/// ratios off. See [`Keyspace::compact_hard`] for what that changes.
fn compact_hard_step(&mut self) -> Option<usize> {
for turn in 0..self.dbs.len() {
let i = (self.next_db + turn) % self.dbs.len();
if let Some(moved) = self.dbs[i].compact_hard() {
self.next_db = (i + 1) % self.dbs.len();
return Some(moved);
}
}
None
}
/// Give one database's dead space back, if any database has enough of it to
/// be worth the move. `None` when no database had a candidate.
///
/// Once per batch, next to the clock. Overwriting a key writes a new record
/// and counts the old one dead, so without this a server holds everything
/// it has ever written: 400000 sets over 100000 keys measured at 742 bytes
/// a key against Redis at 144 for the same load, and the whole difference
/// was dead records nothing ever came back for.
///
/// At most one segment moves per call and the search starts one database
/// further along each time, so the cost of asking is a comparison per
/// database and the cost of acting is bounded by a segment.
pub fn compact_step(&mut self) -> Option<usize> {
for turn in 0..self.dbs.len() {
let i = (self.next_db + turn) % self.dbs.len();
// Nothing has run against this database since it last said it had
// nothing to collect, so it still has nothing to collect and the
// line it lives on stays where it is.
if self.dirty & (1 << i) == 0 {
continue;
}
if let Some(moved) = self.dbs[i].compact_step() {
self.next_db = (i + 1) % self.dbs.len();
return Some(moved);
}
self.dirty &= !(1u64 << i);
}
None
}
}
impl Default for Server {
fn default() -> Server {
Server::new()
}
}
/// What one connection has chosen.
pub struct Session {
db: usize,
id: u64,
name: Vec<u8>,
/// The `HIMPORT` fieldsets this connection has prepared.
///
/// Connection state and not keyspace state, which is the reference's design
/// and not a shortcut: a fieldset is invisible to every other connection and
/// the keys built from one outlive it.
sets: himport::Fieldsets,
}
impl Session {
/// A new connection, on database zero with no name.
#[must_use]
pub fn new(id: u64) -> Session {
Session {
db: 0,
id,
name: Vec::new(),
sets: himport::Fieldsets::default(),
}
}
/// The connection id, which `HELLO` reports and `CLIENT` will.
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
/// Which database this connection is working in.
#[must_use]
pub const fn db(&self) -> usize {
self.db
}
/// The name the client gave itself, empty if it gave none.
#[must_use]
pub fn name(&self) -> &[u8] {
&self.name
}
/// Put everything back the way it was when the connection was opened.
///
/// The protocol is not here because it is not here: it lives in the reply
/// buffer, and `RESET` sets it back there.
pub fn reset(&mut self) {
self.db = 0;
self.name.clear();
// `SELECT` leaves these alone and `RESET` does not, both checked
// against 8.10.1, which is the one pair of answers you could not guess
// from what the command is for.
self.sets.clear();
}
/// Record the name from `HELLO ... SETNAME`.
fn set_name(&mut self, name: &[u8]) {
yo_alloc::allow(|| {
self.name.clear();
self.name.extend_from_slice(name);
});
}
}
/// Run one command and write its reply.
///
/// The name is looked up and the arity is checked here, once, so that no body
/// has to. Everything after that is the command's own.
pub fn execute(server: &mut Server, session: &mut Session, args: Args<'_>, out: &mut Out) -> Flow {
// The decoder never produces a command with no name. If one ever arrives,
// it is not something to answer.
if args.is_empty() {
return Flow::Continue;
}
resolved(server, session, lookup(args.name()), args, out)
}
/// The same, for a caller that has already found the command.
///
/// The engine frames a command before it runs it, and between those two it also
/// asks which key the command touches so the record can be prefetched. That is
/// two more chances to look the name up, and looking it up three times to run it
/// once is three times the cost of the cheapest thing in the path. So the engine
/// resolves the name where it frames the command, carries the answer on the
/// framed command, and both the other two take it from there.
///
/// `spec` is `None` for a name that is not a command, which is the same thing
/// [`lookup`] says and lands in the same reply.
pub fn resolved(
server: &mut Server,
session: &mut Session,
spec: Option<&'static Spec>,
args: Args<'_>,
out: &mut Out,
) -> Flow {
if args.is_empty() {
return Flow::Continue;
}
server.stats.commands += 1;
let Some(spec) = spec else {
write_error(out, &args::unknown_command(args));
return Flow::Continue;
};
if !arity_ok(spec, args.len()) {
server.cmdstats.at(spec).rejected += 1;
write_error(out, &args::wrong_arity(spec.name));
return Flow::Continue;
}
// The limit first, so a server with no `maxmemory`, which is the default and
// is nearly all of them, pays one comparison against a field that is already
// warm. Every command and not only the writes, because that is where Redis
// puts it: making room is the server's job whatever the client asked for,
// and the flag only decides who gets told no when there is no room to make.
//
// The flag is Redis's own `denyoom` and the list of commands carrying it is
// Redis's list, so a command that only frees is let through with nothing
// left, which is what lets a client dig itself out with `DEL`.
if server.maxmemory != 0 && !server.make_room() && spec.flags.contains(&"denyoom") {
server.cmdstats.at(spec).rejected += 1;
out.error_line(b"OOM ", OOM);
return Flow::Continue;
}
// Which databases the maintenance turn after this batch has to ask. Marked
// for every command and not only for the writes, because a read can make
// garbage too: a `GET` on a key whose expiry has passed reaps it, and the
// record it dropped is exactly the kind of thing the collector is for.
// `COPY`, `SWAPDB` and `FLUSHALL` reach a database nobody selected, so the
// two groups that hold them mark all of them rather than the session's.
server.dirty |= match spec.group {
"string" | "bitmap" | "hyperloglog" | "geo" | "set" | "hash" | "list" | "zset"
| "array" | "stream" | "bloom" | "cuckoo" | "cms" | "topk" | "tdigest" => {
1u64 << session.db
}
_ => ALL_DATABASES,
};
let mark = out.len();
// Before the group, because the five that block are list commands and would
// otherwise land in `lists`, which is handed one database and nothing that
// could park a client. The flag is the right thing to branch on rather than
// a list of names: it is what `COMMAND INFO` reports about exactly these
// commands, and the sorted set and stream ones that arrive later carry it
// too.
let done = if spec.flags.contains(&"blocking") {
blocking::execute(server, session, spec, args, out)
} else {
match spec.group {
"string" => {
let db = session.db;
strings::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// Its own group and its own file, and the same values underneath:
// a bitmap is a string, so `STRLEN` on one answers and `SETBIT` on
// something a `SET` left behind works.
"bitmap" => {
let db = session.db;
bits::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// The same again: a sketch is a string with a documented layout, so
// `GET` hands one to a client and `SET` takes it back.
"hyperloglog" => {
let db = session.db;
hll::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"set" => {
let db = session.db;
sets::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// The one hash command whose state is not in the keyspace. A
// fieldset belongs to the connection, so this is handed the session
// as well as the database, the same exception `MIGRATE` gets in the
// keyspace group for the socket it keeps.
"hash" if spec.name == "himport" => {
let db = session.db;
himport::execute(&mut server.dbs[db], &mut session.sets, args, out)
.map(|()| Flow::Continue)
}
"hash" => {
let db = session.db;
hashes::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"list" => {
let db = session.db;
lists::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"zset" => {
let db = session.db;
zsets::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// A geo key is a sorted set and these are sorted set commands with
// arithmetic on the way in and on the way out, so a client can ZREM
// a place out of one and ZCARD it to count them.
"geo" => {
let db = session.db;
geo::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"array" => {
let db = session.db;
arrays::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"graph" => {
let db = session.db;
graph::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// A document under a key, reached by a path. The group is Redis's
// module surface and the storage is ours, the same trade the vector
// set group makes.
"json" => {
let db = session.db;
json::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"vector" => {
let db = session.db;
vectors::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"bloom" => {
let db = session.db;
bloom::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"cuckoo" => {
let db = session.db;
cuckoo::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"cms" => {
let db = session.db;
cms::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"topk" => {
let db = session.db;
topk::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
"tdigest" => {
let db = session.db;
tdigest::execute(&mut server.dbs[db], spec, args, out).map(|()| Flow::Continue)
}
// The clock is read before the database is borrowed, because every
// stream command needs the time and it lives on the server. An
// `XADD` with no ID, an `XCLAIM` working out what is idle and an
// `XINFO` reporting it all have to agree about what moment this is.
"stream" => {
let db = session.db;
let now = server.now_ms();
streams::execute(&mut server.dbs[db], spec, args, now, out).map(|()| Flow::Continue)
}
// The one keyspace command that needs more than the databases,
// because the socket it talks down is held on the server between
// commands and not opened again for each one.
"keyspace" if spec.name == "migrate" => {
migrate::execute(server, session.db, args, out).map(|()| Flow::Continue)
}
// Every database and not the one the session is on, because `COPY` takes
// a `DB n` and writes into a database nobody selected.
"keyspace" => keyspace::execute(&mut server.dbs, session.db, spec, args, out)
.map(|()| Flow::Continue),
"scripting" => scripting::execute(spec, args, out).map(|()| Flow::Continue),
_ => server::execute(server, session, spec, args, out),
}
};
let flow = match done {
Ok(flow) => flow,
Err(e) => {
out.truncate(mark);
write_error(out, &e);
Flow::Continue
}
};
// Counted here and not before the call, which is where Redis counts it, so
// that `INFO commandstats` leaves out the `INFO` that asked for it in the
// same way theirs does.
//
// Failure is read off the reply rather than off the `Result`, because the
// two are not the same set. A command that ran out of arguments comes back
// as an `Err` and a command that was sent the wrong password writes its own
// error line and comes back `Ok`, and both of those are a call that failed.
// The first byte at the mark is what a client would branch on, and it is `-`
// for an error on either protocol and `!` for RESP3's long form.
let row = server.cmdstats.at(spec);
row.calls += 1;
if matches!(out.as_slice().get(mark), Some(b'-' | b'!')) {
row.failed += 1;
}
flow
}
/// The error line for an error value.
///
/// The prefix is what a client branches on, and there are three of them:
/// `WRONGTYPE` for a command sent at the wrong kind of value, `INVALIDOBJ` for a
/// HyperLogLog whose opcodes do not add up, and `ERR` for everything else. The three errors that need a different one,
/// `NOPROTO`, `WRONGPASS` and `OOM`, are written where they are decided rather
/// than routed through here. `OOM` is not a [`Code`] of its own because
/// [`Code::Full`] already covers the string that is too long for
/// `proto-max-bulk-len`, and that one goes out as `ERR` on a real server.
fn write_error(out: &mut Out, e: &Error) {
let prefix: &[u8] = match e.code() {
Code::WrongType => b"WRONGTYPE ",
// Only the HyperLogLog commands answer this one, and the prefix is the
// sentence a client branches on to tell a sketch it cannot read from a
// sketch it sent wrong.
Code::Corrupt => b"INVALIDOBJ ",
_ => b"ERR ",
};
out.error_line(prefix, e.message().as_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
use crate::proto::{Limits, Proto};
use crate::request::Argv;
/// Build the wire bytes for a command.
///
/// Tests go through the codec rather than around it, so an argument in a
/// test is the same borrowed slice a connection produces.
pub(crate) fn encode(parts: &[&[u8]]) -> Vec<u8> {
let mut wire = format!("*{}\r\n", parts.len()).into_bytes();
for p in parts {
wire.extend_from_slice(format!("${}\r\n", p.len()).as_bytes());
wire.extend_from_slice(p);
wire.extend_from_slice(b"\r\n");
}
wire
}
/// A server, a connection and a buffer, driven the way the reactor will.
struct Fixture {
server: Server,
session: Session,
argv: Argv,
out: Out,
}
impl Fixture {
fn new() -> Fixture {
Fixture {
server: Server::new(),
session: Session::new(7),
argv: Argv::new(),
out: Out::new(Proto::Resp2),
}
}
/// Run one command and answer with the bytes it wrote.
fn run(&mut self, parts: &[&[u8]]) -> String {
self.flow(parts).1
}
/// Run one command and answer with the bytes exactly as written.
///
/// [`Fixture::run`] goes through `from_utf8_lossy`, which is fine for
/// every reply that is text and destroys a `DUMP` payload, since a
/// payload is arbitrary bytes and a checksum on the end of them.
fn raw(&mut self, parts: &[&[u8]]) -> Vec<u8> {
let wire = encode(parts);
self.argv.decode(&wire, &Limits::default()).unwrap();
self.out.clear();
execute(
&mut self.server,
&mut self.session,
Args::new(&self.argv, &wire),
&mut self.out,
);
self.out.as_slice().to_vec()
}
/// Move every clock in the server on by `ms`.
fn advance(&mut self, ms: u64) {
for db in 0..DATABASES {
self.server.db(db).clock_mut().advance(ms);
}
}
/// The same, with what the connection should do next.
fn flow(&mut self, parts: &[&[u8]]) -> (Flow, String) {
let wire = encode(parts);
self.argv.decode(&wire, &Limits::default()).unwrap();
self.out.clear();
let flow = execute(
&mut self.server,
&mut self.session,
Args::new(&self.argv, &wire),
&mut self.out,
);
(
flow,
String::from_utf8_lossy(self.out.as_slice()).into_owned(),
)
}
}
/// What a client does all day: write the same keys again and again. Every
/// one of those writes leaves the previous record behind, so a server that
/// never compacts holds every version of every key it has ever been sent.
#[test]
fn rewriting_the_same_keys_does_not_grow_the_server() {
let mut f = Fixture::new();
let val = vec![b'v'; 1024];
let keys: Vec<Vec<u8>> = (0..64).map(|i| format!("key:{i}").into_bytes()).collect();
for k in &keys {
f.run(&[b"SET", k, &val]);
}
f.server.compact_step();
let after_first = f.server.memory_bytes();
// 64 KiB a pass, five hundred passes, and the same 64 keys at the end
// of it. Thirty two megabytes written to hold sixty four kilobytes,
// which is the shape of a real workload and is enough churn to fill
// sixteen segments if nothing ever comes back.
for _ in 0..500 {
for k in &keys {
f.run(&[b"SET", k, &val]);
}
f.server.compact_step();
}
assert!(
f.server.memory_bytes() <= after_first * 2,
"held {} after five hundred passes against {after_first} after one",
f.server.memory_bytes()
);
assert_eq!(f.run(&[b"DBSIZE"]), format!(":{}\r\n", keys.len()));
assert_eq!(f.run(&[b"STRLEN", b"key:7"]), ":1024\r\n");
}
/// The same churn on a database nobody starts on, either side of a quiet
/// spell long enough for the maintenance turn to stop asking about it.
///
/// The turn after each batch skips a database that has already said it has
/// nothing to collect and has not been touched since, which is what keeps a
/// server whose clients are all on database zero from loading and storing
/// in the other fifteen every batch to be told no. Two things could go
/// wrong with that. A database might never be marked at all, so this uses
/// database nine, which nothing marks by accident. And a database whose
/// mark was cleared might never get it back, so this drains the collector
/// until it says there is nothing left, checks the mark really is gone, and
/// then writes another thirty two megabytes through the same sixty four
/// keys. If either went wrong the server would hold all of it.
#[test]
fn a_database_nobody_started_on_is_still_collected() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SELECT", b"9"]), "+OK\r\n");
let val = vec![b'v'; 1024];
let keys: Vec<Vec<u8>> = (0..64).map(|i| format!("key:{i}").into_bytes()).collect();
for k in &keys {
f.run(&[b"SET", k, &val]);
}
while f.server.compact_step().is_some() {}
assert_eq!(
f.server.dirty & (1 << 9),
0,
"database nine was drained and should not be asked again until it is written to"
);
let after_first = f.server.memory_bytes();
for _ in 0..500 {
for k in &keys {
f.run(&[b"SET", k, &val]);
}
f.server.compact_step();
}
assert!(
f.server.memory_bytes() <= after_first * 2,
"held {} after five hundred passes against {after_first} after one",
f.server.memory_bytes()
);
assert_eq!(f.run(&[b"DBSIZE"]), format!(":{}\r\n", keys.len()));
assert_eq!(f.run(&[b"STRLEN", b"key:7"]), ":1024\r\n");
// And nothing landed anywhere else on the way.
f.run(&[b"SELECT", b"0"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
}
#[test]
fn a_command_goes_from_bytes_to_bytes() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$1\r\nv\r\n");
assert_eq!(f.run(&[b"GET", b"nosuch"]), "$-1\r\n");
assert_eq!(f.run(&[b"STRLEN", b"k"]), ":1\r\n");
// The name is matched whatever case it came in, and so are the options.
assert_eq!(f.run(&[b"set", b"k", b"v2", b"xx"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$2\r\nv2\r\n");
}
#[test]
fn deleting_counts_keys_removed_and_existing_counts_arguments_matched() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"1", b"b", b"2", b"c", b"3"]);
// A key named twice exists twice and can only be deleted once, and both
// of those are Redis's answers rather than tidier ones.
assert_eq!(f.run(&[b"EXISTS", b"a", b"a", b"nosuch"]), ":2\r\n");
assert_eq!(f.run(&[b"DEL", b"a", b"a", b"nosuch"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
// UNLINK is the same body and reports the same way.
assert_eq!(f.run(&[b"UNLINK", b"b", b"c"]), ":2\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
}
#[test]
fn type_is_a_simple_string_and_says_none_for_a_key_that_is_not_there() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
// A simple string on both protocols, which is unusual: most replies
// that carry a word are bulk strings.
assert_eq!(f.run(&[b"TYPE", b"k"]), "+string\r\n");
assert_eq!(f.run(&[b"TYPE", b"nosuch"]), "+none\r\n");
}
#[test]
fn touch_counts_the_way_exists_counts() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
assert_eq!(f.run(&[b"TOUCH", b"a", b"b"]), ":2\r\n");
assert_eq!(
f.run(&[b"TOUCH", b"a", b"a"]),
":2\r\n",
"twice counts twice"
);
assert_eq!(f.run(&[b"TOUCH", b"a", b"nosuch"]), ":1\r\n");
assert_eq!(f.run(&[b"TOUCH", b"nosuch"]), ":0\r\n");
}
#[test]
fn a_rename_moves_the_deadline_with_the_value_and_drops_the_one_it_lands_on() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v1", b"EX", b"100"]);
f.run(&[b"SET", b"b", b"v2", b"EX", b"500"]);
assert_eq!(f.run(&[b"RENAME", b"a", b"b"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv1\r\n");
assert_eq!(
f.run(&[b"TTL", b"b"]),
":100\r\n",
"the source's and not b's"
);
assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
}
#[test]
fn a_rename_with_no_source_is_an_error_and_not_a_zero() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"RENAME", b"a", b"b"]), "-ERR no such key\r\n");
// The source is checked before the destination, so this is the error
// and not the zero RENAMENX would otherwise answer for a taken name.
assert_eq!(f.run(&[b"RENAMENX", b"a", b"a"]), "-ERR no such key\r\n");
}
#[test]
fn renamenx_refuses_a_taken_name_including_the_one_it_already_has() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"v1", b"b", b"v2"]);
assert_eq!(f.run(&[b"RENAMENX", b"a", b"b"]), ":0\r\n");
assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv2\r\n");
// Renaming onto itself is 0 here and OK for plain RENAME, which is the
// one call the two disagree about and neither does any work for.
assert_eq!(f.run(&[b"RENAMENX", b"a", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"RENAME", b"a", b"a"]), "+OK\r\n");
assert_eq!(f.run(&[b"RENAMENX", b"a", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"GET", b"c"]), "$2\r\nv1\r\n");
}
#[test]
fn renaming_a_set_does_not_touch_a_member() {
let mut f = Fixture::new();
for i in 0..300 {
f.run(&[b"SADD", b"s", format!("m{i}").as_bytes()]);
}
let before = f.server.memory_bytes();
assert_eq!(f.run(&[b"RENAME", b"s", b"t"]), "+OK\r\n");
assert_eq!(f.run(&[b"SCARD", b"t"]), ":300\r\n");
assert_eq!(f.run(&[b"TYPE", b"t"]), "+set\r\n");
assert!(
f.server.memory_bytes().abs_diff(before) < 256,
"the members were copied: {} against {before}",
f.server.memory_bytes()
);
}
#[test]
fn a_copy_is_a_second_value_and_not_a_second_name() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"m1", b"m2"]);
assert_eq!(f.run(&[b"COPY", b"s", b"t"]), ":1\r\n");
f.run(&[b"SADD", b"t", b"m3"]);
assert_eq!(f.run(&[b"SCARD", b"s"]), ":2\r\n", "the original is intact");
assert_eq!(f.run(&[b"SCARD", b"t"]), ":3\r\n");
}
/// Every type a key can hold, copied, because two of them used to panic.
///
/// `COPY` reads the value out of the source through one match on the type
/// tag, and that match had a catch all at the bottom from back when a set
/// and a hash were the only bodies. The list and the sorted set landed after
/// it and nobody came back, so `COPY mylist other` took the shard down. It
/// is an ordinary command against a type the server supports everywhere
/// else, so this walks all five rather than the two that were broken: the
/// point is that the next type cannot land the same way.
#[test]
fn every_type_can_be_copied() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v1"]);
f.run(&[b"SADD", b"set", b"m1"]);
f.run(&[b"HSET", b"hash", b"f", b"v"]);
f.run(&[b"RPUSH", b"list", b"a", b"b"]);
f.run(&[b"ZADD", b"zset", b"1", b"m1"]);
for name in [
&b"str"[..],
&b"set"[..],
&b"hash"[..],
&b"list"[..],
&b"zset"[..],
] {
let dst = [name, b":copy"].concat();
assert_eq!(
f.run(&[b"COPY", name, &dst]),
":1\r\n",
"copying {}",
String::from_utf8_lossy(name)
);
assert_eq!(f.run(&[b"TYPE", name]), f.run(&[b"TYPE", &dst]));
}
assert_eq!(f.run(&[b"LRANGE", b"list:copy", b"0", b"-1"]), {
let mut want = String::from("*2\r\n");
want.push_str("$1\r\na\r\n$1\r\nb\r\n");
want
});
assert_eq!(f.run(&[b"ZSCORE", b"zset:copy", b"m1"]), "$1\r\n1\r\n");
// And the copy is its own value, not a second name for the source.
f.run(&[b"RPUSH", b"list:copy", b"c"]);
assert_eq!(f.run(&[b"LLEN", b"list"]), ":2\r\n");
assert_eq!(f.run(&[b"LLEN", b"list:copy"]), ":3\r\n");
}
#[test]
fn a_copy_refuses_a_taken_destination_until_it_is_told_it_can_have_it() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v1", b"EX", b"100"]);
f.run(&[b"SET", b"b", b"v2"]);
assert_eq!(f.run(&[b"COPY", b"a", b"b"]), ":0\r\n");
assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv2\r\n");
assert_eq!(f.run(&[b"COPY", b"a", b"b", b"REPLACE"]), ":1\r\n");
assert_eq!(f.run(&[b"GET", b"b"]), "$2\r\nv1\r\n");
assert_eq!(f.run(&[b"TTL", b"b"]), ":100\r\n", "the deadline came too");
assert_eq!(f.run(&[b"COPY", b"nosuch", b"z"]), ":0\r\n");
}
#[test]
fn a_copy_into_another_database_is_a_copy_and_onto_itself_there_is_too() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v1"]);
// Same key, different database, so this is not the same object and is
// an ordinary copy. Same key in the same database is the error below.
assert_eq!(f.run(&[b"COPY", b"a", b"a", b"DB", b"1"]), ":1\r\n");
f.run(&[b"SELECT", b"1"]);
assert_eq!(f.run(&[b"GET", b"a"]), "$2\r\nv1\r\n");
assert_eq!(
f.run(&[b"COPY", b"a", b"a", b"DB", b"0"]),
":0\r\n",
"taken"
);
assert_eq!(
f.run(&[b"COPY", b"a", b"a", b"DB", b"0", b"REPLACE"]),
":1\r\n"
);
}
#[test]
fn sort_takes_its_options_in_any_order_and_the_last_one_wins() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"l", b"3", b"1", b"2"]);
assert_eq!(
f.run(&[b"SORT", b"l"]),
"*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
);
// DESC then ASC is ASC, because the only thing ASC does is undo a DESC.
assert_eq!(
f.run(&[b"SORT", b"l", b"DESC", b"asc"]),
"*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
);
assert_eq!(
f.run(&[b"sort", b"l", b"LIMIT", b"1", b"1", b"DESC"]),
"*1\r\n$1\r\n2\r\n"
);
}
#[test]
fn sort_reads_a_key_per_element_for_by_and_for_get() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"l", b"a", b"b"]);
f.run(&[b"MSET", b"w_a", b"2", b"w_b", b"1", b"d_b", b"bee"]);
// `b` weighs less so it comes first, and its `GET` hits where `a`'s
// misses, which is a nil in the middle of the array and not a short one.
assert_eq!(
f.run(&[b"SORT", b"l", b"BY", b"w_*", b"GET", b"#", b"GET", b"d_*"]),
"*4\r\n$1\r\nb\r\n$3\r\nbee\r\n$1\r\na\r\n$-1\r\n"
);
}
#[test]
fn sort_store_writes_a_list_and_answers_its_length() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"l", b"3", b"1", b"2"]);
assert_eq!(f.run(&[b"SORT", b"l", b"STORE", b"out"]), ":3\r\n");
assert_eq!(f.run(&[b"TYPE", b"out"]), "+list\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"out", b"0", b"-1"]),
"*3\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n3\r\n"
);
// An empty result takes the destination with it rather than leaving a
// list that holds nothing.
assert_eq!(f.run(&[b"SORT", b"missing", b"STORE", b"out"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"out"]), ":0\r\n");
}
#[test]
fn sort_ro_does_not_know_the_word_store() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"l", b"2", b"1"]);
assert_eq!(f.run(&[b"SORT_RO", b"l"]), "*2\r\n$1\r\n1\r\n$1\r\n2\r\n");
assert_eq!(
f.run(&[b"SORT_RO", b"l", b"STORE", b"d"]),
"-ERR syntax error\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
}
#[test]
fn sort_refuses_what_it_cannot_sort() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SORT", b"nosuchkey"]), "*0\r\n");
f.run(&[b"SET", b"s", b"x"]);
assert_eq!(
f.run(&[b"SORT", b"s"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
f.run(&[b"RPUSH", b"words", b"one", b"two"]);
assert_eq!(
f.run(&[b"SORT", b"words"]),
"-ERR One or more scores can't be converted into double\r\n"
);
assert_eq!(
f.run(&[b"SORT", b"words", b"ALPHA"]),
"*2\r\n$3\r\none\r\n$3\r\ntwo\r\n"
);
assert_eq!(f.run(&[b"SORT", b"words", b"BY"]), "-ERR syntax error\r\n");
}
#[test]
fn move_takes_the_key_out_of_one_database_and_puts_it_in_another() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"RPUSH", b"l", b"a", b"b"]), ":2\r\n");
assert_eq!(f.run(&[b"MOVE", b"l", b"1"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"l"]), ":0\r\n");
assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"l", b"0", b"-1"]),
"*2\r\n$1\r\na\r\n$1\r\nb\r\n"
);
// And back, which proves the body survived the trip rather than being
// rebuilt from a copy that happened to look the same.
assert_eq!(f.run(&[b"MOVE", b"l", b"0"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"l"]), ":0\r\n");
}
#[test]
fn move_answers_zero_when_either_end_says_no() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"MOVE", b"nope", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"SET", b"a", b"here"]), "+OK\r\n");
assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"SET", b"a", b"there"]), "+OK\r\n");
assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");
// The destination is taken, so nothing moves and the source is still
// there with what it had.
assert_eq!(f.run(&[b"MOVE", b"a", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"GET", b"a"]), "$4\r\nhere\r\n");
assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"a"]), "$5\r\nthere\r\n");
}
#[test]
fn move_refuses_a_database_that_is_not_one_and_the_one_it_is_on() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"MOVE", b"a", b"0"]),
"-ERR source and destination objects are the same\r\n"
);
assert_eq!(
f.run(&[b"MOVE", b"a", b"99"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"MOVE", b"a", b"-1"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"MOVE", b"a", b"x"]),
"-ERR value is not an integer or out of range\r\n"
);
}
#[test]
fn swapdb_swaps_what_two_connections_would_see() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SET", b"k", b"zero"]), "+OK\r\n");
assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"SET", b"k", b"one"]), "+OK\r\n");
assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");
assert_eq!(f.run(&[b"SWAPDB", b"0", b"1"]), "+OK\r\n");
// Still on database zero, and database zero is a different database.
assert_eq!(f.run(&[b"GET", b"k"]), "$3\r\none\r\n");
assert_eq!(f.run(&[b"SELECT", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
// A database swapped with itself is fine and changes nothing.
assert_eq!(f.run(&[b"SWAPDB", b"1", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
}
#[test]
fn swapdb_says_which_index_it_could_not_read() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"SWAPDB", b"x", b"1"]),
"-ERR invalid first DB index\r\n"
);
assert_eq!(
f.run(&[b"SWAPDB", b"0", b"y"]),
"-ERR invalid second DB index\r\n"
);
// A number too big to be an index on a server that keeps one in an int
// is the same complaint, and a plausible one that is not ours is the
// range complaint instead. The split is Redis's.
assert_eq!(
f.run(&[b"SWAPDB", b"99999999999999", b"1"]),
"-ERR invalid first DB index\r\n"
);
assert_eq!(
f.run(&[b"SWAPDB", b"0", b"99"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"SWAPDB", b"-1", b"0"]),
"-ERR DB index is out of range\r\n"
);
}
#[test]
fn wait_answers_zero_replicas_without_waiting() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SET", b"a", b"v"]), "+OK\r\n");
assert_eq!(f.run(&[b"WAIT", b"0", b"0"]), ":0\r\n");
// A replica that is never going to arrive, and a timeout that would be
// a real wait on a server that had one.
assert_eq!(f.run(&[b"WAIT", b"3", b"1000"]), ":0\r\n");
// Negative replicas is not an error, because zero is already more than
// it asked for.
assert_eq!(f.run(&[b"WAIT", b"-1", b"0"]), ":0\r\n");
assert_eq!(
f.run(&[b"WAIT", b"x", b"0"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"WAIT", b"0", b"-1"]),
"-ERR timeout is negative\r\n"
);
assert_eq!(
f.run(&[b"WAIT", b"0", b"1.5"]),
"-ERR timeout is not an integer or out of range\r\n"
);
}
#[test]
fn waitaof_answers_two_zeroes_and_refuses_a_local_wait() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"WAITAOF", b"0", b"0", b"0"]), "*2\r\n:0\r\n:0\r\n");
assert_eq!(
f.run(&[b"WAITAOF", b"1", b"0", b"0"]),
"-ERR WAITAOF cannot be used when numlocal is set but appendonly is disabled.\r\n"
);
assert_eq!(
f.run(&[b"WAITAOF", b"2", b"0", b"0"]),
"-ERR value is out of range, value must between 0 and 1\r\n"
);
assert_eq!(
f.run(&[b"WAITAOF", b"0", b"-1", b"0"]),
"-ERR value is out of range, must be positive\r\n"
);
// The arguments are all read before the server looks at itself, so a
// bad timeout beats the append only complaint even with numlocal set.
assert_eq!(
f.run(&[b"WAITAOF", b"1", b"0", b"-5"]),
"-ERR timeout is negative\r\n"
);
}
/// The bytes inside a bulk reply, with the header and the trailing break
/// taken off. Every `DUMP` test needs this and none of them care how the
/// length was written.
fn payload(reply: &[u8]) -> Vec<u8> {
let head = reply.windows(2).position(|w| w == b"\r\n").unwrap();
reply[head + 2..reply.len() - 2].to_vec()
}
#[test]
fn a_value_survives_a_dump_and_a_restore() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"hello"]);
f.run(&[b"RPUSH", b"l", b"a", b"b", b"c"]);
f.run(&[b"SADD", b"t", b"1", b"2", b"3"]);
f.run(&[b"SADD", b"u", b"x", b"y"]);
f.run(&[b"HSET", b"h", b"f", b"1", b"g", b"2"]);
f.run(&[b"ZADD", b"z", b"1.5", b"a", b"2.5", b"b"]);
for key in [&b"s"[..], b"l", b"t", b"u", b"h", b"z"] {
let mut copy = key.to_vec();
copy.push(b'2');
let bytes = payload(&f.raw(&[b"DUMP", key]));
assert_eq!(f.run(&[b"RESTORE", ©, b"0", &bytes]), "+OK\r\n");
assert_eq!(f.run(&[b"TYPE", ©]), f.run(&[b"TYPE", key]));
}
assert_eq!(f.run(&[b"GET", b"s2"]), "$5\r\nhello\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"l2", b"0", b"-1"]),
"*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"t2"])), ["1", "2", "3"]);
assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"u2"])), ["x", "y"]);
assert_eq!(f.run(&[b"HGET", b"h2", b"g"]), "$1\r\n2\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z2", b"b"]), "$3\r\n2.5\r\n");
// The encoding survives too, since the payload names the plainest legal
// type and the loader puts the value back on the rung it belongs on.
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"t2"]),
f.run(&[b"OBJECT", b"ENCODING", b"t"])
);
}
#[test]
fn a_dumped_hash_keeps_its_field_deadlines() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"keep", b"1", b"go", b"2"]);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"go"]),
"*1\r\n:1\r\n"
);
let bytes = payload(&f.raw(&[b"DUMP", b"h"]));
assert_eq!(f.run(&[b"RESTORE", b"h2", b"0", &bytes]), "+OK\r\n");
assert_eq!(
f.run(&[b"HTTL", b"h2", b"FIELDS", b"2", b"keep", b"go"]),
"*2\r\n:-1\r\n:100\r\n"
);
}
#[test]
fn dump_leaves_the_deadline_behind_and_restore_is_given_a_new_one() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v", b"EX", b"100"]);
let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
assert_eq!(f.run(&[b"RESTORE", b"b", b"0", &bytes]), "+OK\r\n");
assert_eq!(f.run(&[b"TTL", b"b"]), ":-1\r\n");
assert_eq!(f.run(&[b"RESTORE", b"c", b"5000", &bytes]), "+OK\r\n");
assert_eq!(f.run(&[b"TTL", b"c"]), ":5\r\n");
// An absolute deadline that has already gone is not an error. The key is
// not created and the reply is the same OK a live one gets.
assert_eq!(
f.run(&[b"RESTORE", b"d", b"1", &bytes, b"ABSTTL"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
}
#[test]
fn dump_answers_nothing_for_a_key_that_is_not_there() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"DUMP", b"nope"]), "$-1\r\n");
f.run(&[b"SET", b"gone", b"v", b"PX", b"10"]);
f.advance(50);
assert_eq!(f.run(&[b"DUMP", b"gone"]), "$-1\r\n");
}
#[test]
fn restore_refuses_a_key_that_is_there_unless_it_is_told_to_replace() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"first"]);
f.run(&[b"SET", b"b", b"second"]);
let bytes = payload(&f.raw(&[b"DUMP", b"b"]));
assert_eq!(
f.run(&[b"RESTORE", b"a", b"0", &bytes]),
"-BUSYKEY Target key name already exists.\r\n"
);
assert_eq!(f.run(&[b"GET", b"a"]), "$5\r\nfirst\r\n");
assert_eq!(
f.run(&[b"RESTORE", b"a", b"0", &bytes, b"REPLACE"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"GET", b"a"]), "$6\r\nsecond\r\n");
}
/// The busy key comes before the payload, which is not the order the
/// arguments read in. Whether a key is taken should not depend on whether
/// the bytes behind it happened to be good.
#[test]
fn restore_asks_about_the_key_before_it_looks_at_the_bytes() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v"]);
assert_eq!(
f.run(&[b"RESTORE", b"a", b"0", b"rubbish"]),
"-BUSYKEY Target key name already exists.\r\n"
);
// And the options come before even that, so a bad FREQ beats the busy
// key the same way a bad DB beats a missing source in COPY.
assert_eq!(
f.run(&[b"RESTORE", b"a", b"0", b"rubbish", b"FREQ", b"300"]),
"-ERR Invalid FREQ value, must be >= 0 and <= 255\r\n"
);
}
#[test]
fn restore_can_tell_a_bad_footer_from_bad_bytes() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"hello"]);
let good = payload(&f.raw(&[b"DUMP", b"a"]));
let mut flipped = good.clone();
flipped[2] ^= 0x40;
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &flipped]),
"-ERR DUMP payload version or checksum are wrong\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", b"short"]),
"-ERR DUMP payload version or checksum are wrong\r\n"
);
// A footer that is right over a body that is not. The type byte says
// string and there is nothing behind it, so the checksum agrees and the
// value does not exist.
let mut truncated = good[..1].to_vec();
truncated.extend_from_slice(&good[good.len() - 10..good.len() - 8]);
let crc = yo_common::crc::crc64(0, &truncated);
truncated.extend_from_slice(&crc.to_le_bytes());
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &truncated]),
"-ERR Bad data format\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"b"]), ":0\r\n");
}
#[test]
fn restore_checks_the_three_numbers_a_client_can_get_wrong() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v"]);
let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
assert_eq!(
f.run(&[b"RESTORE", b"b", b"-1", &bytes]),
"-ERR Invalid TTL value, must be >= 0\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &bytes, b"IDLETIME", b"-1"]),
"-ERR Invalid IDLETIME value, must be >= 0\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &bytes, b"FREQ", b"256"]),
"-ERR Invalid FREQ value, must be >= 0 and <= 255\r\n"
);
// Both are accepted and both are then dropped, which is D-26.
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &bytes, b"IDLETIME", b"90"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"c", b"0", &bytes, b"FREQ", b"200", b"REPLACE"]),
"+OK\r\n"
);
}
/// Neither word is refused for being the wrong one. Each is only accepted
/// while the other is unset, so the second of the two falls through to the
/// plain syntax error rather than getting a message of its own.
#[test]
fn restore_takes_idletime_or_freq_and_not_both() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"v"]);
let bytes = payload(&f.raw(&[b"DUMP", b"a"]));
assert_eq!(
f.run(&[
b"RESTORE",
b"b",
b"0",
&bytes,
b"IDLETIME",
b"1",
b"FREQ",
b"2"
]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[
b"RESTORE",
b"b",
b"0",
&bytes,
b"FREQ",
b"2",
b"IDLETIME",
b"1"
]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &bytes, b"FREQ"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"RESTORE", b"b", b"0", &bytes, b"NOSUCH"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn copy_checks_its_options_before_it_looks_for_anything() {
let mut f = Fixture::new();
// No key exists at all, and every one of these is still the option
// complaint rather than a zero, which is the order a real server uses.
assert_eq!(
f.run(&[b"COPY", b"a", b"b", b"DB", b"99"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"COPY", b"a", b"b", b"DB", b"-1"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"COPY", b"a", b"b", b"DB", b"x"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"COPY", b"a", b"b", b"nonsense"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"COPY", b"a", b"a"]),
"-ERR source and destination objects are the same\r\n"
);
// Repeated, reordered and lowercased, and the last DB wins.
assert_eq!(
f.run(&[b"COPY", b"a", b"b", b"dB", b"1", b"rEpLaCe", b"db", b"2"]),
":0\r\n"
);
}
#[test]
fn time_is_two_bulk_strings_and_moves() {
let mut f = Fixture::new();
let first = f.run(&[b"TIME"]);
assert!(first.starts_with("*2\r\n$"), "got {first}");
let parts: Vec<&str> = first.split("\r\n").collect();
let secs: i64 = parts[2].parse().expect("seconds as decimal text");
let micros: i64 = parts[4].parse().expect("microseconds as decimal text");
assert!(secs > 1_700_000_000, "a real wall clock, got {secs}");
assert!((0..1_000_000).contains(µs), "got {micros}");
// The coarse clock the keyspace uses is a cached millisecond that a
// background tick refreshes, so a TIME built on it would answer the
// same microsecond twice in a row here.
assert_ne!(first, f.run(&[b"TIME"]));
}
#[test]
fn a_keyspace_scan_walks_every_key_once() {
let mut f = Fixture::new();
for i in 0..500 {
f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
}
let mut seen: Vec<String> = Vec::new();
let mut cursor = "0".to_owned();
let mut calls = 0;
loop {
let (next, keys) = scan_reply(&f.run(&[b"SCAN", cursor.as_bytes(), b"COUNT", b"32"]));
seen.extend(keys);
cursor = next;
calls += 1;
assert!(calls < 10_000, "the cursor is not advancing");
if cursor == "0" {
break;
}
}
seen.sort();
seen.dedup();
assert_eq!(seen.len(), 500, "every key once and only once");
// And more than one call to get them, or the COUNT is being ignored and
// the loop above proved nothing about resuming.
assert!(calls > 1, "500 keys came back in one batch");
}
#[test]
fn a_scan_narrows_by_pattern_and_by_type() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
f.run(&[b"SADD", b"members", b"a"]);
f.run(&[b"HSET", b"fields", b"f", b"v"]);
let all = |f: &mut Fixture, args: &[&[u8]]| {
let mut out: Vec<String> = Vec::new();
let mut cursor = "0".to_owned();
loop {
let mut line: Vec<&[u8]> = vec![b"SCAN", cursor.as_bytes()];
line.extend_from_slice(args);
let (next, keys) = scan_reply(&f.run(&line));
out.extend(keys);
cursor = next;
if cursor == "0" {
break;
}
}
out.sort();
out
};
assert_eq!(all(&mut f, &[]), ["fields", "members", "str"]);
assert_eq!(all(&mut f, &[b"MATCH", b"*e*"]), ["fields", "members"]);
assert_eq!(all(&mut f, &[b"TYPE", b"set"]), ["members"]);
// Case insensitive, the same as Redis's own comparison.
assert_eq!(all(&mut f, &[b"TYPE", b"HASH"]), ["fields"]);
// A type nothing can hold is not an error, it just matches nothing.
assert!(all(&mut f, &[b"TYPE", b"list"]).is_empty());
assert!(all(&mut f, &[b"TYPE", b"banana"]).is_empty());
// Both filters at once, and they are an and rather than an or.
assert!(all(&mut f, &[b"MATCH", b"str*", b"TYPE", b"set"]).is_empty());
}
#[test]
fn a_scan_says_what_is_wrong_with_it() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SCAN", b"nope"]), "-ERR invalid cursor\r\n");
assert_eq!(f.run(&[b"SCAN", b"-1"]), "-ERR invalid cursor\r\n");
assert_eq!(f.run(&[b"SCAN", b"0", b"MATCH"]), "-ERR syntax error\r\n");
assert_eq!(
f.run(&[b"SCAN", b"0", b"COUNT", b"0"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"SCAN", b"0", b"COUNT", b"x"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"SCAN", b"0", b"WAT", b"1"]),
"-ERR syntax error\r\n"
);
// A cursor the client made up is a cursor. It resumes somewhere
// arbitrary and answers whatever is there, which is what Redis does and
// is the only behaviour that does not need the server to remember every
// cursor it has handed out.
assert!(f.run(&[b"SCAN", b"18446744073709551615"]).starts_with("*2"));
}
#[test]
fn keys_and_randomkey_look_at_the_whole_database() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"KEYS", b"*"]), "*0\r\n");
assert_eq!(f.run(&[b"RANDOMKEY"]), "$-1\r\n");
for name in ["one", "two", "three"] {
f.run(&[b"SET", name.as_bytes(), b"v"]);
}
assert_eq!(sorted(&f.run(&[b"KEYS", b"*"])), ["one", "three", "two"]);
assert_eq!(sorted(&f.run(&[b"KEYS", b"t*"])), ["three", "two"]);
assert_eq!(f.run(&[b"KEYS", b"nothing"]), "*0\r\n");
for _ in 0..50 {
let got = f.run(&[b"RANDOMKEY"]);
assert!(
["$3\r\none\r\n", "$3\r\ntwo\r\n", "$5\r\nthree\r\n"].contains(&got.as_str()),
"got {got}"
);
}
}
#[test]
fn a_walk_does_not_answer_keys_that_have_expired() {
let mut f = Fixture::new();
f.run(&[b"SET", b"alive", b"v"]);
f.run(&[b"SET", b"dead", b"v", b"PX", b"1"]);
f.server.db(0).clock_mut().advance(2);
assert_eq!(
f.run(&[b"DBSIZE"]),
":2\r\n",
"nothing has collected it yet"
);
assert_eq!(f.run(&[b"KEYS", b"*"]), "*1\r\n$5\r\nalive\r\n");
let (_, keys) = scan_reply(&f.run(&[b"SCAN", b"0", b"COUNT", b"1000"]));
assert_eq!(keys, ["alive"]);
for _ in 0..20 {
assert_eq!(f.run(&[b"RANDOMKEY"]), "$5\r\nalive\r\n");
}
// The walk collected it on the way past, which is what makes DBSIZE
// here answer what Redis answers once its own cycle has been round.
assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
}
#[test]
fn a_key_deadline_goes_on_and_comes_back_in_all_four_units() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n", "there and no deadline");
assert_eq!(f.run(&[b"TTL", b"nosuch"]), ":-2\r\n", "not there at all");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
let ms = int(&f.run(&[b"PTTL", b"k"]));
assert!((99_000..=100_000).contains(&ms), "got {ms}");
// The absolute pair, derived from the same one number the store kept.
let at = int(&f.run(&[b"EXPIRETIME", b"k"]));
let at_ms = int(&f.run(&[b"PEXPIRETIME", b"k"]));
assert_eq!(at, (at_ms + 500) / 1000);
assert!(at_ms > 1_700_000_000_000, "an absolute moment, got {at_ms}");
assert_eq!(f.run(&[b"PERSIST", b"k"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n");
assert_eq!(
f.run(&[b"PERSIST", b"k"]),
":0\r\n",
"nothing to take off the second time"
);
assert_eq!(f.run(&[b"PERSIST", b"nosuch"]), ":0\r\n");
assert_eq!(
f.run(&[b"GET", b"k"]),
"$1\r\nv\r\n",
"and the value went through all of that untouched"
);
}
#[test]
fn every_type_can_be_given_a_deadline_and_it_is_the_same_deadline() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
f.run(&[b"SADD", b"set", b"a", b"b"]);
f.run(&[b"HSET", b"hash", b"f", b"v"]);
for key in [b"str".as_slice(), b"set", b"hash"] {
assert_eq!(f.run(&[b"EXPIRE", key, b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", key]), ":100\r\n");
}
// The body is not touched by any of that, which is the whole reason the
// deadline lives in the record and the body lives somewhere else.
assert_eq!(f.run(&[b"SCARD", b"set"]), ":2\r\n");
assert_eq!(f.run(&[b"HGET", b"hash", b"f"]), "$1\r\nv\r\n");
assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
}
#[test]
fn a_deadline_that_has_already_gone_deletes_the_key_now() {
let mut f = Fixture::new();
for key in [b"a".as_slice(), b"b", b"c", b"d"] {
f.run(&[b"SET", key, b"v"]);
}
// Four ways of naming a moment that has passed, and all four are a
// delete answering 1 rather than an error. Zero is a moment, minus one
// is a moment, and the hash field commands refuse the negative one.
assert_eq!(f.run(&[b"EXPIRE", b"a", b"0"]), ":1\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"b", b"-1"]), ":1\r\n");
assert_eq!(f.run(&[b"EXPIREAT", b"c", b"1"]), ":1\r\n");
assert_eq!(f.run(&[b"PEXPIREAT", b"d", b"1"]), ":1\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
assert_eq!(
f.run(&[b"EXPIRE", b"a", b"100"]),
":0\r\n",
"and the key really went, so there is nothing to put a deadline on"
);
}
#[test]
fn the_four_conditions_decide_whether_the_deadline_moves() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"XX"]), ":0\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n", "and XX left it alone");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"GT"]), ":0\r\n");
assert_eq!(
f.run(&[b"EXPIRE", b"k", b"100", b"LT"]),
":1\r\n",
"no deadline reads as infinitely far away, so LT passes where GT fails"
);
assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"NX"]), ":0\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"GT"]), ":0\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"50", b"LT"]), ":1\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"200", b"GT"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":200\r\n");
// The condition is answered before the past check, so this is a 0 and
// the key survives. The other order would delete it.
assert_eq!(f.run(&[b"EXPIRE", b"k", b"0", b"NX"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":1\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"0", b"XX"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n", "and XX let it through");
}
#[test]
fn the_conditions_are_a_set_and_not_a_keyword() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"nx"]), ":1\r\n");
assert_eq!(
f.run(&[b"EXPIRE", b"k", b"100", b"nx", b"nx"]),
":0\r\n",
"the same keyword twice means it once, and NX now has a deadline to fail on"
);
// XX with LT is the one pair that is not either of them on its own: LT
// alone would accept a key with no deadline and this does not.
assert_eq!(f.run(&[b"EXPIRE", b"k", b"200", b"xx", b"gt"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":200\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"gt", b"xx"]), ":0\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"XX", b"LT"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":100\r\n");
f.run(&[b"PERSIST", b"k"]);
assert_eq!(
f.run(&[b"EXPIRE", b"k", b"100", b"XX", b"LT"]),
":0\r\n",
"where LT on its own would have taken it"
);
assert_eq!(f.run(&[b"EXPIRE", b"k", b"100", b"LT"]), ":1\r\n");
}
#[test]
fn a_key_is_gone_once_its_moment_passes() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
f.run(&[b"EXPIRE", b"k", b"100"]);
let at = int(&f.run(&[b"PEXPIRETIME", b"k"]));
f.server.set_clock_ms(at as u64 + 1);
assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
assert_eq!(f.run(&[b"TTL", b"k"]), ":-2\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
}
#[test]
fn the_expiry_commands_refuse_what_a_real_server_refuses() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
for (bad, want) in [
(
&[b"EXPIRE".as_slice(), b"k", b"soon"][..],
"-ERR value is not an integer or out of range\r\n",
),
(
&[b"EXPIRE", b"k", b"100", b"MAYBE"],
"-ERR Unsupported option MAYBE\r\n",
),
(
&[b"EXPIRE", b"k", b"100", b"NX", b"XX"],
"-ERR NX and XX, GT or LT options at the same time are not compatible\r\n",
),
(
&[b"EXPIRE", b"k", b"100", b"NX", b"GT"],
"-ERR NX and XX, GT or LT options at the same time are not compatible\r\n",
),
(
&[b"EXPIRE", b"k", b"100", b"GT", b"LT", b"GT"],
"-ERR GT and LT options at the same time are not compatible\r\n",
),
// Seconds that overflow when multiplied into milliseconds. Every
// message names the command it came from.
(
&[b"EXPIRE", b"k", b"9223372036854775807"],
"-ERR invalid expire time in 'expire' command\r\n",
),
(
&[b"EXPIREAT", b"k", b"9223372036854775807"],
"-ERR invalid expire time in 'expireat' command\r\n",
),
(
&[b"PEXPIRE", b"k", b"9223372036854775807"],
"-ERR invalid expire time in 'pexpire' command\r\n",
),
] {
assert_eq!(f.run(bad), want, "for {bad:?}");
}
assert_eq!(
f.run(&[b"TTL", b"k"]),
":-1\r\n",
"and none of those put a deadline on anything"
);
// The one of the four that has no arithmetic to overflow. Redis takes
// it and holds the number as given, and a record here holds forty six
// bits, so it lands in the year 4199 instead. D-17.
assert_eq!(
f.run(&[b"PEXPIREAT", b"k", b"9223372036854775807"]),
":1\r\n"
);
assert_eq!(f.run(&[b"PEXPIRETIME", b"k"]), ":70368744177663\r\n");
}
#[test]
fn flushing_empties_this_database_or_every_one_of_them() {
let mut f = Fixture::new();
f.run(&[b"SELECT", b"0"]);
f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
f.run(&[b"SELECT", b"1"]);
f.run(&[b"SET", b"c", b"3"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
// ASYNC and SYNC are both taken and neither changes anything, since the
// keyspace is empty before the OK goes out either way.
assert_eq!(f.run(&[b"FLUSHDB", b"async"]), "+OK\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
// Only database one was emptied.
f.run(&[b"SELECT", b"0"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":2\r\n");
assert_eq!(f.run(&[b"FLUSHALL", b"SYNC"]), "+OK\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
f.run(&[b"SELECT", b"1"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
// Anything else after the name is a syntax error, and so is a third
// argument even when the second one is a word we take.
assert_eq!(f.run(&[b"FLUSHALL", b"nope"]), "-ERR syntax error\r\n");
assert_eq!(
f.run(&[b"FLUSHDB", b"sync", b"sync"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn the_script_cache_and_the_library_set_answer_for_being_empty() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SCRIPT", b"FLUSH"]), "+OK\r\n");
assert_eq!(f.run(&[b"SCRIPT", b"FLUSH", b"async"]), "+OK\r\n");
assert_eq!(f.run(&[b"FUNCTION", b"FLUSH", b"SYNC"]), "+OK\r\n");
// Nothing is cached, so nothing is there, one answer per hash asked
// about.
assert_eq!(
f.run(&[b"SCRIPT", b"EXISTS", b"aaaa", b"bbbb"]),
"*2\r\n:0\r\n:0\r\n"
);
assert_eq!(f.run(&[b"FUNCTION", b"LIST"]), "*0\r\n");
assert_eq!(
f.run(&[b"FUNCTION", b"LIST", b"LIBRARYNAME", b"x", b"WITHCODE"]),
"*0\r\n"
);
assert_eq!(
f.run(&[b"FUNCTION", b"DELETE", b"nosuch"]),
"-ERR Library not found\r\n"
);
// Redis's two messages here are its own, one per container, and one of
// them reads like a typo.
assert_eq!(
f.run(&[b"SCRIPT", b"FLUSH", b"nope"]),
"-ERR SCRIPT FLUSH only support SYNC|ASYNC option\r\n"
);
assert_eq!(
f.run(&[b"FUNCTION", b"FLUSH", b"nope"]),
"-ERR FUNCTION FLUSH only supports SYNC|ASYNC option\r\n"
);
// A second argument after the mode is the generic one instead, because
// the count is checked before the word is looked at.
assert_eq!(
f.run(&[b"FUNCTION", b"FLUSH", b"sync", b"sync"]),
"-ERR unknown subcommand or wrong number of arguments for 'flush'. Try FUNCTION HELP.\r\n"
);
assert_eq!(
f.run(&[b"FUNCTION", b"LIST", b"bogus"]),
"-ERR Unknown argument bogus\r\n"
);
assert_eq!(
f.run(&[b"SCRIPT", b"EXISTS"]),
"-ERR wrong number of arguments for 'script|exists' command\r\n"
);
// The ones that need an interpreter are not here, and say so rather
// than answering OK to a load that loaded nothing.
assert_eq!(
f.run(&[b"SCRIPT", b"LOAD", b"return 1"]),
"-ERR unknown subcommand 'LOAD'. Try SCRIPT HELP.\r\n"
);
assert_eq!(
f.run(&[b"FUNCTION", b"STATS"]),
"-ERR unknown subcommand 'STATS'. Try FUNCTION HELP.\r\n"
);
}
#[test]
fn a_counter_is_an_integer_and_not_a_string_of_digits() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"INCR", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"INCRBY", b"c", b"41"]), ":42\r\n");
assert_eq!(f.run(&[b"DECRBY", b"c", b"2"]), ":40\r\n");
// Read back as a string it is still an integer, written out as digits
// only because somebody asked for them.
assert_eq!(f.run(&[b"GET", b"c"]), "$2\r\n40\r\n");
assert_eq!(f.run(&[b"INCRBYFLOAT", b"c", b"0.5"]), "$4\r\n40.5\r\n");
// A counter that is not a number is the error the store raises and this
// layer only spells, which is the whole point of the split.
f.run(&[b"SET", b"k", b"hello"]);
assert_eq!(
f.run(&[b"INCR", b"k"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"INCRBYFLOAT", b"c", b"inf"]),
"-ERR increment would produce NaN or Infinity\r\n"
);
}
/// Every one of these was read off a running 8.8. They are the answers a
/// client library's own test suite checks, and the shapes are not
/// guessable: `DIGEST` is hexadecimal in a bulk string, `MSETEX` is an
/// integer, `INCREX` is a pair.
#[test]
fn the_newer_commands_reply_in_the_shapes_a_real_server_sends() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SET", b"k", b"hello"]), "+OK\r\n");
// The same digest a real 8.8 answers for the same five bytes, which is
// what makes `IFDEQ` usable against a mixed deployment.
assert_eq!(f.run(&[b"DIGEST", b"k"]), "$16\r\n9555e8555c62dcfd\r\n");
assert_eq!(f.run(&[b"DIGEST", b"nosuch"]), "$-1\r\n");
assert_eq!(f.run(&[b"MSETEX", b"1", b"a", b"1"]), ":1\r\n");
assert_eq!(f.run(&[b"MSETEX", b"1", b"a", b"2", b"NX"]), ":0\r\n");
assert_eq!(f.run(&[b"GET", b"a"]), "$1\r\n1\r\n");
assert_eq!(f.run(&[b"INCREX", b"n"]), "*2\r\n:1\r\n:1\r\n");
assert_eq!(
f.run(&[b"INCREX", b"n", b"BYINT", b"5", b"UBOUND", b"3"]),
"*2\r\n:1\r\n:0\r\n",
"a refused increment reports the value it left alone and applied nothing"
);
assert_eq!(
f.run(&[
b"INCREX",
b"n",
b"BYINT",
b"5",
b"UBOUND",
b"3",
b"SATURATE"
]),
"*2\r\n:3\r\n:2\r\n"
);
assert_eq!(f.run(&[b"DELEX", b"a", b"IFEQ", b"2"]), ":0\r\n");
assert_eq!(f.run(&[b"DELEX", b"a", b"IFEQ", b"1"]), ":1\r\n");
}
#[test]
fn the_same_answers_come_out_in_resp3_spelling() {
let mut f = Fixture::new();
assert!(f.run(&[b"HELLO", b"3"]).starts_with("%7\r\n"));
assert_eq!(f.run(&[b"GET", b"nosuch"]), "_\r\n");
// A float counter is a double on RESP3 and the digits in a bulk string
// on RESP2, and `INCRBYFLOAT` is a bulk string on both.
assert_eq!(
f.run(&[b"INCREX", b"c", b"BYFLOAT", b"1.5"]),
"*2\r\n,1.5\r\n,1.5\r\n"
);
assert_eq!(f.run(&[b"INCRBYFLOAT", b"f", b"2.5"]), "$3\r\n2.5\r\n");
// `RESET` puts the protocol back, which is the part that is easy to
// miss and leaves a pooled connection speaking the wrong one.
assert_eq!(f.run(&[b"RESET"]), "+RESET\r\n");
assert_eq!(f.run(&[b"GET", b"nosuch"]), "$-1\r\n");
}
#[test]
fn a_command_nobody_has_heard_of_is_an_error_and_not_a_closed_socket() {
let mut f = Fixture::new();
let (flow, reply) = f.flow(&[b"NOPE", b"a", b"b"]);
assert_eq!(flow, Flow::Continue);
assert_eq!(
reply,
"-ERR unknown command 'NOPE', with args beginning with: 'a' 'b' \r\n"
);
// A name with a line ending in it cannot write its own frame into the
// stream, which is the reason the error writer maps them to spaces.
let reply = f.run(&[b"NO\r\n+PONG\r\nPE"]);
assert_eq!(reply.matches("\r\n").count(), 1);
}
#[test]
fn arity_is_checked_before_the_command_is() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"GET"]),
"-ERR wrong number of arguments for 'get' command\r\n"
);
assert_eq!(
f.run(&[b"MSET", b"k"]),
"-ERR wrong number of arguments for 'mset' command\r\n"
);
// The table says `PING` takes one or more and a real server then
// refuses three, which is the sort of thing that only shows up against
// the real thing.
assert_eq!(
f.run(&[b"PING", b"a", b"b"]),
"-ERR wrong number of arguments for 'ping' command\r\n"
);
assert_eq!(f.run(&[b"PING"]), "+PONG\r\n");
assert_eq!(f.run(&[b"PING", b"hi"]), "$2\r\nhi\r\n");
// `DELEX` takes two or four and nothing between.
assert_eq!(
f.run(&[b"DELEX", b"k", b"IFEQ"]),
"-ERR wrong number of arguments for 'delex' command\r\n"
);
}
/// The option rules, all of them measured against 8.8 rather than read off
/// the documentation. The surprising one is that `SET` accepts the same
/// keyword twice and `INCREX` does not.
#[test]
fn the_option_combinations_are_the_ones_a_real_server_accepts() {
let mut f = Fixture::new();
let syntax = "-ERR syntax error\r\n";
assert_eq!(f.run(&[b"SET", b"k", b"v", b"NX", b"XX"]), syntax);
assert_eq!(f.run(&[b"SET", b"k", b"v", b"NX", b"IFEQ", b"a"]), syntax);
assert_eq!(
f.run(&[b"SET", b"k", b"v", b"KEEPTTL", b"EX", b"5"]),
syntax
);
assert_eq!(
f.run(&[b"SET", b"k", b"v", b"EX", b"5", b"PX", b"5"]),
syntax
);
assert_eq!(f.run(&[b"SET", b"k", b"v", b"PERSIST"]), syntax);
// Twice is fine, and the last one wins.
assert_eq!(
f.run(&[b"SET", b"k", b"v", b"EX", b"5", b"EX", b"100"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"SET", b"k", b"v", b"XX", b"XX"]), "+OK\r\n");
assert_eq!(f.run(&[b"SET", b"k", b"v", b"GET", b"GET"]), "$1\r\nv\r\n");
// `INCREX` refuses what `SET` allows.
assert_eq!(
f.run(&[b"INCREX", b"n", b"BYINT", b"1", b"BYINT", b"2"]),
syntax
);
assert_eq!(
f.run(&[b"INCREX", b"n", b"ENX"]),
"-ERR ENX flag requires an expiration\r\n"
);
assert_eq!(
f.run(&[b"INCREX", b"n", b"UBOUND", b"abc"]),
"-ERR UBOUND is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"INCREX", b"n", b"LBOUND", b"10", b"UBOUND", b"5"]),
"-ERR LBOUND can't be greater than UBOUND\r\n"
);
assert_eq!(
f.run(&[b"LCS", b"a", b"b", b"LEN", b"IDX"]),
"-ERR If you want both the length and indexes, please just use IDX.\r\n"
);
}
/// Where the expiration rules bite. The one worth the test is `GETEX` on a
/// key that is not there, which answers null without ever looking at the
/// expiration it was given.
#[test]
fn the_expiry_rules_are_redis_own() {
let mut f = Fixture::new();
let bad = "-ERR invalid expire time in 'set' command\r\n";
assert_eq!(f.run(&[b"SET", b"k", b"v", b"EX", b"0"]), bad);
assert_eq!(f.run(&[b"SET", b"k", b"v", b"EX", b"-1"]), bad);
assert_eq!(f.run(&[b"SET", b"k", b"v", b"EXAT", b"0"]), bad);
assert_eq!(
f.run(&[b"SET", b"k", b"v", b"EX", b"9999999999999999"]),
bad
);
assert_eq!(
f.run(&[b"SET", b"k", b"v", b"PX", b"99999999999999999999"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"SETEX", b"k", b"0", b"v"]),
"-ERR invalid expire time in 'setex' command\r\n"
);
assert_eq!(f.run(&[b"GETEX", b"nosuch", b"EX", b"0"]), "$-1\r\n");
assert_eq!(f.run(&[b"GETEX", b"nosuch", b"EX", b"abc"]), "$-1\r\n");
assert_eq!(
f.run(&[b"GETEX", b"nosuch", b"KEEPTTL"]),
"-ERR syntax error\r\n",
"the option list is still checked before the key is looked up"
);
// A deadline in the past is accepted and the key goes with it.
assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
assert_eq!(f.run(&[b"SET", b"k", b"v", b"EXAT", b"1"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
}
#[test]
fn mset_takes_its_pairs_from_the_read_buffer() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"MSET", b"a", b"1", b"b", b"2"]), "+OK\r\n");
assert_eq!(
f.run(&[b"MGET", b"a", b"b", b"nosuch"]),
"*3\r\n$1\r\n1\r\n$1\r\n2\r\n$-1\r\n"
);
assert_eq!(f.run(&[b"MSETNX", b"b", b"9", b"c", b"3"]), ":0\r\n");
assert_eq!(f.run(&[b"MSETNX", b"c", b"3", b"d", b"4"]), ":1\r\n");
assert_eq!(
f.run(&[b"MSETEX", b"2", b"e", b"5"]),
"-ERR wrong number of key-value pairs\r\n"
);
assert_eq!(
f.run(&[b"MSETEX", b"0", b"e", b"5"]),
"-ERR invalid numkeys value\r\n"
);
assert_eq!(
f.run(&[b"MSETEX", b"abc", b"e", b"5"]),
"-ERR invalid numkeys value\r\n"
);
}
#[test]
fn lcs_answers_the_length_the_string_and_the_runs() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"ohmytext", b"b", b"mynewtext"]);
assert_eq!(f.run(&[b"LCS", b"a", b"b"]), "$6\r\nmytext\r\n");
assert_eq!(f.run(&[b"LCS", b"a", b"b", b"LEN"]), ":6\r\n");
assert_eq!(
f.run(&[b"LCS", b"a", b"b", b"IDX", b"MINMATCHLEN", b"4"]),
"*4\r\n$7\r\nmatches\r\n*1\r\n*2\r\n*2\r\n:4\r\n:7\r\n*2\r\n:5\r\n:8\r\n$3\r\nlen\r\n:6\r\n"
);
// Without `IDX` the two options that only mean something with it are
// accepted and ignored, which is what a real server does.
assert_eq!(
f.run(&[b"LCS", b"a", b"b", b"MINMATCHLEN", b"4", b"WITHMATCHLEN"]),
"$6\r\nmytext\r\n"
);
}
#[test]
fn select_moves_the_connection_and_the_databases_stay_apart() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"zero"]);
assert_eq!(f.run(&[b"SELECT", b"4"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$-1\r\n");
f.run(&[b"SET", b"k", b"four"]);
assert_eq!(f.run(&[b"SELECT", b"0"]), "+OK\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
assert_eq!(
f.run(&[b"SELECT", b"99"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"SELECT", b"-1"]),
"-ERR DB index is out of range\r\n"
);
assert_eq!(
f.run(&[b"SELECT", b"abc"]),
"-ERR value is not an integer or out of range\r\n"
);
// `RESET` brings it back to zero.
f.run(&[b"SELECT", b"4"]);
f.run(&[b"RESET"]);
assert_eq!(f.run(&[b"GET", b"k"]), "$4\r\nzero\r\n");
}
#[test]
fn hello_agrees_on_a_protocol_and_refuses_the_ones_that_do_not_exist() {
let mut f = Fixture::new();
let reply = f.run(&[b"HELLO"]);
assert!(reply.starts_with("*14\r\n"), "{reply}");
assert!(reply.contains("$5\r\nredis\r\n"), "{reply}");
assert!(reply.contains("$5\r\n8.8.0\r\n"), "{reply}");
assert!(
reply.contains(":7\r\n"),
"the connection id is in there: {reply}"
);
assert_eq!(
f.run(&[b"HELLO", b"4"]),
"-NOPROTO unsupported protocol version\r\n"
);
assert_eq!(
f.run(&[b"HELLO", b"abc"]),
"-ERR Protocol version is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"HELLO", b"3", b"SETNAME"]),
"-ERR Syntax error in HELLO option 'SETNAME'\r\n"
);
assert!(
f.run(&[b"HELLO", b"3", b"SETNAME", b"bob"])
.starts_with("%7\r\n")
);
assert_eq!(f.session.name(), b"bob");
f.run(&[b"RESET"]);
assert_eq!(f.session.name(), b"");
}
#[test]
fn command_describes_this_server_in_the_shape_a_driver_reads() {
let mut f = Fixture::new();
let count = format!(":{}\r\n", COMMANDS.len());
assert_eq!(f.run(&[b"COMMAND", b"COUNT"]), count);
let info = f.run(&[b"COMMAND", b"INFO", b"get"]);
assert_eq!(
info,
"*1\r\n*10\r\n$3\r\nget\r\n:2\r\n*2\r\n+readonly\r\n+fast\r\n:1\r\n:1\r\n:1\r\n\
*3\r\n+@read\r\n+@string\r\n+@fast\r\n*0\r\n*0\r\n*0\r\n"
);
// A null in the list, and the plain one: `$-1` and not `*-1`.
assert_eq!(f.run(&[b"COMMAND", b"INFO", b"nosuch"]), "*1\r\n$-1\r\n");
assert_eq!(
f.run(&[b"COMMAND", b"LIST", b"FILTERBY", b"PATTERN", b"getr*"]),
"*1\r\n$8\r\ngetrange\r\n"
);
assert_eq!(
f.run(&[b"COMMAND", b"NOPE"]),
"-ERR unknown subcommand 'NOPE'. Try COMMAND HELP.\r\n"
);
}
/// A cluster aware client asks this question and then routes on the
/// answer, so `MSETEX`, whose keys are not where the table says, is the one
/// that matters.
#[test]
fn command_getkeys_finds_the_keys_including_the_hidden_ones() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"COMMAND", b"GETKEYS", b"get", b"k"]),
"*1\r\n$1\r\nk\r\n"
);
assert_eq!(
f.run(&[b"COMMAND", b"GETKEYS", b"mset", b"a", b"1", b"b", b"2"]),
"*2\r\n$1\r\na\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[
b"COMMAND", b"GETKEYS", b"msetex", b"2", b"a", b"1", b"b", b"2"
]),
"*2\r\n$1\r\na\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[b"COMMAND", b"GETKEYS", b"ping"]),
"-ERR The command has no key arguments\r\n"
);
assert_eq!(
f.run(&[b"COMMAND", b"GETKEYS", b"set"]),
"-ERR Invalid number of arguments specified for command\r\n"
);
}
#[test]
fn config_answers_what_it_can_and_refuses_what_it_cannot() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
"*2\r\n$9\r\nmaxmemory\r\n$1\r\n0\r\n"
);
// A pattern matches more than one, and a setting two patterns both ask
// for is still sent once.
let both = f.run(&[b"CONFIG", b"GET", b"maxmemory*", b"maxmemory"]);
assert!(both.starts_with("*6\r\n"), "{both}");
assert_eq!(f.run(&[b"CONFIG", b"GET", b"nosuch"]), "*0\r\n");
assert_eq!(f.run(&[b"CONFIG", b"SET", b"appendonly", b"no"]), "+OK\r\n");
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"appendonly", b"yes"]),
"-ERR CONFIG SET failed (possibly related to argument 'appendonly') - can't set immutable config\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"nosuch", b"1"]),
"-ERR Unknown option or number of arguments for CONFIG SET - 'nosuch'\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"GET"]),
"-ERR wrong number of arguments for 'config|get' command\r\n"
);
// Too few arguments and an odd number of them are different
// complaints, which is the sort of thing only the real server tells
// you.
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"appendonly"]),
"-ERR wrong number of arguments for 'config|set' command\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"appendonly", b"no", b"maxmemory"]),
"-ERR syntax error\r\n"
);
assert_eq!(f.run(&[b"CONFIG", b"RESETSTAT"]), "+OK\r\n");
assert_eq!(
f.run(&[b"CONFIG", b"REWRITE"]),
"-ERR The server is running without a config file\r\n"
);
}
#[test]
fn the_eviction_policy_reads_back_what_was_written_to_it() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
"*2\r\n$16\r\nmaxmemory-policy\r\n$10\r\nnoeviction\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"AllKeys-LFU"]),
"+OK\r\n",
"the name is matched without regard to case, like every other one"
);
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
"*2\r\n$16\r\nmaxmemory-policy\r\n$11\r\nallkeys-lfu\r\n"
);
// And INFO agrees with CONFIG, which it did not when it was a literal.
assert!(
f.run(&[b"INFO", b"memory"])
.contains("maxmemory_policy:allkeys-lfu"),
"INFO and CONFIG disagree about the policy"
);
// The refusal names every legal value in the order the real server's
// enum table lists them, because a client comparing the message compares
// the whole string.
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"garbage"]),
"-ERR CONFIG SET failed (possibly related to argument 'maxmemory-policy') - argument(s) must be one of the following: volatile-lru, volatile-lfu, volatile-random, volatile-ttl, volatile-lrm, allkeys-lru, allkeys-lfu, allkeys-random, allkeys-lrm, noeviction\r\n"
);
// A bad pair leaves the good one in the same command alone, and the
// policy is checked by the same pass that checks the numbers.
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory-policy"]),
"*2\r\n$16\r\nmaxmemory-policy\r\n$11\r\nallkeys-lfu\r\n"
);
f.run(&[
b"CONFIG",
b"SET",
b"hash-max-listpack-entries",
b"7",
b"maxmemory-policy",
b"nonsense",
]);
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
"*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n"
);
}
#[test]
fn the_three_eviction_numbers_read_back_too() {
let mut f = Fixture::new();
for (name, default, set) in [
("maxmemory-samples", "5", "12"),
("lfu-log-factor", "10", "3"),
("lfu-decay-time", "1", "60"),
] {
let get = || {
format!(
"*2\r\n${}\r\n{name}\r\n${}\r\n{default}\r\n",
name.len(),
default.len()
)
};
assert_eq!(f.run(&[b"CONFIG", b"GET", name.as_bytes()]), get());
assert_eq!(
f.run(&[b"CONFIG", b"SET", name.as_bytes(), set.as_bytes()]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"GET", name.as_bytes()]),
format!(
"*2\r\n${}\r\n{name}\r\n${}\r\n{set}\r\n",
name.len(),
set.len()
)
);
// A number that is not a number is refused with the same sentence
// every other number gets, which names the setting the client typed.
assert_eq!(
f.run(&[b"CONFIG", b"SET", name.as_bytes(), b"soon"]),
format!(
"-ERR CONFIG SET failed (possibly related to argument '{name}') - argument couldn't be parsed into an integer\r\n"
)
);
}
}
#[test]
fn the_memory_limit_reads_back_in_bytes_whatever_the_unit_was() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
"*2\r\n$9\r\nmaxmemory\r\n$1\r\n0\r\n",
"no limit is the default"
);
// The pairing is Redis's and it is a trap: the bare letter is a power of
// ten and the one with the b is a power of two.
for (typed, bytes) in [
(&b"1024"[..], "1024"),
(b"1k", "1000"),
(b"1kb", "1024"),
(b"1M", "1000000"),
(b"1Mb", "1048576"),
(b"1gb", "1073741824"),
(b"100mb", "104857600"),
] {
assert_eq!(f.run(&[b"CONFIG", b"SET", b"maxmemory", typed]), "+OK\r\n");
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxmemory"]),
format!("*2\r\n$9\r\nmaxmemory\r\n${}\r\n{bytes}\r\n", bytes.len()),
"set {}",
String::from_utf8_lossy(typed)
);
}
assert!(
f.run(&[b"INFO", b"memory"]).contains("maxmemory:104857600"),
"the report agrees with the setting"
);
// A unit nobody has heard of, and a negative number, which is not a very
// large one however it is spelled.
for bad in [&b"1tb"[..], b"-1", b"", b"lots"] {
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"maxmemory", bad]),
"-ERR CONFIG SET failed (possibly related to argument 'maxmemory') - argument must be a memory value\r\n",
"refused {}",
String::from_utf8_lossy(bad)
);
}
assert!(
f.run(&[b"INFO", b"memory"]).contains("maxmemory:104857600"),
"and the refusal left the old one alone"
);
}
#[test]
fn a_write_is_refused_when_there_is_no_room_and_nothing_to_evict() {
let mut f = Fixture::new();
f.run(&[b"SET", b"here", b"already"]);
// A byte, which is under what an empty server holds, so nothing this
// command could do would get it under. The default policy is
// `noeviction`, so nothing is what it does.
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1"]);
assert_eq!(
f.run(&[b"SET", b"k", b"v"]),
"-OOM command not allowed when used memory > 'maxmemory'.\r\n"
);
assert_eq!(
f.run(&[b"LPUSH", b"l", b"v"]),
"-OOM command not allowed when used memory > 'maxmemory'.\r\n"
);
// Reading is allowed, and so is the one thing that would help.
assert_eq!(f.run(&[b"GET", b"here"]), "$7\r\nalready\r\n");
assert_eq!(f.run(&[b"DEL", b"here"]), ":1\r\n");
assert!(f.run(&[b"INFO", b"stats"]).contains("evicted_keys:0"));
// Taking the limit away lets the write through again.
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"0"]);
assert_eq!(f.run(&[b"SET", b"k", b"v"]), "+OK\r\n");
}
#[test]
fn an_allkeys_policy_makes_room_instead_of_refusing() {
let mut f = Fixture::new();
let val = vec![b'v'; 256];
for i in 0..24000u32 {
let k = format!("key:{i:08}");
f.run(&[b"SET", k.as_bytes(), &val]);
}
let full = f.server.memory_bytes();
assert!(
full > 3 * 1024 * 1024,
"the arena is several segments: {full}"
);
// Two megabytes under what it is holding, which is one segment's worth,
// so getting there means giving a whole segment back and not just
// dropping a few records.
let limit = full - 2 * 1024 * 1024;
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lru"]);
f.run(&[
b"CONFIG",
b"SET",
b"maxmemory",
limit.to_string().as_bytes(),
]);
// Writes keep working the whole way down. The budget means one command
// does not do it all, so this runs until the server has settled and
// checks that nothing was refused on the way.
for i in 0..2000u32 {
let k = format!("new:{i:08}");
assert_eq!(
f.run(&[b"SET", k.as_bytes(), &val]),
"+OK\r\n",
"write {i} was refused"
);
f.server.refresh_memory();
if f.server.memory_bytes() <= limit {
break;
}
}
assert!(
f.server.memory_bytes() <= limit,
"it never got under: {} against {limit}",
f.server.memory_bytes()
);
let info = f.run(&[b"INFO", b"stats"]);
assert!(!info.contains("evicted_keys:0"), "{info}");
assert!(
f.run(&[b"DBSIZE"]) != ":0\r\n",
"and it did not empty the database to get there"
);
}
#[test]
fn the_running_total_and_the_walk_agree_on_a_mixed_keyspace() {
// The limit is judged against a number kept as the collections move,
// rather than found by asking all of them, and the two have to be the
// same number or the limit is enforced against a fiction. This does the
// things that move it, which is growing a collection, shrinking one,
// changing its representation, deleting it and reusing its slot, across
// all five types, and checks the two against each other as it goes.
let mut f = Fixture::new();
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
let big = vec![b'v'; 200];
for i in 0..400u32 {
let n = i.to_string();
let n = n.as_bytes();
f.run(&[b"SADD", b"s", n]);
f.run(&[b"SADD", b"s2", &big]);
f.run(&[b"HSET", b"h", n, &big]);
f.run(&[b"RPUSH", b"l", &big]);
f.run(&[b"ZADD", b"z", n, n]);
f.run(&[b"ARSET", b"a", n, &big]);
if i % 7 == 0 {
f.run(&[b"SREM", b"s", n]);
f.run(&[b"HDEL", b"h", n]);
f.run(&[b"LPOP", b"l"]);
f.run(&[b"ZREM", b"z", n]);
f.run(&[b"ARDEL", b"a", n]);
}
if i % 53 == 0 {
// Every type deleted and made again, so a slot goes on the free
// list and comes back holding something else.
f.run(&[b"DEL", b"s2"]);
}
assert_eq!(
f.server.settled_memory(),
f.server.memory_bytes(),
"after round {i}"
);
}
// The run has to have built something, or the two numbers agreeing is
// two zeroes agreeing.
assert_eq!(f.run(&[b"DBSIZE"]), ":6\r\n");
assert!(
f.server.memory_bytes() > 512 * 1024,
"{}",
f.server.memory_bytes()
);
// And it survives the collections going away entirely.
f.run(&[b"FLUSHALL"]);
assert_eq!(f.server.settled_memory(), f.server.memory_bytes());
}
#[test]
fn taking_the_limit_away_stops_the_counting_and_putting_it_back_starts_again() {
// A server with no limit does not keep the running total, so setting a
// limit on a database that is already full has to start it from a walk.
// If it did not, the first reading would be zero and the server would
// think it had all the room in the world.
let mut f = Fixture::new();
for i in 0..200u32 {
let n = i.to_string();
f.run(&[b"SADD", b"s", n.as_bytes()]);
f.run(&[b"HSET", b"h", n.as_bytes(), b"value"]);
}
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
assert_eq!(f.server.settled_memory(), f.server.memory_bytes());
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"0"]);
for i in 200..400u32 {
let n = i.to_string();
f.run(&[b"SADD", b"s", n.as_bytes()]);
}
f.run(&[b"CONFIG", b"SET", b"maxmemory", b"1gb"]);
assert_eq!(
f.server.settled_memory(),
f.server.memory_bytes(),
"the writes it was not watching are in the number it started from"
);
}
#[test]
fn evicted_keys_and_expired_keys_are_different_numbers() {
let mut f = Fixture::new();
// Nothing has been evicted and nothing can be under the default policy,
// so this stays at zero while the other one moves.
f.run(&[b"SET", b"gone", b"v", b"PX", b"1"]);
f.server.db(0).clock_mut().advance(20);
f.run(&[b"GET", b"gone"]);
let info = f.run(&[b"INFO", b"stats"]);
assert!(info.contains("expired_keys:1"), "{info}");
assert!(info.contains("evicted_keys:0"), "{info}");
}
#[test]
fn the_object_subcommands_follow_the_policy() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"v"]);
// Under the default the clock is kept and the counter is not, and under
// an LFU policy it is the other way round. Each subcommand refuses on
// the side where its reading of the three bytes means nothing.
assert_eq!(f.run(&[b"OBJECT", b"IDLETIME", b"s"]), ":0\r\n");
assert!(
f.run(&[b"OBJECT", b"FREQ", b"s"])
.starts_with("-ERR An LFU maxmemory policy is not selected"),
);
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lfu"]);
assert!(
f.run(&[b"OBJECT", b"IDLETIME", b"s"])
.starts_with("-ERR An LFU maxmemory policy is selected"),
);
// The key was written under a clock policy, so what comes back is that
// clock read as a counter. It is a number and not an error, which is the
// point: switching at runtime does not invalidate anything, it only makes
// the old field mean something else until the key is used again.
assert!(
f.run(&[b"OBJECT", b"FREQ", b"s"]).starts_with(':'),
"FREQ should answer under an LFU policy"
);
}
#[test]
fn object_says_which_rung_of_the_ladder_a_key_is_on() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"hello"]);
f.run(&[b"SET", b"n", b"123"]);
f.run(&[b"SADD", b"si", b"1", b"2", b"3"]);
f.run(&[b"SADD", b"ss", b"a", b"b"]);
f.run(&[b"HSET", b"h", b"f", b"v"]);
for (key, want) in [
(b"s".as_slice(), "embstr"),
(b"n", "int"),
(b"si", "intset"),
(b"ss", "listpack"),
(b"h", "listpack"),
] {
let reply = f.run(&[b"OBJECT", b"ENCODING", key]);
assert_eq!(reply, format!("${}\r\n{want}\r\n", want.len()));
}
// A field deadline widens the blob rather than promoting it, and this
// is the only place a client can see that happen.
f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"f"]);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"h"]),
"$10\r\nlistpackex\r\n"
);
assert_eq!(f.run(&[b"OBJECT", b"REFCOUNT", b"s"]), ":1\r\n");
assert_eq!(f.run(&[b"OBJECT", b"IDLETIME", b"s"]), ":0\r\n");
assert!(f.run(&[b"OBJECT", b"HELP"]).starts_with("*14\r\n+OBJECT "));
}
#[test]
fn object_answers_nil_for_a_key_that_is_not_there() {
let mut f = Fixture::new();
for sub in [b"ENCODING".as_slice(), b"REFCOUNT", b"IDLETIME", b"FREQ"] {
assert_eq!(
f.run(&[b"OBJECT", sub, b"nokey"]),
"$-1\r\n",
"a nil and not an error, which is what 8.10.1 does"
);
}
// And the key is looked up before FREQ has its complaint, so the
// complaint only reaches a key that exists.
f.run(&[b"SET", b"s", b"v"]);
assert!(
f.run(&[b"OBJECT", b"FREQ", b"s"])
.starts_with("-ERR An LFU maxmemory policy is not"),
);
assert_eq!(
f.run(&[b"OBJECT", b"NOPE", b"s"]),
"-ERR unknown subcommand 'NOPE'. Try OBJECT HELP.\r\n"
);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING"]),
"-ERR wrong number of arguments for 'object|encoding' command\r\n"
);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"s", b"extra"]),
"-ERR wrong number of arguments for 'object|encoding' command\r\n"
);
assert_eq!(
f.run(&[b"OBJECT"]),
"-ERR wrong number of arguments for 'object' command\r\n"
);
}
#[test]
fn config_moves_the_ladder_and_object_encoding_agrees() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
"*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n",
"512 and not the 128 everyone remembers, which is what 8.10.1 says"
);
// The old spelling is the same number under a different name, and a
// glob that catches both sends both.
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"hash-max-ziplist-entries"]),
"*2\r\n$24\r\nhash-max-ziplist-entries\r\n$3\r\n512\r\n"
);
assert!(
f.run(&[b"CONFIG", b"GET", b"hash-max-*"])
.starts_with("*8\r\n")
);
assert!(
f.run(&[b"CONFIG", b"GET", b"set-max-*"])
.starts_with("*6\r\n")
);
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2", b"c", b"3"]);
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"h"]), "$8\r\nlistpack\r\n");
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"hash-max-ziplist-entries", b"2"]),
"+OK\r\n",
"written under the old name and read back under the new one"
);
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
"*2\r\n$25\r\nhash-max-listpack-entries\r\n$1\r\n2\r\n"
);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"h"]),
"$8\r\nlistpack\r\n",
"the hash that already exists is left exactly where it was"
);
f.run(&[b"HSET", b"h2", b"a", b"1", b"b", b"2", b"c", b"3"]);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"h2"]),
"$9\r\nhashtable\r\n",
"and the next one built goes straight to a table"
);
// The set has three of these and all three move.
f.run(&[b"CONFIG", b"SET", b"set-max-intset-entries", b"2"]);
f.run(&[b"SADD", b"s", b"1", b"2", b"3"]);
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"s"]), "$8\r\nlistpack\r\n");
f.run(&[b"CONFIG", b"SET", b"set-max-listpack-value", b"2"]);
f.run(&[b"SADD", b"s2", b"abcdefgh"]);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"s2"]),
"$9\r\nhashtable\r\n"
);
}
#[test]
fn config_set_takes_all_of_the_ladder_or_none_of_it() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"CONFIG",
b"SET",
b"hash-max-listpack-entries",
b"7",
b"set-max-listpack-entries",
b"abc"
]),
"-ERR CONFIG SET failed (possibly related to argument 'set-max-listpack-entries') - argument couldn't be parsed into an integer\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"hash-max-listpack-entries"]),
"*2\r\n$25\r\nhash-max-listpack-entries\r\n$3\r\n512\r\n",
"the pair in front of the bad one did not go in"
);
// The name in the complaint is the one that was typed, so the old
// spelling comes back as the old spelling.
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"hash-max-ziplist-entries", b"abc"]),
"-ERR CONFIG SET failed (possibly related to argument 'hash-max-ziplist-entries') - argument couldn't be parsed into an integer\r\n"
);
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"set-max-intset-entries", b"-1"]),
"-ERR CONFIG SET failed (possibly related to argument 'set-max-intset-entries') - argument must be between 0 and 9223372036854775807 inclusive\r\n"
);
// A number past what an i64 holds is the parse complaint and not the
// range one, which is upstream reading it before it checks it.
assert_eq!(
f.run(&[
b"CONFIG",
b"SET",
b"set-max-intset-entries",
b"99999999999999999999"
]),
"-ERR CONFIG SET failed (possibly related to argument 'set-max-intset-entries') - argument couldn't be parsed into an integer\r\n"
);
assert_eq!(
f.run(&[
b"CONFIG",
b"SET",
b"set-max-intset-entries",
b"9223372036854775807"
]),
"+OK\r\n"
);
}
#[test]
fn a_setting_moved_on_one_database_moved_on_all_of_them() {
let mut f = Fixture::new();
f.run(&[b"CONFIG", b"SET", b"hash-max-listpack-entries", b"1"]);
f.run(&[b"SELECT", b"3"]);
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"h"]),
"$9\r\nhashtable\r\n",
"these are one server wide number in Redis, whatever a Keyspace carries"
);
}
#[test]
fn info_reports_the_numbers_it_can_stand_behind() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"1", b"b", b"2"]);
let all = f.run(&[b"INFO"]);
assert!(all.contains("redis_version:8.8.0"), "{all}");
assert!(
all.contains(concat!("yo_version:", env!("CARGO_PKG_VERSION"))),
"{all}"
);
assert!(all.contains("db0:keys=2,expires=0,avg_ttl=0"), "{all}");
assert!(all.contains("role:master"), "{all}");
// One section is one section.
let clients = f.run(&[b"INFO", b"clients"]);
assert!(clients.contains("connected_clients:0"), "{clients}");
assert!(!clients.contains("redis_version"), "{clients}");
assert_eq!(f.run(&[b"INFO", b"nosuch"]), "$0\r\n\r\n");
}
/// The sections a bare `INFO` gives back, and the ones you have to ask for.
///
/// This is Redis's `unit/info-command` written against the fixture. Every
/// assertion in it is one of theirs, in their order, and the two fields it
/// turns on are the two that suite was failing on: `master_repl_offset`,
/// which is in the default set, and `rejected_calls`, which is not.
#[test]
fn commandstats_is_asked_for_and_replication_is_not() {
let mut f = Fixture::new();
for arg in ["", "all", "default", "everything"] {
let info = if arg.is_empty() {
f.run(&[b"INFO"])
} else {
f.run(&[b"INFO", arg.as_bytes()])
};
assert!(info.contains("redis_version"), "{arg}: {info}");
assert!(info.contains("used_cpu_user"), "{arg}: {info}");
assert!(info.contains("used_memory"), "{arg}: {info}");
assert!(!info.contains("sentinel_tilt"), "{arg}: {info}");
let asked = arg == "all" || arg == "everything";
assert_eq!(
info.contains("rejected_calls"),
asked,
"{arg} should{} carry the command counters: {info}",
if asked { "" } else { " not" }
);
}
let cpu = f.run(&[b"INFO", b"cpu"]);
assert!(cpu.contains("used_cpu_user"), "{cpu}");
assert!(!cpu.contains("used_memory"), "{cpu}");
// Their case, to make the point that a section name is not case
// sensitive any more than a command name is.
let stats = f.run(&[b"INFO", b"commandSTATS"]);
assert!(!stats.contains("used_memory"), "{stats}");
assert!(stats.contains("rejected_calls"), "{stats}");
// Two sections named, and neither of them pulls in a third.
let pair = f.run(&[b"INFO", b"cpu", b"sentinel"]);
assert!(pair.contains("used_cpu_user"), "{pair}");
assert!(!pair.contains("master_repl_offset"), "{pair}");
let with_all = f.run(&[b"INFO", b"cpu", b"all"]);
assert!(with_all.contains("used_memory"), "{with_all}");
assert!(with_all.contains("master_repl_offset"), "{with_all}");
assert!(with_all.contains("rejected_calls"), "{with_all}");
// A section named twice is still written once.
assert_eq!(
with_all.matches("used_cpu_user_children").count(),
1,
"{with_all}"
);
let with_default = f.run(&[b"INFO", b"cpu", b"default"]);
assert!(with_default.contains("used_memory"), "{with_default}");
assert!(
with_default.contains("master_repl_offset"),
"{with_default}"
);
assert!(!with_default.contains("rejected_calls"), "{with_default}");
assert_eq!(
with_default.matches("used_cpu_user_children").count(),
1,
"{with_default}"
);
}
/// The memory section says what this process may use, not what the machine
/// has.
///
/// The distinction is the whole point of it. A server inside a container
/// that reports the host's memory is a server whose operator sizes it for
/// memory it will be killed for touching, so all three numbers are there:
/// what the machine has, what the cgroup allows, and the quarter of the
/// tighter one that pools are sized from.
#[test]
fn info_memory_reports_the_cap_and_the_quarter_of_it_that_gets_used() {
let mut f = Fixture::new();
let info = f.run(&[b"INFO", b"memory"]);
for field in [
"total_system_memory:",
"mem_cgroup_limit:",
"mem_limit:",
"mem_budget:",
] {
assert!(info.contains(field), "no {field} in {info}");
}
let field = |name: &str| -> u64 {
info.lines()
.find_map(|l| l.strip_prefix(name))
.unwrap_or_else(|| panic!("no {name} in {info}"))
.trim()
.parse()
.unwrap_or_else(|_| panic!("{name} is not a number in {info}"))
};
let limit = field("mem_limit:");
assert_eq!(field("mem_budget:"), limit / 4, "{info}");
// Zero means there is no limit to report, which is a real answer on a
// machine with no cgroups and no way to ask how big it is.
if limit != 0 {
let host = field("total_system_memory:");
let cgroup = field("mem_cgroup_limit:");
assert!(
limit == host || limit == cgroup,
"the limit came from neither number: {info}"
);
}
}
/// The three counters, each on the path that raises it.
///
/// `calls` on a command that worked, `failed_calls` on one that ran and
/// answered with an error, and `rejected_calls` on one that never ran at
/// all. The last two are the pair that is easy to collapse into one number
/// and that Redis keeps apart, because a client sending the wrong number of
/// arguments and a client asking for a list element that is not there are
/// not the same problem.
#[test]
fn a_command_counts_what_it_did_separately_from_what_it_refused() {
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
f.run(&[b"SET", b"k", b"w"]);
// Ran, and answered with an error, because `k` is not a list.
f.run(&[b"LPUSH", b"k", b"x"]);
// Never ran: `LPUSH` takes at least three arguments.
f.run(&[b"LPUSH", b"k"]);
let stats = f.run(&[b"INFO", b"commandstats"]);
assert!(
stats.contains("cmdstat_set:calls=2,rejected_calls=0,failed_calls=0"),
"{stats}"
);
assert!(
stats.contains("cmdstat_lpush:calls=1,rejected_calls=1,failed_calls=1"),
"{stats}"
);
assert!(
!stats.contains("cmdstat_zadd"),
"a command nobody has sent has no row: {stats}"
);
}
/// A cache that writes with a deadline and never reads back used to hold
/// every key it had ever written, because lazy expiry needs somebody to walk
/// past a key before it can reclaim it and nobody ever did.
#[test]
fn the_active_sweep_reclaims_keys_no_client_comes_back_for() {
let mut f = Fixture::new();
for i in 0..3_000u32 {
f.run(&[b"SET", format!("d{i}").as_bytes(), b"v", b"PX", b"50"]);
}
for i in 0..1_000u32 {
f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
}
assert_eq!(f.run(&[b"DBSIZE"]), ":4000\r\n");
f.advance(100);
assert_eq!(
f.run(&[b"DBSIZE"]),
":4000\r\n",
"DBSIZE counts records and nothing has read past the dead ones yet"
);
// What the shard loop does, one slice at a time.
let mut spent = 0;
for _ in 0..2_000 {
spent += f.server.expire_step(4096);
if f.run(&[b"DBSIZE"]) == ":1000\r\n" {
break;
}
}
assert_eq!(f.run(&[b"DBSIZE"]), ":1000\r\n", "spent {spent} looks");
assert!(f.run(&[b"INFO", b"stats"]).contains("expired_keys:3000"));
for i in 0..1_000u32 {
assert_eq!(
f.run(&[b"GET", format!("k{i}").as_bytes()]),
"$1\r\nv\r\n",
"it took a key that had no deadline"
);
}
}
#[test]
fn a_sweep_of_a_server_with_no_deadlines_anywhere_costs_nothing() {
let mut f = Fixture::new();
for i in 0..2_000u32 {
f.run(&[b"SET", format!("k{i}").as_bytes(), b"v"]);
}
assert_eq!(f.server.expire_step(4096), 0);
// And one database having them does not make the other fifteen pay.
f.run(&[b"SELECT", b"3"]);
f.run(&[b"SET", b"x", b"v", b"PX", b"50"]);
f.advance(100);
for _ in 0..64 {
f.server.expire_step(4096);
}
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
f.run(&[b"SELECT", b"0"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":2000\r\n");
assert_eq!(f.server.expire_step(4096), 0, "and it is quiet again");
}
/// The gate, which is what stops a maintenance slice that runs every hundred
/// nanoseconds from drawing a sample every hundred nanoseconds.
#[test]
fn the_sweep_the_loop_calls_runs_at_most_once_a_millisecond() {
let mut f = Fixture::new();
for i in 0..500u32 {
f.run(&[b"SET", format!("d{i}").as_bytes(), b"v", b"PX", b"50"]);
}
f.advance(100);
let at = f.server.db(0).clock().now_ms();
f.server.set_clock_ms(at);
// A small budget, so that one slice cannot finish the job and a second
// one having nothing to do would mean the gate and not an empty
// database.
assert!(f.server.expire_slice(8) > 0, "the first one works");
for _ in 0..1_000 {
assert_eq!(
f.server.expire_slice(8),
0,
"the millisecond has not moved and neither should this"
);
}
assert!(
f.server.db(0).expires() > 400,
"there is plenty left to take"
);
f.server.set_clock_ms(at + 1);
assert!(f.server.expire_slice(8) > 0, "and then it goes again");
}
/// `expires=` used to be a hardcoded zero, which meant a dashboard watching
/// how much of a cache is volatile was reading a constant.
#[test]
fn info_keyspace_counts_the_keys_that_have_a_deadline() {
let mut f = Fixture::new();
f.run(&[b"MSET", b"a", b"1", b"b", b"2", b"c", b"3"]);
assert!(
f.run(&[b"INFO", b"keyspace"])
.contains("db0:keys=3,expires=0"),
"none of them has one yet"
);
f.run(&[b"EXPIRE", b"a", b"1000"]);
f.run(&[b"EXPIRE", b"b", b"1000"]);
let two = f.run(&[b"INFO", b"keyspace"]);
assert!(two.contains("db0:keys=3,expires=2"), "{two}");
f.run(&[b"PERSIST", b"a"]);
f.run(&[b"DEL", b"b"]);
let none = f.run(&[b"INFO", b"keyspace"]);
assert!(none.contains("db0:keys=2,expires=0"), "{none}");
// Each database answers for itself, the way Redis reports it.
f.run(&[b"SELECT", b"1"]);
f.run(&[b"SET", b"x", b"1", b"EX", b"1000"]);
let both = f.run(&[b"INFO", b"keyspace"]);
assert!(both.contains("db0:keys=2,expires=0"), "{both}");
assert!(both.contains("db1:keys=1,expires=1"), "{both}");
}
#[cfg(unix)]
#[test]
fn info_cpu_reports_processor_time_that_was_really_measured() {
let mut f = Fixture::new();
let cpu = f.run(&[b"INFO", b"cpu"]);
assert!(cpu.contains("# CPU"), "{cpu}");
// Redis's unit/info-command asks for this one by name in three tests.
assert!(cpu.contains("used_cpu_user:"), "{cpu}");
assert!(cpu.contains("used_cpu_sys:"), "{cpu}");
assert!(cpu.contains("used_cpu_user_children:0.000000"), "{cpu}");
assert!(!cpu.contains("redis_version"), "{cpu}");
// It is a measurement and not a constant, so it goes up when work
// happens. A tight loop rather than a sleep, because sleeping is the
// one thing that does not move this number.
let before = used_cpu_user(&cpu);
let mut n = 0u64;
let mut rounds = 0;
while used_cpu_user(&f.run(&[b"INFO", b"cpu"])) <= before {
for i in 0..1_000_000u64 {
n = n.wrapping_add(i.wrapping_mul(i));
}
rounds += 1;
// A bound rather than a spin, so a platform where this number does
// not move fails here instead of hanging. Even a clock with whole
// millisecond granularity gets there in the first round or two.
assert!(rounds < 1_000, "cpu time never moved, n is {n}");
}
}
/// Pull `used_cpu_user` back out of an `INFO cpu` reply.
#[cfg(unix)]
fn used_cpu_user(info: &str) -> f64 {
info.lines()
.find_map(|l| l.strip_prefix("used_cpu_user:"))
.expect("no used_cpu_user in the reply")
.trim()
.parse()
.expect("used_cpu_user is not a number")
}
/// The safety net under the rule that a body checks its arguments before
/// it writes anything. `MGET` writes its array header first and then reads
/// each key, so if a later argument could fail the header would already be
/// out. Nothing in the string group does that today and this is what would
/// catch the first one that did.
#[test]
fn a_command_that_fails_leaves_nothing_half_written() {
let mut f = Fixture::new();
let reply = f.run(&[b"SETRANGE", b"k", b"-1", b"x"]);
assert_eq!(reply, "-ERR offset is out of range\r\n");
assert!(!reply.contains(':'), "no integer went out in front of it");
}
#[test]
fn quit_answers_first_and_closes_after() {
let mut f = Fixture::new();
let (flow, reply) = f.flow(&[b"QUIT"]);
assert_eq!(reply, "+OK\r\n");
assert_eq!(flow, Flow::Close);
}
/// A server that has not been asked to stop is not stopping, and one that
/// has says so without writing anything back.
///
/// The empty reply is the point. Redis answers nothing at all here and the
/// client sees the socket close, and an `OK` would be a promise from a
/// process that is about to not exist.
#[test]
fn shutdown_writes_nothing_and_sets_the_flag() {
let mut f = Fixture::new();
assert!(!f.server.stopping(), "nobody has asked yet");
let (flow, reply) = f.flow(&[b"SHUTDOWN"]);
assert_eq!(reply, "");
assert_eq!(flow, Flow::Close);
assert!(f.server.stopping());
}
/// Every flag combination 8.10.1 takes, and every one it refuses.
///
/// The refusals are the half worth pinning down. `SAVE` and `NOSAVE`
/// contradict each other, `ABORT` says to do nothing so it cannot be
/// combined with a word about how to do it, and repeating any one of them
/// is fine. All of it was read off a running 8.10.1 rather than worked out
/// from the documentation, which does not say.
#[test]
fn shutdown_takes_the_flags_redis_takes() {
for flags in [
&[b"NOSAVE".as_slice()][..],
&[b"SAVE"],
&[b"NOW"],
&[b"FORCE"],
&[b"nosave"],
&[b"NOW", b"NOW"],
&[b"SAVE", b"SAVE"],
&[b"NOSAVE", b"NOW", b"FORCE"],
] {
let mut f = Fixture::new();
let mut parts = vec![b"SHUTDOWN".as_slice()];
parts.extend_from_slice(flags);
let (flow, reply) = f.flow(&parts);
assert_eq!(reply, "", "SHUTDOWN {flags:?} answered something");
assert_eq!(flow, Flow::Close, "SHUTDOWN {flags:?} did not close");
assert!(f.server.stopping(), "SHUTDOWN {flags:?} did not stop");
}
for flags in [
&[b"BOGUS".as_slice()][..],
&[b"SAVE", b"NOSAVE"],
&[b"NOSAVE", b"SAVE"],
&[b"ABORT", b"NOW"],
&[b"NOSAVE", b"ABORT"],
&[b"NOW", b"FORCE", b"ABORT"],
] {
let mut f = Fixture::new();
let mut parts = vec![b"SHUTDOWN".as_slice()];
parts.extend_from_slice(flags);
assert_eq!(
f.run(&parts),
"-ERR syntax error\r\n",
"SHUTDOWN {flags:?} was accepted"
);
assert!(!f.server.stopping(), "SHUTDOWN {flags:?} stopped anyway");
}
}
/// `ABORT` has nothing to call off, ever.
///
/// A shutdown here is decided and done inside one turn of the loop, so
/// there is no window in which one is in progress. That makes Redis's
/// message for a cancel with nothing to cancel the right answer every time
/// rather than only when nothing happens to be pending. Two `ABORT`s is
/// still one `ABORT`, which is what 8.10.1 does.
#[test]
fn shutdown_abort_never_has_anything_to_abort() {
let mut f = Fixture::new();
for parts in [
&[b"SHUTDOWN".as_slice(), b"ABORT"][..],
&[b"SHUTDOWN", b"ABORT", b"ABORT"],
] {
assert_eq!(f.run(parts), "-ERR No shutdown in progress.\r\n");
assert!(!f.server.stopping(), "an abort stopped the server");
}
}
/// A fixture whose server writes into a directory of its own.
///
/// Every test here really writes files, because the whole point of the
/// command is the files and a backup that is only a state machine would
/// pass a test suite and fail the first person who tried to restore one.
/// The directory carries the test's name so that the suite can run its
/// tests in parallel the way it always does.
struct Backups {
f: Fixture,
dir: PathBuf,
}
impl Backups {
fn new(name: &str) -> Backups {
let dir = std::env::temp_dir().join(format!("yo-backup-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("could not make a temporary directory");
let mut f = Fixture::new();
f.server.set_dir(dir.clone());
Backups { f, dir }
}
fn run(&mut self, parts: &[&[u8]]) -> String {
self.f.run(parts)
}
/// The names in `backupdir`, sorted, so a test can say what is on disk.
fn files(&self) -> Vec<String> {
let mut names: Vec<String> = match std::fs::read_dir(self.dir.join("backupdir")) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect(),
Err(_) => Vec::new(),
};
names.sort();
names
}
fn read(&self, name: &str) -> Vec<u8> {
std::fs::read(self.dir.join("backupdir").join(name)).expect("could not read")
}
}
impl Drop for Backups {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
/// The four states and the moves between them, in the order a client walks
/// them, with the files checked at every step.
#[test]
fn backup_walks_the_states_the_reference_walks() {
let mut b = Backups::new("states");
let status = |b: &mut Backups| b.run(&[b"BACKUP", b"STATUS"]);
assert!(status(&mut b).contains("idle"));
assert!(b.files().is_empty(), "an idle server has written a backup");
assert_eq!(b.run(&[b"BACKUP", b"START"]), "+OK\r\n");
assert!(status(&mut b).contains("incrementing"));
assert_eq!(b.files(), ["appendonly.aof.1.base.rdb"]);
assert_eq!(b.run(&[b"BACKUP", b"SEAL"]), "+OK\r\n");
assert!(status(&mut b).contains("sealed"));
assert_eq!(
b.files(),
[
"appendonly.aof.1.base.rdb",
"appendonly.aof.1.incr.aof",
"appendonly.aof.manifest",
]
);
assert_eq!(b.run(&[b"BACKUP", b"CLEANUP"]), "+OK\r\n");
assert!(status(&mut b).contains("idle"));
assert!(b.files().is_empty(), "cleanup left something behind");
}
/// Every move that is refused, in the reference's words.
#[test]
fn backup_refuses_the_moves_the_reference_refuses() {
let mut b = Backups::new("refusals");
assert_eq!(
b.run(&[b"BACKUP", b"SEAL"]),
"-ERR No backup ready to seal (must be in the incrementing state)\r\n"
);
assert_eq!(
b.run(&[b"BACKUP", b"ABORT"]),
"-ERR No backup in progress\r\n"
);
// Cleanup from idle is not an error, it is a way of saying there was
// nothing to clean up.
assert_eq!(b.run(&[b"BACKUP", b"CLEANUP"]), "+OK\r\n");
b.run(&[b"BACKUP", b"START"]);
assert_eq!(
b.run(&[b"BACKUP", b"START"]),
"-ERR A backup is already in progress, ABORT it first\r\n"
);
assert_eq!(
b.run(&[b"BACKUP", b"CLEANUP"]),
"-ERR Backup is in progress\r\n"
);
b.run(&[b"BACKUP", b"SEAL"]);
assert_eq!(
b.run(&[b"BACKUP", b"START"]),
"-ERR A sealed backup exists, CLEANUP it first\r\n"
);
assert_eq!(
b.run(&[b"BACKUP", b"SEAL"]),
"-ERR No backup ready to seal (must be in the incrementing state)\r\n"
);
assert_eq!(
b.run(&[b"BACKUP", b"ABORT"]),
"-ERR No backup in progress\r\n"
);
}
/// An abort takes the base file away and leaves a state saying who did it.
///
/// The next backup takes the next sequence number rather than reusing the
/// one whose files were just thrown away, so a directory somebody copied a
/// half finished backup out of cannot end up with two different files under
/// one name.
#[test]
fn backup_abort_removes_the_file_and_says_who_did_it() {
let mut b = Backups::new("abort");
b.run(&[b"BACKUP", b"START"]);
assert_eq!(b.run(&[b"BACKUP", b"ABORT"]), "+OK\r\n");
let status = b.run(&[b"BACKUP", b"STATUS"]);
assert!(status.contains("failed"), "{status}");
assert!(status.contains("aborted by user"), "{status}");
assert!(b.files().is_empty(), "abort left the base file behind");
assert_eq!(b.run(&[b"BACKUP", b"LIST"]), "*0\r\n");
// A start from failed works, and is the second backup.
assert_eq!(b.run(&[b"BACKUP", b"START"]), "+OK\r\n");
assert_eq!(b.files(), ["appendonly.aof.2.base.rdb"]);
let status = b.run(&[b"BACKUP", b"STATUS"]);
assert!(status.contains("incrementing"), "{status}");
assert!(!status.contains("aborted"), "the old error was kept");
}
/// `LIST` names nothing, then one file, then three, and they are absolute.
#[test]
fn backup_list_names_the_files_that_are_pinned_so_far() {
let mut b = Backups::new("list");
assert_eq!(b.run(&[b"BACKUP", b"LIST"]), "*0\r\n");
b.run(&[b"BACKUP", b"START"]);
let base = b.dir.join("backupdir").join("appendonly.aof.1.base.rdb");
let base = base.to_string_lossy().into_owned();
assert_eq!(
b.run(&[b"BACKUP", b"LIST"]),
format!("*1\r\n${}\r\n{base}\r\n", base.len())
);
b.run(&[b"BACKUP", b"SEAL"]);
let listed = b.run(&[b"BACKUP", b"LIST"]);
assert!(listed.starts_with("*3\r\n"), "{listed}");
// The order is the manifest's order, base then incremental then the
// manifest itself, which is the order a restore needs them in.
let names: Vec<&str> = listed
.lines()
.filter(|l| l.starts_with('/') || l.contains(":\\"))
.collect();
assert_eq!(names.len(), 3, "{listed}");
assert!(names[0].ends_with("appendonly.aof.1.base.rdb"), "{listed}");
assert!(names[1].ends_with("appendonly.aof.1.incr.aof"), "{listed}");
assert!(names[2].ends_with("appendonly.aof.manifest"), "{listed}");
}
/// The base file is the dataset as it was at `START` and not at `SEAL`.
///
/// That is D-46 and it is the one thing about this a client can notice, so
/// it is pinned here rather than left to be discovered by whoever restores
/// one. The incremental file is empty for the same reason: there is no
/// append only log underneath this server to copy the writes in between out
/// of.
#[test]
fn a_backup_holds_the_dataset_as_it_was_at_start() {
let mut b = Backups::new("contents");
b.run(&[b"SET", b"bk", b"v1"]);
b.run(&[b"BACKUP", b"START"]);
b.run(&[b"SET", b"bk", b"v2"]);
b.run(&[b"BACKUP", b"SEAL"]);
let base = b.read("appendonly.aof.1.base.rdb");
assert!(base.starts_with(b"REDIS"), "not an RDB file");
assert!(base.windows(2).any(|w| w == b"v1"), "the value is missing");
assert!(
!base.windows(2).any(|w| w == b"v2"),
"the base file moved on after START"
);
// The aux field a loader acts on, and the one that says this file is
// the base of an append only file rather than a standalone dump. Its
// value is the one byte string 1, which the encoder writes as an
// integer the way a real server writes it.
let at = base
.windows(8)
.position(|w| w == b"aof-base")
.expect("no aof-base aux field");
assert_eq!(&base[at + 8..at + 10], b"\xc0\x01", "{:?}", &base[at..]);
assert!(b.read("appendonly.aof.1.incr.aof").is_empty());
assert_eq!(
String::from_utf8(b.read("appendonly.aof.manifest")).expect("the manifest is text"),
"file appendonly.aof.1.base.rdb seq 1 type b\n\
file appendonly.aof.1.incr.aof seq 1 type i startoffset 0 endoffset 0\n"
);
}
/// `STATUS` is a map of four pairs on RESP3 and the same pairs flat on
/// RESP2, which is what every other map shaped reply in this server does.
#[test]
fn backup_status_is_a_map_on_resp3_and_a_flat_array_on_resp2() {
let mut b = Backups::new("status");
b.f.server.set_clock_ms(1_700_000_000_000);
assert_eq!(
b.run(&[b"BACKUP", b"STATUS"]),
"*8\r\n$5\r\nstate\r\n$4\r\nidle\r\n$5\r\nerror\r\n$0\r\n\r\n\
$10\r\nstart_time\r\n:0\r\n$8\r\nend_time\r\n:0\r\n"
);
b.f.out = Out::new(Proto::Resp3);
b.run(&[b"BACKUP", b"START"]);
assert_eq!(
b.run(&[b"BACKUP", b"STATUS"]),
"%4\r\n$5\r\nstate\r\n$12\r\nincrementing\r\n$5\r\nerror\r\n$0\r\n\r\n\
$10\r\nstart_time\r\n:1700000000\r\n$8\r\nend_time\r\n:0\r\n"
);
b.run(&[b"BACKUP", b"SEAL"]);
let sealed = b.run(&[b"BACKUP", b"STATUS"]);
assert!(sealed.contains("end_time\r\n:1700000000"), "{sealed}");
}
/// A sealed backup that nobody cleans up goes away on its own once
/// `backup-sealed-ttl` seconds have passed since the seal.
#[test]
fn a_sealed_backup_is_swept_away_after_the_timeout() {
let mut b = Backups::new("ttl");
b.f.server.set_clock_ms(1_000_000);
assert_eq!(
b.run(&[b"CONFIG", b"SET", b"backup-sealed-ttl", b"60"]),
"+OK\r\n"
);
b.run(&[b"BACKUP", b"START"]);
b.run(&[b"BACKUP", b"SEAL"]);
// A minute short of the deadline, nothing happens.
b.f.server.set_clock_ms(1_000_000 + 59_000);
b.f.server.backup_expire();
assert!(b.run(&[b"BACKUP", b"STATUS"]).contains("sealed"));
assert_eq!(b.files().len(), 3);
b.f.server.set_clock_ms(1_000_000 + 60_000);
b.f.server.backup_expire();
let status = b.run(&[b"BACKUP", b"STATUS"]);
assert!(status.contains("idle"), "{status}");
assert!(b.files().is_empty(), "the timeout left the files behind");
// Zero is the default and means a sealed backup is kept for ever.
b.run(&[b"CONFIG", b"SET", b"backup-sealed-ttl", b"0"]);
b.run(&[b"BACKUP", b"START"]);
b.run(&[b"BACKUP", b"SEAL"]);
b.f.server.set_clock_ms(9_000_000_000);
b.f.server.backup_expire();
assert!(b.run(&[b"BACKUP", b"STATUS"]).contains("sealed"));
}
/// The three settings around the command, read and written the way 8.10.1
/// reads and writes them.
#[test]
fn the_backup_settings_behave_the_way_the_reference_does() {
let mut b = Backups::new("config");
let dir = b.dir.to_string_lossy().into_owned();
assert_eq!(
b.run(&[b"CONFIG", b"GET", b"dir"]),
format!("*2\r\n$3\r\ndir\r\n${}\r\n{dir}\r\n", dir.len())
);
assert_eq!(
b.run(&[b"CONFIG", b"GET", b"backupdirname"]),
"*2\r\n$13\r\nbackupdirname\r\n$9\r\nbackupdir\r\n"
);
assert_eq!(
b.run(&[b"CONFIG", b"GET", b"backup-sealed-ttl"]),
"*2\r\n$17\r\nbackup-sealed-ttl\r\n$1\r\n0\r\n"
);
// `dir` is a protected config, so it is refused even for the value it
// already holds, and `backupdirname` is immutable.
assert_eq!(
b.run(&[b"CONFIG", b"SET", b"dir", dir.as_bytes()]),
"-ERR CONFIG SET failed (possibly related to argument 'dir') - can't set protected config\r\n"
);
assert_eq!(
b.run(&[b"CONFIG", b"SET", b"backupdirname", b"other"]),
"-ERR CONFIG SET failed (possibly related to argument 'backupdirname') - can't set immutable config\r\n"
);
assert!(
b.run(&[b"CONFIG", b"SET", b"backup-sealed-ttl", b"abc"])
.contains("argument couldn't be parsed into an integer")
);
assert!(
b.run(&[b"CONFIG", b"SET", b"backup-sealed-ttl", b"-1"])
.contains("argument must be between 0 and 9223372036854775807 inclusive")
);
}
/// The help text, which has `HELP` in it twice because the reference's does.
#[test]
fn backup_help_is_the_text_the_reference_sends() {
let mut f = Fixture::new();
let help = f.run(&[b"BACKUP", b"HELP"]);
assert!(help.starts_with("*17\r\n"), "{help}");
assert!(
help.contains("+BACKUP <subcommand> [<arg> [value] [opt] ...]. Subcommands are:\r\n")
);
assert!(help.contains("+ Start a new backup into the configured 'backupdirname'.\r\n"));
assert!(help.contains("+ Freeze the current backup (BASE + INCR + manifest).\r\n"));
assert!(help.contains("+ Return this help.\r\n+HELP\r\n+ Print this help.\r\n"));
}
/// What a mistyped `BACKUP` gets told.
///
/// The arity error names `backup` where the reference names `backup|start`,
/// which is D-46: the table reports one arity for the container the way the
/// reference does, and the per subcommand table that would carry the better
/// name is not built yet. Every subcommand is exactly two words, so nothing
/// legal is refused by it.
#[test]
fn backup_refuses_what_it_cannot_read() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"BACKUP"]),
"-ERR wrong number of arguments for 'backup' command\r\n"
);
assert_eq!(
f.run(&[b"BACKUP", b"START", b"x"]),
"-ERR wrong number of arguments for 'backup' command\r\n"
);
assert_eq!(
f.run(&[b"BACKUP", b"NOPE"]),
"-ERR unknown subcommand 'NOPE'. Try BACKUP HELP.\r\n"
);
}
#[test]
fn the_command_counter_counts_every_command_including_the_bad_ones() {
let mut f = Fixture::new();
f.run(&[b"PING"]);
f.run(&[b"NOPE"]);
f.run(&[b"GET"]);
assert_eq!(f.server.stats.commands, 3);
}
#[test]
fn a_set_goes_from_bytes_to_bytes() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SADD", b"s", b"a", b"b", b"c"]), ":3\r\n");
assert_eq!(f.run(&[b"SADD", b"s", b"b", b"d"]), ":1\r\n");
assert_eq!(f.run(&[b"SCARD", b"s"]), ":4\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"s", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"s", b"z"]), ":0\r\n");
assert_eq!(f.run(&[b"TYPE", b"s"]), "+set\r\n");
assert_eq!(
f.run(&[b"SMISMEMBER", b"s", b"a", b"z", b"d"]),
"*3\r\n:1\r\n:0\r\n:1\r\n"
);
assert_eq!(f.run(&[b"SREM", b"s", b"a", b"z"]), ":1\r\n");
assert_eq!(f.run(&[b"SCARD", b"s"]), ":3\r\n");
}
#[test]
fn a_set_command_at_a_key_that_is_not_there_answers_empty() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SCARD", b"nope"]), ":0\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"nope", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"SREM", b"nope", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"SMEMBERS", b"nope"]), "*0\r\n");
assert_eq!(
f.run(&[b"SMISMEMBER", b"nope", b"a", b"b"]),
"*2\r\n:0\r\n:0\r\n"
);
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n", "and made nothing");
}
#[test]
fn smembers_answers_a_set_on_resp3_and_an_array_on_resp2() {
// Not cosmetic. A RESP3 client that gets a `~` hands the caller a set
// and one that gets a `*` hands it a list, without either of them being
// told which command was sent.
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"one"]);
assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "*1\r\n$3\r\none\r\n");
f.run(&[b"HELLO", b"3"]);
assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "~1\r\n$3\r\none\r\n");
}
#[test]
fn an_integer_member_comes_back_as_the_digits_it_never_stored() {
// An intset holds the number, so these digits exist for the first time
// in the reply buffer.
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"42"]);
assert_eq!(f.run(&[b"SMEMBERS", b"s"]), "*1\r\n$2\r\n42\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"s", b"42"]), ":1\r\n");
assert_eq!(
f.run(&[b"SISMEMBER", b"s", b"042"]),
":0\r\n",
"the member is the bytes and not the number they parse to"
);
}
#[test]
fn the_wrong_command_at_the_wrong_type_says_so_both_ways() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
f.run(&[b"SADD", b"set", b"a"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
assert_eq!(f.run(&[b"SADD", b"str", b"a"]), wrong);
assert_eq!(f.run(&[b"SCARD", b"str"]), wrong);
assert_eq!(f.run(&[b"SMEMBERS", b"str"]), wrong);
assert_eq!(f.run(&[b"SMISMEMBER", b"str", b"a"]), wrong);
assert_eq!(f.run(&[b"GET", b"set"]), wrong);
assert_eq!(f.run(&[b"APPEND", b"set", b"x"]), wrong);
assert_eq!(f.run(&[b"INCR", b"set"]), wrong);
assert_eq!(f.run(&[b"STRLEN", b"set"]), wrong);
// MGET is the one that does not, because Redis gives nil for the odd
// key out rather than failing the good keys next to it.
assert_eq!(
f.run(&[b"MGET", b"str", b"set", b"nope"]),
"*3\r\n$1\r\nv\r\n$-1\r\n$-1\r\n"
);
// And plain SET overwrites any type, which takes the body with it.
assert_eq!(f.run(&[b"SET", b"set", b"now a string"]), "+OK\r\n");
assert_eq!(f.run(&[b"TYPE", b"set"]), "+string\r\n");
}
#[test]
fn a_wrongtype_leaves_nothing_half_written() {
// SMISMEMBER writes an array header and then one reply per member, so
// it is the first command in the server that could get a header out in
// front of an error if it checked its key in the wrong order.
let mut f = Fixture::new();
f.run(&[b"SET", b"k", b"v"]);
let reply = f.run(&[b"SMISMEMBER", b"k", b"a", b"b"]);
assert!(reply.starts_with("-WRONGTYPE"), "got {reply}");
assert!(!reply.contains('*'), "an array header went out in front");
}
#[test]
fn emptying_a_set_takes_the_key_with_it() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"a", b"b"]);
assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
assert_eq!(f.run(&[b"SREM", b"s", b"a", b"b"]), ":2\r\n");
assert_eq!(f.run(&[b"EXISTS", b"s"]), ":0\r\n");
assert_eq!(f.run(&[b"TYPE", b"s"]), "+none\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
}
/// Pull the cursor and the members out of one `SSCAN` reply.
///
/// Crude on purpose. A test that walked a set through a real client would
/// be testing the client, and what these tests are about is the shape of
/// the bytes and the fact that a walk sees every member once.
fn split_scan(reply: &str) -> (String, Vec<String>) {
let mut lines = reply.split("\r\n");
assert_eq!(lines.next(), Some("*2"), "got {reply}");
lines.next().expect("the cursor header");
let cursor = lines.next().expect("the cursor").to_owned();
let header = lines.next().expect("the member header");
let n: usize = header[1..].parse().expect("a member count");
let mut members = Vec::with_capacity(n);
for _ in 0..n {
lines.next().expect("a member header");
members.push(lines.next().expect("a member").to_owned());
}
(cursor, members)
}
#[test]
fn popping_takes_a_member_off_the_set_and_hands_it_back() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"a", b"b", b"c", b"d"]);
let one = f.run(&[b"SPOP", b"s"]);
assert!(
["$1\r\na\r\n", "$1\r\nb\r\n", "$1\r\nc\r\n", "$1\r\nd\r\n"].contains(&one.as_str()),
"got {one}"
);
assert_eq!(f.run(&[b"SCARD", b"s"]), ":3\r\n");
// A count takes that many, and the last one takes the key with it.
let (_, rest) = ("", f.run(&[b"SPOP", b"s", b"3"]));
assert!(rest.starts_with("*3\r\n"), "got {rest}");
assert_eq!(f.run(&[b"EXISTS", b"s"]), ":0\r\n");
// And a pop at a key that is not there is a nil, not an empty bulk.
assert_eq!(f.run(&[b"SPOP", b"s"]), "$-1\r\n");
assert_eq!(f.run(&[b"SPOP", b"s", b"2"]), "*0\r\n");
}
#[test]
fn the_two_draws_disagree_about_the_reply_type_and_they_are_right_to() {
// The one place in the server where the reply type carries something
// the command name does not. SPOP's members are distinct so a RESP3
// client can build a set out of them. SRANDMEMBER with a negative count
// can hand back the same member three times, and a set would lose two.
let mut f = Fixture::new();
f.run(&[b"HELLO", b"3"]);
f.run(&[b"SADD", b"s", b"a", b"b", b"c"]);
assert!(f.run(&[b"SPOP", b"s", b"2"]).starts_with("~2\r\n"));
// And a positive count is an array too, since Redis makes it one.
assert!(f.run(&[b"SRANDMEMBER", b"s", b"1"]).starts_with("*1\r\n"));
// A negative count against a set of one is where the difference bites:
// the same member three times, which is a three element reply and would
// have been a one element reply if it had gone out as a set.
f.run(&[b"SADD", b"one", b"z"]);
assert_eq!(
f.run(&[b"SRANDMEMBER", b"one", b"-3"]),
"*3\r\n$1\r\nz\r\n$1\r\nz\r\n$1\r\nz\r\n"
);
}
#[test]
fn drawing_a_member_removes_nothing_and_says_nil_at_a_missing_key() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"only"]);
assert_eq!(f.run(&[b"SRANDMEMBER", b"s"]), "$4\r\nonly\r\n");
assert_eq!(f.run(&[b"SRANDMEMBER", b"s"]), "$4\r\nonly\r\n");
assert_eq!(f.run(&[b"SCARD", b"s"]), ":1\r\n");
assert_eq!(f.run(&[b"SRANDMEMBER", b"nope"]), "$-1\r\n");
// The count form answers an empty array rather than a nil, which is the
// pair of answers Redis gives and is not the pair it looks like.
assert_eq!(f.run(&[b"SRANDMEMBER", b"nope", b"3"]), "*0\r\n");
assert_eq!(f.run(&[b"SRANDMEMBER", b"nope", b"-3"]), "*0\r\n");
// Asking for more than is there answers all of it once and not padding.
assert_eq!(f.run(&[b"SRANDMEMBER", b"s", b"9"]), "*1\r\n$4\r\nonly\r\n");
}
#[test]
fn a_pop_count_that_is_not_a_positive_number_says_so() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"a"]);
let bad = "-ERR value is out of range, must be positive\r\n";
assert_eq!(f.run(&[b"SPOP", b"s", b"-1"]), bad);
assert_eq!(f.run(&[b"SPOP", b"s", b"abc"]), bad);
assert_eq!(f.run(&[b"SCARD", b"s"]), ":1\r\n", "and took nothing");
// Zero is allowed and is a real answer rather than an error.
assert_eq!(f.run(&[b"SPOP", b"s", b"0"]), "*0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"s"]), ":1\r\n");
}
#[test]
fn a_scan_walks_a_set_of_any_size_exactly_once() {
let mut f = Fixture::new();
let members: Vec<Vec<u8>> = (0..300).map(|i| format!("m{i}").into_bytes()).collect();
let args: Vec<&[u8]> = [&b"SADD"[..], &b"s"[..]]
.into_iter()
.chain(members.iter().map(Vec::as_slice))
.collect();
f.run(&args);
let mut seen = Vec::new();
let mut cursor = "0".to_owned();
loop {
let reply = f.run(&[b"SSCAN", b"s", cursor.as_bytes()]);
let (next, got) = split_scan(&reply);
seen.extend(got);
cursor = next;
if cursor == "0" {
break;
}
}
seen.sort();
seen.dedup();
assert_eq!(seen.len(), 300, "a walk saw a member twice or missed one");
// A set small enough to be a listpack answers in one call whatever
// cursor it was handed, which is what Redis does for that encoding.
f.run(&[b"SADD", b"small", b"a", b"b", b"c"]);
let (cursor, got) = split_scan(&f.run(&[b"SSCAN", b"small", b"0", b"COUNT", b"1"]));
assert_eq!(cursor, "0");
assert_eq!(got.len(), 3);
// And a key that is not there is a finished scan of nothing.
assert_eq!(f.run(&[b"SSCAN", b"nope", b"0"]), "*2\r\n$1\r\n0\r\n*0\r\n");
}
#[test]
fn a_scan_takes_match_and_count_and_refuses_anything_else() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"aa", b"ab", b"ba", b"12", b"13"]);
let (_, got) = split_scan(&f.run(&[b"SSCAN", b"s", b"0", b"MATCH", b"a*"]));
let mut got = got;
got.sort();
assert_eq!(got, ["aa", "ab"]);
// An integer member has no digits stored anywhere, so MATCH is the one
// place a scan pays to write some.
let (_, got) = split_scan(&f.run(&[b"SSCAN", b"s", b"0", b"MATCH", b"1?"]));
let mut got = got;
got.sort();
assert_eq!(got, ["12", "13"]);
assert_eq!(f.run(&[b"SSCAN", b"s", b"abc"]), "-ERR invalid cursor\r\n");
assert_eq!(f.run(&[b"SSCAN", b"s", b"-1"]), "-ERR invalid cursor\r\n");
assert_eq!(
f.run(&[b"SSCAN", b"s", b"0", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
// A count under one is a syntax error and not a range error, which is
// the odder of Redis's two answers and the reason it is copied exactly.
assert_eq!(
f.run(&[b"SSCAN", b"s", b"0", b"COUNT", b"0"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn moving_a_member_takes_it_off_one_set_and_puts_it_on_another() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"src", b"a", b"b"]);
f.run(&[b"SADD", b"dst", b"c"]);
assert_eq!(f.run(&[b"SMOVE", b"src", b"dst", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"src", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"SISMEMBER", b"dst", b"a"]), ":1\r\n");
// A member that is not in the source is a zero and moves nothing.
assert_eq!(f.run(&[b"SMOVE", b"src", b"dst", b"zz"]), ":0\r\n");
assert_eq!(f.run(&[b"SCARD", b"dst"]), ":2\r\n");
// A destination that does not exist gets made, and a source that runs
// out goes away.
assert_eq!(f.run(&[b"SMOVE", b"src", b"fresh", b"b"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"src"]), ":0\r\n");
assert_eq!(f.run(&[b"SMEMBERS", b"fresh"]), "*1\r\n$1\r\nb\r\n");
}
#[test]
fn moving_checks_the_types_in_the_order_redis_checks_them() {
// Not the order it looks like it should be. A source that is not there
// answers zero without ever looking at the destination, so this is a
// zero and not a WRONGTYPE even though the destination is a string.
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
f.run(&[b"SADD", b"set", b"a"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
assert_eq!(f.run(&[b"SMOVE", b"nope", b"str", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"SMOVE", b"str", b"set", b"a"]), wrong);
assert_eq!(f.run(&[b"SMOVE", b"set", b"str", b"a"]), wrong);
assert_eq!(f.run(&[b"SPOP", b"str"]), wrong);
assert_eq!(f.run(&[b"SRANDMEMBER", b"str"]), wrong);
assert_eq!(f.run(&[b"SSCAN", b"str", b"0"]), wrong);
assert_eq!(
f.run(&[b"SISMEMBER", b"set", b"a"]),
":1\r\n",
"and none of that moved anything"
);
}
#[test]
fn a_scan_leaves_nothing_half_written_when_its_arguments_are_wrong() {
// SSCAN writes an outer array header before it walks, so it is the
// command most likely to get bytes out in front of an error.
let mut f = Fixture::new();
f.run(&[b"SADD", b"s", b"a"]);
for bad in [
&[b"SSCAN".as_slice(), b"s", b"abc"][..],
&[b"SSCAN".as_slice(), b"s", b"0", b"COUNT", b"nope"][..],
&[b"SSCAN".as_slice(), b"s", b"0", b"MATCH"][..],
] {
let reply = f.run(bad);
assert!(reply.starts_with("-ERR"), "got {reply}");
assert!(!reply.contains('*'), "an array header went out in front");
}
}
#[test]
fn a_hash_writes_reads_and_deletes_its_fields() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]), ":2\r\n");
assert_eq!(f.run(&[b"HSET", b"h", b"a", b"9"]), ":0\r\n", "a was there");
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n9\r\n");
assert_eq!(f.run(&[b"HGET", b"h", b"nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"HGET", b"nokey", b"a"]), "$-1\r\n");
assert_eq!(f.run(&[b"HLEN", b"h"]), ":2\r\n");
assert_eq!(f.run(&[b"HEXISTS", b"h", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"HEXISTS", b"h", b"nope"]), ":0\r\n");
assert_eq!(f.run(&[b"HSTRLEN", b"h", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"HSTRLEN", b"h", b"nope"]), ":0\r\n");
// The value the client sent is `9`, so HGET h b must not find the `2`
// that is a value. A search with a step of one would have.
assert_eq!(f.run(&[b"HGET", b"h", b"2"]), "$-1\r\n");
assert_eq!(f.run(&[b"HDEL", b"h", b"a", b"nope"]), ":1\r\n");
assert_eq!(f.run(&[b"HDEL", b"h", b"b"]), ":1\r\n");
assert_eq!(
f.run(&[b"EXISTS", b"h"]),
":0\r\n",
"and losing the last field lost the key"
);
}
#[test]
fn hgetall_answers_a_map_on_resp3_and_the_same_pairs_flat_on_resp2() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
assert_eq!(f.run(&[b"HGETALL", b"h"]), "*2\r\n$1\r\na\r\n$1\r\n1\r\n");
assert_eq!(f.run(&[b"HGETALL", b"nokey"]), "*0\r\n");
assert_eq!(f.run(&[b"HKEYS", b"h"]), "*1\r\n$1\r\na\r\n");
assert_eq!(f.run(&[b"HVALS", b"h"]), "*1\r\n$1\r\n1\r\n");
assert_eq!(f.run(&[b"HKEYS", b"nokey"]), "*0\r\n");
f.run(&[b"HELLO", b"3"]);
assert_eq!(f.run(&[b"HGETALL", b"h"]), "%1\r\n$1\r\na\r\n$1\r\n1\r\n");
assert_eq!(
f.run(&[b"HGETALL", b"nokey"]),
"%0\r\n",
"a missing key is the empty hash and never a nil"
);
assert_eq!(
f.run(&[b"HKEYS", b"h"]),
"*1\r\n$1\r\na\r\n",
"and the two that answer one side stay arrays"
);
}
#[test]
fn hmget_answers_once_per_field_and_hmset_answers_ok() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"HMSET", b"h", b"a", b"1", b"c", b"3"]), "+OK\r\n");
assert_eq!(
f.run(&[b"HMGET", b"h", b"a", b"b", b"c"]),
"*3\r\n$1\r\n1\r\n$-1\r\n$1\r\n3\r\n",
"the reply is positional, so b is a nil and not a gap"
);
assert_eq!(
f.run(&[b"HMGET", b"nokey", b"a", b"b"]),
"*2\r\n$-1\r\n$-1\r\n",
"and a missing key is all nils rather than an empty array"
);
assert_eq!(f.run(&[b"HSETNX", b"h", b"a", b"9"]), ":0\r\n");
assert_eq!(f.run(&[b"HSETNX", b"h", b"z", b"9"]), ":1\r\n");
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
}
#[test]
fn a_hash_counts_up_and_says_so_when_it_cannot() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"HINCRBY", b"h", b"n", b"5"]), ":5\r\n");
assert_eq!(f.run(&[b"HINCRBY", b"h", b"n", b"-7"]), ":-2\r\n");
assert_eq!(f.run(&[b"HGET", b"h", b"n"]), "$2\r\n-2\r\n");
assert_eq!(
f.run(&[b"HINCRBYFLOAT", b"h", b"f", b"10.5"]),
"$4\r\n10.5\r\n",
"a bulk string and not a double, on both protocols"
);
f.run(&[b"HSET", b"h", b"s", b"words"]);
let bad = f.run(&[b"HINCRBY", b"h", b"s", b"1"]);
assert!(
bad.starts_with("-ERR hash value is not an integer"),
"{bad}"
);
let bad = f.run(&[b"HINCRBY", b"h", b"n", b"nope"]);
assert!(
bad.starts_with("-ERR value is not an integer"),
"a bad argument is not yet a hash value, {bad}"
);
assert_eq!(
f.run(&[b"HGET", b"h", b"s"]),
"$5\r\nwords\r\n",
"and neither of them wrote anything"
);
}
#[test]
fn a_hash_scan_walks_every_pair_once_and_novalues_drops_half_of_it() {
let mut f = Fixture::new();
for i in 0..500 {
let field = format!("field-{i}");
let value = format!("value-{i}");
f.run(&[b"HSET", b"h", field.as_bytes(), value.as_bytes()]);
}
let mut seen: Vec<String> = Vec::new();
let mut cursor = "0".to_owned();
loop {
let reply = f.run(&[b"HSCAN", b"h", cursor.as_bytes(), b"COUNT", b"32"]);
let (next, items) = scan_reply(&reply);
assert_eq!(items.len() % 2, 0, "a pair went out half written");
for pair in items.chunks(2) {
assert_eq!(
pair[0].strip_prefix("field-"),
pair[1].strip_prefix("value-"),
"a field came back with someone else's value"
);
seen.push(pair[0].clone());
}
cursor = next;
if cursor == "0" {
break;
}
}
seen.sort();
seen.dedup();
assert_eq!(seen.len(), 500, "every field once and only once");
let (_, items) = scan_reply(&f.run(&[b"HSCAN", b"h", b"0", b"NOVALUES", b"COUNT", b"32"]));
assert!(
items.iter().all(|s| s.starts_with("field-")),
"NOVALUES still sent the values"
);
let (_, one) = scan_reply(&f.run(&[
b"HSCAN",
b"h",
b"0",
b"MATCH",
b"field-499",
b"COUNT",
b"1000",
]));
assert_eq!(one, ["field-499", "value-499"], "MATCH is on the field");
}
#[test]
fn hrandfield_draws_what_it_was_asked_for_and_nests_values_on_resp3() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
assert_eq!(f.run(&[b"HRANDFIELD", b"h"]), "$1\r\na\r\n");
assert_eq!(f.run(&[b"HRANDFIELD", b"nokey"]), "$-1\r\n");
assert_eq!(f.run(&[b"HRANDFIELD", b"nokey", b"3"]), "*0\r\n");
assert_eq!(
f.run(&[b"HRANDFIELD", b"h", b"3"]),
"*1\r\n$1\r\na\r\n",
"a positive count is capped at the size of the hash"
);
assert_eq!(
f.run(&[b"HRANDFIELD", b"h", b"-3"]),
"*3\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n",
"and a negative one repeats itself"
);
assert_eq!(
f.run(&[b"HRANDFIELD", b"h", b"1", b"WITHVALUES"]),
"*2\r\n$1\r\na\r\n$1\r\n1\r\n",
"flat on RESP2"
);
f.run(&[b"HELLO", b"3"]);
assert_eq!(
f.run(&[b"HRANDFIELD", b"h", b"1", b"WITHVALUES"]),
"*1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n",
"and nested on RESP3, but still an array and never a map"
);
}
#[test]
fn every_hash_command_says_wrongtype_and_writes_nothing() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"HSET".as_slice(), b"str", b"f", b"v"][..],
&[b"HMSET".as_slice(), b"str", b"f", b"v"][..],
&[b"HSETNX".as_slice(), b"str", b"f", b"v"][..],
&[b"HGET".as_slice(), b"str", b"f"][..],
&[b"HMGET".as_slice(), b"str", b"f"][..],
&[b"HDEL".as_slice(), b"str", b"f"][..],
&[b"HLEN".as_slice(), b"str"][..],
&[b"HEXISTS".as_slice(), b"str", b"f"][..],
&[b"HSTRLEN".as_slice(), b"str", b"f"][..],
&[b"HGETALL".as_slice(), b"str"][..],
&[b"HKEYS".as_slice(), b"str"][..],
&[b"HVALS".as_slice(), b"str"][..],
&[b"HINCRBY".as_slice(), b"str", b"f", b"1"][..],
&[b"HINCRBYFLOAT".as_slice(), b"str", b"f", b"1"][..],
&[b"HRANDFIELD".as_slice(), b"str"][..],
&[b"HRANDFIELD".as_slice(), b"str", b"2"][..],
&[b"HSCAN".as_slice(), b"str", b"0"][..],
] {
let reply = f.run(cmd);
assert_eq!(reply, wrong, "{:?}", cmd[0]);
}
assert_eq!(
f.run(&[b"GET", b"str"]),
"$1\r\nv\r\n",
"and none of them touched the value"
);
}
#[test]
fn a_hash_scan_leaves_nothing_half_written_when_its_arguments_are_wrong() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"f", b"v"]);
for bad in [
&[b"HSCAN".as_slice(), b"h", b"abc"][..],
&[b"HSCAN".as_slice(), b"h", b"0", b"COUNT", b"nope"][..],
&[b"HSCAN".as_slice(), b"h", b"0", b"COUNT", b"0"][..],
&[b"HSCAN".as_slice(), b"h", b"0", b"MATCH"][..],
] {
let reply = f.run(bad);
assert!(reply.starts_with("-ERR"), "got {reply}");
assert!(!reply.contains('*'), "an array header went out in front");
}
}
#[test]
fn a_field_deadline_goes_on_and_comes_back_in_all_four_units() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"3", b"a", b"b", b"nope"]),
"*3\r\n:100\r\n:-1\r\n:-2\r\n",
"one answer per field, and the two sentinels are TTL's own"
);
// The same deadline in the other three units, all of them derived from
// the one number the store kept.
let ms = int_reply(&f.run(&[b"HPTTL", b"h", b"FIELDS", b"1", b"a"]));
assert!((99_000..=100_000).contains(&ms), "got {ms}");
let at = int_reply(&f.run(&[b"HEXPIRETIME", b"h", b"FIELDS", b"1", b"a"]));
let at_ms = int_reply(&f.run(&[b"HPEXPIRETIME", b"h", b"FIELDS", b"1", b"a"]));
assert_eq!(at, at_ms.div_euclid(1000) + i64::from(at_ms % 1000 != 0));
assert!(at_ms > 1_700_000_000_000, "an absolute moment, got {at_ms}");
assert_eq!(
f.run(&[b"HPERSIST", b"h", b"FIELDS", b"3", b"a", b"b", b"nope"]),
"*3\r\n:1\r\n:-1\r\n:-2\r\n",
"one for the deadline taken off, and it does not say what it was"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n"
);
assert_eq!(
f.run(&[b"HGET", b"h", b"a"]),
"$1\r\n1\r\n",
"and the field is still there with the value it had"
);
}
#[test]
fn a_deadline_that_has_already_gone_deletes_the_field_now() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
assert_eq!(
f.run(&[b"HEXPIREAT", b"h", b"1", b"FIELDS", b"1", b"a"]),
"*1\r\n:2\r\n",
"two, and not one, because nothing was stored"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$-1\r\n");
assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");
assert_eq!(
f.run(&[b"HPEXPIREAT", b"h", b"1", b"FIELDS", b"1", b"b"]),
"*1\r\n:2\r\n"
);
assert_eq!(
f.run(&[b"EXISTS", b"h"]),
":0\r\n",
"and the last field going took the key with it"
);
// Zero is a delete and not an error, where minus one is an error. That
// is Redis's split and it is easy to get backwards.
f.run(&[b"HSET", b"h", b"a", b"1"]);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"0", b"FIELDS", b"1", b"a"]),
"*1\r\n:2\r\n"
);
}
#[test]
fn a_field_is_gone_once_its_moment_passes() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
assert_eq!(
f.run(&[b"HPEXPIRE", b"h", b"20", b"FIELDS", b"1", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n", "not yet");
// Time moves once per turn of the event loop and nowhere else, so a
// test moves it by hand rather than by sleeping. There is nothing to
// sleep for: the deadline is a number and so is the clock.
f.server.db(0).clock_mut().advance(60);
assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$-1\r\n");
assert_eq!(
f.run(&[b"HGETALL", b"h"]),
"*2\r\n$1\r\nb\r\n$1\r\n2\r\n",
"and the walks do not hand back a field that has expired"
);
}
#[test]
fn a_missing_key_answers_the_no_field_sentinel_for_every_field() {
let mut f = Fixture::new();
for cmd in [
&[
b"HEXPIRE".as_slice(),
b"nokey",
b"100",
b"FIELDS",
b"2",
b"a",
b"b",
][..],
&[b"HTTL".as_slice(), b"nokey", b"FIELDS", b"2", b"a", b"b"][..],
&[b"HPTTL".as_slice(), b"nokey", b"FIELDS", b"2", b"a", b"b"][..],
&[
b"HEXPIRETIME".as_slice(),
b"nokey",
b"FIELDS",
b"2",
b"a",
b"b",
][..],
&[
b"HPERSIST".as_slice(),
b"nokey",
b"FIELDS",
b"2",
b"a",
b"b",
][..],
] {
assert_eq!(f.run(cmd), "*2\r\n:-2\r\n:-2\r\n", "{:?}", cmd[0]);
}
}
#[test]
fn writing_a_field_clears_the_deadline_that_was_on_it() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
f.run(&[b"HEXPIRE", b"h", b"100", b"FIELDS", b"1", b"a"]);
f.run(&[b"HSET", b"h", b"a", b"2"]);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n",
"Redis has done this since 7.4, and it is why HGETEX exists"
);
}
#[test]
fn the_four_conditions_reach_the_store_the_way_they_were_written() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"100", b"XX", b"FIELDS", b"1", b"a"]),
"*1\r\n:0\r\n",
"XX on a field with no deadline changes nothing"
);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"100", b"NX", b"FIELDS", b"1", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"200", b"NX", b"FIELDS", b"1", b"a"]),
"*1\r\n:0\r\n",
"and NX will not move one that is already there"
);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"50", b"GT", b"FIELDS", b"1", b"a"]),
"*1\r\n:0\r\n"
);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"500", b"GT", b"FIELDS", b"1", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"HEXPIRE", b"h", b"50", b"LT", b"FIELDS", b"1", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:50\r\n"
);
}
#[test]
fn the_field_ttl_family_leaves_nothing_half_written_on_a_bad_argument() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
for (bad, want) in [
(
&[b"HEXPIRE".as_slice(), b"h", b"-1", b"FIELDS", b"1", b"a"][..],
"-ERR invalid expire time, must be >= 0",
),
(
&[
b"HEXPIRE".as_slice(),
b"h",
b"9999999999999999",
b"FIELDS",
b"1",
b"a",
][..],
"-ERR invalid expire time in 'hexpire' command",
),
(
&[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELD", b"1", b"a"][..],
"-ERR wrong number of arguments for 'hexpire' command",
),
(
&[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELDS", b"0", b"a"][..],
"-ERR Parameter `numFields` should be greater than 0",
),
(
&[b"HEXPIRE".as_slice(), b"h", b"100", b"FIELDS", b"2", b"a"][..],
"-ERR wrong number of arguments",
),
(
&[b"HTTL".as_slice(), b"h", b"FIELDS", b"3", b"a", b"b"][..],
"-ERR wrong number of arguments",
),
] {
let reply = f.run(bad);
assert!(reply.starts_with(want), "wanted {want}, got {reply}");
assert!(!reply.contains('*'), "an array header went out in front");
}
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n",
"and not one of them put a deadline on anything"
);
}
#[test]
fn every_field_ttl_command_says_wrongtype_and_writes_nothing() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"HEXPIRE".as_slice(), b"str", b"100", b"FIELDS", b"1", b"f"][..],
&[
b"HPEXPIRE".as_slice(),
b"str",
b"100",
b"FIELDS",
b"1",
b"f",
][..],
&[
b"HEXPIREAT".as_slice(),
b"str",
b"9999999999",
b"FIELDS",
b"1",
b"f",
][..],
&[
b"HPEXPIREAT".as_slice(),
b"str",
b"9999999999999",
b"FIELDS",
b"1",
b"f",
][..],
&[b"HTTL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[b"HPTTL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[b"HEXPIRETIME".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[b"HPEXPIRETIME".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[b"HPERSIST".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
] {
assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
}
assert_eq!(
f.run(&[b"GET", b"str"]),
"$1\r\nv\r\n",
"and none of them touched the value"
);
}
#[test]
fn hgetdel_hands_the_value_out_and_then_takes_the_field() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1", b"b", b"2"]);
assert_eq!(
f.run(&[b"HGETDEL", b"h", b"FIELDS", b"2", b"a", b"nope"]),
"*2\r\n$1\r\n1\r\n$-1\r\n",
"positional, so the field that was not there is a nil in its place"
);
assert_eq!(f.run(&[b"HLEN", b"h"]), ":1\r\n");
assert_eq!(
f.run(&[b"HGETDEL", b"nokey", b"FIELDS", b"1", b"a"]),
"*1\r\n$-1\r\n"
);
assert_eq!(
f.run(&[b"HGETDEL", b"h", b"FIELDS", b"1", b"b"]),
"*1\r\n$1\r\n2\r\n"
);
assert_eq!(
f.run(&[b"EXISTS", b"h"]),
":0\r\n",
"and the last field took the key"
);
}
#[test]
fn hgetex_reads_and_moves_the_deadline_in_one_command() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
assert_eq!(
f.run(&[b"HGETEX", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n$1\r\n1\r\n"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n",
"no option means leave it alone, which is the one place this is not GETEX"
);
f.run(&[b"HGETEX", b"h", b"EX", b"100", b"FIELDS", b"1", b"a"]);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:100\r\n"
);
f.run(&[b"HGETEX", b"h", b"FIELDS", b"1", b"a"]);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:100\r\n",
"and a plain read really does leave it alone"
);
assert_eq!(
f.run(&[b"HGETEX", b"h", b"PERSIST", b"FIELDS", b"1", b"a"]),
"*1\r\n$1\r\n1\r\n"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n"
);
assert_eq!(
f.run(&[b"HGETEX", b"h", b"EXAT", b"1", b"FIELDS", b"1", b"a"]),
"*1\r\n$1\r\n1\r\n",
"the value goes out before the deadline that has already gone is applied"
);
assert_eq!(f.run(&[b"EXISTS", b"h"]), ":0\r\n");
assert_eq!(
f.run(&[b"HGETEX", b"nokey", b"EX", b"100", b"FIELDS", b"1", b"a"]),
"*1\r\n$-1\r\n"
);
}
#[test]
fn hsetex_writes_all_of_it_or_none_of_it() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"HSETEX", b"h", b"FIELDS", b"1", b"a", b"1"]),
":1\r\n"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
assert_eq!(
f.run(&[
b"HSETEX", b"h", b"FNX", b"FIELDS", b"2", b"a", b"9", b"new", b"9"
]),
":0\r\n",
"FNX wants every field named to be missing"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
assert_eq!(
f.run(&[b"HEXISTS", b"h", b"new"]),
":0\r\n",
"and none of the list was written"
);
assert_eq!(
f.run(&[
b"HSETEX", b"h", b"FXX", b"FIELDS", b"2", b"a", b"9", b"nope", b"9"
]),
":0\r\n",
"and FXX wants every one of them to be there"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n1\r\n");
assert_eq!(
f.run(&[b"HSETEX", b"h", b"FXX", b"FIELDS", b"1", b"a", b"9"]),
":1\r\n"
);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n9\r\n");
assert_eq!(
f.run(&[b"HSETEX", b"gone", b"FXX", b"FIELDS", b"1", b"a", b"1"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"EXISTS", b"gone"]),
":0\r\n",
"a key with no fields cannot meet FXX and is not created trying"
);
}
#[test]
fn hsetex_clears_the_deadline_unless_it_is_told_to_keep_it() {
let mut f = Fixture::new();
f.run(&[b"HSETEX", b"h", b"EX", b"100", b"FIELDS", b"1", b"a", b"1"]);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:100\r\n"
);
f.run(&[b"HSETEX", b"h", b"KEEPTTL", b"FIELDS", b"1", b"a", b"2"]);
assert_eq!(f.run(&[b"HGET", b"h", b"a"]), "$1\r\n2\r\n");
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:100\r\n",
"KEEPTTL put back what the write cleared"
);
f.run(&[b"HSETEX", b"h", b"FIELDS", b"1", b"a", b"3"]);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n",
"and without it a write clears the deadline the way HSET does"
);
// Any order, because Redis reads these in a loop and not in a fixed
// sequence.
assert_eq!(
f.run(&[
b"HSETEX", b"h", b"PX", b"100000", b"FXX", b"FIELDS", b"1", b"a", b"4"
]),
":1\r\n"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:100\r\n"
);
assert_eq!(
f.run(&[b"HSETEX", b"h", b"EXAT", b"1", b"FIELDS", b"1", b"a", b"5"]),
":1\r\n",
"written, and not the separate code the HEXPIRE family has for this"
);
assert_eq!(
f.run(&[b"EXISTS", b"h"]),
":0\r\n",
"and storing it and then removing it emptied the hash"
);
}
#[test]
fn the_last_three_hash_commands_word_their_mistakes_their_own_way() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"h", b"a", b"1"]);
for (bad, want) in [
// HGETDEL has three sentences of its own for these three mistakes.
(
&[b"HGETDEL".as_slice(), b"h", b"FIELDS", b"0", b"a"][..],
"-ERR Number of fields must be a positive integer",
),
(
&[b"HGETDEL".as_slice(), b"h", b"FIELDS", b"2", b"a"][..],
"-ERR The `numfields` parameter must match the number of arguments",
),
(
&[b"HGETDEL".as_slice(), b"h", b"FIELD", b"1", b"a"][..],
"-ERR Mandatory argument FIELDS is missing or not at the right position",
),
// And HGETEX and HSETEX have three different ones between them.
(
&[b"HGETEX".as_slice(), b"h", b"FIELDS", b"0", b"a"][..],
"-ERR invalid number of fields",
),
(
&[b"HGETEX".as_slice(), b"h", b"FIELDS", b"2", b"a"][..],
"-ERR wrong number of arguments",
),
(
&[b"HGETEX".as_slice(), b"h", b"FIELD", b"1", b"a"][..],
"-ERR unknown argument: FIELD",
),
(
&[
b"HGETEX".as_slice(),
b"h",
b"KEEPTTL",
b"FIELDS",
b"1",
b"a",
][..],
"-ERR unknown argument: KEEPTTL",
),
(
&[
b"HGETEX".as_slice(),
b"h",
b"EX",
b"100",
b"PERSIST",
b"FIELDS",
b"1",
b"a",
][..],
"-ERR Only one of EX, PX, EXAT, PXAT or PERSIST arguments can be specified",
),
(
&[
b"HSETEX".as_slice(),
b"h",
b"EX",
b"1",
b"KEEPTTL",
b"FIELDS",
b"1",
b"a",
b"1",
][..],
"-ERR Only one of EX, PX, EXAT, PXAT or KEEPTTL arguments can be specified",
),
(
&[
b"HSETEX".as_slice(),
b"h",
b"FNX",
b"FXX",
b"FIELDS",
b"1",
b"a",
b"1",
][..],
"-ERR Only one of FXX or FNX arguments can be specified",
),
(
&[
b"HSETEX".as_slice(),
b"h",
b"FIELDS",
b"2",
b"a",
b"1",
b"b",
][..],
"-ERR wrong number of arguments",
),
(
&[
b"HGETEX".as_slice(),
b"h",
b"EX",
b"-1",
b"FIELDS",
b"1",
b"a",
][..],
"-ERR invalid expire time, must be >= 0",
),
(
&[
b"HGETEX".as_slice(),
b"h",
b"PXAT",
b"99999999999999",
b"FIELDS",
b"1",
b"a",
][..],
"-ERR invalid expire time in 'hgetex' command",
),
(
&[
b"HSETEX".as_slice(),
b"h",
b"EX",
b"abc",
b"FIELDS",
b"1",
b"a",
b"1",
][..],
"-ERR value is not an integer or out of range",
),
] {
let reply = f.run(bad);
assert!(reply.starts_with(want), "wanted {want}, got {reply}");
assert!(!reply.contains('*'), "an array header went out in front");
}
assert_eq!(
f.run(&[b"HGET", b"h", b"a"]),
"$1\r\n1\r\n",
"and not one of them wrote anything"
);
assert_eq!(
f.run(&[b"HTTL", b"h", b"FIELDS", b"1", b"a"]),
"*1\r\n:-1\r\n"
);
}
#[test]
fn the_last_three_hash_commands_say_wrongtype_and_write_nothing() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"HGETDEL".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[b"HGETEX".as_slice(), b"str", b"FIELDS", b"1", b"f"][..],
&[
b"HGETEX".as_slice(),
b"str",
b"EX",
b"100",
b"FIELDS",
b"1",
b"f",
][..],
&[b"HSETEX".as_slice(), b"str", b"FIELDS", b"1", b"f", b"v"][..],
] {
assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
}
assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
}
/// The two orders `HIMPORT` juggles, which are not the same order.
///
/// Values arrive in the order the fields were declared in and the hash is
/// built in sorted order, so the first value is not generally the first
/// field. And the sort is by length before bytes, which nothing else here
/// sorts names with: `b` comes before `aa` where a plain byte comparison
/// would put `aa` first. Both read off 8.10.1.
#[test]
fn himport_writes_declared_values_into_sorted_fields() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"b", b"aa", b"a"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"shape", b"1", b"2", b"3"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"HKEYS", b"k"]), bulks(&["a", "b", "aa"]));
assert_eq!(
f.run(&[b"HGETALL", b"k"]),
bulks(&["a", "3", "b", "1", "aa", "2"])
);
}
/// It replaces the key rather than writing over it, so a field the fieldset
/// does not name is gone afterwards and so is the deadline.
#[test]
fn himport_set_replaces_the_whole_key() {
let mut f = Fixture::new();
f.run(&[b"HSET", b"k", b"gone", b"old", b"a", b"old"]);
f.run(&[b"EXPIRE", b"k", b"100"]);
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"a", b"b"]);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"shape", b"1", b"2"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"HGETALL", b"k"]), bulks(&["a", "1", "b", "2"]));
assert_eq!(f.run(&[b"TTL", b"k"]), ":-1\r\n");
}
/// A fieldset is connection state. `SELECT` leaves them alone and `RESET`
/// throws them away, and a key built from one outlives it.
#[test]
fn himport_fieldsets_belong_to_the_connection_and_not_to_the_keyspace() {
let mut f = Fixture::new();
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"a"]);
f.run(&[b"SELECT", b"1"]);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"shape", b"1"]),
"+OK\r\n"
);
f.run(&[b"SELECT", b"0"]);
assert_eq!(f.run(&[b"RESET"]), "+RESET\r\n");
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k2", b"shape", b"1"]),
"-ERR no such fieldset\r\n"
);
}
/// Which complaint wins when a line is wrong in more than one place.
///
/// The type of the key beats both of the others, so a `HIMPORT SET` against
/// a string is a WRONGTYPE even when the fieldset is missing too, which is
/// the ordering a real server has and not the one the argument order
/// suggests.
#[test]
fn himport_complains_in_the_order_a_real_server_does() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"a", b"b"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"str", b"nope", b"1"]),
wrong,
"the type beats a missing fieldset"
);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"str", b"shape", b"1"]),
wrong,
"and it beats a value count that does not fit"
);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"nope", b"1"]),
"-ERR no such fieldset\r\n"
);
// One sentence for too few and for too many alike.
for values in [&[b"1".as_slice()][..], &[b"1".as_slice(), b"2", b"3"][..]] {
let mut line: Vec<&[u8]> = vec![b"HIMPORT", b"SET", b"k", b"shape"];
line.extend_from_slice(values);
assert_eq!(
f.run(&line),
"-ERR value count does not match fieldset field count\r\n",
"{} values into two fields",
values.len()
);
}
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
}
/// The arity of each subcommand, and the unknown one.
#[test]
fn himport_checks_each_subcommand_count_under_its_own_name() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"HIMPORT"]),
"-ERR wrong number of arguments for 'himport' command\r\n"
);
for (rest, name) in [
(&["PREPARE"][..], "prepare"),
(&["PREPARE", "fs"][..], "prepare"),
(&["SET"][..], "set"),
(&["SET", "k"][..], "set"),
(&["SET", "k", "fs"][..], "set"),
(&["DISCARD"][..], "discard"),
(&["DISCARD", "a", "b"][..], "discard"),
(&["DISCARDALL", "x"][..], "discardall"),
] {
let mut line: Vec<&[u8]> = vec![b"HIMPORT"];
line.extend(rest.iter().map(|a| a.as_bytes()));
assert_eq!(
f.run(&line),
format!("-ERR wrong number of arguments for 'himport|{name}' command\r\n"),
"HIMPORT {}",
rest.join(" ")
);
}
assert_eq!(
f.run(&[b"HIMPORT", b"NOPE", b"x"]),
"-ERR unknown subcommand 'NOPE'. Try HIMPORT HELP.\r\n"
);
}
/// A `PREPARE` that fails leaves the name pointing where it pointed, which
/// is the answer of the two that could not be guessed from outside.
#[test]
fn a_failed_himport_prepare_leaves_the_old_fieldset_alone() {
let mut f = Fixture::new();
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"a", b"b"]);
assert_eq!(
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"c", b"c"]),
"-ERR duplicate field name in fieldset\r\n"
);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"shape", b"1", b"2"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"HGETALL", b"k"]), bulks(&["a", "1", "b", "2"]));
}
/// Preparing the same name twice replaces it, and the two discards count
/// what they took rather than answering OK.
#[test]
fn himport_prepare_replaces_and_the_discards_count() {
let mut f = Fixture::new();
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"a", b"b"]);
f.run(&[b"HIMPORT", b"PREPARE", b"shape", b"z"]);
assert_eq!(
f.run(&[b"HIMPORT", b"SET", b"k", b"shape", b"1"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"HGETALL", b"k"]), bulks(&["z", "1"]));
assert_eq!(f.run(&[b"HIMPORT", b"DISCARD", b"shape"]), ":1\r\n");
assert_eq!(f.run(&[b"HIMPORT", b"DISCARD", b"shape"]), ":0\r\n");
f.run(&[b"HIMPORT", b"PREPARE", b"one", b"a"]);
f.run(&[b"HIMPORT", b"PREPARE", b"two", b"a"]);
assert_eq!(f.run(&[b"HIMPORT", b"DISCARDALL"]), ":2\r\n");
assert_eq!(f.run(&[b"HIMPORT", b"DISCARDALL"]), ":0\r\n");
}
/// The one integer of a single element array reply.
/// The number out of a plain integer reply.
///
/// [`int_reply`] is the same thing wrapped in a one element array, which is
/// the shape every hash field command answers in.
fn int(reply: &str) -> i64 {
let body = reply
.strip_prefix(':')
.and_then(|s| s.strip_suffix("\r\n"))
.unwrap_or_else(|| panic!("wanted an integer, got {reply}"));
body.parse().expect("an integer")
}
fn int_reply(reply: &str) -> i64 {
let body = reply
.strip_prefix("*1\r\n:")
.and_then(|s| s.strip_suffix("\r\n"))
.unwrap_or_else(|| panic!("wanted one integer, got {reply}"));
body.parse().expect("an integer")
}
/// The cursor and the flat items of a scan reply.
fn scan_reply(reply: &str) -> (String, Vec<String>) {
let mut lines = reply.split("\r\n");
assert_eq!(lines.next(), Some("*2"), "got {reply}");
lines.next().expect("the cursor header");
let cursor = lines.next().expect("a cursor").to_owned();
let header = lines.next().expect("an item count");
let n: usize = header[1..].parse().expect("a count");
let mut items = Vec::with_capacity(n);
for _ in 0..n {
lines.next().expect("an item header");
items.push(lines.next().expect("an item").to_owned());
}
(cursor, items)
}
/// The members of a set reply, sorted, since none of these promise an
/// order and a test that asserted one would be asserting an accident.
fn sorted(reply: &str) -> Vec<String> {
let mut lines = reply.split("\r\n");
let header = lines.next().expect("a header");
assert!(
header.starts_with('*') || header.starts_with('~'),
"got {reply}"
);
let n: usize = header[1..].parse().expect("a member count");
let mut got = Vec::with_capacity(n);
for _ in 0..n {
lines.next().expect("a member header");
got.push(lines.next().expect("a member").to_owned());
}
got.sort();
got
}
#[test]
fn the_algebra_answers_what_the_sets_share_and_do_not() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"1", b"2", b"3"]);
f.run(&[b"SADD", b"b", b"2", b"3", b"4"]);
f.run(&[b"SADD", b"c", b"3", b"4", b"5"]);
assert_eq!(sorted(&f.run(&[b"SINTER", b"a", b"b", b"c"])), ["3"]);
assert_eq!(
sorted(&f.run(&[b"SUNION", b"a", b"b", b"c"])),
["1", "2", "3", "4", "5"]
);
assert_eq!(sorted(&f.run(&[b"SDIFF", b"a", b"b"])), ["1"]);
assert_eq!(sorted(&f.run(&[b"SINTER", b"a"])), ["1", "2", "3"]);
// A key that is not there is an empty set, which empties an
// intersection and does nothing at all to a union.
assert_eq!(f.run(&[b"SINTER", b"a", b"nope"]), "*0\r\n");
assert_eq!(sorted(&f.run(&[b"SUNION", b"a", b"nope"])), ["1", "2", "3"]);
assert_eq!(f.run(&[b"SDIFF", b"nope", b"a"]), "*0\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":3\r\n", "and none of it made a key");
}
#[test]
fn the_algebra_answers_a_set_on_resp3_and_an_array_on_resp2() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"x"]);
assert_eq!(f.run(&[b"SINTER", b"a"]), "*1\r\n$1\r\nx\r\n");
assert_eq!(f.run(&[b"SUNION", b"a"]), "*1\r\n$1\r\nx\r\n");
assert_eq!(f.run(&[b"SDIFF", b"a"]), "*1\r\n$1\r\nx\r\n");
f.run(&[b"HELLO", b"3"]);
assert_eq!(f.run(&[b"SINTER", b"a"]), "~1\r\n$1\r\nx\r\n");
assert_eq!(f.run(&[b"SUNION", b"a"]), "~1\r\n$1\r\nx\r\n");
assert_eq!(f.run(&[b"SDIFF", b"a"]), "~1\r\n$1\r\nx\r\n");
assert_eq!(f.run(&[b"SINTER", b"nope"]), "~0\r\n");
}
#[test]
fn a_store_form_writes_a_key_and_answers_how_big_it_is() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"1", b"2", b"3"]);
f.run(&[b"SADD", b"b", b"2", b"3", b"4"]);
assert_eq!(f.run(&[b"SINTERSTORE", b"d", b"a", b"b"]), ":2\r\n");
assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"d"])), ["2", "3"]);
assert_eq!(f.run(&[b"SUNIONSTORE", b"d", b"a", b"b"]), ":4\r\n");
assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"d"])), ["1", "2", "3", "4"]);
assert_eq!(f.run(&[b"SDIFFSTORE", b"d", b"a", b"b"]), ":1\r\n");
assert_eq!(f.run(&[b"SMEMBERS", b"d"]), "*1\r\n$1\r\n1\r\n");
// An empty answer deletes the destination rather than leaving an empty
// set behind, and the destination may be one of the sources.
assert_eq!(f.run(&[b"SDIFFSTORE", b"d", b"a", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
assert_eq!(f.run(&[b"SINTERSTORE", b"a", b"a", b"b"]), ":2\r\n");
assert_eq!(sorted(&f.run(&[b"SMEMBERS", b"a"])), ["2", "3"]);
// And a destination holding something else is overwritten, the same way
// SET overwrites, rather than refused.
f.run(&[b"SET", b"str", b"v"]);
assert_eq!(f.run(&[b"SUNIONSTORE", b"str", b"b"]), ":3\r\n");
assert_eq!(f.run(&[b"TYPE", b"str"]), "+set\r\n");
}
#[test]
fn sintercard_counts_without_building_and_stops_at_a_limit() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"1", b"2", b"3", b"4"]);
f.run(&[b"SADD", b"b", b"2", b"3", b"4", b"5"]);
assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"b"]), ":3\r\n");
assert_eq!(
f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"2"]),
":2\r\n"
);
assert_eq!(
f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"0"]),
":3\r\n",
"a limit of zero is no limit"
);
assert_eq!(f.run(&[b"SINTERCARD", b"1", b"a"]), ":4\r\n");
assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"nope"]), ":0\r\n");
// The counted keys are what make its three error messages its own.
assert_eq!(
f.run(&[b"SINTERCARD", b"0", b"a"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[b"SINTERCARD", b"abc", b"a"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[b"SINTERCARD", b"3", b"a", b"b"]),
"-ERR Number of keys can't be greater than number of args\r\n"
);
assert_eq!(
f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"LIMIT", b"-1"]),
"-ERR LIMIT can't be negative\r\n"
);
assert_eq!(
f.run(&[b"SINTERCARD", b"2", b"a", b"b", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
// A key really can be called LIMIT, which is why the count exists.
f.run(&[b"SADD", b"LIMIT", b"2"]);
assert_eq!(f.run(&[b"SINTERCARD", b"2", b"a", b"LIMIT"]), ":1\r\n");
}
/// The two Redis 8.10 added, which are SINTERCARD's shape over a union and
/// over a difference. Every number here was read off 8.10.1 first.
#[test]
fn sunioncard_and_sdiffcard_count_without_building() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"1", b"2", b"3", b"4"]);
f.run(&[b"SADD", b"b", b"3", b"4", b"5", b"6"]);
assert_eq!(f.run(&[b"SUNIONCARD", b"2", b"a", b"b"]), ":6\r\n");
assert_eq!(
f.run(&[b"SUNIONCARD", b"2", b"a", b"b", b"LIMIT", b"2"]),
":2\r\n"
);
assert_eq!(
f.run(&[b"SUNIONCARD", b"2", b"a", b"b", b"LIMIT", b"0"]),
":6\r\n",
"a limit of zero is no limit"
);
assert_eq!(f.run(&[b"SUNIONCARD", b"1", b"a"]), ":4\r\n");
assert_eq!(
f.run(&[b"SUNIONCARD", b"2", b"a", b"nope"]),
":4\r\n",
"a missing key adds nothing to a union"
);
assert_eq!(f.run(&[b"SDIFFCARD", b"2", b"a", b"b"]), ":2\r\n");
assert_eq!(
f.run(&[b"SDIFFCARD", b"2", b"a", b"b", b"LIMIT", b"1"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"SDIFFCARD", b"2", b"b", b"a"]),
":2\r\n",
"a difference is not symmetric"
);
assert_eq!(f.run(&[b"SDIFFCARD", b"1", b"a"]), ":4\r\n");
assert_eq!(f.run(&[b"SDIFFCARD", b"2", b"a", b"nope"]), ":4\r\n");
assert_eq!(
f.run(&[b"SDIFFCARD", b"2", b"nope", b"a"]),
":0\r\n",
"nothing taken away from nothing"
);
// The same three messages SINTERCARD has, because the line is the same
// line and is parsed once for all three.
for name in [b"SUNIONCARD".as_slice(), b"SDIFFCARD".as_slice()] {
assert_eq!(
f.run(&[name, b"0", b"a"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[name, b"abc", b"a"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[name, b"-1", b"a"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[name, b"3", b"a", b"b"]),
"-ERR Number of keys can't be greater than number of args\r\n"
);
assert_eq!(
f.run(&[name, b"2", b"a", b"b", b"LIMIT", b"-1"]),
"-ERR LIMIT can't be negative\r\n"
);
assert_eq!(
f.run(&[name, b"2", b"a", b"b", b"LIMIT", b"abc"]),
"-ERR LIMIT can't be negative\r\n",
"a LIMIT that is not a number gets the negative message too"
);
assert_eq!(
f.run(&[name, b"2", b"a", b"b", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[name, b"2", b"a", b"b", b"LIMIT"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[name, b"2", b"a", b"b", b"LIMIT", b"1", b"X"]),
"-ERR syntax error\r\n"
);
}
// And a key called LIMIT is a key, here as much as on SINTERCARD.
f.run(&[b"SADD", b"LIMIT", b"2"]);
assert_eq!(f.run(&[b"SUNIONCARD", b"2", b"a", b"LIMIT"]), ":4\r\n");
assert_eq!(f.run(&[b"SDIFFCARD", b"2", b"a", b"LIMIT"]), ":3\r\n");
}
#[test]
fn the_algebra_answers_wrongtype_before_it_writes_anything() {
let mut f = Fixture::new();
f.run(&[b"SADD", b"a", b"1"]);
f.run(&[b"SADD", b"d", b"old"]);
f.run(&[b"SET", b"str", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for bad in [
&[b"SINTER".as_slice(), b"a", b"str"][..],
&[b"SUNION".as_slice(), b"str"][..],
&[b"SDIFF".as_slice(), b"a", b"str"][..],
&[b"SINTERCARD".as_slice(), b"2", b"a", b"str"][..],
&[b"SINTERSTORE".as_slice(), b"d", b"a", b"str"][..],
&[b"SUNIONSTORE".as_slice(), b"d", b"str"][..],
&[b"SDIFFSTORE".as_slice(), b"d", b"a", b"str"][..],
] {
let reply = f.run(bad);
assert_eq!(reply, wrong, "for {:?}", bad[0]);
}
assert_eq!(
f.run(&[b"SMEMBERS", b"d"]),
"*1\r\n$3\r\nold\r\n",
"and the destination was left alone every time"
);
}
/// The leak a set can spring that nothing on the wire would ever show: the
/// key goes, the body does not, and `DBSIZE` looks right the whole time.
#[test]
fn churning_sets_does_not_grow_the_server() {
let mut f = Fixture::new();
let members: Vec<Vec<u8>> = (0..200).map(|i| format!("m{i}").into_bytes()).collect();
let args: Vec<&[u8]> = std::iter::once(&b"SADD"[..])
.chain(std::iter::once(&b"s"[..]))
.chain(members.iter().map(Vec::as_slice))
.collect();
f.run(&args);
f.run(&[b"DEL", b"s"]);
f.server.compact_step();
let after_first = f.server.memory_bytes();
for _ in 0..200 {
f.run(&args);
f.run(&[b"DEL", b"s"]);
f.server.compact_step();
}
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
assert!(
f.server.memory_bytes() <= after_first * 2,
"held {} after two hundred passes against {after_first} after one",
f.server.memory_bytes()
);
}
// --------------------------------------------------------------- bitmaps
/// The two single bit commands, and the encoding rule underneath them.
///
/// A write always leaves the value `raw` and a read never re-encodes, which
/// is why the `int` key here is still `int` after a `GETBIT` and is `raw`
/// with its first digit changed after a `SETBIT`.
#[test]
fn a_bit_is_written_and_read_back_and_a_write_unpacks_an_int() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"SETBIT", b"k", b"7", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"GET", b"k"]), "$1\r\n\u{1}\r\n");
assert_eq!(f.run(&[b"GETBIT", b"k", b"7"]), ":1\r\n");
assert_eq!(f.run(&[b"GETBIT", b"k", b"6"]), ":0\r\n");
assert_eq!(f.run(&[b"GETBIT", b"k", b"100"]), ":0\r\n");
assert_eq!(f.run(&[b"SETBIT", b"k", b"7", b"0"]), ":1\r\n");
// Writing a nought past the end still creates the key and still pads.
assert_eq!(f.run(&[b"SETBIT", b"nk", b"0", b"0"]), ":0\r\n");
assert_eq!(f.run(&[b"STRLEN", b"nk"]), ":1\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"nk"]), "$3\r\nraw\r\n");
f.run(&[b"SET", b"num", b"12345"]);
assert_eq!(f.run(&[b"GETBIT", b"num", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"num"]), "$3\r\nint\r\n");
assert_eq!(f.run(&[b"SETBIT", b"num", b"1", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"num"]), "$3\r\nraw\r\n");
assert_eq!(f.run(&[b"GET", b"num"]), "$5\r\nq2345\r\n");
}
/// Counting, in bytes and in bits.
///
/// The `0 -5 BIT` row is 25 on a real 8.10.1 and Redis's own documentation
/// says 22 for it. The server is the thing being copied here.
#[test]
fn bits_are_counted_over_a_range_of_bytes_or_of_bits() {
let mut f = Fixture::new();
f.run(&[b"SET", b"mykey", b"foobar"]);
assert_eq!(f.run(&[b"BITCOUNT", b"mykey"]), ":26\r\n");
assert_eq!(f.run(&[b"BITCOUNT", b"mykey", b"0", b"0"]), ":4\r\n");
assert_eq!(f.run(&[b"BITCOUNT", b"mykey", b"1", b"1"]), ":6\r\n");
assert_eq!(
f.run(&[b"BITCOUNT", b"mykey", b"1", b"1", b"BYTE"]),
":6\r\n"
);
assert_eq!(
f.run(&[b"BITCOUNT", b"mykey", b"0", b"-5", b"BIT"]),
":25\r\n"
);
assert_eq!(
f.run(&[b"BITCOUNT", b"mykey", b"5", b"30", b"BIT"]),
":17\r\n"
);
assert_eq!(f.run(&[b"BITCOUNT", b"nokey"]), ":0\r\n");
// A start past the end is left where it is and the end is pulled back,
// so the range comes out backwards and counts nothing.
assert_eq!(f.run(&[b"BITCOUNT", b"mykey", b"10", b"20"]), ":0\r\n");
// A lone start is a syntax error here, where BITPOS allows it.
assert_eq!(
f.run(&[b"BITCOUNT", b"mykey", b"0"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"BITCOUNT", b"mykey", b"0", b"1", b"NIB"]),
"-ERR syntax error\r\n"
);
}
/// Searching, and the one place a miss is not minus one.
///
/// A search for a nought that runs to the end of the string answers the
/// length in bits, because the string is treated as if it had noughts after
/// it forever. Give it an explicit end and it answers minus one instead.
#[test]
fn a_search_for_a_nought_past_the_end_answers_the_length_in_bits() {
let mut f = Fixture::new();
f.run(&[b"SET", b"ones", b"\xff\xff\xff"]);
assert_eq!(f.run(&[b"BITPOS", b"ones", b"0"]), ":24\r\n");
assert_eq!(f.run(&[b"BITPOS", b"ones", b"0", b"0"]), ":24\r\n");
assert_eq!(f.run(&[b"BITPOS", b"ones", b"0", b"0", b"-1"]), ":-1\r\n");
assert_eq!(f.run(&[b"BITPOS", b"ones", b"0", b"0", b"3"]), ":-1\r\n");
assert_eq!(f.run(&[b"BITPOS", b"ones", b"1"]), ":0\r\n");
f.run(&[b"SET", b"mid", b"\x00\xff\xf0"]);
assert_eq!(f.run(&[b"BITPOS", b"mid", b"1", b"0"]), ":8\r\n");
assert_eq!(f.run(&[b"BITPOS", b"mid", b"1", b"2"]), ":16\r\n");
assert_eq!(
f.run(&[b"BITPOS", b"mid", b"1", b"0", b"-1", b"BIT"]),
":8\r\n"
);
// A missing key is all noughts, so a one is never found and a nought is
// at position zero.
assert_eq!(f.run(&[b"BITPOS", b"gone", b"1"]), ":-1\r\n");
assert_eq!(f.run(&[b"BITPOS", b"gone", b"0"]), ":0\r\n");
}
/// The eight operations, with the answers a real server gives for them.
#[test]
fn the_eight_combinations_write_what_a_real_server_writes() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"abc"]);
f.run(&[b"SET", b"b", b"abd"]);
let cases: &[(&[u8], &str)] = &[
(b"AND", "ab`"),
(b"OR", "abg"),
(b"XOR", "\u{0}\u{0}\u{7}"),
(b"DIFF", "\u{0}\u{0}\u{3}"),
(b"DIFF1", "\u{0}\u{0}\u{4}"),
(b"ANDOR", "ab`"),
(b"ONE", "\u{0}\u{0}\u{7}"),
];
for (op, want) in cases {
assert_eq!(f.run(&[b"BITOP", op, b"d", b"a", b"b"]), ":3\r\n", "{op:?}");
assert_eq!(
f.run(&[b"GET", b"d"]),
format!("$3\r\n{want}\r\n"),
"{op:?}"
);
}
// The one whose answer is not text, so it is compared as bytes.
assert_eq!(f.run(&[b"BITOP", b"NOT", b"d", b"a"]), ":3\r\n");
assert_eq!(f.raw(&[b"GET", b"d"]), b"$3\r\n\x9e\x9d\x9c\r\n".to_vec());
// A missing source is a string of noughts as long as it needs to be, so
// an AND against one writes three zero bytes rather than nothing.
assert_eq!(f.run(&[b"BITOP", b"AND", b"d", b"a", b"gone"]), ":3\r\n");
assert_eq!(f.run(&[b"GET", b"d"]), "$3\r\n\u{0}\u{0}\u{0}\r\n");
// Every source missing is an empty result, and an empty result takes
// the destination with it.
f.run(&[b"SET", b"dest", b"x"]);
assert_eq!(f.run(&[b"BITOP", b"AND", b"dest", b"g1", b"g2"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"dest"]), ":0\r\n");
}
/// What `BITOP` says when it is asked for something it cannot do.
#[test]
fn bitop_names_the_operation_in_its_own_complaints() {
let mut f = Fixture::new();
f.run(&[b"SET", b"a", b"abc"]);
assert_eq!(
f.run(&[b"BITOP", b"nope", b"d", b"a"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"BITOP", b"NOT", b"d", b"a", b"a"]),
"-ERR BITOP NOT must be called with a single source key.\r\n"
);
for op in [&b"DIFF"[..], b"DIFF1", b"ANDOR"] {
assert_eq!(
f.run(&[b"BITOP", op, b"d", b"a"]),
format!(
"-ERR BITOP {} must be called with at least two source keys.\r\n",
String::from_utf8_lossy(op)
)
);
}
f.run(&[b"LPUSH", b"l", b"x"]);
assert_eq!(
f.run(&[b"BITOP", b"AND", b"d", b"a", b"l"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
}
/// Packed fields, the three overflow policies and the `#` offset.
#[test]
fn bitfield_reads_and_writes_packed_fields() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"BITFIELD", b"bf"]), "*0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"bf"]), ":0\r\n");
assert_eq!(
f.run(&[
b"BITFIELD",
b"bf",
b"INCRBY",
b"u2",
b"100",
b"1",
b"GET",
b"u4",
b"0"
]),
"*2\r\n:1\r\n:0\r\n"
);
// The field at bit 100 is two bits wide, so it ends in the thirteenth
// byte and the value grew to thirteen bytes to hold it.
assert_eq!(f.run(&[b"STRLEN", b"bf"]), ":13\r\n");
// A `#` offset counts in fields rather than in bits.
assert_eq!(
f.run(&[
b"BITFIELD",
b"bf",
b"SET",
b"u8",
b"#0",
b"255",
b"GET",
b"u8",
b"#0"
]),
"*2\r\n:0\r\n:255\r\n"
);
assert_eq!(
f.run(&[
b"BITFIELD",
b"bf",
b"OVERFLOW",
b"SAT",
b"INCRBY",
b"i8",
b"0",
b"120",
b"INCRBY",
b"i8",
b"0",
b"120"
]),
"*2\r\n:119\r\n:127\r\n"
);
assert_eq!(
f.run(&[
b"BITFIELD",
b"bf2",
b"OVERFLOW",
b"FAIL",
b"INCRBY",
b"u2",
b"0",
b"5"
]),
"*1\r\n$-1\r\n"
);
assert_eq!(
f.run(&[
b"BITFIELD",
b"bf3",
b"OVERFLOW",
b"WRAP",
b"INCRBY",
b"u2",
b"0",
b"5"
]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"BITFIELD", b"bf3", b"GET", b"i64", b"0"]),
"*1\r\n:4611686018427387904\r\n"
);
}
/// A bad subcommand anywhere in the line stops all of it.
///
/// Redis checks the whole argument list before it runs any of it, so the
/// `SET` in front of the bad type here never happens and the key it would
/// have created is not there afterwards.
#[test]
fn a_bad_bitfield_subcommand_leaves_the_key_alone() {
let mut f = Fixture::new();
let bad_type = "-ERR Invalid bitfield type. Use something like i16 u8. Note that u64 is not supported but i64 is.\r\n";
assert_eq!(
f.run(&[
b"BITFIELD",
b"bad",
b"SET",
b"u8",
b"0",
b"1",
b"GET",
b"u99",
b"0"
]),
bad_type
);
assert_eq!(f.run(&[b"EXISTS", b"bad"]), ":0\r\n");
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"GET", b"u64", b"0"]),
bad_type
);
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"GET"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"NOPE", b"u8", b"0"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"OVERFLOW"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[
b"BITFIELD",
b"bad",
b"OVERFLOW",
b"NOPE",
b"GET",
b"u8",
b"0"
]),
"-ERR Invalid OVERFLOW type specified\r\n"
);
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"SET", b"u8", b"0", b"notanum"]),
"-ERR value is not an integer or out of range\r\n"
);
for at in [&b"#-1"[..], b"abc"] {
assert_eq!(
f.run(&[b"BITFIELD", b"bad", b"GET", b"u8", at]),
"-ERR bit offset is not an integer or out of range\r\n"
);
}
}
/// The read only twin reads, refuses to write, and creates nothing.
#[test]
fn bitfield_ro_answers_gets_and_refuses_the_rest() {
let mut f = Fixture::new();
f.run(&[b"SET", b"n", b"123"]);
assert_eq!(
f.run(&[b"BITFIELD_RO", b"n", b"GET", b"u8", b"0"]),
"*1\r\n:49\r\n"
);
// A read does not unpack an int the way a write does.
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"n"]), "$3\r\nint\r\n");
// An OVERFLOW word is allowed even though nothing here can overflow.
assert_eq!(
f.run(&[
b"BITFIELD_RO",
b"n",
b"OVERFLOW",
b"SAT",
b"GET",
b"u8",
b"0"
]),
"*1\r\n:49\r\n"
);
for sub in [&b"SET"[..], b"INCRBY"] {
assert_eq!(
f.run(&[b"BITFIELD_RO", b"n", sub, b"u8", b"0", b"1"]),
"-ERR BITFIELD_RO only supports the GET subcommand\r\n"
);
}
assert_eq!(
f.run(&[b"BITFIELD_RO", b"gone", b"GET", b"u8", b"100"]),
"*1\r\n:0\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"gone"]), ":0\r\n");
}
/// The offsets a bitmap command will not take.
#[test]
fn an_offset_off_the_end_of_the_world_is_refused() {
let mut f = Fixture::new();
let bad = "-ERR bit offset is not an integer or out of range\r\n";
for arg in [&b"abc"[..], b"-1", b"4294967296"] {
assert_eq!(f.run(&[b"SETBIT", b"k", arg, b"1"]), bad);
assert_eq!(f.run(&[b"GETBIT", b"k", arg]), bad);
}
for arg in [&b"2"[..], b"-1"] {
assert_eq!(
f.run(&[b"BITPOS", b"k", arg]),
"-ERR The bit argument must be 1 or 0.\r\n"
);
}
assert_eq!(
f.run(&[b"BITPOS", b"k", b"abc"]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"BITPOS", b"k", b"0", b"5", b"BIT"]),
"-ERR value is not an integer or out of range\r\n"
);
let bad_bit = "-ERR bit is not an integer or out of range\r\n";
assert_eq!(f.run(&[b"SETBIT", b"k", b"0", b"2"]), bad_bit);
assert_eq!(f.run(&[b"SETBIT", b"k", b"0", b"abc"]), bad_bit);
}
/// Every one of the seven refuses a key that is not a string.
#[test]
fn every_bitmap_command_says_wrongtype() {
let mut f = Fixture::new();
f.run(&[b"LPUSH", b"l", b"x"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
let cases: &[&[&[u8]]] = &[
&[b"SETBIT", b"l", b"0", b"1"],
&[b"GETBIT", b"l", b"0"],
&[b"BITCOUNT", b"l"],
&[b"BITPOS", b"l", b"1"],
&[b"BITOP", b"AND", b"d", b"l"],
&[b"BITFIELD", b"l", b"GET", b"u8", b"0"],
&[b"BITFIELD_RO", b"l", b"GET", b"u8", b"0"],
];
for case in cases {
assert_eq!(f.run(case), wrong, "{:?}", case[0]);
}
}
// --------------------------------------------------------- hyperloglogs
#[test]
fn a_sketch_is_added_to_and_counted() {
let mut f = Fixture::new();
// Creating the key counts as a change, even with nothing to add.
assert_eq!(f.run(&[b"PFADD", b"h"]), ":1\r\n");
assert_eq!(f.run(&[b"PFADD", b"h"]), ":0\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"h"]), ":0\r\n");
assert_eq!(f.run(&[b"STRLEN", b"h"]), ":18\r\n");
// And it is a string, which is not an implementation detail: a client
// can `GET` a sketch out of one server and `SET` it into another.
assert_eq!(f.run(&[b"TYPE", b"h"]), "+string\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"h"]), "$3\r\nraw\r\n");
assert_eq!(f.run(&[b"PFADD", b"h", b"a", b"b", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"PFADD", b"h", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"h"]), ":3\r\n");
}
#[test]
fn the_bytes_of_a_sketch_are_the_ones_a_real_server_writes() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"h", b"a", b"b", b"c"]);
// Not text, so it is compared as bytes.
let want = b"HYLL\x01\0\0\0\0\0\0\0\0\0\0\x80\x60\xf3\x80\x50\xb1\x84\x4b\xfb\x80\x42\x5a";
let mut reply = b"$27\r\n".to_vec();
reply.extend_from_slice(want);
reply.extend_from_slice(b"\r\n");
assert_eq!(f.raw(&[b"GET", b"h"]), reply);
}
#[test]
fn counting_several_keys_counts_their_union() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"a", b"x", b"y"]);
f.run(&[b"PFADD", b"b", b"y", b"z"]);
assert_eq!(f.run(&[b"PFCOUNT", b"a"]), ":2\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"a", b"b"]), ":3\r\n");
// A key that is not there is an empty sketch, not an error and not
// something that gets created by being counted.
assert_eq!(f.run(&[b"PFCOUNT", b"gone"]), ":0\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"a", b"gone"]), ":2\r\n");
assert_eq!(f.run(&[b"EXISTS", b"gone"]), ":0\r\n");
}
#[test]
fn a_merge_keeps_what_the_destination_had() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"a", b"x", b"y"]);
f.run(&[b"PFADD", b"b", b"z"]);
assert_eq!(f.run(&[b"PFMERGE", b"d", b"a", b"b"]), "+OK\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"d"]), ":3\r\n");
// The destination is one of the sources, so a second merge adds to it.
f.run(&[b"PFADD", b"c", b"w"]);
assert_eq!(f.run(&[b"PFMERGE", b"d", b"c"]), "+OK\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"d"]), ":4\r\n");
// And with no sources it is a no-op that still answers OK and still
// creates a destination that was not there.
assert_eq!(f.run(&[b"PFMERGE", b"fresh"]), "+OK\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"fresh"]), ":0\r\n");
}
#[test]
fn the_debug_forms_answer_four_different_shapes() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"h", b"a", b"b", b"c"]);
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"h"]), "+sparse\r\n");
assert_eq!(
f.run(&[b"PFDEBUG", b"DECODE", b"h"]),
"$44\r\nZ:8436 v:1,1 Z:4274 v:2,1 Z:3068 v:1,1 Z:603\r\n"
);
assert_eq!(f.run(&[b"PFDEBUG", b"TODENSE", b"h"]), ":1\r\n");
assert_eq!(f.run(&[b"PFDEBUG", b"TODENSE", b"h"]), ":0\r\n");
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"h"]), "+dense\r\n");
assert_eq!(f.run(&[b"STRLEN", b"h"]), ":12304\r\n");
assert_eq!(f.run(&[b"PFCOUNT", b"h"]), ":3\r\n");
// A dense sketch has no opcodes left to print.
assert_eq!(
f.run(&[b"PFDEBUG", b"DECODE", b"h"]),
"-ERR HLL encoding is not sparse\r\n"
);
// All 16384 registers, of which three are not nought.
let reply = f.run(&[b"PFDEBUG", b"GETREG", b"h"]);
assert!(reply.starts_with("*16384\r\n"), "{}", &reply[..16]);
assert_eq!(reply.matches(":0\r\n").count(), 16381);
assert_eq!(reply.matches(":1\r\n").count(), 2);
assert_eq!(reply.matches(":2\r\n").count(), 1);
assert_eq!(f.run(&[b"PFSELFTEST"]), "+OK\r\n");
}
#[test]
fn a_string_that_is_not_a_sketch_is_refused_with_its_own_sentence() {
let mut f = Fixture::new();
f.run(&[b"SET", b"plain", b"not a sketch"]);
let not_hll = "-WRONGTYPE Key is not a valid HyperLogLog string value.\r\n";
assert_eq!(f.run(&[b"PFADD", b"plain", b"a"]), not_hll);
assert_eq!(f.run(&[b"PFCOUNT", b"plain"]), not_hll);
assert_eq!(f.run(&[b"PFMERGE", b"plain"]), not_hll);
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"plain"]), not_hll);
// A key that is not a string at all gets the ordinary sentence, and a
// destination that would have been written is not created.
f.run(&[b"RPUSH", b"l", b"x"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
assert_eq!(f.run(&[b"PFADD", b"l", b"a"]), wrong);
assert_eq!(f.run(&[b"PFCOUNT", b"l"]), wrong);
assert_eq!(f.run(&[b"PFMERGE", b"dest", b"l"]), wrong);
assert_eq!(f.run(&[b"EXISTS", b"dest"]), ":0\r\n");
assert_eq!(f.run(&[b"PFDEBUG", b"GETREG", b"l"]), wrong);
}
#[test]
fn pfdebug_has_its_own_complaints() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"h", b"a"]);
// The word is quoted exactly as the client spelled it, and this is not
// the "Try X HELP." sentence every other container command uses.
assert_eq!(
f.run(&[b"PFDEBUG", b"NOPE", b"h"]),
"-ERR Unknown PFDEBUG subcommand 'NOPE'\r\n"
);
// Where all three of the real commands take a missing key as empty.
let gone = "-ERR The specified key does not exist\r\n";
assert_eq!(f.run(&[b"PFDEBUG", b"GETREG", b"missing"]), gone);
assert_eq!(f.run(&[b"PFDEBUG", b"DECODE", b"missing"]), gone);
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"missing"]), gone);
assert_eq!(f.run(&[b"PFDEBUG", b"TODENSE", b"missing"]), gone);
assert_eq!(
f.run(&[b"PFDEBUG"]),
"-ERR wrong number of arguments for 'pfdebug' command\r\n"
);
assert_eq!(
f.run(&[b"PFSELFTEST", b"x"]),
"-ERR wrong number of arguments for 'pfselftest' command\r\n"
);
}
#[test]
fn a_sketch_whose_opcodes_do_not_add_up_says_so() {
let mut f = Fixture::new();
f.run(&[b"PFADD", b"h", b"a", b"b", b"c"]);
// The sketch with its last byte cut off, which is still a header and a
// magic and is a run length encoding that stops short of register 16384.
let reply = f.raw(&[b"GET", b"h"]);
let short = reply[5..reply.len() - 3].to_vec();
f.run(&[b"SET", b"h", &short]);
assert_eq!(
f.run(&[b"PFCOUNT", b"h"]),
"-INVALIDOBJ Corrupted HLL object detected\r\n"
);
}
#[test]
fn a_sketch_survives_a_dump_and_a_restore_in_both_encodings() {
let mut f = Fixture::new();
// One that stays sparse and one that has gone dense, since the payload
// carries the bytes and the two encodings are different lengths.
f.run(&[b"PFADD", b"small", b"a", b"b", b"c"]);
for i in 0..10_000u32 {
let ele = format!("e{i}");
f.run(&[b"PFADD", b"big", ele.as_bytes()]);
}
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"small"]), "+sparse\r\n");
assert_eq!(f.run(&[b"PFDEBUG", b"ENCODING", b"big"]), "+dense\r\n");
for key in [&b"small"[..], b"big"] {
let mut copy = key.to_vec();
copy.push(b'2');
let bytes = payload(&f.raw(&[b"DUMP", key]));
assert_eq!(f.run(&[b"RESTORE", ©, b"0", &bytes]), "+OK\r\n");
// The bytes, the encoding and the estimate all come back, which is
// the whole of what byte compatibility across a round trip means.
assert_eq!(f.raw(&[b"GET", ©]), f.raw(&[b"GET", key]));
assert_eq!(
f.run(&[b"PFDEBUG", b"ENCODING", ©]),
f.run(&[b"PFDEBUG", b"ENCODING", key])
);
assert_eq!(f.run(&[b"PFCOUNT", ©]), f.run(&[b"PFCOUNT", key]));
}
assert_eq!(f.run(&[b"PFCOUNT", b"small2"]), ":3\r\n");
assert_eq!(f.run(&[b"STRLEN", b"big2"]), ":12304\r\n");
}
/// One RESP2 bulk string. The JSON replies are almost all one of these and
/// the text inside them has quotes in it, so writing the frame out by hand
/// buries the part of the assertion that matters.
fn bulk(s: &str) -> String {
format!("${}\r\n{s}\r\n", s.len())
}
/// A RESP2 array of bulk strings, which is what most of the list replies
/// are and what writing them out by hand in every assertion looks like.
fn bulks(parts: &[&str]) -> String {
let mut s = format!("*{}\r\n", parts.len());
for p in parts {
s.push_str(&format!("${}\r\n{p}\r\n", p.len()));
}
s
}
#[test]
fn a_list_is_pushed_from_both_ends_and_the_left_one_reverses() {
let mut f = Fixture::new();
// Each element in turn goes at the head, so the last one sent is at the
// front when it is over. That reads like a bug in the client and it is
// what every Redis has always done.
assert_eq!(f.run(&[b"LPUSH", b"k", b"a", b"b", b"c"]), ":3\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["c", "b", "a"])
);
assert_eq!(f.run(&[b"RPUSH", b"k", b"d"]), ":4\r\n");
assert_eq!(f.run(&[b"LLEN", b"k"]), ":4\r\n");
assert_eq!(f.run(&[b"LPOP", b"k"]), "$1\r\nc\r\n");
assert_eq!(f.run(&[b"RPOP", b"k"]), "$1\r\nd\r\n");
assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "a"]));
assert_eq!(f.run(&[b"TYPE", b"k"]), "+list\r\n");
}
#[test]
fn the_x_pushes_refuse_to_bring_a_list_back_to_life() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"LPUSHX", b"k", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"RPUSHX", b"k", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
f.run(&[b"RPUSH", b"k", b"a"]);
assert_eq!(f.run(&[b"LPUSHX", b"k", b"z"]), ":2\r\n");
assert_eq!(f.run(&[b"RPUSHX", b"k", b"y"]), ":3\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["z", "a", "y"])
);
}
/// The four ways a pop can come back with nothing, which are three
/// different replies and a RESP2 client can tell all of them apart.
#[test]
fn an_empty_pop_is_a_different_nothing_with_a_count_and_without() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"LPOP", b"nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"LPOP", b"nope", b"2"]), "*-1\r\n");
assert_eq!(f.run(&[b"RPOP", b"nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"RPOP", b"nope", b"2"]), "*-1\r\n");
f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
// A count of zero against a list that is there is an empty array and
// not a null array, which is the fourth answer.
assert_eq!(f.run(&[b"LPOP", b"k", b"0"]), "*0\r\n");
assert_eq!(f.run(&[b"LPOP", b"k", b"1"]), bulks(&["a"]));
// More than there is takes what there is and the key goes with it.
assert_eq!(f.run(&[b"RPOP", b"k", b"9"]), bulks(&["c", "b"]));
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
}
#[test]
fn a_pop_count_has_its_own_sentence_and_a_third_argument_is_an_arity_error() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a"]);
let range = "-ERR value is out of range, must be positive\r\n";
assert_eq!(f.run(&[b"LPOP", b"k", b"-1"]), range);
assert_eq!(f.run(&[b"LPOP", b"k", b"abc"]), range);
assert_eq!(f.run(&[b"RPOP", b"k", b"-1"]), range);
// Redis calls this an arity error and not a syntax error, which is a
// distinction it does not always make.
assert_eq!(
f.run(&[b"LPOP", b"k", b"1", b"2"]),
"-ERR wrong number of arguments for 'lpop' command\r\n"
);
assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n");
}
#[test]
fn a_range_takes_negative_ends_and_clamps_the_ones_that_run_off() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["a", "b", "c"])
);
assert_eq!(f.run(&[b"LRANGE", b"k", b"-2", b"-1"]), bulks(&["b", "c"]));
assert_eq!(f.run(&[b"LRANGE", b"k", b"1", b"1"]), bulks(&["b"]));
assert_eq!(f.run(&[b"LRANGE", b"k", b"5", b"10"]), "*0\r\n");
assert_eq!(f.run(&[b"LRANGE", b"k", b"2", b"1"]), "*0\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"-100", b"100"]),
bulks(&["a", "b", "c"])
);
// A key that is not there is an empty range and not a nil, which is the
// one place a list disagrees with a set.
assert_eq!(f.run(&[b"LRANGE", b"nope", b"0", b"-1"]), "*0\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"a", b"b"]),
"-ERR value is not an integer or out of range\r\n"
);
}
#[test]
fn an_index_reads_and_writes_from_whichever_end_is_nearer() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
assert_eq!(f.run(&[b"LINDEX", b"k", b"0"]), "$1\r\na\r\n");
assert_eq!(f.run(&[b"LINDEX", b"k", b"-1"]), "$1\r\nc\r\n");
assert_eq!(f.run(&[b"LINDEX", b"k", b"99"]), "$-1\r\n");
assert_eq!(f.run(&[b"LINDEX", b"nope", b"0"]), "$-1\r\n");
assert_eq!(f.run(&[b"LSET", b"k", b"-1", b"z"]), "+OK\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["a", "b", "z"])
);
// Both ways of missing are errors here rather than a nil, because a
// list is never empty and there is nothing else the reply could be.
assert_eq!(
f.run(&[b"LSET", b"k", b"99", b"z"]),
"-ERR index out of range\r\n"
);
assert_eq!(
f.run(&[b"LSET", b"nope", b"0", b"z"]),
"-ERR no such key\r\n"
);
}
#[test]
fn linsert_says_three_things_with_one_signed_number() {
let mut f = Fixture::new();
// Zero for a key that is not there, which is not the same as minus one
// for a pivot that is not in a list that is.
assert_eq!(
f.run(&[b"LINSERT", b"nope", b"BEFORE", b"a", b"x"]),
":0\r\n"
);
f.run(&[b"RPUSH", b"k", b"a", b"b"]);
assert_eq!(f.run(&[b"LINSERT", b"k", b"before", b"a", b"X"]), ":3\r\n");
assert_eq!(f.run(&[b"LINSERT", b"k", b"AFTER", b"b", b"Y"]), ":4\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["X", "a", "b", "Y"])
);
assert_eq!(
f.run(&[b"LINSERT", b"k", b"BEFORE", b"zz", b"x"]),
":-1\r\n"
);
assert_eq!(
f.run(&[b"LINSERT", b"k", b"SIDEWAYS", b"a", b"x"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn lrem_counts_in_three_directions_and_takes_the_key_when_it_empties() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b", b"a", b"c", b"a"]);
assert_eq!(f.run(&[b"LREM", b"k", b"2", b"a"]), ":2\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"k", b"0", b"-1"]),
bulks(&["b", "c", "a"])
);
assert_eq!(f.run(&[b"LREM", b"k", b"-1", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "c"]));
assert_eq!(f.run(&[b"LREM", b"k", b"0", b"b"]), ":1\r\n");
assert_eq!(f.run(&[b"LREM", b"k", b"0", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
assert_eq!(f.run(&[b"LREM", b"nope", b"0", b"a"]), ":0\r\n");
}
#[test]
fn ltrim_keeps_a_window_and_an_empty_one_deletes_the_key() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b", b"c", b"d"]);
assert_eq!(f.run(&[b"LTRIM", b"k", b"1", b"-2"]), "+OK\r\n");
assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["b", "c"]));
// `LTRIM k 1 0` is the documented way to empty a list, so it has to
// leave `EXISTS` answering zero rather than leaving an empty one.
assert_eq!(f.run(&[b"LTRIM", b"k", b"1", b"0"]), "+OK\r\n");
assert_eq!(f.run(&[b"EXISTS", b"k"]), ":0\r\n");
assert_eq!(f.run(&[b"LTRIM", b"nope", b"0", b"-1"]), "+OK\r\n");
}
#[test]
fn lpos_walks_from_either_end_and_stops_where_it_is_told() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"p", b"a", b"b", b"c", b"a", b"b", b"c", b"a"]);
assert_eq!(f.run(&[b"LPOS", b"p", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"LPOS", b"p", b"a", b"RANK", b"-1"]), ":6\r\n");
assert_eq!(f.run(&[b"LPOS", b"p", b"a", b"RANK", b"2"]), ":3\r\n");
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"2"]),
"*2\r\n:0\r\n:3\r\n"
);
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"RANK", b"-1", b"COUNT", b"0"]),
"*3\r\n:6\r\n:3\r\n:0\r\n"
);
// MAXLEN counts elements looked at and not matches found, so three
// stops after `a b c` and finds the one match in it.
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"0", b"MAXLEN", b"3"]),
"*1\r\n:0\r\n"
);
// Nothing found is three different replies depending on how it was
// asked and whether the key is there at all.
assert_eq!(f.run(&[b"LPOS", b"p", b"zz"]), "$-1\r\n");
assert_eq!(f.run(&[b"LPOS", b"p", b"zz", b"COUNT", b"0"]), "*0\r\n");
assert_eq!(f.run(&[b"LPOS", b"nope", b"a"]), "$-1\r\n");
assert_eq!(f.run(&[b"LPOS", b"nope", b"a", b"COUNT", b"2"]), "*0\r\n");
}
#[test]
fn lpos_words_its_three_mistakes_the_way_redis_does() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"p", b"a"]);
// The whole sentence and not a prefix, because the older wording of it
// is still all over the internet and clients match on the text.
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"RANK", b"0"]),
"-ERR RANK can't be zero: use 1 to start from the first match, 2 from the second ... or use negative to start from the end of the list\r\n"
);
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"COUNT", b"-1"]),
"-ERR COUNT can't be negative\r\n"
);
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"MAXLEN", b"-1"]),
"-ERR MAXLEN can't be negative\r\n"
);
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"RANK"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"LPOS", b"p", b"a", b"FOO", b"1"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn a_move_takes_from_one_end_and_gives_to_another_even_on_one_key() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b", b"c"]);
assert_eq!(f.run(&[b"RPOPLPUSH", b"k", b"d"]), "$1\r\nc\r\n");
assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["a", "b"]));
assert_eq!(f.run(&[b"LRANGE", b"d", b"0", b"-1"]), bulks(&["c"]));
assert_eq!(
f.run(&[b"LMOVE", b"k", b"d", b"LEFT", b"RIGHT"]),
"$1\r\na\r\n"
);
assert_eq!(f.run(&[b"LRANGE", b"d", b"0", b"-1"]), bulks(&["c", "a"]));
// The same key twice is the documented way to rotate a list and falls
// out of taking the element before deciding where to put it.
f.run(&[b"DEL", b"r"]);
f.run(&[b"RPUSH", b"r", b"1", b"2", b"3"]);
assert_eq!(f.run(&[b"RPOPLPUSH", b"r", b"r"]), "$1\r\n3\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"r", b"0", b"-1"]),
bulks(&["3", "1", "2"])
);
assert_eq!(
f.run(&[b"LMOVE", b"nope", b"d", b"LEFT", b"LEFT"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"LMOVE", b"r", b"d", b"LEFT", b"SIDEWAYS"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn a_move_checks_the_destination_before_it_takes_anything() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a", b"b"]);
f.run(&[b"SET", b"str", b"v"]);
assert_eq!(
f.run(&[b"LMOVE", b"k", b"str", b"LEFT", b"LEFT"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
// The element is still where it was, rather than having gone nowhere.
assert_eq!(f.run(&[b"LRANGE", b"k", b"0", b"-1"]), bulks(&["a", "b"]));
}
#[test]
fn a_block_move_orders_the_block_by_the_ends_and_the_ordering_word() {
// OBO is what you get from sending LMOVE that many times, BULK keeps
// the source order. The two only differ when both ends are the same,
// which is the whole reason the word exists.
for (from, to, order, want) in [
("LEFT", "RIGHT", "OBO", ["a", "b"]),
("LEFT", "RIGHT", "BULK", ["a", "b"]),
("LEFT", "LEFT", "OBO", ["b", "a"]),
("LEFT", "LEFT", "BULK", ["a", "b"]),
("RIGHT", "LEFT", "OBO", ["d", "e"]),
("RIGHT", "LEFT", "BULK", ["d", "e"]),
("RIGHT", "RIGHT", "OBO", ["e", "d"]),
("RIGHT", "RIGHT", "BULK", ["d", "e"]),
] {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"s", b"a", b"b", b"c", b"d", b"e"]);
let how = format!("{from} {to} {order}");
let reply = f.run(&[
b"LMOVEM",
b"s",
b"d",
from.as_bytes(),
to.as_bytes(),
b"COUNT",
b"2",
order.as_bytes(),
]);
assert_eq!(reply, bulks(&want), "the reply for {how}");
assert_eq!(
f.run(&[b"LRANGE", b"d", b"0", b"-1"]),
bulks(&want),
"the destination for {how}"
);
}
}
#[test]
fn a_block_move_of_one_needs_no_count_at_all() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"s", b"a", b"b", b"c"]);
assert_eq!(
f.run(&[b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT"]),
bulks(&["a"])
);
assert_eq!(f.run(&[b"LRANGE", b"s", b"0", b"-1"]), bulks(&["b", "c"]));
// Six and seven arguments are neither of the two forms, so the
// reference calls both of them a syntax error rather than guessing.
assert_eq!(
f.run(&[b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"2"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn a_block_move_with_exactly_takes_all_of_them_or_none() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"s", b"a", b"b", b"c"]);
// A null array and not a null bulk string, which `redis-cli` prints as
// `(nil)` either way and only the raw wire tells apart. What it would
// have sent is an array, so its nothing is an array's nothing.
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"EXACTLY", b"99", b"BULK"
]),
"*-1\r\n"
);
assert_eq!(
f.run(&[b"LRANGE", b"s", b"0", b"-1"]),
bulks(&["a", "b", "c"])
);
// COUNT takes what there is, and an emptied source goes away.
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"99", b"BULK"
]),
bulks(&["a", "b", "c"])
);
assert_eq!(f.run(&[b"EXISTS", b"s"]), ":0\r\n");
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"1", b"BULK"
]),
"*-1\r\n"
);
}
#[test]
fn a_block_move_onto_itself_rotates_by_the_count() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"s", b"a", b"b", b"c"]);
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"s", b"LEFT", b"RIGHT", b"COUNT", b"2", b"BULK"
]),
bulks(&["a", "b"])
);
assert_eq!(
f.run(&[b"LRANGE", b"s", b"0", b"-1"]),
bulks(&["c", "a", "b"])
);
}
#[test]
fn a_block_move_reads_the_count_before_the_ordering_word() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"s", b"a", b"b"]);
f.run(&[b"SET", b"str", b"v"]);
let count = "-ERR count should be greater than 0\r\n";
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"abc", b"NOPE"
]),
count
);
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"0", b"BULK"
]),
count
);
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"COUNT", b"1", b"NOPE"
]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"d", b"LEFT", b"RIGHT", b"NOPE", b"abc", b"BULK"
]),
"-ERR syntax error\r\n"
);
// Every argument is read before the keys are looked at, so a bad count
// beats a wrong type even when the type is wrong on the source.
assert_eq!(
f.run(&[
b"LMOVEM", b"str", b"d", b"LEFT", b"RIGHT", b"COUNT", b"abc", b"BULK"
]),
count
);
assert_eq!(
f.run(&[
b"LMOVEM", b"s", b"str", b"LEFT", b"RIGHT", b"COUNT", b"1", b"BULK"
]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
assert_eq!(f.run(&[b"LRANGE", b"s", b"0", b"-1"]), bulks(&["a", "b"]));
}
#[test]
fn lmpop_answers_from_the_first_key_that_has_anything() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"b", b"1", b"2", b"3"]);
// The name of the key that answered comes back with the elements,
// because the client cannot work out which one it was.
assert_eq!(
f.run(&[b"LMPOP", b"2", b"a", b"b", b"LEFT", b"COUNT", b"2"]),
"*2\r\n$1\r\nb\r\n*2\r\n$1\r\n1\r\n$1\r\n2\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"2", b"a", b"b", b"RIGHT"]),
"*2\r\n$1\r\nb\r\n*1\r\n$1\r\n3\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"b"]), ":0\r\n");
// A null array and not a null, even though what it stands in for is an
// array holding a key name and then another array.
assert_eq!(f.run(&[b"LMPOP", b"2", b"a", b"b", b"LEFT"]), "*-1\r\n");
}
#[test]
fn lmpop_has_its_own_words_for_a_count_and_for_a_key_count() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a"]);
assert_eq!(
f.run(&[b"LMPOP", b"0", b"k", b"LEFT"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"-1", b"k", b"LEFT"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"COUNT", b"0"]),
"-ERR count should be greater than 0\r\n"
);
// A key count that eats the direction is a syntax error and not a
// sentence about key counts, because the direction is simply not there.
assert_eq!(
f.run(&[b"LMPOP", b"3", b"k", b"LEFT"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"COUNT", b"1", b"x"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"1", b"k", b"LEFT", b"FOO", b"1"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"LMPOP", b"1", b"k", b"SIDEWAYS"]),
"-ERR syntax error\r\n"
);
assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n");
}
#[test]
fn every_list_command_says_wrongtype_and_writes_nothing() {
let mut f = Fixture::new();
f.run(&[b"SET", b"str", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"LPUSH".as_slice(), b"str", b"a"][..],
&[b"RPUSH", b"str", b"a"],
&[b"LPUSHX", b"str", b"a"],
&[b"RPUSHX", b"str", b"a"],
&[b"LPOP", b"str"],
&[b"LPOP", b"str", b"2"],
&[b"RPOP", b"str"],
&[b"LLEN", b"str"],
&[b"LRANGE", b"str", b"0", b"-1"],
&[b"LINDEX", b"str", b"0"],
&[b"LSET", b"str", b"0", b"a"],
&[b"LINSERT", b"str", b"BEFORE", b"a", b"b"],
&[b"LREM", b"str", b"0", b"a"],
&[b"LTRIM", b"str", b"0", b"-1"],
&[b"LPOS", b"str", b"a"],
&[b"LPOS", b"str", b"a", b"COUNT", b"0"],
&[b"RPOPLPUSH", b"str", b"d"],
&[b"LMOVE", b"str", b"d", b"LEFT", b"LEFT"],
&[b"LMPOP", b"1", b"str", b"LEFT"],
] {
assert_eq!(f.run(cmd), wrong, "{:?}", String::from_utf8_lossy(cmd[0]));
}
assert_eq!(f.run(&[b"GET", b"str"]), "$1\r\nv\r\n");
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
}
/// A timeout is not an integer and it is not an ordinary float either: the
/// three sentences it can answer with are its own, and which one a given
/// argument gets is not what reading the code would suggest.
#[test]
fn a_timeout_has_three_ways_of_being_wrong() {
let mut f = Fixture::new();
let not_float = "-ERR timeout is not a float or out of range\r\n";
let range = "-ERR timeout is out of range\r\n";
for (bad, want) in [
(&[b"BLPOP".as_slice(), b"k", b"abc"][..], not_float),
(&[b"BLPOP", b"k", b"nan"], not_float),
(&[b"BLPOP", b"k", b""], not_float),
// Whitespace on either side, which `strtold` would take and Redis
// does not.
(&[b"BLPOP", b"k", b" 1"], not_float),
(&[b"BLPOP", b"k", b"1 "], not_float),
(&[b"BLPOP", b"k", b"-1"], "-ERR timeout is negative\r\n"),
(&[b"BLPOP", b"k", b"-0.1"], "-ERR timeout is negative\r\n"),
// These three parse, so they are not the not-a-float error, and all
// three are further off than an i64 of milliseconds reaches.
(&[b"BLPOP", b"k", b"1e400"], range),
(&[b"BLPOP", b"k", b"inf"], range),
(&[b"BLPOP", b"k", b"9999999999999999"], range),
(&[b"BRPOP", b"k", b"abc"], not_float),
(
&[b"BLMOVE", b"a", b"b", b"LEFT", b"RIGHT", b"abc"],
not_float,
),
(
&[b"BRPOPLPUSH", b"a", b"b", b"-1"],
"-ERR timeout is negative\r\n",
),
(&[b"BLMPOP", b"abc", b"1", b"k", b"LEFT"], not_float),
] {
assert_eq!(f.run(bad), want, "for {bad:?}");
}
}
/// A timeout of exactly zero means no timeout, and there are two ways of
/// writing exactly zero.
#[test]
fn a_zero_timeout_waits_and_the_smallest_positive_one_does_not() {
let mut f = Fixture::new();
for timeout in [b"0".as_slice(), b"0.0", b"-0.0"] {
let (flow, out) = f.flow(&[b"BLPOP", b"k", timeout]);
assert_eq!(flow, Flow::Block, "for {timeout:?}");
assert!(out.is_empty(), "for {timeout:?}");
}
// Positive, so it is a real deadline, and the deadline is this
// millisecond. Nothing is written here either: the reply comes from the
// sweep, which is the engine's and not this layer's.
let (flow, out) = f.flow(&[b"BLPOP", b"k", b"0.0000001"]);
assert_eq!(flow, Flow::Block);
assert!(out.is_empty());
}
#[test]
fn a_blocking_command_that_can_be_answered_answers_like_the_one_it_wraps() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"L", b"a", b"b", b"c", b"d", b"e"]);
// The one difference from LPOP: the reply names the key that answered,
// which is what makes BLPOP over several keys usable.
assert_eq!(
f.flow(&[b"BLPOP", b"nope", b"L", b"0"]),
(Flow::Continue, "*2\r\n$1\r\nL\r\n$1\r\na\r\n".to_owned())
);
assert_eq!(
f.run(&[b"BRPOP", b"L", b"0"]),
"*2\r\n$1\r\nL\r\n$1\r\ne\r\n"
);
assert_eq!(
f.run(&[
b"BLMPOP", b"0", b"2", b"nope", b"L", b"LEFT", b"COUNT", b"2"
]),
"*2\r\n$1\r\nL\r\n*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"BLMOVE", b"L", b"D", b"LEFT", b"RIGHT", b"0"]),
"$1\r\nd\r\n"
);
assert_eq!(
f.run(&[b"EXISTS", b"L"]),
":0\r\n",
"and the key went with it"
);
assert_eq!(f.run(&[b"LRANGE", b"D", b"0", b"-1"]), "*1\r\n$1\r\nd\r\n");
// Onto itself, which is how a list is rotated and is a real thing to ask
// a blocking move for.
f.run(&[b"RPUSH", b"D", b"x"]);
assert_eq!(f.run(&[b"BRPOPLPUSH", b"D", b"D", b"0"]), "$1\r\nx\r\n");
assert_eq!(
f.run(&[b"LRANGE", b"D", b"0", b"-1"]),
"*2\r\n$1\r\nx\r\n$1\r\nd\r\n"
);
}
#[test]
fn blmpop_reads_its_count_and_its_key_count_the_way_lmpop_does() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"k", b"a"]);
for (bad, want) in [
(
&[b"BLMPOP".as_slice(), b"0", b"0", b"k", b"LEFT"][..],
"-ERR numkeys should be greater than 0\r\n",
),
(
&[b"BLMPOP", b"0", b"-1", b"k", b"LEFT"],
"-ERR numkeys should be greater than 0\r\n",
),
// Two keys named and one given, so the word that should have been
// the direction is a key and there is no direction left.
(
&[b"BLMPOP", b"0", b"2", b"k", b"LEFT"],
"-ERR syntax error\r\n",
),
(
&[b"BLMPOP", b"0", b"1", b"k", b"SIDEWAYS"],
"-ERR syntax error\r\n",
),
(
&[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT"],
"-ERR syntax error\r\n",
),
(
&[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"2", b"x"],
"-ERR syntax error\r\n",
),
// A count that is not a number at all gets the same sentence a zero
// or a negative one gets, rather than the usual one about integers.
(
&[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"0"],
"-ERR count should be greater than 0\r\n",
),
(
&[b"BLMPOP", b"0", b"1", b"k", b"LEFT", b"COUNT", b"abc"],
"-ERR count should be greater than 0\r\n",
),
] {
assert_eq!(f.run(bad), want, "for {bad:?}");
}
assert_eq!(f.run(&[b"LLEN", b"k"]), ":1\r\n", "and none of them popped");
}
#[test]
fn a_blocking_move_reads_its_directions_before_its_timeout() {
let mut f = Fixture::new();
// Both are wrong. Redis checks the directions first, so this is the
// syntax error and not a complaint about the timeout.
assert_eq!(
f.run(&[b"BLMOVE", b"a", b"b", b"UP", b"DOWN", b"abc"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"BLMOVE", b"a", b"b", b"LEFT", b"DOWN", b"0.05"]),
"-ERR syntax error\r\n"
);
}
/// `BLMOVEM` answers exactly what `LMOVEM` answers when it does not have to
/// wait, which is the same relationship every other command in this file has
/// with the one it wraps.
#[test]
fn a_blocking_block_move_that_can_be_answered_answers_like_lmovem() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"L", b"a", b"b", b"c", b"d", b"e"]);
assert_eq!(
f.flow(&[b"BLMOVEM", b"L", b"D", b"LEFT", b"RIGHT", b"0"]),
(Flow::Continue, "*1\r\n$1\r\na\r\n".to_owned())
);
assert_eq!(
f.run(&[
b"BLMOVEM", b"L", b"D", b"RIGHT", b"RIGHT", b"0", b"COUNT", b"2", b"OBO"
]),
bulks(&["e", "d"])
);
assert_eq!(
f.run(&[b"LRANGE", b"D", b"0", b"-1"]),
bulks(&["a", "e", "d"])
);
// `EXACTLY` with enough there does not wait either.
assert_eq!(
f.run(&[
b"BLMOVEM", b"L", b"D", b"LEFT", b"RIGHT", b"0", b"EXACTLY", b"2", b"BULK"
]),
bulks(&["b", "c"])
);
assert_eq!(f.run(&[b"EXISTS", b"L"]), ":0\r\n", "and the key went");
}
/// The one thing `BLMOVEM` decides differently from the other five: `COUNT`
/// is ready as soon as there is anything and `EXACTLY` is not ready until the
/// whole block has arrived.
#[test]
fn a_blocking_block_move_waits_for_the_whole_block_only_under_exactly() {
let mut f = Fixture::new();
f.run(&[b"RPUSH", b"L", b"a", b"b"]);
// Two there and three asked for. `COUNT` takes the two.
assert_eq!(
f.flow(&[
b"BLMOVEM", b"L", b"D", b"LEFT", b"RIGHT", b"0", b"COUNT", b"3", b"BULK"
]),
(Flow::Continue, bulks(&["a", "b"]))
);
f.run(&[b"RPUSH", b"L", b"a", b"b"]);
// The same line with `EXACTLY` parks instead, and takes nothing on the
// way past.
assert_eq!(
f.flow(&[
b"BLMOVEM", b"L", b"D", b"LEFT", b"RIGHT", b"0", b"EXACTLY", b"3", b"BULK"
])
.0,
Flow::Block
);
assert_eq!(f.run(&[b"LRANGE", b"L", b"0", b"-1"]), bulks(&["a", "b"]));
}
#[test]
fn a_blocking_block_move_reads_its_directions_then_its_timeout_then_its_count() {
let mut f = Fixture::new();
let syntax = "-ERR syntax error\r\n";
// All three are wrong and the directions are read first.
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"UP", b"DOWN", b"abc", b"NOPE", b"x", b"y"
]),
syntax
);
// Directions fine, timeout and count both wrong, so the timeout wins.
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"abc", b"COUNT", b"abc", b"BULK"
]),
"-ERR timeout is not a float or out of range\r\n"
);
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"-1", b"COUNT", b"1", b"BULK"
]),
"-ERR timeout is negative\r\n"
);
// And with the timeout fine, the count before the ordering word.
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"0", b"COUNT", b"abc", b"NOPE"
]),
"-ERR count should be greater than 0\r\n"
);
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"0", b"COUNT", b"1", b"NOPE"
]),
syntax
);
// Seven and eight arguments are neither of the two forms, the same way
// six and seven are for `LMOVEM`.
assert_eq!(
f.run(&[b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"0", b"COUNT"]),
syntax
);
assert_eq!(
f.run(&[
b"BLMOVEM", b"a", b"b", b"LEFT", b"RIGHT", b"0", b"COUNT", b"2"
]),
syntax
);
}
/// The four ways a blocking command sees a key of another type, and the one
/// way it does not.
#[test]
fn a_blocking_command_errors_on_a_wrong_type_rather_than_waiting_on_it() {
let mut f = Fixture::new();
f.run(&[b"SET", b"S", b"v"]);
f.run(&[b"RPUSH", b"D", b"x"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
assert_eq!(f.run(&[b"BLPOP", b"S", b"0"]), wrong);
// Every key is checked even when an earlier one would have blocked, so
// an empty key in front of a string does not hide it.
assert_eq!(f.run(&[b"BLPOP", b"E", b"S", b"0"]), wrong);
assert_eq!(f.run(&[b"BRPOP", b"S", b"0"]), wrong);
assert_eq!(f.run(&[b"BLMPOP", b"0", b"1", b"S", b"LEFT"]), wrong);
assert_eq!(f.run(&[b"BRPOPLPUSH", b"S", b"D", b"0"]), wrong);
// The destination, which is only reached because the source has
// something in it.
assert_eq!(f.run(&[b"BRPOPLPUSH", b"D", b"S", b"0"]), wrong);
assert_eq!(f.run(&[b"LRANGE", b"D", b"0", b"-1"]), "*1\r\n$1\r\nx\r\n");
assert_eq!(
f.run(&[b"BLMOVEM", b"S", b"D", b"LEFT", b"RIGHT", b"0"]),
wrong
);
assert_eq!(
f.run(&[b"BLMOVEM", b"D", b"S", b"LEFT", b"RIGHT", b"0"]),
wrong
);
// And the one that does not: an empty source means the destination is
// never looked at, so this waits rather than erroring, and on a real
// server it times out.
assert_eq!(
f.flow(&[b"BLMOVE", b"E", b"S", b"LEFT", b"RIGHT", b"0.1"])
.0,
Flow::Block
);
// `BLMOVEM` has a second way of not being ready, and it hides the
// destination just as well: the source is a list with two elements in it
// and `EXACTLY` wants three, so the string never gets looked at.
assert_eq!(
f.flow(&[b"BLMOVEM", b"E", b"S", b"LEFT", b"RIGHT", b"0.1"])
.0,
Flow::Block
);
f.run(&[b"RPUSH", b"E", b"1", b"2"]);
assert_eq!(
f.flow(&[
b"BLMOVEM", b"E", b"S", b"LEFT", b"RIGHT", b"0.1", b"EXACTLY", b"3", b"BULK"
])
.0,
Flow::Block
);
}
/// The same churn the set and the string get, because a list that leaks a
/// chunk per push looks exactly like one that does not until it has run for
/// an afternoon.
#[test]
fn churning_lists_does_not_grow_the_server() {
let mut f = Fixture::new();
let vals: Vec<Vec<u8>> = (0..200).map(|i| format!("v{i}").into_bytes()).collect();
let args: Vec<&[u8]> = [&b"RPUSH"[..], &b"k"[..]]
.into_iter()
.chain(vals.iter().map(Vec::as_slice))
.collect();
f.run(&args);
f.run(&[b"DEL", b"k"]);
f.server.compact_step();
let after_first = f.server.memory_bytes();
for _ in 0..200 {
f.run(&args);
f.run(&[b"LTRIM", b"k", b"1", b"0"]);
f.server.compact_step();
}
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
assert!(
f.server.memory_bytes() <= after_first * 2,
"held {} after two hundred passes against {after_first} after one",
f.server.memory_bytes()
);
}
// ------------------------------------------------------------ sorted set
#[test]
fn a_sorted_set_takes_scores_and_gives_them_back() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b"]), ":2\r\n");
assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"ZCARD", b"z"]), ":3\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), "$1\r\n2\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"nokey", b"b"]), "$-1\r\n");
assert_eq!(
f.run(&[b"ZMSCORE", b"z", b"a", b"nope", b"c"]),
"*3\r\n$1\r\n1\r\n$-1\r\n$1\r\n3\r\n"
);
assert_eq!(f.run(&[b"ZREM", b"z", b"a", b"nope"]), ":1\r\n");
assert_eq!(f.run(&[b"ZCARD", b"z"]), ":2\r\n");
// The key goes when the last member does.
assert_eq!(f.run(&[b"ZREM", b"z", b"b", b"c"]), ":2\r\n");
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
}
#[test]
fn a_score_is_a_double_on_resp3_and_digits_on_resp2() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1.5", b"a", b"inf", b"b", b"-inf", b"c"]);
assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), "$3\r\n1.5\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), "$3\r\ninf\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"c"]), "$4\r\n-inf\r\n");
f.out = Out::new(Proto::Resp3);
assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), ",1.5\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"b"]), ",inf\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"c"]), ",-inf\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"nope"]), "_\r\n");
}
#[test]
fn the_zadd_options_gate_what_gets_written() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"5", b"a"]);
// NX leaves a member that is there alone, XX will not create one.
assert_eq!(f.run(&[b"ZADD", b"z", b"NX", b"9", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"a"]), "$1\r\n5\r\n");
assert_eq!(f.run(&[b"ZADD", b"z", b"XX", b"9", b"new"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":1\r\n");
// GT and LT only move a score one way.
assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"CH", b"3", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"CH", b"7", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"ZADD", b"z", b"LT", b"CH", b"9", b"a"]), ":0\r\n");
// CH counts a moved score and plain ZADD does not.
assert_eq!(f.run(&[b"ZADD", b"z", b"1", b"a", b"1", b"b"]), ":1\r\n");
assert_eq!(
f.run(&[b"ZADD", b"z", b"CH", b"2", b"a", b"2", b"c"]),
":2\r\n"
);
}
#[test]
fn zadd_incr_answers_a_score_or_nothing_at_all() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"5", b"m"]), "$1\r\n5\r\n");
assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"2", b"m"]), "$1\r\n7\r\n");
// A gate that refuses is the string nil, because the reply it stands in
// for is a score.
assert_eq!(
f.run(&[b"ZADD", b"z", b"NX", b"INCR", b"2", b"m"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"ZADD", b"z", b"XX", b"INCR", b"2", b"gone"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"ZADD", b"z", b"GT", b"INCR", b"-1", b"m"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"ZADD", b"z", b"GT", b"INCR", b"1", b"m"]),
"$1\r\n8\r\n"
);
assert_eq!(f.run(&[b"ZINCRBY", b"z", b"2", b"m"]), "$2\r\n10\r\n");
assert_eq!(f.run(&[b"ZINCRBY", b"z", b"1", b"fresh"]), "$1\r\n1\r\n");
}
#[test]
fn the_two_infinities_will_not_be_added_together() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"inf", b"m"]);
let nan = "-ERR resulting score is not a number (NaN)\r\n";
assert_eq!(f.run(&[b"ZINCRBY", b"z", b"-inf", b"m"]), nan);
assert_eq!(f.run(&[b"ZADD", b"z", b"INCR", b"-inf", b"m"]), nan);
assert_eq!(f.run(&[b"ZSCORE", b"z", b"m"]), "$3\r\ninf\r\n");
// And a key made for an increment that then fails does not stay behind.
assert_eq!(f.run(&[b"ZINCRBY", b"gone", b"1", b"m"]), "$1\r\n1\r\n");
}
#[test]
fn zadd_says_its_mistakes_the_way_redis_says_them() {
let mut f = Fixture::new();
// The pairs are counted before the options are looked at, so this is a
// syntax error about having none and not a complaint about NX and XX.
assert_eq!(
f.run(&[b"ZADD", b"z", b"NX", b"XX"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ZADD", b"z", b"NX", b"XX", b"1", b"a"]),
"-ERR XX and NX options at the same time are not compatible\r\n"
);
let gtlt = "-ERR GT, LT, and/or NX options at the same time are not compatible\r\n";
assert_eq!(f.run(&[b"ZADD", b"z", b"NX", b"GT", b"1", b"a"]), gtlt);
assert_eq!(f.run(&[b"ZADD", b"z", b"GT", b"LT", b"1", b"a"]), gtlt);
assert_eq!(
f.run(&[b"ZADD", b"z", b"INCR", b"1", b"a", b"2", b"b"]),
"-ERR INCR option supports a single increment-element pair\r\n"
);
// An odd number of arguments after the options.
assert_eq!(
f.run(&[b"ZADD", b"z", b"1", b"a", b"2"]),
"-ERR syntax error\r\n"
);
// Every score is read before the first is stored.
assert_eq!(
f.run(&[b"ZADD", b"z", b"1", b"a", b"nonsense", b"b"]),
"-ERR value is not a valid float\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
}
#[test]
fn a_rank_says_where_a_member_sits_from_either_end() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(f.run(&[b"ZRANK", b"z", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"ZRANK", b"z", b"c"]), ":2\r\n");
assert_eq!(f.run(&[b"ZREVRANK", b"z", b"c"]), ":0\r\n");
assert_eq!(f.run(&[b"ZREVRANK", b"z", b"a"]), ":2\r\n");
// WITHSCORE changes both shapes: the answer and the nothing.
assert_eq!(
f.run(&[b"ZRANK", b"z", b"b", b"WITHSCORE"]),
"*2\r\n:1\r\n$1\r\n2\r\n"
);
assert_eq!(f.run(&[b"ZRANK", b"z", b"nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"ZRANK", b"z", b"nope", b"WITHSCORE"]), "*-1\r\n");
assert_eq!(f.run(&[b"ZRANK", b"nokey", b"a", b"WITHSCORE"]), "*-1\r\n");
// A bad option is a syntax error and one argument too many is an arity
// error, which is Redis's split.
assert_eq!(
f.run(&[b"ZRANK", b"z", b"b", b"bogus"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ZREVRANK", b"z", b"b", b"WITHSCORE", b"more"]),
"-ERR wrong number of arguments for 'zrevrank' command\r\n"
);
}
#[test]
fn the_two_counts_read_their_two_kinds_of_bound() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(f.run(&[b"ZCOUNT", b"z", b"-inf", b"+inf"]), ":3\r\n");
assert_eq!(f.run(&[b"ZCOUNT", b"z", b"2", b"3"]), ":2\r\n");
assert_eq!(f.run(&[b"ZCOUNT", b"z", b"(1", b"3"]), ":2\r\n");
assert_eq!(f.run(&[b"ZCOUNT", b"z", b"(1", b"(3"]), ":1\r\n");
assert_eq!(f.run(&[b"ZCOUNT", b"nokey", b"-inf", b"+inf"]), ":0\r\n");
assert_eq!(
f.run(&[b"ZCOUNT", b"z", b"bogus", b"3"]),
"-ERR min or max is not a float\r\n"
);
f.run(&[b"ZADD", b"l", b"0", b"a", b"0", b"b", b"0", b"c"]);
assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"-", b"+"]), ":3\r\n");
assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"[a", b"(c"]), ":2\r\n");
assert_eq!(f.run(&[b"ZLEXCOUNT", b"l", b"(a", b"+"]), ":2\r\n");
// A bare member is not a bound, because a member can start with any
// byte and there would be no way to say the bracket if it were optional.
assert_eq!(
f.run(&[b"ZLEXCOUNT", b"l", b"a", b"c"]),
"-ERR min or max not valid string range item\r\n"
);
}
/// The three ways `ZRANGE` can be asked for a window, forwards and back.
///
/// Every byte in here was read off a real 8.10.1 rather than worked out,
/// because the interesting part of this command is not what it selects, it
/// is which of the two ends the client is expected to name first.
#[test]
fn one_range_command_selects_by_rank_or_score_or_name() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
"*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"-2", b"-1"]),
"*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(f.run(&[b"ZRANGE", b"z", b"5", b"9"]), "*0\r\n");
assert_eq!(f.run(&[b"ZRANGE", b"nokey", b"0", b"-1"]), "*0\r\n");
// REV over ranks reverses the walk and leaves the two arguments alone,
// because a rank counts from the end the walk starts at.
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"REV"]),
"*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"(1", b"+inf", b"BYSCORE"]),
"*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
// And REV over scores does swap them, since a bound does not count from
// anywhere. This is the one line of the parse that tells the two apart.
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"+inf", b"(1", b"BYSCORE", b"REV"]),
"*2\r\n$1\r\nc\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"-", b"+", b"BYLEX"]),
"*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"+", b"-", b"BYLEX", b"REV"]),
"*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
);
}
/// The older spellings, which are the same six windows with the mode in the
/// name and the high end named first on the three that go backwards.
#[test]
fn the_older_range_spellings_name_their_high_end_first() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.run(&[b"ZREVRANGE", b"z", b"0", b"-1"]),
"*3\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\na\r\n"
);
assert_eq!(
f.run(&[b"ZREVRANGE", b"z", b"0", b"0", b"WITHSCORES"]),
"*2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
assert_eq!(
f.run(&[b"ZRANGEBYSCORE", b"z", b"(1", b"3"]),
"*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"ZREVRANGEBYSCORE", b"z", b"3", b"(1"]),
"*2\r\n$1\r\nc\r\n$1\r\nb\r\n"
);
// The two arguments the wrong way round is an empty answer and not an
// error, which is what the swap being in the parse rather than in the
// window buys.
assert_eq!(f.run(&[b"ZREVRANGEBYSCORE", b"z", b"(1", b"3"]), "*0\r\n");
assert_eq!(
f.run(&[b"ZRANGEBYLEX", b"z", b"[a", b"(c"]),
"*2\r\n$1\r\na\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[b"ZREVRANGEBYLEX", b"z", b"(c", b"[a"]),
"*2\r\n$1\r\nb\r\n$1\r\na\r\n"
);
// BYSCORE, BYLEX and REV mean nothing to these, so they are not another
// way of spelling the mode, they are a syntax error.
for cmd in [
&[b"ZREVRANGE".as_slice(), b"z", b"0", b"-1", b"BYSCORE"][..],
&[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"REV"],
&[b"ZRANGEBYLEX", b"z", b"[a", b"[c", b"BYLEX"],
] {
assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{:?}", cmd[0]);
}
}
/// `LIMIT` and `WITHSCORES`, which every one of these commands reads and
/// only some of them accept.
#[test]
fn limit_and_withscores_are_read_by_all_of_them_and_refused_afterwards() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.run(&[
b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"1", b"1"
]),
"*1\r\n$1\r\nb\r\n"
);
// A negative offset skips past everything, a negative count is no bound.
assert_eq!(
f.run(&[
b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"-1", b"2"
]),
"*0\r\n"
);
assert_eq!(
f.run(&[
b"ZRANGE", b"z", b"-inf", b"+inf", b"BYSCORE", b"LIMIT", b"0", b"-1"
]),
"*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
// The two options in either order, which falls out of the parse loop.
let both = "*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n";
assert_eq!(
f.run(&[
b"ZRANGEBYSCORE",
b"z",
b"1",
b"3",
b"WITHSCORES",
b"LIMIT",
b"0",
b"2"
]),
both
);
assert_eq!(
f.run(&[
b"ZRANGEBYSCORE",
b"z",
b"1",
b"3",
b"LIMIT",
b"0",
b"2",
b"WITHSCORES"
]),
both
);
// LIMIT on a range by rank is refused after the whole option list has
// been read, so this complains about LIMIT and not about WITHSCORES.
let needs_by = "-ERR syntax error, LIMIT is only supported in combination with either BYSCORE or BYLEX\r\n";
assert_eq!(
f.run(&[
b"ZREVRANGE",
b"z",
b"0",
b"-1",
b"WITHSCORES",
b"LIMIT",
b"0",
b"1"
]),
needs_by
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"LIMIT", b"0", b"1"]),
needs_by
);
let not_bylex = "-ERR syntax error, WITHSCORES not supported in combination with BYLEX\r\n";
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"-", b"+", b"BYLEX", b"WITHSCORES"]),
not_bylex
);
assert_eq!(
f.run(&[b"ZRANGEBYLEX", b"z", b"[a", b"[c", b"WITHSCORES"]),
not_bylex
);
// Two modes at once, an option nobody knows, a LIMIT missing its count,
// and the three number errors, which are three different sentences.
for cmd in [
&[
b"ZRANGE".as_slice(),
b"z",
b"0",
b"-1",
b"BYSCORE",
b"BYLEX",
][..],
&[b"ZRANGE", b"z", b"0", b"-1", b"junk"],
&[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"LIMIT", b"0"],
] {
assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
}
assert_eq!(
f.run(&[b"ZRANGEBYSCORE", b"z", b"bad", b"3"]),
"-ERR min or max is not a float\r\n"
);
assert_eq!(
f.run(&[b"ZRANGEBYLEX", b"z", b"a", b"[c"]),
"-ERR min or max not valid string range item\r\n"
);
assert_eq!(
f.run(&[b"ZRANGEBYSCORE", b"z", b"1", b"3", b"LIMIT", b"a", b"2"]),
"-ERR value is not an integer or out of range\r\n"
);
}
/// `WITHSCORES` is the one place in this group where the two protocols
/// disagree about the shape of the reply and not just the type of a value.
#[test]
fn withscores_nests_on_resp3_and_flattens_on_resp2() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
"*6\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
f.out = Out::new(Proto::Resp3);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
"*3\r\n*2\r\n$1\r\na\r\n,1\r\n*2\r\n$1\r\nb\r\n,2\r\n*2\r\n$1\r\nc\r\n,3\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
"*3\r\n$1\r\na\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
}
/// The store form, which is the same parse with the destination in front.
#[test]
fn a_range_store_writes_the_window_into_another_key() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(f.run(&[b"ZRANGESTORE", b"d", b"z", b"0", b"-1"]), ":3\r\n");
// A window that selects nothing deletes the destination rather than
// leaving an empty sorted set, because an empty one does not exist.
assert_eq!(f.run(&[b"ZRANGESTORE", b"d", b"z", b"5", b"9"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
assert_eq!(
f.run(&[b"ZRANGESTORE", b"d", b"z", b"(1", b"+inf", b"BYSCORE"]),
":2\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"d", b"0", b"-1", b"WITHSCORES"]),
"*4\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
// The destination is allowed to be the source, because the result is
// built whole before anything is written over.
assert_eq!(f.run(&[b"ZRANGESTORE", b"z", b"z", b"1", b"2"]), ":2\r\n");
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1", b"WITHSCORES"]),
"*4\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
// It takes every option ZRANGE takes except WITHSCORES, which is a
// plain syntax error here and not the sentence about BYLEX.
assert_eq!(
f.run(&[b"ZRANGESTORE", b"d", b"z", b"0", b"-1", b"WITHSCORES"]),
"-ERR syntax error\r\n"
);
}
/// The three removals, which are the read side's window with the walk
/// turned into a removal and no options at all.
#[test]
fn the_three_removals_share_their_window_with_the_reads() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(f.run(&[b"ZREMRANGEBYRANK", b"z", b"0", b"0"]), ":1\r\n");
assert_eq!(
f.run(&[b"ZRANGE", b"z", b"0", b"-1"]),
"*2\r\n$1\r\nb\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"ZREMRANGEBYSCORE", b"z", b"(2", b"+inf"]),
":1\r\n"
);
assert_eq!(f.run(&[b"ZRANGE", b"z", b"0", b"-1"]), "*1\r\n$1\r\nb\r\n");
// The last member going takes the key with it.
assert_eq!(f.run(&[b"ZREMRANGEBYLEX", b"z", b"-", b"+"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
assert_eq!(
f.run(&[b"ZREMRANGEBYRANK", b"nokey", b"0", b"-1"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"ZREMRANGEBYRANK", b"z", b"0", b"x"]),
"-ERR value is not an integer or out of range\r\n"
);
}
/// The algebra, which is one gather and three names for it.
#[test]
fn the_three_algebra_commands_combine_scores_and_order_the_answer_once() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"d"]);
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"y"]),
"*4\r\n$1\r\na\r\n$1\r\nc\r\n$1\r\nb\r\n$1\r\nd\r\n"
);
// The scores are added where a member is in both, and the answer comes
// out in the order those combined scores put it in.
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"y", b"WITHSCORES"]),
"*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n12\r\n$1\r\nd\r\n$2\r\n20\r\n"
);
assert_eq!(
f.run(&[
b"ZUNION",
b"2",
b"z",
b"y",
b"WEIGHTS",
b"2",
b"3",
b"WITHSCORES"
]),
"*8\r\n$1\r\na\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n6\r\n$1\r\nb\r\n$2\r\n34\r\n$1\r\nd\r\n$2\r\n60\r\n"
);
assert_eq!(
f.run(&[
b"ZUNION",
b"2",
b"z",
b"y",
b"AGGREGATE",
b"MIN",
b"WITHSCORES"
]),
"*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nd\r\n$2\r\n20\r\n"
);
assert_eq!(
f.run(&[
b"ZUNION",
b"2",
b"z",
b"y",
b"AGGREGATE",
b"MAX",
b"WITHSCORES"
]),
"*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n10\r\n$1\r\nd\r\n$2\r\n20\r\n"
);
assert_eq!(
f.run(&[b"ZINTER", b"2", b"z", b"y", b"WITHSCORES"]),
"*2\r\n$1\r\nb\r\n$2\r\n12\r\n"
);
assert_eq!(
f.run(&[b"ZDIFF", b"2", b"z", b"y", b"WITHSCORES"]),
"*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
assert_eq!(f.run(&[b"ZUNION", b"1", b"nokey"]), "*0\r\n");
// A plain set is an input, and it behaves as a sorted set in which
// every member scores one.
f.run(&[b"SADD", b"p", b"a", b"d"]);
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"p", b"WITHSCORES"]),
"*8\r\n$1\r\nd\r\n$1\r\n1\r\n$1\r\na\r\n$1\r\n2\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
// A difference never combines two scores, so it has nothing for either
// of the two options to do and refuses both.
for cmd in [
&[
b"ZDIFF".as_slice(),
b"2",
b"z",
b"y",
b"WEIGHTS",
b"1",
b"1",
][..],
&[b"ZDIFF", b"2", b"z", b"y", b"AGGREGATE", b"MIN"],
] {
assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
}
}
/// The count of keys, which is what lets a key be named `WEIGHTS`.
#[test]
fn the_algebra_counts_its_keys_and_says_so_when_the_count_is_wrong() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a"]);
f.run(&[b"ZADD", b"y", b"2", b"b"]);
// Redis names the command in this one, so each spelling says its own.
assert_eq!(
f.run(&[b"ZUNION", b"0", b"z"]),
"-ERR at least 1 input key is needed for 'zunion' command\r\n"
);
assert_eq!(
f.run(&[b"ZUNION", b"-1", b"z"]),
"-ERR at least 1 input key is needed for 'zunion' command\r\n"
);
assert_eq!(
f.run(&[b"ZINTERCARD", b"0", b"z"]),
"-ERR at least 1 input key is needed for 'zintercard' command\r\n"
);
// A count bigger than the line is a plain syntax error, which reads
// oddly and is what Redis says.
assert_eq!(
f.run(&[b"ZUNION", b"3", b"z", b"y"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ZUNION", b"x", b"z"]),
"-ERR value is not an integer or out of range\r\n"
);
// A WEIGHTS list that is not one per key is a syntax error, and a
// weight that is not a number gets a sentence of its own.
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"y", b"WEIGHTS", b"1"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"y", b"WEIGHTS", b"a", b"b"]),
"-ERR weight value is not a float\r\n"
);
assert_eq!(
f.run(&[b"ZUNION", b"2", b"z", b"y", b"AGGREGATE", b"NOPE"]),
"-ERR syntax error\r\n"
);
}
/// The three store forms, which answer a count and take no WITHSCORES.
#[test]
fn the_algebra_stores_answer_a_count_and_delete_an_empty_destination() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"d"]);
assert_eq!(f.run(&[b"ZUNIONSTORE", b"d", b"2", b"z", b"y"]), ":4\r\n");
assert_eq!(
f.run(&[b"ZRANGE", b"d", b"0", b"-1", b"WITHSCORES"]),
"*8\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nc\r\n$1\r\n3\r\n$1\r\nb\r\n$2\r\n12\r\n$1\r\nd\r\n$2\r\n20\r\n"
);
assert_eq!(f.run(&[b"ZINTERSTORE", b"d", b"2", b"z", b"y"]), ":1\r\n");
assert_eq!(f.run(&[b"ZDIFFSTORE", b"d", b"2", b"z", b"y"]), ":2\r\n");
// An empty result deletes the destination rather than leaving an empty
// sorted set, because an empty one does not exist.
assert_eq!(
f.run(&[b"ZINTERSTORE", b"d", b"2", b"z", b"nokey"]),
":0\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"d"]), ":0\r\n");
// The destination is allowed to name its own source.
assert_eq!(f.run(&[b"ZUNIONSTORE", b"z", b"2", b"z", b"y"]), ":4\r\n");
assert_eq!(f.run(&[b"ZCARD", b"z"]), ":4\r\n");
for cmd in [
&[
b"ZUNIONSTORE".as_slice(),
b"d",
b"2",
b"z",
b"y",
b"WITHSCORES",
][..],
&[
b"ZDIFFSTORE",
b"d",
b"2",
b"z",
b"y",
b"WEIGHTS",
b"1",
b"1",
],
] {
assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
}
}
/// `ZINTERCARD`, which counts without building anything.
#[test]
fn intercard_counts_and_stops_at_its_limit() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
f.run(&[b"ZADD", b"y", b"10", b"b", b"20", b"c", b"30", b"d"]);
assert_eq!(f.run(&[b"ZINTERCARD", b"2", b"z", b"y"]), ":2\r\n");
// A limit of zero is no limit, which is Redis's reading of it.
assert_eq!(
f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"0"]),
":2\r\n"
);
assert_eq!(
f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"1"]),
":1\r\n"
);
// A negative limit and a limit that is not a number at all get the same
// sentence, which looks like a mistake in Redis and is copied as one.
let bad = "-ERR LIMIT can't be negative\r\n";
assert_eq!(
f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"-1"]),
bad
);
assert_eq!(
f.run(&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT", b"x"]),
bad
);
for cmd in [
&[b"ZINTERCARD".as_slice(), b"3", b"z", b"y"][..],
&[b"ZINTERCARD", b"2", b"z", b"y", b"LIMIT"],
&[b"ZINTERCARD", b"2", b"z", b"y", b"junk", b"1"],
] {
assert_eq!(f.run(cmd), "-ERR syntax error\r\n", "{cmd:?}");
}
}
/// `ZRANDMEMBER`, which answers two different shapes out of one name.
#[test]
fn a_draw_answers_one_member_or_an_array_of_them() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
// No count is one member or a nil, a count is an array that may be
// empty, and those are two reply types the client has to tell apart.
assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey"]), "$-1\r\n");
assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey", b"3"]), "*0\r\n");
assert_eq!(f.run(&[b"ZRANDMEMBER", b"z", b"0"]), "*0\r\n");
assert!(f.run(&[b"ZRANDMEMBER", b"z"]).starts_with("$1\r\n"));
// A positive count draws without replacement, so a count over the size
// answers the whole set and never a member twice.
let all = f.run(&[b"ZRANDMEMBER", b"z", b"10"]);
assert!(all.starts_with("*3\r\n"), "{all}");
for m in ["a", "b", "c"] {
assert!(all.contains(m), "{all}");
}
// A negative one draws with replacement and answers exactly as many as
// it was asked for, whatever the size of the set.
assert!(
f.run(&[b"ZRANDMEMBER", b"z", b"-5"]).starts_with("*5\r\n"),
"five draws with replacement"
);
assert!(
f.run(&[b"ZRANDMEMBER", b"z", b"2", b"WITHSCORES"])
.starts_with("*4\r\n"),
"two pairs, flat on RESP2"
);
f.out = Out::new(Proto::Resp3);
let got = f.run(&[b"ZRANDMEMBER", b"z", b"2", b"WITHSCORES"]);
assert!(got.starts_with("*2\r\n*2\r\n"), "{got}");
assert_eq!(f.run(&[b"ZRANDMEMBER", b"nokey"]), "_\r\n");
f.out = Out::new(Proto::Resp2);
assert_eq!(
f.run(&[b"ZRANDMEMBER", b"z", b"2", b"junk"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ZRANDMEMBER", b"z", b"x"]),
"-ERR value is not an integer or out of range\r\n"
);
}
/// `ZSCAN`, and the one sorted set reply where a score is not a double.
#[test]
fn a_sorted_set_scan_answers_pairs_of_strings_on_both_protocols() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
let all = "*2\r\n$1\r\n0\r\n*6\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n$1\r\nc\r\n$1\r\n3\r\n";
assert_eq!(f.run(&[b"ZSCAN", b"z", b"0"]), all);
assert_eq!(f.run(&[b"ZSCAN", b"z", b"0", b"COUNT", b"10"]), all);
assert_eq!(
f.run(&[b"ZSCAN", b"z", b"0", b"MATCH", b"a*"]),
"*2\r\n$1\r\n0\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
assert_eq!(
f.run(&[b"ZSCAN", b"nokey", b"0"]),
"*2\r\n$1\r\n0\r\n*0\r\n"
);
// A score stays a bulk string on RESP3, which is the one place the two
// protocols agree about a score and everywhere else they do not.
f.out = Out::new(Proto::Resp3);
assert_eq!(f.run(&[b"ZSCAN", b"z", b"0"]), all);
f.out = Out::new(Proto::Resp2);
assert_eq!(
f.run(&[b"ZSCAN", b"z", b"0", b"NOVALUES"]),
"-ERR NOVALUES option can only be used in HSCAN\r\n"
);
assert_eq!(f.run(&[b"ZSCAN", b"z", b"-1"]), "-ERR invalid cursor\r\n");
assert_eq!(
f.run(&[b"ZSCAN", b"z", b"0", b"COUNT", b"0"]),
"-ERR syntax error\r\n"
);
}
/// The count is what decides the shape, and its value is not.
#[test]
fn a_sorted_set_pop_changes_shape_when_it_is_given_a_count() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
// No count, so one flat pair, and the score is a bulk string on RESP2.
assert_eq!(f.run(&[b"ZPOPMIN", b"z"]), "*2\r\n$1\r\na\r\n$1\r\n1\r\n");
assert_eq!(f.run(&[b"ZPOPMAX", b"z"]), "*2\r\n$1\r\nc\r\n$1\r\n3\r\n");
f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]);
// A count, so pairs, and on RESP2 they are flattened into one run.
assert_eq!(
f.run(&[b"ZPOPMIN", b"z", b"2"]),
"*4\r\n$1\r\na\r\n$1\r\n1\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
// An empty array rather than a null, which is where a sorted set pop and
// a list pop part company, and the same answer a count of zero gives.
assert_eq!(f.run(&[b"ZPOPMIN", b"nokey"]), "*0\r\n");
assert_eq!(f.run(&[b"ZPOPMIN", b"nokey", b"2"]), "*0\r\n");
assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"0"]), "*0\r\n");
// The last member takes the key with it.
assert_eq!(
f.run(&[b"ZPOPMIN", b"z", b"9"]),
"*2\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b"]);
f.out = Out::new(Proto::Resp3);
assert_eq!(f.run(&[b"ZPOPMIN", b"z"]), "*2\r\n$1\r\na\r\n,1\r\n");
assert_eq!(
f.run(&[b"ZPOPMIN", b"z", b"1"]),
"*1\r\n*2\r\n$1\r\nb\r\n,2\r\n"
);
f.out = Out::new(Proto::Resp2);
// Both of these are the range error rather than the usual sentence about
// integers, which is the odd answer and so the one worth copying.
let bad = "-ERR value is out of range, must be positive\r\n";
assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"x"]), bad);
assert_eq!(f.run(&[b"ZPOPMIN", b"z", b"-1"]), bad);
assert_eq!(
f.run(&[b"ZPOPMIN", b"z", b"1", b"2"]),
"-ERR syntax error\r\n"
);
}
/// `ZMPOP`, which is `LMPOP` with scores and the same parse.
#[test]
fn a_multi_key_pop_names_the_key_that_answered_and_nests_its_pairs() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.run(&[b"ZMPOP", b"2", b"nokey", b"z", b"MIN"]),
"*2\r\n$1\r\nz\r\n*1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// Nested on RESP2 as well, because the key name is already in front of
// the pairs and there is nothing left to flatten into.
assert_eq!(
f.run(&[b"ZMPOP", b"1", b"z", b"MAX", b"COUNT", b"2"]),
"*2\r\n$1\r\nz\r\n*2\r\n*2\r\n$1\r\nc\r\n$1\r\n3\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
// A null array and not a null, the same as LMPOP.
assert_eq!(f.run(&[b"ZMPOP", b"1", b"nokey", b"MIN"]), "*-1\r\n");
f.out = Out::new(Proto::Resp3);
assert_eq!(f.run(&[b"ZMPOP", b"1", b"nokey", b"MIN"]), "_\r\n");
f.out = Out::new(Proto::Resp2);
let numkeys = "-ERR numkeys should be greater than 0\r\n";
for bad in [
&[b"ZMPOP".as_slice(), b"0", b"z", b"MIN"][..],
&[b"ZMPOP", b"-1", b"z", b"MIN"],
&[b"ZMPOP", b"x", b"z", b"MIN"],
] {
assert_eq!(f.run(bad), numkeys, "{:?}", bad[1]);
}
let count = "-ERR count should be greater than 0\r\n";
for bad in [
&[b"ZMPOP".as_slice(), b"1", b"z", b"MIN", b"COUNT", b"0"][..],
&[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"-1"],
&[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"x"],
] {
assert_eq!(f.run(bad), count, "{:?}", bad[5]);
}
let syntax = "-ERR syntax error\r\n";
for bad in [
// Two keys named and one given, so the word that should have been
// the direction is a key and there is no direction left.
&[b"ZMPOP".as_slice(), b"2", b"z", b"MIN"][..],
&[b"ZMPOP", b"1", b"z", b"SIDEWAYS"],
&[b"ZMPOP", b"1", b"z", b"MIN", b"junk"],
&[b"ZMPOP", b"1", b"z", b"MIN", b"COUNT", b"1", b"junk"],
] {
assert_eq!(f.run(bad), syntax, "{bad:?}");
}
}
/// The three that wait, when there is something there and they do not have
/// to. `BZPOPMIN` is the one reply in the group that is three flat elements.
#[test]
fn the_sorted_set_pops_that_wait_answer_like_the_ones_they_wrap() {
let mut f = Fixture::new();
f.run(&[b"ZADD", b"z", b"1", b"a", b"2", b"b", b"3", b"c"]);
assert_eq!(
f.flow(&[b"BZPOPMIN", b"nokey", b"z", b"0"]),
(
Flow::Continue,
"*3\r\n$1\r\nz\r\n$1\r\na\r\n$1\r\n1\r\n".to_owned()
)
);
assert_eq!(
f.run(&[b"BZPOPMAX", b"z", b"0"]),
"*3\r\n$1\r\nz\r\n$1\r\nc\r\n$1\r\n3\r\n"
);
f.run(&[b"ZADD", b"z", b"1", b"a", b"3", b"c"]);
assert_eq!(
f.run(&[
b"BZMPOP", b"0", b"2", b"nokey", b"z", b"MIN", b"COUNT", b"2"
]),
"*2\r\n$1\r\nz\r\n*2\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
f.out = Out::new(Proto::Resp3);
assert_eq!(
f.run(&[b"BZPOPMIN", b"z", b"0"]),
"*3\r\n$1\r\nz\r\n$1\r\nc\r\n,3\r\n"
);
f.out = Out::new(Proto::Resp2);
// Nothing to take, so the client is parked and nothing was written.
assert_eq!(
f.flow(&[b"BZPOPMIN", b"z", b"0"]),
(Flow::Block, String::new())
);
assert_eq!(
f.flow(&[b"BZMPOP", b"0", b"1", b"z", b"MIN"]),
(Flow::Block, String::new())
);
// The timeout is read before the key count, so this complains about the
// timeout and not about the count.
assert_eq!(
f.run(&[b"BZMPOP", b"abc", b"0", b"z", b"MIN"]),
"-ERR timeout is not a float or out of range\r\n"
);
assert_eq!(
f.run(&[b"BZMPOP", b"0", b"0", b"z", b"MIN"]),
"-ERR numkeys should be greater than 0\r\n"
);
assert_eq!(
f.run(&[b"BZPOPMIN", b"z", b"-1"]),
"-ERR timeout is negative\r\n"
);
}
/// A parked sorted set client is served by whatever puts a member under one
/// of its keys, and is not served by something of another type landing
/// there.
#[test]
fn a_parked_sorted_set_client_waits_for_a_member_and_not_for_a_key() {
let mut f = Fixture::new();
assert_eq!(f.flow(&[b"BZPOPMIN", b"z", b"0"]).0, Flow::Block);
assert_eq!(f.server.waiters().len(), 1);
// A string under the key is not what it asked for, so it stays parked
// rather than being handed a WRONGTYPE on a command that was accepted.
f.run(&[b"SET", b"z", b"v"]);
let mut out = Out::new(Proto::Resp2);
assert!(!f.server.serve_waiter(0, 0, &mut out));
assert!(out.as_slice().is_empty());
f.run(&[b"DEL", b"z"]);
f.run(&[b"ZADD", b"z", b"5", b"m"]);
assert!(f.server.serve_waiter(0, 0, &mut out));
assert_eq!(
core::str::from_utf8(out.as_slice()).expect("ascii"),
"*3\r\n$1\r\nz\r\n$1\r\nm\r\n$1\r\n5\r\n"
);
// And the member is gone, which is what makes a queue of workers on a
// sorted set work at all.
assert_eq!(f.run(&[b"EXISTS", b"z"]), ":0\r\n");
}
#[test]
fn every_sorted_set_command_says_wrongtype_and_writes_nothing() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"ZADD".as_slice(), b"s", b"1", b"a"][..],
&[b"ZINCRBY", b"s", b"1", b"a"],
&[b"ZCARD", b"s"],
&[b"ZSCORE", b"s", b"a"],
&[b"ZMSCORE", b"s", b"a"],
&[b"ZREM", b"s", b"a"],
&[b"ZRANK", b"s", b"a"],
&[b"ZREVRANK", b"s", b"a"],
&[b"ZCOUNT", b"s", b"1", b"2"],
&[b"ZLEXCOUNT", b"s", b"-", b"+"],
&[b"ZRANGE", b"s", b"0", b"-1"],
&[b"ZREVRANGE", b"s", b"0", b"-1"],
&[b"ZRANGEBYSCORE", b"s", b"1", b"2"],
&[b"ZREVRANGEBYSCORE", b"s", b"2", b"1"],
&[b"ZRANGEBYLEX", b"s", b"-", b"+"],
&[b"ZREVRANGEBYLEX", b"s", b"+", b"-"],
&[b"ZRANGESTORE", b"d", b"s", b"0", b"-1"],
&[b"ZREMRANGEBYRANK", b"s", b"0", b"-1"],
&[b"ZREMRANGEBYSCORE", b"s", b"1", b"2"],
&[b"ZREMRANGEBYLEX", b"s", b"-", b"+"],
&[b"ZUNION", b"1", b"s"],
&[b"ZINTER", b"1", b"s"],
&[b"ZDIFF", b"1", b"s"],
&[b"ZUNIONSTORE", b"d", b"1", b"s"],
&[b"ZINTERSTORE", b"d", b"1", b"s"],
&[b"ZDIFFSTORE", b"d", b"1", b"s"],
&[b"ZINTERCARD", b"1", b"s"],
&[b"ZRANDMEMBER", b"s"],
&[b"ZSCAN", b"s", b"0"],
&[b"ZPOPMIN", b"s"],
&[b"ZPOPMAX", b"s", b"2"],
&[b"ZMPOP", b"1", b"s", b"MIN"],
&[b"BZPOPMIN", b"s", b"0"],
&[b"BZPOPMAX", b"s", b"0"],
&[b"BZMPOP", b"0", b"1", b"s", b"MIN"],
] {
assert_eq!(f.run(cmd), wrong, "{:?}", cmd[0]);
}
assert_eq!(f.run(&[b"GET", b"s"]), "$1\r\nv\r\n");
}
/// The same churn the set, the string and the list get, because a sorted
/// set that leaks a tree node per add looks exactly like one that does not
/// until it has run for an afternoon.
#[test]
fn churning_sorted_sets_does_not_grow_the_server() {
let mut f = Fixture::new();
let members: Vec<Vec<u8>> = (0..200).map(|i| format!("m{i}").into_bytes()).collect();
let scores: Vec<Vec<u8>> = (0..200).map(|i| format!("{i}").into_bytes()).collect();
let mut args: Vec<&[u8]> = vec![b"ZADD", b"z"];
for i in 0..200 {
args.push(&scores[i]);
args.push(&members[i]);
}
f.run(&args);
f.run(&[b"DEL", b"z"]);
f.server.compact_step();
let after_first = f.server.memory_bytes();
for _ in 0..200 {
f.run(&args);
f.run(&[b"DEL", b"z"]);
f.server.compact_step();
}
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
assert!(
f.server.memory_bytes() <= after_first * 2,
"held {} after two hundred passes against {after_first} after one",
f.server.memory_bytes()
);
}
// ------------------------------------------------------------------- geo
/// The three places every Redis geo example uses, and one more.
///
/// Every reply this section asserts on came off a running 8.10.1 with these
/// three loaded, byte for byte, including the number of digits in a
/// coordinate and the four places on a distance.
fn sicily(f: &mut Fixture) {
f.run(&[
b"GEOADD",
b"Sicily",
b"13.361389",
b"38.115556",
b"Palermo",
b"15.087269",
b"37.502669",
b"Catania",
]);
f.run(&[
b"GEOADD",
b"Sicily",
b"13.583333",
b"37.316667",
b"Agrigento",
]);
}
#[test]
fn places_go_in_as_scores_and_come_back_as_positions() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"GEOADD",
b"Sicily",
b"13.361389",
b"38.115556",
b"Palermo",
b"15.087269",
b"37.502669",
b"Catania"
]),
":2\r\n"
);
// A geo key is a sorted set and says so, which is not an implementation
// detail either: a client removes a place with ZREM and counts them
// with ZCARD, and the score is the number a real server stores.
assert_eq!(f.run(&[b"TYPE", b"Sicily"]), "+zset\r\n");
assert_eq!(
f.run(&[b"ZSCORE", b"Sicily", b"Palermo"]),
"$16\r\n3479099956230698\r\n"
);
assert_eq!(
f.run(&[b"GEOPOS", b"Sicily", b"Palermo", b"NonExisting"]),
"*2\r\n*2\r\n$18\r\n13.361389338970184\r\n$16\r\n38.1155563954963\r\n*-1\r\n"
);
assert_eq!(
f.run(&[
b"GEOHASH",
b"Sicily",
b"Palermo",
b"Catania",
b"NonExisting"
]),
"*3\r\n$11\r\nsqc8b49rny0\r\n$11\r\nsqdtr74hyu0\r\n$-1\r\n"
);
// A key that is not there is an empty one, and the two nulls are not
// the same null: GEOPOS answers the array one and GEOHASH the string
// one, which a RESP2 client can tell apart.
assert_eq!(f.run(&[b"GEOPOS", b"nokey", b"a"]), "*1\r\n*-1\r\n");
assert_eq!(f.run(&[b"GEOHASH", b"nokey", b"a"]), "*1\r\n$-1\r\n");
}
#[test]
fn a_distance_comes_back_with_four_places_in_whatever_unit_was_asked_for() {
let mut f = Fixture::new();
sicily(&mut f);
assert_eq!(
f.run(&[b"GEODIST", b"Sicily", b"Palermo", b"Catania"]),
"$11\r\n166274.1516\r\n"
);
assert_eq!(
f.run(&[b"GEODIST", b"Sicily", b"Palermo", b"Catania", b"km"]),
"$8\r\n166.2742\r\n"
);
assert_eq!(
f.run(&[b"GEODIST", b"Sicily", b"Palermo", b"Catania", b"mi"]),
"$8\r\n103.3182\r\n"
);
// A member that is not there and a key that is not there are the same
// nil, and the unit is read before the key is looked up, so a bad unit
// on a missing key is still an error.
assert_eq!(
f.run(&[b"GEODIST", b"Sicily", b"Palermo", b"Foo"]),
"$-1\r\n"
);
assert_eq!(f.run(&[b"GEODIST", b"nokey", b"a", b"b"]), "$-1\r\n");
assert_eq!(
f.run(&[b"GEODIST", b"nokey", b"a", b"b", b"parsecs"]),
"-ERR unsupported unit provided. please use M, KM, FT, MI\r\n"
);
assert_eq!(
f.run(&[b"GEODIST", b"Sicily", b"a", b"b", b"km", b"extra"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn a_search_finds_what_is_inside_it_nearest_first() {
let mut f = Fixture::new();
sicily(&mut f);
let all = "*3\r\n$7\r\nCatania\r\n$9\r\nAgrigento\r\n$7\r\nPalermo\r\n";
assert_eq!(
f.run(&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"200",
b"km",
b"ASC"
]),
all
);
// The older spelling of the same search, which is the same nine boxes
// and the same order.
assert_eq!(
f.run(&[b"GEORADIUS", b"Sicily", b"15", b"37", b"200", b"km", b"ASC"]),
all
);
assert_eq!(
f.run(&[
b"GEORADIUS_RO",
b"Sicily",
b"15",
b"37",
b"200",
b"km",
b"ASC"
]),
all
);
// A count with no ordering means the nearest ones, so DESC has to be
// asked for to get the far end.
assert_eq!(
f.run(&[
b"GEORADIUS",
b"Sicily",
b"15",
b"37",
b"200",
b"km",
b"DESC",
b"COUNT",
b"1"
]),
"*1\r\n$7\r\nPalermo\r\n"
);
assert_eq!(
f.run(&[
b"GEORADIUS",
b"Sicily",
b"15",
b"37",
b"200",
b"km",
b"COUNT",
b"1"
]),
"*1\r\n$7\r\nCatania\r\n"
);
// Nothing inside a kilometre of that point, and nothing in a key that
// is not there, and both are the empty array rather than an error.
let empty = "*0\r\n";
assert_eq!(
f.run(&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km"
]),
empty
);
assert_eq!(
f.run(&[
b"GEOSEARCH",
b"nokey",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km"
]),
empty
);
assert_eq!(
f.run(&[b"GEORADIUSBYMEMBER", b"nokey", b"m", b"1", b"km"]),
empty
);
}
#[test]
fn a_search_centred_on_a_member_starts_from_where_that_member_is() {
let mut f = Fixture::new();
sicily(&mut f);
assert_eq!(
f.run(&[b"GEORADIUSBYMEMBER", b"Sicily", b"Agrigento", b"100", b"km"]),
"*2\r\n$9\r\nAgrigento\r\n$7\r\nPalermo\r\n"
);
// The member itself is nothing away from itself, which is where the
// fixed point writer's zero shows up on the wire.
let with_dist = "*2\r\n*2\r\n$9\r\nAgrigento\r\n$6\r\n0.0000\r\n*2\r\n$7\r\nPalermo\r\n$7\r\n90.9778\r\n";
assert_eq!(
f.run(&[
b"GEORADIUSBYMEMBER_RO",
b"Sicily",
b"Agrigento",
b"100",
b"km",
b"WITHDIST"
]),
with_dist
);
assert_eq!(
f.run(&[
b"GEOSEARCH",
b"Sicily",
b"FROMMEMBER",
b"Agrigento",
b"BYRADIUS",
b"100",
b"km",
b"ASC",
b"WITHDIST"
]),
with_dist
);
assert_eq!(
f.run(&[b"GEORADIUSBYMEMBER", b"Sicily", b"Nowhere", b"100", b"km"]),
"-ERR could not decode requested zset member\r\n"
);
}
#[test]
fn a_box_search_reports_the_distance_the_hash_and_the_coordinates() {
let mut f = Fixture::new();
sicily(&mut f);
// Three options asked for, so each result is a four element array of
// the member, the distance, the hash and a pair. The order of the three
// is Redis's and not the order they were written in the command.
assert_eq!(
f.run(&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYBOX",
b"400",
b"400",
b"km",
b"ASC",
b"WITHCOORD",
b"WITHDIST",
b"WITHHASH"
]),
"*3\r\n*4\r\n$7\r\nCatania\r\n$7\r\n56.4413\r\n:3479447370796909\r\n*2\r\n\
$18\r\n15.087267458438873\r\n$17\r\n37.50266842333162\r\n\
*4\r\n$9\r\nAgrigento\r\n$8\r\n130.4235\r\n:3479030013248308\r\n*2\r\n\
$18\r\n13.583331406116486\r\n$18\r\n37.316668049938166\r\n\
*4\r\n$7\r\nPalermo\r\n$8\r\n190.4424\r\n:3479099956230698\r\n*2\r\n\
$18\r\n13.361389338970184\r\n$16\r\n38.1155563954963\r\n"
);
}
#[test]
fn a_store_writes_the_hashes_and_a_storedist_writes_the_distances() {
let mut f = Fixture::new();
sicily(&mut f);
let hashes = "*6\r\n$9\r\nAgrigento\r\n$16\r\n3479030013248308\r\n\
$7\r\nPalermo\r\n$16\r\n3479099956230698\r\n\
$7\r\nCatania\r\n$16\r\n3479447370796909\r\n";
assert_eq!(
f.run(&[
b"GEOSEARCHSTORE",
b"dst",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"200",
b"km",
b"ASC"
]),
":3\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"dst", b"0", b"-1", b"WITHSCORES"]),
hashes
);
// The same again through the older spelling, which stores the same
// scores, so a key written by either is a geo key.
assert_eq!(
f.run(&[
b"GEORADIUS",
b"Sicily",
b"15",
b"37",
b"200",
b"km",
b"STORE",
b"dst3"
]),
":3\r\n"
);
assert_eq!(
f.run(&[b"ZRANGE", b"dst3", b"0", b"-1", b"WITHSCORES"]),
hashes
);
// STOREDIST stores the distance in the search unit instead, and those
// are full doubles rather than the four places WITHDIST writes. The
// numbers on the right are what 8.10.1 stored for this search, and they
// are compared with a tolerance rather than byte for byte because the
// last bit of a haversine is the platform's sin, cos and asin: this
// machine and that one disagree in the sixteenth digit, and so do two
// Redis builds. Everything a client actually reads back is four places
// and is asserted exactly above.
assert_eq!(
f.run(&[
b"GEOSEARCHSTORE",
b"dst2",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"200",
b"km",
b"ASC",
b"STOREDIST"
]),
":3\r\n"
);
for (member, want) in [
("Catania", 56.441_257_870_158_19),
("Agrigento", 130.423_487_067_147_14),
("Palermo", 190.442_429_847_757_92),
] {
let reply = f.run(&[b"ZSCORE", b"dst2", member.as_bytes()]);
let got: f64 = reply
.trim_start_matches(|c: char| c != '\n')
.trim()
.parse()
.unwrap_or_else(|_| panic!("{member} scored {reply:?}"));
assert!(
(got - want).abs() < 1e-9,
"{member} scored {got} not {want}"
);
}
// The order they went in is the order the scores put them in, which is
// the point of storing the distance rather than the hash.
assert_eq!(
f.run(&[b"ZRANGE", b"dst2", b"0", b"-1"]),
"*3\r\n$7\r\nCatania\r\n$9\r\nAgrigento\r\n$7\r\nPalermo\r\n"
);
// A search that finds nothing takes the destination with it rather than
// leaving what was there, and a source key that is not there is a
// search that finds nothing.
assert_eq!(
f.run(&[
b"GEOSEARCHSTORE",
b"dst",
b"nokey",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"200",
b"km"
]),
":0\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"dst"]), ":0\r\n");
}
#[test]
fn the_gates_on_geoadd_are_the_ones_zadd_has() {
let mut f = Fixture::new();
sicily(&mut f);
// XX on a member that is already where it is changes nothing, and NX on
// one that is there refuses to move it.
assert_eq!(
f.run(&[
b"GEOADD",
b"Sicily",
b"XX",
b"CH",
b"13.361389",
b"38.115556",
b"Palermo"
]),
":0\r\n"
);
assert_eq!(
f.run(&[
b"GEOADD",
b"Sicily",
b"NX",
b"13.361389",
b"38.9",
b"Palermo"
]),
":0\r\n"
);
assert_eq!(
f.run(&[
b"GEOADD",
b"Sicily",
b"CH",
b"13.361389",
b"38.9",
b"Palermo"
]),
":1\r\n"
);
// Out of range, and nothing is stored: the whole call is refused rather
// than the good pairs going in and the bad one stopping it.
assert_eq!(
f.run(&[
b"GEOADD",
b"new",
b"13.361389",
b"38.115556",
b"here",
b"181",
b"38",
b"there"
]),
"-ERR invalid longitude,latitude pair 181.000000,38.000000\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"new"]), ":0\r\n");
assert_eq!(
f.run(&[b"GEOADD", b"new", b"x", b"38", b"here"]),
"-ERR value is not a valid float\r\n"
);
// The count of triples is checked before the two gates are, and a call
// with no triples at all reaches the same sentence.
assert_eq!(
f.run(&[b"GEOADD", b"new", b"13", b"38", b"here", b"and"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"GEOADD", b"new", b"NX", b"XX", b"CH"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"GEOADD", b"new", b"CH", b"CH", b"CH", b"CH"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"GEOADD", b"new", b"NX", b"CH"]),
"-ERR wrong number of arguments for 'geoadd' command\r\n"
);
}
/// The sentences a search answers, which are its contract as much as the
/// results are.
#[test]
fn every_way_a_search_can_be_written_wrong_has_its_own_sentence() {
let mut f = Fixture::new();
sicily(&mut f);
let cases: &[(&[&[u8]], &str)] = &[
(
&[b"GEORADIUS", b"Sicily", b"15", b"37", b"x", b"km"],
"-ERR need numeric radius\r\n",
),
(
&[b"GEORADIUS", b"Sicily", b"15", b"37", b"-1", b"km"],
"-ERR radius cannot be negative\r\n",
),
(
&[b"GEORADIUS", b"Sicily", b"15", b"37", b"1", b"parsecs"],
"-ERR unsupported unit provided. please use M, KM, FT, MI\r\n",
),
(
&[b"GEORADIUS", b"Sicily", b"181", b"37", b"1", b"km"],
"-ERR invalid longitude,latitude pair 181.000000,37.000000\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYBOX",
b"x",
b"1",
b"km",
],
"-ERR need numeric width\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYBOX",
b"1",
b"y",
b"km",
],
"-ERR need numeric height\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYBOX",
b"-1",
b"1",
b"km",
],
"-ERR height or width cannot be negative\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
b"ANY",
],
"-ERR the ANY argument requires COUNT argument\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
b"COUNT",
b"0",
],
"-ERR COUNT must be > 0\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"BYRADIUS",
b"1",
b"km",
b"BYBOX",
b"1",
b"1",
b"km",
],
"-ERR syntax error\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMMEMBER",
b"Palermo",
b"FROMLONLAT",
b"1",
b"2",
b"BYRADIUS",
b"1",
b"km",
],
"-ERR syntax error\r\n",
),
// The two options a GEOSEARCH cannot leave out, each with its own
// sentence, and the command quoted the way the client spelled it.
(
&[
b"geosearch",
b"Sicily",
b"BYRADIUS",
b"1",
b"km",
b"ASC",
b"WITHDIST",
],
"-ERR exactly one of FROMMEMBER or FROMLONLAT can be specified for geosearch\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"ASC",
b"WITHDIST",
],
"-ERR exactly one of BYRADIUS and BYBOX can be specified for GEOSEARCH\r\n",
),
// A store cannot also be asked for the distance, and the two
// families name themselves differently in the same sentence.
(
&[
b"GEOSEARCHSTORE",
b"d",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
b"WITHCOORD",
],
"-ERR GEOSEARCHSTORE is not compatible with WITHDIST, WITHHASH and WITHCOORD options\r\n",
),
(
&[
b"GEORADIUS",
b"Sicily",
b"15",
b"37",
b"1",
b"km",
b"WITHDIST",
b"STORE",
b"d",
],
"-ERR STORE option in GEORADIUS is not compatible with WITHDIST, WITHHASH and WITHCOORD options\r\n",
),
// The read only forms have no store at all, so the word is a stray
// one, and GEOSEARCH's STOREDIST is only a GEOSEARCHSTORE option.
(
&[
b"GEORADIUS_RO",
b"Sicily",
b"15",
b"37",
b"1",
b"km",
b"STORE",
b"d",
],
"-ERR syntax error\r\n",
),
(
&[
b"GEOSEARCH",
b"Sicily",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
b"STOREDIST",
],
"-ERR syntax error\r\n",
),
];
for (parts, want) in cases {
assert_eq!(&f.run(parts), want, "{:?}", parts[0]);
}
}
/// A wrong type wins over a bad argument, because the key is looked up
/// first, and every one of the ten says the same thing about it.
#[test]
fn every_geo_command_says_wrongtype() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
let cases: &[&[&[u8]]] = &[
&[b"GEOADD", b"s", b"13", b"38", b"m"],
&[b"GEOPOS", b"s", b"m"],
&[b"GEOHASH", b"s", b"m"],
&[b"GEODIST", b"s", b"a", b"b"],
&[
b"GEOSEARCH",
b"s",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
],
&[
b"GEOSEARCHSTORE",
b"d",
b"s",
b"FROMLONLAT",
b"15",
b"37",
b"BYRADIUS",
b"1",
b"km",
],
&[b"GEORADIUS", b"s", b"15", b"37", b"1", b"km"],
&[b"GEORADIUS_RO", b"s", b"15", b"37", b"1", b"km"],
&[b"GEORADIUSBYMEMBER", b"s", b"m", b"1", b"km"],
&[b"GEORADIUSBYMEMBER_RO", b"s", b"m", b"1", b"km"],
];
for case in cases {
assert_eq!(f.run(case), wrong, "{:?}", case[0]);
}
// And it wins over an argument that will not parse, which is the whole
// reason the lookup comes first.
assert_eq!(
f.run(&[b"GEORADIUS", b"s", b"15", b"37", b"x", b"km"]),
wrong
);
}
// ----------------------------------------------------------------- array
#[test]
fn an_array_writes_at_any_index_and_reads_back_what_it_sent() {
let mut f = Fixture::new();
// Three consecutive positions from a high index, and the reply is how
// many of them were empty before rather than how many were written.
assert_eq!(
f.run(&[b"ARSET", b"a", b"1000", b"x", b"y", b"z"]),
":3\r\n"
);
assert_eq!(f.run(&[b"ARSET", b"a", b"1000", b"X", b"Y"]), ":0\r\n");
assert_eq!(f.run(&[b"ARGET", b"a", b"1000"]), "$1\r\nX\r\n");
assert_eq!(f.run(&[b"ARGET", b"a", b"1002"]), "$1\r\nz\r\n");
// A hole and a key that is not there are the same answer.
assert_eq!(f.run(&[b"ARGET", b"a", b"999"]), "$-1\r\n");
assert_eq!(f.run(&[b"ARGET", b"nope", b"0"]), "$-1\r\n");
assert_eq!(
f.run(&[b"ARMGET", b"a", b"1002", b"999", b"1000"]),
"*3\r\n$1\r\nz\r\n$-1\r\n$1\r\nX\r\n"
);
// Scattered pairs in one command, last write wins within it.
assert_eq!(f.run(&[b"ARMSET", b"a", b"5", b"p", b"5", b"q"]), ":1\r\n");
assert_eq!(f.run(&[b"ARGET", b"a", b"5"]), "$1\r\nq\r\n");
}
/// The two numbers an array reports are not the same number, and one of
/// them does not fit a signed integer.
#[test]
fn the_length_is_the_high_water_mark_and_the_count_is_the_population() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARLEN", b"nope"]), ":0\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"nope"]), ":0\r\n");
f.run(&[b"ARMSET", b"a", b"0", b"x", b"9", b"y"]);
assert_eq!(f.run(&[b"ARLEN", b"a"]), ":10\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":2\r\n");
// Deleting in the middle leaves the high water mark where it was.
assert_eq!(f.run(&[b"ARDEL", b"a", b"0"]), ":1\r\n");
assert_eq!(f.run(&[b"ARLEN", b"a"]), ":10\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":1\r\n");
// The top of the space is addressable, and its length is a number with
// bit sixty three set, so the reply has to be unsigned or it comes back
// negative.
f.run(&[b"ARSET", b"top", b"18446744073709551614", b"z"]);
assert_eq!(f.run(&[b"ARLEN", b"top"]), ":18446744073709551615\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"top"]), ":1\r\n");
// And one past it does not exist, so a write that would reach it fails
// before any of it lands.
assert_eq!(
f.run(&[b"ARSET", b"over", b"18446744073709551614", b"a", b"b"]),
"-ERR array index overflow\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"over"]), ":0\r\n");
}
/// One reply per position and not one per element, which is the whole
/// reason the range is capped.
#[test]
fn a_range_read_answers_for_the_holes_too_and_is_capped_at_a_million() {
let mut f = Fixture::new();
f.run(&[b"ARSET", b"a", b"1", b"x"]);
assert_eq!(
f.run(&[b"ARGETRANGE", b"a", b"0", b"3"]),
"*4\r\n$-1\r\n$1\r\nx\r\n$-1\r\n$-1\r\n"
);
// The two ends may come in either order, and the answer is reversed
// rather than empty.
assert_eq!(
f.run(&[b"ARGETRANGE", b"a", b"3", b"0"]),
"*4\r\n$-1\r\n$-1\r\n$1\r\nx\r\n$-1\r\n"
);
// A key that is not there reads like an array of nothing but holes.
assert_eq!(
f.run(&[b"ARGETRANGE", b"nope", b"0", b"1"]),
"*2\r\n$-1\r\n$-1\r\n"
);
// A range wider than a million positions is refused and not trimmed,
// because against a missing key it is a request for as many nulls as
// the range is wide.
assert_eq!(
f.run(&[b"ARGETRANGE", b"nope", b"0", b"18446744073709551614"]),
"-ERR range exceeds maximum of 1000000 items\r\n"
);
}
/// Every index in the argument list is read before the key is touched, so
/// a bad one at the end leaves nothing half written.
#[test]
fn a_bad_index_late_in_the_line_writes_none_of_the_earlier_ones() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"ARMSET", b"a", b"0", b"x", b"-1", b"y"]),
"-ERR invalid array index\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
f.run(&[b"ARSET", b"a", b"0", b"x", b"y", b"z"]);
assert_eq!(
f.run(&[b"ARDEL", b"a", b"0", b"01"]),
"-ERR invalid array index\r\n"
);
assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":3\r\n");
// An index is unsigned here, so the numbers a list would take are not
// the last element, they are errors.
assert_eq!(
f.run(&[b"ARGET", b"a", b"-1"]),
"-ERR invalid array index\r\n"
);
// And a pair list with an odd tail is an arity error rather than a
// syntax one.
assert_eq!(
f.run(&[b"ARMSET", b"a", b"0", b"x", b"1"]),
"-ERR wrong number of arguments for 'armset' command\r\n"
);
assert_eq!(
f.run(&[b"ARDELRANGE", b"a", b"0", b"1", b"2"]),
"-ERR wrong number of arguments for 'ardelrange' command\r\n"
);
}
#[test]
fn a_range_delete_costs_the_elements_and_takes_the_key_when_it_empties() {
let mut f = Fixture::new();
f.run(&[b"ARSET", b"a", b"0", b"0", b"1", b"2", b"3", b"4"]);
assert_eq!(f.run(&[b"ARDELRANGE", b"a", b"3", b"1"]), ":3\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"a"]), ":2\r\n");
// Two ranges in one command, and the second one covers the whole space
// without walking it.
assert_eq!(
f.run(&[
b"ARDELRANGE",
b"a",
b"100",
b"200",
b"0",
b"18446744073709551614"
]),
":2\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"a"]), ":0\r\n");
assert_eq!(f.run(&[b"ARDELRANGE", b"nope", b"0", b"1"]), ":0\r\n");
assert_eq!(f.run(&[b"ARDEL", b"nope", b"0"]), ":0\r\n");
}
/// A value goes out as the bytes it came in as, whichever of the three ways
/// the array found to store it.
#[test]
fn a_value_comes_back_byte_for_byte_however_it_was_packed() {
let mut f = Fixture::new();
let long = vec![b'v'; 200];
f.run(&[
b"ARMSET", b"a", b"0", b"42", b"1", b"007", b"2", b"3.5", b"3", b"3.14", b"4",
b"short", b"5", &long, b"6", b"-0",
]);
// 42 is an integer, 007 is not one because it does not print back the
// same, 3.5 survives a double and 3.14 does not, and the last two are a
// word packed string and a blob.
assert_eq!(
f.run(&[b"ARGETRANGE", b"a", b"0", b"6"]),
format!(
"*7\r\n$2\r\n42\r\n$3\r\n007\r\n$3\r\n3.5\r\n$4\r\n3.14\r\n$5\r\nshort\r\n$200\r\n{}\r\n$2\r\n-0\r\n",
String::from_utf8_lossy(&long)
)
);
}
#[test]
fn an_array_is_a_type_and_an_encoding_a_client_can_see() {
let mut f = Fixture::new();
f.run(&[b"ARSET", b"a", b"0", b"x"]);
assert_eq!(f.run(&[b"TYPE", b"a"]), "+array\r\n");
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"a"]),
"$12\r\nsliced-array\r\n"
);
// And it is a body like any other, so the key commands work on it.
assert_eq!(f.run(&[b"EXPIRE", b"a", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"PERSIST", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"COPY", b"a", b"b"]), ":1\r\n");
assert_eq!(f.run(&[b"ARGET", b"b", b"0"]), "$1\r\nx\r\n");
assert_eq!(f.run(&[b"RENAME", b"a", b"c"]), "+OK\r\n");
assert_eq!(f.run(&[b"ARCOUNT", b"c"]), ":1\r\n");
}
#[test]
fn every_array_command_refuses_a_key_holding_something_else() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
for cmd in [
&[b"ARSET".as_ref(), b"s", b"0", b"x"][..],
&[b"ARMSET".as_ref(), b"s", b"0", b"x"][..],
&[b"ARGET".as_ref(), b"s", b"0"][..],
&[b"ARMGET".as_ref(), b"s", b"0"][..],
&[b"ARGETRANGE".as_ref(), b"s", b"0", b"1"][..],
&[b"ARLEN".as_ref(), b"s"][..],
&[b"ARCOUNT".as_ref(), b"s"][..],
&[b"ARDEL".as_ref(), b"s", b"0"][..],
&[b"ARDELRANGE".as_ref(), b"s", b"0", b"1"][..],
&[b"ARINSERT".as_ref(), b"s", b"x"][..],
&[b"ARRING".as_ref(), b"s", b"4", b"x"][..],
&[b"ARNEXT".as_ref(), b"s"][..],
&[b"ARSEEK".as_ref(), b"s", b"1"][..],
&[b"ARLASTITEMS".as_ref(), b"s", b"1"][..],
&[b"ARSCAN".as_ref(), b"s", b"0", b"1"][..],
&[b"ARGREP".as_ref(), b"s", b"0", b"1", b"EXACT", b"v"][..],
&[b"AROP".as_ref(), b"s", b"0", b"1", b"SUM"][..],
&[b"ARINFO".as_ref(), b"s"][..],
] {
assert_eq!(f.run(cmd), wrong, "{}", String::from_utf8_lossy(cmd[0]));
}
}
/// Two of the array commands look the key up before they read the index and
/// the rest read the index first, so the same broken argument gets two
/// different errors depending on which command it went to.
#[test]
fn a_bad_index_reports_the_type_only_where_redis_reports_it() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"v"]);
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
let bad = "-ERR invalid array index\r\n";
assert_eq!(f.run(&[b"ARGET", b"s", b"-1"]), wrong);
assert_eq!(f.run(&[b"ARMGET", b"s", b"0", b"-1"]), wrong);
assert_eq!(f.run(&[b"ARSET", b"s", b"-1", b"x"]), bad);
assert_eq!(f.run(&[b"ARDEL", b"s", b"-1"]), bad);
assert_eq!(f.run(&[b"ARSCAN", b"s", b"-1", b"0"]), bad);
assert_eq!(f.run(&[b"ARGREP", b"s", b"-1", b"0", b"EXACT", b"v"]), bad);
// And on a key that is an array the index is just an index.
f.run(&[b"ARSET", b"a", b"0", b"x"]);
assert_eq!(f.run(&[b"ARGET", b"a", b"-1"]), bad);
assert_eq!(f.run(&[b"ARGET", b"nope", b"-1"]), bad);
}
#[test]
fn an_append_follows_a_cursor_the_client_can_move() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARNEXT", b"nope"]), ":0\r\n");
assert_eq!(f.run(&[b"ARINSERT", b"a", b"x", b"y"]), ":1\r\n");
assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":2\r\n");
assert_eq!(f.run(&[b"ARINSERT", b"a", b"z"]), ":2\r\n");
assert_eq!(f.run(&[b"ARGET", b"a", b"2"]), "$1\r\nz\r\n");
// A seek says where the next one goes, and a missing key has no cursor
// to move and is not created by the asking.
assert_eq!(f.run(&[b"ARSEEK", b"nope", b"5"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"nope"]), ":0\r\n");
assert_eq!(f.run(&[b"ARSEEK", b"a", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":100\r\n");
assert_eq!(f.run(&[b"ARINSERT", b"a", b"far"]), ":100\r\n");
assert_eq!(f.run(&[b"ARSEEK", b"a", b"0"]), ":1\r\n");
assert_eq!(f.run(&[b"ARNEXT", b"a"]), ":0\r\n");
// The top of the space is the one index only ARSEEK will take, and it
// leaves the cursor with nowhere to go.
assert_eq!(f.run(&[b"ARSEEK", b"a", b"18446744073709551615"]), ":1\r\n");
assert_eq!(f.run(&[b"ARNEXT", b"a"]), "$-1\r\n");
assert_eq!(
f.run(&[b"ARINSERT", b"a", b"x"]),
"-ERR insert index overflow\r\n"
);
assert_eq!(
f.run(&[b"ARSET", b"a", b"18446744073709551615", b"x"]),
"-ERR invalid array index\r\n"
);
}
#[test]
fn a_ring_keeps_the_newest_and_renumbers_them_when_it_is_resized() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARRING", b"r", b"3", b"a", b"b", b"c"]), ":2\r\n");
assert_eq!(f.run(&[b"ARRING", b"r", b"3", b"d", b"e"]), ":1\r\n");
assert_eq!(f.run(&[b"ARLEN", b"r"]), ":3\r\n");
assert_eq!(
f.run(&[b"ARGETRANGE", b"r", b"0", b"2"]),
"*3\r\n$1\r\nd\r\n$1\r\ne\r\n$1\r\nc\r\n"
);
// Growing it after it has wrapped puts the survivors back in the order
// they arrived, which is the whole point of paying for the rebuild.
assert_eq!(f.run(&[b"ARRING", b"r", b"5", b"f"]), ":3\r\n");
assert_eq!(
f.run(&[b"ARGETRANGE", b"r", b"0", b"3"]),
"*4\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n$1\r\nf\r\n"
);
// The size is read before the key, so a bad one is a bad size wherever
// it is sent.
assert_eq!(
f.run(&[b"ARRING", b"r", b"0", b"x"]),
"-ERR size must be positive\r\n"
);
assert_eq!(
f.run(&[b"ARRING", b"r", b"big", b"x"]),
"-ERR invalid size\r\n"
);
}
#[test]
fn the_last_items_walk_back_from_the_cursor_and_report_the_holes() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARLASTITEMS", b"nope", b"5"]), "*0\r\n");
f.run(&[b"ARRING", b"r", b"4", b"a", b"b", b"c", b"d", b"e"]);
assert_eq!(
f.run(&[b"ARLASTITEMS", b"r", b"3"]),
"*3\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n"
);
assert_eq!(
f.run(&[b"ARLASTITEMS", b"r", b"3", b"rev"]),
"*3\r\n$1\r\ne\r\n$1\r\nd\r\n$1\r\nc\r\n"
);
assert_eq!(
f.run(&[b"ARLASTITEMS", b"r", b"99"]),
"*4\r\n$1\r\nb\r\n$1\r\nc\r\n$1\r\nd\r\n$1\r\ne\r\n",
"more than there is gets what there is"
);
// Nothing asked for is an empty reply, and Redis answers that before it
// has read the option or looked at the key.
assert_eq!(f.run(&[b"ARLASTITEMS", b"r", b"0", b"junk"]), "*0\r\n");
assert_eq!(
f.run(&[b"ARLASTITEMS", b"r", b"1", b"junk"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ARLASTITEMS", b"r", b"nine"]),
"-ERR invalid COUNT\r\n"
);
// With no cursor the tail of the array is the anchor, and a hole inside
// the window is reported as one.
f.run(&[b"ARMSET", b"h", b"0", b"x", b"2", b"z"]);
assert_eq!(
f.run(&[b"ARLASTITEMS", b"h", b"5"]),
"*2\r\n$-1\r\n$1\r\nz\r\n"
);
}
#[test]
fn a_scan_answers_pairs_for_what_is_there_and_skips_what_is_not() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARSCAN", b"nope", b"0", b"10"]), "*0\r\n");
f.run(&[b"ARMSET", b"a", b"0", b"x", b"7", b"y", b"1000000", b"z"]);
// The whole index space, which ARGETRANGE refuses and this one answers
// in three visits because holes cost nothing.
assert_eq!(
f.run(&[b"ARSCAN", b"a", b"0", b"18446744073709551614"]),
"*3\r\n*2\r\n:0\r\n$1\r\nx\r\n*2\r\n:7\r\n$1\r\ny\r\n*2\r\n:1000000\r\n$1\r\nz\r\n"
);
assert_eq!(
f.run(&[
b"ARSCAN",
b"a",
b"18446744073709551614",
b"0",
b"LIMIT",
b"1"
]),
"*1\r\n*2\r\n:1000000\r\n$1\r\nz\r\n"
);
assert_eq!(f.run(&[b"ARSCAN", b"a", b"1", b"6"]), "*0\r\n");
assert_eq!(
f.run(&[b"ARSCAN", b"a", b"0", b"10", b"LIMIT", b"0"]),
"-ERR LIMIT must be positive\r\n"
);
assert_eq!(
f.run(&[b"ARSCAN", b"a", b"0", b"10", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"ARSCAN", b"a", b"0", b"10", b"LIMIT"]),
"-ERR wrong number of arguments for 'arscan' command\r\n"
);
}
#[test]
fn a_grep_answers_the_indexes_whose_elements_match() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"ARGREP", b"nope", b"0", b"10", b"EXACT", b"x"]),
"*0\r\n"
);
f.run(&[b"ARSET", b"a", b"0", b"alpha", b"beta", b"gamma", b"ALPHA"]);
// The two bounds take the ends of the array as well as an index, and a
// reversed range is walked backwards the way ARSCAN walks one.
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-", b"+", b"GLOB", b"*a"]),
"*3\r\n:0\r\n:1\r\n:2\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"+", b"-", b"GLOB", b"*a"]),
"*3\r\n:2\r\n:1\r\n:0\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"1", b"2", b"GLOB", b"*a"]),
"*2\r\n:1\r\n:2\r\n"
);
// One test each. NOCASE reaches all four of them and it may be written
// after the pattern it applies to.
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-", b"+", b"EXACT", b"alpha"]),
"*1\r\n:0\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-", b"+", b"EXACT", b"alpha", b"NOCASE"]),
"*2\r\n:0\r\n:3\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-", b"+", b"MATCH", b"mm"]),
"*1\r\n:2\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-", b"+", b"RE", b"^[bg]"]),
"*2\r\n:1\r\n:2\r\n"
);
// OR is the default and AND has to be asked for, and either way the
// last of a repeated option wins.
let both: &[&[u8]] = &[
b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al",
];
assert_eq!(f.run(both), "*2\r\n:0\r\n:1\r\n");
assert_eq!(
f.run(&[
b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al", b"AND"
]),
"*0\r\n"
);
assert_eq!(
f.run(&[
b"ARGREP", b"a", b"-", b"+", b"EXACT", b"beta", b"MATCH", b"al", b"AND", b"OR"
]),
"*2\r\n:0\r\n:1\r\n"
);
// WITHVALUES turns each hit into a pair, and LIMIT counts the hits and
// not the positions it had to look at.
assert_eq!(
f.run(&[
b"ARGREP",
b"a",
b"-",
b"+",
b"MATCH",
b"a",
b"WITHVALUES",
b"LIMIT",
b"2"
]),
"*2\r\n*2\r\n:0\r\n$5\r\nalpha\r\n*2\r\n:1\r\n$4\r\nbeta\r\n"
);
assert_eq!(
f.run(&[
b"ARGREP", b"a", b"-", b"+", b"EXACT", b"ALPHA", b"LIMIT", b"1"
]),
"*1\r\n:3\r\n"
);
}
/// Everything ARGREP refuses, in the order it refuses it.
#[test]
fn a_grep_reports_a_broken_command_the_way_redis_does() {
let mut f = Fixture::new();
f.run(&[b"ARSET", b"a", b"0", b"alpha"]);
let syntax = "-ERR syntax error\r\n";
// The bounds are read before the plan, so a bad index beats a bad
// predicate whichever way round the two are written.
assert_eq!(
f.run(&[b"ARGREP", b"a", b"-1", b"0", b"NOPE", b"x"]),
"-ERR invalid array index\r\n"
);
assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOPE", b"x"]), syntax);
// A keyword with nothing after it, and a command that asks for nothing.
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOCASE", b"EXACT"]),
syntax
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT"]),
syntax
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"NOCASE", b"WITHVALUES"]),
syntax,
"a command with no predicate in it at all"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT", b"0"]),
"-ERR LIMIT must be positive\r\n"
);
assert_eq!(
f.run(&[
b"ARGREP", b"a", b"0", b"1", b"EXACT", b"x", b"LIMIT", b"nine"
]),
"-ERR value is not an integer or out of range\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", b""]),
"-ERR regular expression is empty\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", b"(a"]),
"-ERR invalid regular expression: Missing ')'\r\n"
);
assert_eq!(
f.run(&[b"ARGREP", b"a", b"0", b"1", b"RE", br"(a)\1"]),
"-ERR regular expression backreferences are not supported\r\n"
);
// The arity is minus six, so a predicate keyword with no pattern after
// it is short by one and never reaches the parser.
let arity = "-ERR wrong number of arguments for 'argrep' command\r\n";
assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1", b"EXACT"]), arity);
assert_eq!(f.run(&[b"ARGREP", b"a", b"0", b"1"]), arity);
}
#[test]
fn an_op_reduces_a_range_to_one_number() {
let mut f = Fixture::new();
f.run(&[b"ARSET", b"a", b"0", b"1", b"2.5", b"word", b"-4"]);
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"SUM"]),
"$4\r\n-0.5\r\n"
);
assert_eq!(f.run(&[b"AROP", b"a", b"0", b"10", b"min"]), "$2\r\n-4\r\n");
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"MAX"]),
"$3\r\n2.5\r\n"
);
assert_eq!(f.run(&[b"AROP", b"a", b"0", b"10", b"USED"]), ":4\r\n");
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"MATCH", b"word"]),
":1\r\n"
);
// An aggregate is written with seventeen significant digits, which is
// Redis's own choice and not what a score comes back as.
f.run(&[b"ARSET", b"t", b"0", b"0.1", b"0.2"]);
assert_eq!(
f.run(&[b"AROP", b"t", b"0", b"10", b"SUM"]),
"$19\r\n0.30000000000000004\r\n"
);
assert_eq!(f.run(&[b"ZADD", b"z", b"0.3", b"m"]), ":1\r\n");
assert_eq!(f.run(&[b"ZSCORE", b"z", b"m"]), "$3\r\n0.3\r\n");
// Nothing to work with is a null, and a missing key is a null for the
// aggregates and a zero for the two that count.
f.run(&[b"ARSET", b"w", b"0", b"word"]);
assert_eq!(f.run(&[b"AROP", b"w", b"0", b"10", b"SUM"]), "$-1\r\n");
assert_eq!(f.run(&[b"AROP", b"nope", b"0", b"10", b"SUM"]), "$-1\r\n");
assert_eq!(f.run(&[b"AROP", b"nope", b"0", b"10", b"USED"]), ":0\r\n");
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"NOPE"]),
"-ERR unknown operation\r\n"
);
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"MATCH"]),
"-ERR MATCH requires a value argument\r\n"
);
assert_eq!(
f.run(&[b"AROP", b"a", b"0", b"10", b"SUM", b"extra"]),
"-ERR wrong number of arguments for 'arop' command\r\n"
);
}
#[test]
fn the_info_is_a_map_and_a_missing_key_is_an_error() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"ARINFO", b"nope"]), "-ERR no such key\r\n");
f.run(&[b"ARINSERT", b"a", b"x", b"y"]);
let short = f.run(&[b"ARINFO", b"a"]);
assert!(
short.starts_with("*14\r\n"),
"seven pairs on RESP2: {short}"
);
assert!(short.contains("$5\r\ncount\r\n:2\r\n"), "{short}");
assert!(
short.contains("$17\r\nnext-insert-index\r\n:2\r\n"),
"{short}"
);
assert!(short.contains("$10\r\nslice-size\r\n:4096\r\n"), "{short}");
let full = f.run(&[b"ARINFO", b"a", b"full"]);
assert!(full.starts_with("*24\r\n"), "twelve pairs: {full}");
// Two values one apart are held sparsely, so the dense count is zero and
// the two dense averages have nothing to average.
assert!(full.contains("$12\r\ndense-slices\r\n:0\r\n"), "{full}");
assert!(full.contains("$13\r\nsparse-slices\r\n:1\r\n"), "{full}");
assert!(
full.contains("$14\r\navg-dense-size\r\n$1\r\n0\r\n"),
"{full}"
);
assert_eq!(f.run(&[b"ARINFO", b"a", b"nope"]), "-ERR syntax error\r\n");
// On RESP3 the same reply is a map and the averages are doubles.
let mut g = Fixture::new();
g.run(&[b"HELLO", b"3"]);
g.run(&[b"ARINSERT", b"a", b"x"]);
let map = g.run(&[b"ARINFO", b"a", b"FULL"]);
assert!(map.starts_with("%12\r\n"), "{map}");
assert!(map.contains("$5\r\ncount\r\n:1\r\n"), "{map}");
assert!(map.contains("$14\r\navg-dense-size\r\n,0\r\n"), "{map}");
}
#[test]
fn a_double_on_the_wire_is_written_the_way_redis_writes_one() {
let mut f = Fixture::new();
// Whole numbers up to two to the sixty second come back as integers,
// and past that the digit generator takes over and uses an exponent.
for (score, want) in [
("3", "3"),
("3.5", "3.5"),
("0.3", "0.3"),
("1e30", "1e+30"),
("1e19", "1e+19"),
("1e-7", "1e-7"),
("0.000001", "0.000001"),
("4611686018427387904", "4611686018427387904"),
("-0", "-0"),
] {
f.run(&[b"ZADD", b"z", score.as_bytes(), b"m"]);
assert_eq!(
f.run(&[b"ZSCORE", b"z", b"m"]),
format!("${}\r\n{want}\r\n", want.len()),
"score {score}"
);
}
// The same bytes on RESP3, where the reply is a double rather than a
// bulk string.
let mut g = Fixture::new();
g.run(&[b"HELLO", b"3"]);
g.run(&[b"ZADD", b"z", b"1e30", b"m"]);
assert_eq!(g.run(&[b"ZSCORE", b"z", b"m"]), ",1e+30\r\n");
// The two float increments are not this printer. They go through
// ld2string in its human mode, which is a fixed point conversion with
// the trailing zeros taken off, so they never write an exponent, and
// they reply with a bulk string on both protocols.
assert_eq!(
g.run(&[b"INCRBYFLOAT", b"s", b"1e30"]),
"$31\r\n1000000000000000000000000000000\r\n"
);
assert_eq!(g.run(&[b"INCRBYFLOAT", b"t", b"0.1"]), "$3\r\n0.1\r\n");
assert_eq!(
g.run(&[b"HINCRBYFLOAT", b"h", b"f", b"1e19"]),
"$20\r\n10000000000000000000\r\n"
);
}
// ----------------------------------------------------------------- graph
#[test]
fn a_node_comes_back_with_the_fields_it_went_in_with() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"G.NADD", b"social", b"ada", b"name", b"Ada", b"born", b"1815"
]),
":1\r\n"
);
// The year comes back as the four bytes that were sent and not as a
// number, because every property is text and there is nothing on the
// wire that says which of `1815` and `"1815"` the client meant. The
// fields are in the document's order, which is sorted by name, because
// that is what makes a field lookup a binary search.
assert_eq!(
f.run(&[b"G.NGET", b"social", b"ada"]),
"*4\r\n$4\r\nborn\r\n$4\r\n1815\r\n$4\r\nname\r\n$3\r\nAda\r\n"
);
// A second write to the same id replaces the document and says so with
// a zero, so an ingest can count what it created.
assert_eq!(
f.run(&[b"G.NADD", b"social", b"ada", b"name", b"Ada Lovelace"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"G.NGET", b"social", b"ada"]),
"*2\r\n$4\r\nname\r\n$12\r\nAda Lovelace\r\n"
);
// A node with no properties is an empty map and not a null, which is
// how a client tells an isolated node from one that is not there.
assert_eq!(f.run(&[b"G.NADD", b"social", b"grace"]), ":1\r\n");
assert_eq!(f.run(&[b"G.NGET", b"social", b"grace"]), "*0\r\n");
assert_eq!(f.run(&[b"G.NGET", b"social", b"nobody"]), "$-1\r\n");
assert_eq!(f.run(&[b"G.NGET", b"nokey", b"ada"]), "$-1\r\n");
// A field with no value creates nothing, because the pairs are checked
// before the key is touched.
assert_eq!(
f.run(&[b"G.NADD", b"fresh", b"n", b"lonely"]),
"-ERR syntax error\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"fresh"]), ":0\r\n");
// On RESP3 the same reply is a map.
let mut g = Fixture::new();
g.run(&[b"HELLO", b"3"]);
g.run(&[b"G.NADD", b"social", b"ada", b"name", b"Ada"]);
assert_eq!(
g.run(&[b"G.NGET", b"social", b"ada"]),
"%1\r\n$4\r\nname\r\n$3\r\nAda\r\n"
);
}
#[test]
fn an_edge_creates_the_ends_it_needs() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"G.EADD", b"social", b"ada", b"grace", b"FOLLOWS", b"since", b"1843"
]),
":1\r\n"
);
// Neither end was written first and both are there, as empty nodes.
assert_eq!(f.run(&[b"G.NGET", b"social", b"ada"]), "*0\r\n");
assert_eq!(f.run(&[b"G.NGET", b"social", b"grace"]), "*0\r\n");
assert_eq!(
f.run(&[b"G.OUT", b"social", b"ada", b"FOLLOWS"]),
"*2\r\n$1\r\n0\r\n*1\r\n$5\r\ngrace\r\n"
);
assert_eq!(
f.run(&[b"G.IN", b"social", b"grace", b"FOLLOWS"]),
"*2\r\n$1\r\n0\r\n*1\r\n$3\r\nada\r\n"
);
// The same pair under the same label again updates the edge rather than
// making a second one.
assert_eq!(
f.run(&[
b"G.EADD", b"social", b"ada", b"grace", b"FOLLOWS", b"since", b"1844"
]),
":0\r\n"
);
assert_eq!(f.run(&[b"G.DEG", b"social", b"ada", b"FOLLOWS"]), ":1\r\n");
// A different label between the same pair is a different edge.
assert_eq!(
f.run(&[b"G.EADD", b"social", b"ada", b"grace", b"WORKS_WITH"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"G.DEG", b"social", b"ada", b"WORKS_WITH"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"G.EDEL", b"social", b"ada", b"grace", b"FOLLOWS"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"G.EDEL", b"social", b"ada", b"grace", b"FOLLOWS"]),
":0\r\n"
);
// A label nothing has used, an end that is not there, and a key that is
// not there are all a zero rather than an error.
assert_eq!(
f.run(&[b"G.EDEL", b"social", b"ada", b"grace", b"NEVER"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"G.EDEL", b"social", b"ada", b"nobody", b"FOLLOWS"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"G.EDEL", b"nokey", b"ada", b"grace", b"FOLLOWS"]),
":0\r\n"
);
}
/// A run is paged the way `SCAN` is paged, so a client that can walk one
/// can walk the other.
#[test]
fn a_hop_answers_a_cursor_and_a_page() {
let mut f = Fixture::new();
for i in 0..25u32 {
let dst = format!("n{i}");
f.run(&[b"G.EADD", b"social", b"hub", dst.as_bytes(), b"FOLLOWS"]);
}
// Ten without being asked, and the cursor is where to carry on from.
let first = f.run(&[b"G.OUT", b"social", b"hub", b"FOLLOWS"]);
assert!(first.starts_with("*2\r\n$2\r\n10\r\n*10\r\n"), "{first}");
let mut seen = 0;
let mut cursor = String::from("0");
loop {
let page = f.run(&[
b"G.OUT",
b"social",
b"hub",
b"FOLLOWS",
b"COUNT",
b"7",
b"CURSOR",
cursor.as_bytes(),
]);
let (head, rest) = page.split_once("\r\n*").expect("a cursor and a page");
cursor = head
.rsplit("\r\n")
.next()
.expect("the cursor line")
.to_string();
seen += rest
.split_once("\r\n")
.expect("the page length")
.0
.parse::<usize>()
.expect("a length");
if cursor == "0" {
break;
}
}
assert_eq!(seen, 25, "every neighbour once across the pages");
// A cursor past the end is an empty page and not an error, and so is a
// key or a label that is not there.
assert_eq!(
f.run(&[b"G.OUT", b"social", b"hub", b"FOLLOWS", b"CURSOR", b"900"]),
"*2\r\n$1\r\n0\r\n*0\r\n"
);
assert_eq!(
f.run(&[b"G.OUT", b"social", b"hub", b"NEVER"]),
"*2\r\n$1\r\n0\r\n*0\r\n"
);
assert_eq!(
f.run(&[b"G.OUT", b"nokey", b"hub", b"FOLLOWS"]),
"*2\r\n$1\r\n0\r\n*0\r\n"
);
assert_eq!(
f.run(&[b"G.OUT", b"social", b"hub", b"FOLLOWS", b"COUNT", b"0"]),
"-ERR COUNT must be a positive integer\r\n"
);
assert_eq!(
f.run(&[b"G.OUT", b"social", b"hub", b"FOLLOWS", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
}
#[test]
fn a_degree_counts_one_way_or_both() {
let mut f = Fixture::new();
f.run(&[b"G.EADD", b"social", b"a", b"b", b"F"]);
f.run(&[b"G.EADD", b"social", b"a", b"c", b"F"]);
f.run(&[b"G.EADD", b"social", b"d", b"a", b"F"]);
assert_eq!(f.run(&[b"G.DEG", b"social", b"a", b"F"]), ":2\r\n");
assert_eq!(f.run(&[b"G.DEG", b"social", b"a", b"F", b"OUT"]), ":2\r\n");
assert_eq!(f.run(&[b"G.DEG", b"social", b"a", b"F", b"IN"]), ":1\r\n");
assert_eq!(f.run(&[b"G.DEG", b"social", b"a", b"F", b"BOTH"]), ":3\r\n");
assert_eq!(f.run(&[b"G.DEG", b"social", b"nobody", b"F"]), ":0\r\n");
assert_eq!(f.run(&[b"G.DEG", b"social", b"a", b"NEVER"]), ":0\r\n");
assert_eq!(f.run(&[b"G.DEG", b"nokey", b"a", b"F"]), ":0\r\n");
assert_eq!(
f.run(&[b"G.DEG", b"social", b"a", b"F", b"SIDEWAYS"]),
"-ERR syntax error\r\n"
);
}
/// A walk answers which nodes it can reach and not by how many routes, so a
/// node two ways out is in the frontier once.
#[test]
fn a_walk_reaches_each_node_once_however_many_ways_there_are() {
let mut f = Fixture::new();
for (src, dst) in [
("ada", "grace"),
("ada", "alan"),
("grace", "edsger"),
("alan", "edsger"),
("edsger", "barbara"),
] {
f.run(&[b"G.EADD", b"social", src.as_bytes(), dst.as_bytes(), b"F"]);
}
// Two hops without being asked, the start left out, and edsger once
// even though both of the first hop's nodes point at it.
assert_eq!(
f.run(&[b"G.NEIGH", b"social", b"ada", b"F"]),
"*3\r\n$5\r\ngrace\r\n$4\r\nalan\r\n$6\r\nedsger\r\n"
);
assert_eq!(
f.run(&[b"G.NEIGH", b"social", b"ada", b"F", b"DEPTH", b"1"]),
"*2\r\n$5\r\ngrace\r\n$4\r\nalan\r\n"
);
let deep = f.run(&[b"G.NEIGH", b"social", b"ada", b"F", b"DEPTH", b"9"]);
assert!(deep.starts_with("*4\r\n"), "the whole component: {deep}");
assert!(deep.contains("$7\r\nbarbara\r\n"), "{deep}");
// COUNT stops the walk rather than trimming what it found.
assert_eq!(
f.run(&[b"G.NEIGH", b"social", b"ada", b"F", b"COUNT", b"1"]),
"*1\r\n$5\r\ngrace\r\n"
);
// A node nothing leaves is an empty array and not an error.
assert_eq!(f.run(&[b"G.NEIGH", b"social", b"barbara", b"F"]), "*0\r\n");
assert_eq!(f.run(&[b"G.NEIGH", b"social", b"ada", b"NEVER"]), "*0\r\n");
assert_eq!(f.run(&[b"G.NEIGH", b"nokey", b"ada", b"F"]), "*0\r\n");
assert_eq!(
f.run(&[b"G.NEIGH", b"social", b"ada", b"F", b"DEPTH", b"0"]),
"-ERR DEPTH must be a positive integer\r\n"
);
assert_eq!(
f.run(&[b"G.NEIGH", b"social", b"ada", b"F", b"NOPE", b"1"]),
"-ERR syntax error\r\n"
);
}
/// The two sided search, which is the whole reason `G.PATH` is a command
/// and not something a client builds out of `G.OUT`.
#[test]
fn a_path_is_the_shortest_one_and_goes_over_any_label() {
let mut f = Fixture::new();
// A chain of six, and a shortcut that makes a shorter way round under a
// second label so the search has to take either kind of hop.
for i in 0..6u32 {
let src = format!("n{i}");
let dst = format!("n{}", i + 1);
f.run(&[b"G.EADD", b"road", src.as_bytes(), dst.as_bytes(), b"STEP"]);
}
assert_eq!(
f.run(&[b"G.PATH", b"road", b"n0", b"n6"]),
"*7\r\n$2\r\nn0\r\n$2\r\nn1\r\n$2\r\nn2\r\n$2\r\nn3\r\n$2\r\nn4\r\n$2\r\nn5\r\n$2\r\nn6\r\n"
);
f.run(&[b"G.EADD", b"road", b"n0", b"n5", b"JUMP"]);
assert_eq!(
f.run(&[b"G.PATH", b"road", b"n0", b"n6"]),
"*3\r\n$2\r\nn0\r\n$2\r\nn5\r\n$2\r\nn6\r\n"
);
// A node to itself is a path of one, and a depth too short to reach is
// no path at all.
assert_eq!(
f.run(&[b"G.PATH", b"road", b"n2", b"n2"]),
"*1\r\n$2\r\nn2\r\n"
);
assert_eq!(
f.run(&[b"G.PATH", b"road", b"n0", b"n6", b"MAXDEPTH", b"1"]),
"*0\r\n"
);
// Direction counts: the chain only goes one way.
assert_eq!(f.run(&[b"G.PATH", b"road", b"n6", b"n0"]), "*0\r\n");
// An unreachable node, a node that is not there, and a key that is not
// there are the same empty answer.
f.run(&[b"G.NADD", b"road", b"island"]);
assert_eq!(f.run(&[b"G.PATH", b"road", b"n0", b"island"]), "*0\r\n");
assert_eq!(f.run(&[b"G.PATH", b"road", b"n0", b"nobody"]), "*0\r\n");
assert_eq!(f.run(&[b"G.PATH", b"nokey", b"n0", b"n6"]), "*0\r\n");
assert_eq!(
f.run(&[b"G.PATH", b"road", b"n0", b"n6", b"NOPE", b"3"]),
"-ERR syntax error\r\n"
);
}
/// The point of the escape in the record tag: the keyspace owns a graph key
/// the way it owns every other key, and none of these commands know a graph
/// exists.
#[test]
fn the_keyspace_sees_a_graph_key_like_any_other() {
let mut f = Fixture::new();
f.run(&[b"G.EADD", b"social", b"ada", b"grace", b"F"]);
assert_eq!(f.run(&[b"TYPE", b"social"]), "+graph\r\n");
assert_eq!(
f.run(&[b"OBJECT", b"ENCODING", b"social"]),
"$9\r\nadjacency\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"social"]), ":1\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
assert_eq!(f.run(&[b"KEYS", b"*"]), "*1\r\n$6\r\nsocial\r\n");
// A graph is counted against the server the way every other body is,
// which is what `maxmemory` will read when this key is a million nodes.
// There is no `MEMORY USAGE` command yet, so this asks the server.
let held = f.server.memory_bytes();
for i in 0..200u32 {
let dst = format!("n{i}");
f.run(&[b"G.EADD", b"big", b"hub", dst.as_bytes(), b"F"]);
}
assert!(
f.server.memory_bytes() > held,
"two hundred edges cost something: {held} then {}",
f.server.memory_bytes()
);
f.run(&[b"DEL", b"big"]);
// An expiry, then a rename, then a move to another database, all of
// which are the keyspace moving a record it cannot look inside.
assert_eq!(f.run(&[b"EXPIRE", b"social", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"PERSIST", b"social"]), ":1\r\n");
assert_eq!(f.run(&[b"RENAME", b"social", b"net"]), "+OK\r\n");
assert_eq!(f.run(&[b"MOVE", b"net", b"1"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"net"]), ":0\r\n");
f.run(&[b"SELECT", b"1"]);
assert_eq!(f.run(&[b"G.DEG", b"net", b"ada", b"F"]), ":1\r\n");
assert_eq!(f.run(&[b"DEL", b"net"]), ":1\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
f.run(&[b"G.NADD", b"g", b"n"]);
assert_eq!(f.run(&[b"FLUSHDB"]), "+OK\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
}
/// Neither `COPY` nor `DUMP` has a byte shape for a graph, so both say so
/// rather than answering the way they answer for a key that is not there.
#[test]
fn a_graph_cannot_be_copied_or_dumped() {
let mut f = Fixture::new();
f.run(&[b"G.NADD", b"social", b"ada"]);
assert_eq!(
f.run(&[b"COPY", b"social", b"other"]),
"-ERR COPY is not supported for a graph\r\n"
);
assert_eq!(
f.run(&[b"COPY", b"social", b"other", b"DB", b"1"]),
"-ERR COPY is not supported for a graph\r\n"
);
assert_eq!(
f.run(&[b"DUMP", b"social"]),
"-ERR DUMP is not supported for a graph\r\n"
);
// A refused copy leaves both keys exactly as they were.
assert_eq!(f.run(&[b"EXISTS", b"social", b"other"]), ":1\r\n");
}
/// A graph key is a key, so the commands for the other types refuse it and
/// the graph commands refuse theirs.
#[test]
fn a_graph_and_a_string_are_the_wrong_type_for_each_other() {
let wrong = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n";
let mut f = Fixture::new();
f.run(&[b"G.NADD", b"social", b"ada"]);
assert_eq!(f.run(&[b"GET", b"social"]), wrong);
assert_eq!(f.run(&[b"LPUSH", b"social", b"x"]), wrong);
assert_eq!(f.run(&[b"SADD", b"social", b"x"]), wrong);
f.run(&[b"SET", b"str", b"v"]);
for cmd in [
vec![b"G.NADD".as_ref(), b"str", b"n"],
vec![b"G.NGET".as_ref(), b"str", b"n"],
vec![b"G.NDEL".as_ref(), b"str", b"n"],
vec![b"G.EADD".as_ref(), b"str", b"a", b"b", b"F"],
vec![b"G.EDEL".as_ref(), b"str", b"a", b"b", b"F"],
vec![b"G.OUT".as_ref(), b"str", b"a", b"F"],
vec![b"G.IN".as_ref(), b"str", b"a", b"F"],
vec![b"G.DEG".as_ref(), b"str", b"a", b"F"],
vec![b"G.NEIGH".as_ref(), b"str", b"a", b"F"],
vec![b"G.PATH".as_ref(), b"str", b"a", b"b"],
] {
assert_eq!(f.run(&cmd), wrong, "{:?}", cmd[0]);
}
}
/// Every other collection here takes its key with it when its last member
/// goes, and a graph is no different.
#[test]
fn a_graph_goes_when_its_last_node_does() {
let mut f = Fixture::new();
f.run(&[
b"G.EADD", b"social", b"ada", b"grace", b"F", b"since", b"1843",
]);
assert_eq!(f.run(&[b"G.NDEL", b"social", b"ada"]), ":1\r\n");
// The node and the edges that hung off it are both gone.
assert_eq!(f.run(&[b"G.NGET", b"social", b"ada"]), "$-1\r\n");
assert_eq!(
f.run(&[b"G.DEG", b"social", b"grace", b"F", b"IN"]),
":0\r\n"
);
assert_eq!(f.run(&[b"G.NDEL", b"social", b"ada"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"social"]), ":1\r\n");
assert_eq!(f.run(&[b"G.NDEL", b"social", b"grace"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"social"]), ":0\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":0\r\n");
assert_eq!(f.run(&[b"G.NDEL", b"nokey", b"ada"]), ":0\r\n");
// The id the removed node had is not handed out again, so a client
// holding an id from an earlier reply cannot have it mean another node.
f.run(&[b"G.NADD", b"social", b"first"]);
f.run(&[b"G.NADD", b"social", b"second"]);
f.run(&[b"G.NDEL", b"social", b"first"]);
f.run(&[b"G.EADD", b"social", b"third", b"second", b"F"]);
assert_eq!(
f.run(&[b"G.OUT", b"social", b"third", b"F"]),
"*2\r\n$1\r\n0\r\n*1\r\n$6\r\nsecond\r\n"
);
}
// ------------------------------------------------------------------ json
/// The two path syntaxes answer different shapes, which is the thing a
/// client is most likely to be broken by and so the thing to pin first.
#[test]
fn a_json_path_answers_a_set_and_a_legacy_path_answers_a_value() {
let mut f = Fixture::new();
let doc = br#"{"a":1,"b":{"c":true}}"#;
assert_eq!(f.run(&[b"JSON.SET", b"doc", b"$", doc]), "+OK\r\n");
// No path at all is the legacy root and not `$`, so the document comes
// back as itself rather than wrapped.
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"a":1,"b":{"c":true}}"#)
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b"$.a"]), bulk("[1]"));
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("1"));
assert_eq!(f.run(&[b"JSON.GET", b"doc", b"$..c"]), bulk("[true]"));
// A path that matched nothing is an empty set on one syntax and an
// error on the other, and the error does not quote the path.
assert_eq!(f.run(&[b"JSON.GET", b"doc", b"$.nope"]), bulk("[]"));
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".nope"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"nokey"]), "$-1\r\n");
// The key is a document to the rest of the keyspace, under the name
// RedisJSON registers, and every generic command works on it.
assert_eq!(f.run(&[b"TYPE", b"doc"]), "+ReJSON-RL\r\n");
assert_eq!(f.run(&[b"EXISTS", b"doc"]), ":1\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"doc"]), bulk("raw"));
assert_eq!(f.run(&[b"DEL", b"doc"]), ":1\r\n");
assert_eq!(f.run(&[b"JSON.GET", b"doc"]), "$-1\r\n");
}
/// The two error lines RedisJSON sends without a prefix in front of them.
///
/// Every other error this server writes starts `ERR` or `WRONGTYPE`. These
/// two do not, on a real server, and a differential harness compares the
/// whole line.
#[test]
fn the_two_json_errors_that_carry_no_prefix() {
let mut f = Fixture::new();
f.run(&[b"SET", b"plain", b"x"]);
let wrong = "-Existing key has wrong Redis type\r\n";
assert_eq!(f.run(&[b"JSON.GET", b"plain"]), wrong);
assert_eq!(f.run(&[b"JSON.SET", b"plain", b"$", b"1"]), wrong);
assert_eq!(f.run(&[b"JSON.DEL", b"plain"]), wrong);
assert_eq!(f.run(&[b"JSON.TYPE", b"plain"]), wrong);
assert_eq!(f.run(&[b"JSON.CLEAR", b"plain"]), wrong);
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":{"z":1},"b":{"z":2}}"#]);
// A wildcard that matched something writes to all of it. A wildcard
// that matched nothing would have to invent a place, and that is the
// other unprefixed line.
assert_eq!(f.run(&[b"JSON.SET", b"doc", b"$.*.z", b"9"]), "+OK\r\n");
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"a":{"z":9},"b":{"z":9}}"#)
);
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.*.y", b"9"]),
"-Err wrong static path\r\n"
);
}
/// What `JSON.SET` does with a path that named nowhere.
#[test]
fn json_set_creates_one_field_and_refuses_to_invent_the_rest() {
let mut f = Fixture::new();
// A key that is not there can only be written whole.
assert_eq!(
f.run(&[b"JSON.SET", b"new", b".a", b"1"]),
"-ERR new objects must be created at the root\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"new"]), ":0\r\n");
// The root check comes before NX and XX, which is the order a real
// server checks them in.
assert_eq!(
f.run(&[b"JSON.SET", b"new", b".a", b"1", b"NX"]),
"-ERR new objects must be created at the root\r\n"
);
assert_eq!(f.run(&[b"JSON.SET", b"new", b"$", b"1", b"XX"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.SET", b"new", b"$", b"1", b"NX"]), "+OK\r\n");
f.run(&[
b"JSON.SET",
b"doc",
b"$",
br#"{"o":{},"arr":[1,2],"s":"x"}"#,
]);
// One step past a container that is there is a place to write.
assert_eq!(f.run(&[b"JSON.SET", b"doc", b"$.o.made", b"1"]), "+OK\r\n");
// One step past something that is not, or past something that is not an
// object, is not an error and is not a write either.
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.nope.made", b"1"]),
"$-1\r\n"
);
assert_eq!(f.run(&[b"JSON.SET", b"doc", b"$.s.made", b"1"]), "$-1\r\n");
// An index past the end does not append. JSON.ARRAPPEND appends.
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.arr[5]", b"9"]),
"-ERR array index out of range\r\n"
);
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.arr[2]", b"9"]),
"-ERR array index out of range\r\n"
);
assert_eq!(f.run(&[b"JSON.SET", b"doc", b"$.arr[1]", b"9"]), "+OK\r\n");
// NX on a path that is there and XX on a path that is not are both a
// nil and neither changes anything.
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.o.made", b"2", b"NX"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.gone", b"2", b"XX"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"o":{"made":1},"s":"x","arr":[1,9]}"#)
);
// Text that is not JSON is refused before the key is touched. The
// line has no `ERR` in front of it, which is this command's and not
// every command's, and is in D-37.
assert!(
f.run(&[b"JSON.SET", b"doc", b"$.s", b"nope"])
.starts_with("-this is not the start of a value")
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".s"]), bulk("\"x\""));
}
/// `JSON.DEL`, `JSON.TYPE`, `JSON.TOGGLE` and `JSON.CLEAR`, each of which
/// answers a count or a word rather than text.
#[test]
fn the_json_commands_that_do_not_answer_text() {
let mut f = Fixture::new();
let doc = br#"{"a":1,"t":true,"o":{"x":1},"arr":[1,2],"f":1.5,"s":"x","n":null}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
assert_eq!(f.run(&[b"JSON.TYPE", b"doc"]), bulk("object"));
assert_eq!(f.run(&[b"JSON.TYPE", b"doc", b".a"]), bulk("integer"));
assert_eq!(f.run(&[b"JSON.TYPE", b"doc", b".f"]), bulk("number"));
assert_eq!(
f.run(&[b"JSON.TYPE", b"doc", b"$.a"]),
format!("*1\r\n{}", bulk("integer"))
);
// The one place a legacy path that matched nothing is a nil rather than
// an error, which lines up with a key that is not there.
assert_eq!(f.run(&[b"JSON.TYPE", b"doc", b".nope"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.TYPE", b"nokey"]), "$-1\r\n");
// A boolean flips and answers the value it now has, as an integer on
// one syntax and as the word on the other.
assert_eq!(f.run(&[b"JSON.TOGGLE", b"doc", b"$.t"]), "*1\r\n:0\r\n");
assert_eq!(f.run(&[b"JSON.TOGGLE", b"doc", b".t"]), bulk("true"));
// Something that is not a boolean is a hole on one syntax and one
// sentence covering both cases on the other.
assert_eq!(f.run(&[b"JSON.TOGGLE", b"doc", b"$.a"]), "*1\r\n$-1\r\n");
assert_eq!(
f.run(&[b"JSON.TOGGLE", b"doc", b".a"]),
"-ERR Path does not exist or not a bool\r\n"
);
assert_eq!(
f.run(&[b"JSON.TOGGLE", b"doc", b".nope"]),
"-ERR Path does not exist or not a bool\r\n"
);
assert_eq!(
f.run(&[b"JSON.TOGGLE", b"nokey", b"$.a"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
// Clearing empties containers and zeroes numbers and leaves everything
// else alone, and counts only what it changed.
assert_eq!(f.run(&[b"JSON.CLEAR", b"doc", b"$.s"]), ":0\r\n");
assert_eq!(f.run(&[b"JSON.CLEAR", b"doc", b"$.*"]), ":4\r\n");
assert_eq!(f.run(&[b"JSON.CLEAR", b"doc", b"$.*"]), ":0\r\n");
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"a":0,"f":0,"n":null,"o":{},"s":"x","t":true,"arr":[]}"#)
);
// Deleting counts what it removed, and deleting the root is deleting
// the key.
assert_eq!(f.run(&[b"JSON.DEL", b"doc", b"$.nope"]), ":0\r\n");
assert_eq!(f.run(&[b"JSON.DEL", b"doc", b"$.a"]), ":1\r\n");
// Deleting the last member of the root container deletes the key, the
// same way popping the last element off a list does. It is a rule about
// deleting and not about shape: a document written as an empty object
// by JSON.SET stays, because nothing was removed from it.
assert_eq!(f.run(&[b"JSON.FORGET", b"doc", b"$.*"]), ":6\r\n");
assert_eq!(f.run(&[b"EXISTS", b"doc"]), ":0\r\n");
assert_eq!(f.run(&[b"JSON.GET", b"doc"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.DEL", b"doc"]), ":0\r\n");
assert_eq!(f.run(&[b"JSON.SET", b"empty", b"$", b"{}"]), "+OK\r\n");
assert_eq!(f.run(&[b"EXISTS", b"empty"]), ":1\r\n");
assert_eq!(f.run(&[b"JSON.GET", b"empty"]), bulk("{}"));
assert_eq!(f.run(&[b"JSON.DEL", b"nokey"]), ":0\r\n");
}
/// `JSON.GET` with more than one path, and with a layout.
///
/// The wrapper the reply is built in is laid out too, so what a path
/// matched starts one level in for a single JSONPath and two for one of
/// several, and getting that wrong is the kind of thing only a byte for
/// byte comparison catches.
#[test]
fn json_get_lays_out_the_wrapper_it_builds() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":1,"b":[1,{"c":2}]}"#]);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$.a", b"$.b"]),
bulk(r#"{"$.a":[1],"$.b":[[1,{"c":2}]]}"#)
);
// Legacy paths are not wrapped, even when there are several of them.
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".a", b".b"]),
bulk(r#"{".a":1,".b":[1,{"c":2}]}"#)
);
let fmt: &[&[u8]] = &[b"INDENT", b" ", b"NEWLINE", b"\n", b"SPACE", b" "];
let mut one = vec![b"JSON.GET".as_slice(), b"doc"];
one.extend_from_slice(fmt);
one.push(b"$.b");
assert_eq!(
f.run(&one),
bulk("[\n [\n 1,\n {\n \"c\": 2\n }\n ]\n]")
);
let mut two = vec![b"JSON.GET".as_slice(), b"doc"];
two.extend_from_slice(fmt);
two.push(b"$.a");
two.push(b"$.nope");
assert_eq!(
f.run(&two),
bulk("{\n \"$.a\": [\n 1\n ],\n \"$.nope\": []\n}")
);
// The options are read before the paths and in any order, and a
// document with nothing to lay out is the same either way.
let mut root = vec![b"JSON.GET".as_slice(), b"doc", b"SPACE", b" "];
root.push(b".a");
assert_eq!(f.run(&root), bulk("1"));
}
/// `JSON.MGET`, which is the only command here that reads more than one key
/// and so the only one whose answer has holes in it.
#[test]
fn json_mget_answers_once_per_key_whatever_is_under_them() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"one", b"$", br#"{"a":1}"#]);
f.run(&[b"JSON.SET", b"two", b"$", br#"{"a":2}"#]);
f.run(&[b"SET", b"plain", b"x"]);
assert_eq!(
f.run(&[b"JSON.MGET", b"one", b"two", b"$.a"]),
format!("*2\r\n{}{}", bulk("[1]"), bulk("[2]"))
);
// A key that is not there and a key holding something else are both a
// hole rather than an error, the way MGET treats a hash.
assert_eq!(
f.run(&[b"JSON.MGET", b"one", b"nokey", b"plain", b".a"]),
format!("*3\r\n{}$-1\r\n$-1\r\n", bulk("1"))
);
// A legacy path that matched nothing is a hole too, because one bad
// answer should not lose the others.
assert_eq!(f.run(&[b"JSON.MGET", b"one", b".nope"]), "*1\r\n$-1\r\n");
}
/// The four commands that ask how big something is, and the four different
/// sets of answers they give for the same three failures.
///
/// There is no pattern in this and there is no reading it off the
/// documentation either. It was read off a running RedisJSON one line at a
/// time, and it is written down here because the error text is what a client
/// library branches on.
#[test]
fn the_json_commands_that_answer_a_size_disagree_about_every_failure() {
let mut f = Fixture::new();
let doc = br#"{"a":[1,2,3],"o":{"x":1,"y":2},"s":"hello","n":7}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
assert_eq!(f.run(&[b"JSON.ARRLEN", b"doc", b".a"]), ":3\r\n");
assert_eq!(f.run(&[b"JSON.ARRLEN", b"doc", b"$.a"]), "*1\r\n:3\r\n");
assert_eq!(f.run(&[b"JSON.OBJLEN", b"doc", b".o"]), ":2\r\n");
assert_eq!(f.run(&[b"JSON.STRLEN", b"doc", b".s"]), ":5\r\n");
assert_eq!(
f.run(&[b"JSON.OBJKEYS", b"doc", b".o"]),
format!("*2\r\n{}{}", bulk("x"), bulk("y"))
);
// A JSONPath answers one entry per match and a hole for a match of the
// wrong kind, which is the one shape all four agree on.
assert_eq!(
f.run(&[b"JSON.ARRLEN", b"doc", b"$.*"]),
"*4\r\n:3\r\n$-1\r\n$-1\r\n$-1\r\n"
);
// A legacy path that matched nothing. Two of them are an error and two
// of them are a nil, and the two errors do not use the same sentence.
assert_eq!(
f.run(&[b"JSON.ARRLEN", b"doc", b".nope"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRLEN", b"doc", b".nope"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(f.run(&[b"JSON.OBJLEN", b"doc", b".nope"]), "$-1\r\n");
// A nil bulk and not an empty array, even though the answer would have
// been an array, which is what RedisJSON sends here too.
assert_eq!(f.run(&[b"JSON.OBJKEYS", b"doc", b".nope"]), "$-1\r\n");
// The JSONPath spelling of the same question is an empty array, since
// no match is not a failure on that syntax.
assert_eq!(f.run(&[b"JSON.OBJKEYS", b"doc", b"$.nope"]), "*0\r\n");
// A legacy path that matched the wrong kind of value. Now two of them
// are an ERR and two of them are a WRONGTYPE, and it is not the same
// two.
assert_eq!(
f.run(&[b"JSON.ARRLEN", b"doc", b".n"]),
"-ERR Path does not exist or not an array\r\n"
);
assert_eq!(
f.run(&[b"JSON.OBJKEYS", b"doc", b".n"]),
"-ERR Path does not exist or not an object\r\n"
);
assert_eq!(
f.run(&[b"JSON.OBJLEN", b"doc", b".n"]),
"-WRONGTYPE wrong type of path value - expected object\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRLEN", b"doc", b".n"]),
"-WRONGTYPE wrong type of path value - expected string\r\n"
);
// A key that is not there, where the two syntaxes swap over: the legacy
// path is the quiet answer and the JSONPath is the error.
assert_eq!(f.run(&[b"JSON.ARRLEN", b"nokey", b".a"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.OBJLEN", b"nokey", b".a"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.STRLEN", b"nokey", b".a"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.OBJKEYS", b"nokey", b".a"]), "$-1\r\n");
assert_eq!(
f.run(&[b"JSON.ARRLEN", b"nokey", b"$.a"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
// Except this one, which answers about the path instead.
assert_eq!(
f.run(&[b"JSON.OBJLEN", b"nokey", b"$.a"]),
"-ERR Path does not exist or not an object\r\n"
);
}
/// `JSON.ARRAPPEND`, `JSON.ARRINSERT`, `JSON.ARRTRIM` and `JSON.ARRPOP`.
///
/// The four of them share one error line for a path that named something
/// that is not an array, and they disagree about what an index outside the
/// array means: insert refuses it and the other two clamp.
#[test]
fn the_json_array_writes_agree_on_the_errors_and_not_on_the_indexes() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,2,3],"n":7}"#]);
assert_eq!(f.run(&[b"JSON.ARRAPPEND", b"doc", b".a", b"4"]), ":4\r\n");
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b"$.a", b"5", b"6"]),
"*1\r\n:6\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("[1,2,3,4,5,6]"));
// A negative index counts back from the end, and the end itself is a
// place to insert at, so an insert at the length is an append.
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b".a", b"-1", b"0"]),
":7\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".a"]),
bulk("[1,2,3,4,5,0,6]")
);
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b".a", b"7", b"9"]),
":8\r\n"
);
// One past the end is not, and neither is one before the front.
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b".a", b"9", b"9"]),
"-ERR index out of bounds\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b".a", b"-9", b"9"]),
"-ERR index out of bounds\r\n"
);
// Trim takes both ends inclusive and clamps both of them, so a start
// past the end leaves an empty array rather than an error.
f.run(&[b"JSON.SET", b"doc", b"$.a", b"[1,2,3,4,5]"]);
assert_eq!(
f.run(&[b"JSON.ARRTRIM", b"doc", b".a", b"1", b"3"]),
":3\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("[2,3,4]"));
assert_eq!(
f.run(&[b"JSON.ARRTRIM", b"doc", b".a", b"-2", b"99"]),
":2\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("[3,4]"));
assert_eq!(
f.run(&[b"JSON.ARRTRIM", b"doc", b".a", b"9", b"9"]),
":0\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("[]"));
// Pop clamps as well, its default is the last element, and an empty
// array pops a nil rather than failing.
f.run(&[b"JSON.SET", b"doc", b"$.a", b"[1,2,3]"]);
assert_eq!(f.run(&[b"JSON.ARRPOP", b"doc", b".a"]), bulk("3"));
assert_eq!(f.run(&[b"JSON.ARRPOP", b"doc", b".a", b"0"]), bulk("1"));
assert_eq!(f.run(&[b"JSON.ARRPOP", b"doc", b".a", b"99"]), bulk("2"));
assert_eq!(f.run(&[b"JSON.ARRPOP", b"doc", b".a"]), "$-1\r\n");
// One sentence covers a path that matched nothing and a path that
// matched the wrong kind of value, for all four of them.
for call in [
&[&b"JSON.ARRAPPEND"[..], b"doc", b"PATH", b"1"][..],
&[&b"JSON.ARRTRIM"[..], b"doc", b"PATH", b"1", b"1"][..],
&[&b"JSON.ARRPOP"[..], b"doc", b"PATH", b"1"][..],
&[&b"JSON.ARRINSERT"[..], b"doc", b"PATH", b"0", b"1"][..],
] {
for path in [&b".n"[..], &b".nope"[..]] {
let args: Vec<&[u8]> = call
.iter()
.map(|a| if *a == b"PATH" { path } else { *a })
.collect();
assert_eq!(
f.run(&args),
"-ERR Path does not exist or not an array\r\n",
"{} {}",
String::from_utf8_lossy(call[0]),
String::from_utf8_lossy(path)
);
}
}
// A key that is not there is the same sentence for all four, on either
// syntax, and it is about the key and not about the path.
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"nokey", b".a", b"1"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRPOP", b"nokey", b"$.a"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
// The values are parsed before the key is touched, so text that is not
// JSON leaves the document alone.
// Text that is not JSON is refused before the key is touched, and
// the line has no `ERR` in front of it, which is D-37.
assert!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b".a", b"nope"])
.starts_with("-this is not the start of a value")
);
assert_eq!(f.run(&[b"JSON.GET", b"doc", b".a"]), bulk("[]"));
}
/// `JSON.ARRINSERT` refuses the whole command when any one of the arrays a
/// path matched cannot take the index, which is D-36.
///
/// RedisJSON walks the matches, inserts into each one it can, and returns
/// the error on the first one it cannot, leaving the earlier inserts in the
/// document. A write here is one list of edits applied together, so either
/// all of them happen or none of them do.
#[test]
fn json_arrinsert_is_all_or_nothing_across_the_matches() {
let mut f = Fixture::new();
let doc = br#"{"a":[1,2,3],"n":{"a":[9,8],"in":{"a":[1]}}}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b"$..a", b"-2", b"0"]),
"-ERR index out of bounds\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"a":[1,2,3],"n":{"a":[9,8],"in":{"a":[1]}}}"#)
);
// Every match can take the index, so every match gets it.
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b"$..a", b"0", b"0"]),
"*3\r\n:4\r\n:3\r\n:2\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc"]),
bulk(r#"{"a":[0,1,2,3],"n":{"a":[0,9,8],"in":{"a":[0,1]}}}"#)
);
}
/// `JSON.ARRINDEX`, whose stop is exclusive and whose start clamps to the
/// last element rather than to one past it.
///
/// Both of those read like mistakes and both are what RedisJSON does. The
/// start is the one that bites: a start of five into an array of four still
/// looks at the fourth, so a search that should have run out of array comes
/// back with an answer.
#[test]
fn json_arrindex_has_an_exclusive_stop_and_a_start_that_cannot_run_off_the_end() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,2,3,1],"n":7}"#]);
assert_eq!(f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"2"]), ":1\r\n");
assert_eq!(f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"9"]), ":-1\r\n");
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b"$.a", b"2"]),
"*1\r\n:1\r\n"
);
// Zero as the stop means the end rather than the front, so leaving it
// off and passing it are the same thing.
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"1", b"1", b"0"]),
":3\r\n"
);
// The stop is exclusive, so a stop of three does not look at index
// three.
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"1", b"1", b"3"]),
":-1\r\n"
);
// The start clamps to the last element in both directions, which is why
// a start of four, five or minus one all find the 1 at index three.
for start in [&b"4"[..], &b"5"[..], &b"-1"[..]] {
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"1", start]),
":3\r\n",
"{}",
String::from_utf8_lossy(start)
);
}
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"1", b"-100"]),
":0\r\n"
);
// An empty array is the one case that comes back with nothing, since
// the stop is zero and the loop never starts.
f.run(&[b"JSON.SET", b"doc", b"$.a", b"[]"]);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"1", b"1"]),
":-1\r\n"
);
// The comparison is structural rather than one of the encoded bytes,
// because an object in a stored document holds its keys as intern table
// ids where one parsed off the wire holds them as bytes.
f.run(&[b"JSON.SET", b"doc", b"$.a", br#"[{"k":1},[1,2],"s"]"#]);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", br#"{"k":1}"#]),
":0\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"[1,2]"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".a", b"[2,1]"]),
":-1\r\n"
);
// Its errors are a third set again: a missing legacy path is the short
// sentence, the wrong kind of value is a WRONGTYPE, and a key that is
// not there is about the path on either syntax.
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".nope", b"1"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"doc", b".n", b"1"]),
"-WRONGTYPE wrong type of path value - expected array\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"nokey", b".a", b"1"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.ARRINDEX", b"nokey", b"$.a", b"1"]),
"-ERR Path does not exist\r\n"
);
}
/// The number family answers text and keeps an integer an integer until
/// something in the sum is not one.
#[test]
fn the_json_number_family_answers_json_text_and_keeps_its_integers() {
let mut f = Fixture::new();
let doc = br#"{"i":7,"f":1.5,"neg":-2,"s":"ab"}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
// A legacy path answers the new value as JSON text in a bulk string,
// not as a number, which is the shape all three of them use.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".i", b"2"]),
bulk("9").as_str()
);
// A JSONPath answers a bulk string holding a JSON array.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.i", b"2"]),
bulk("[11]").as_str()
);
// Two integers stay an integer and a double anywhere in it makes the
// answer a double, which the document then holds.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".i", b"2.0"]),
bulk("13.0").as_str()
);
assert_eq!(
f.run(&[b"JSON.TYPE", b"doc", b".i"]),
bulk("number").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMMULTBY", b"doc", b".f", b"2"]),
bulk("3.0").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMPOWBY", b"doc", b".neg", b"3"]),
bulk("-8").as_str()
);
// A power of a half is a square root, and the square root of a negative
// number is the error that says the answer is not a number.
f.run(&[b"JSON.SET", b"doc", b"$.f", b"1.5"]);
assert_eq!(
f.run(&[b"JSON.NUMPOWBY", b"doc", b".f", b"0.5"]),
bulk("1.224744871391589").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMPOWBY", b"doc", b".neg", b"0.5"]),
"-ERR result is not a number\r\n"
);
// An integer answer that does not fit is refused rather than promoted,
// and a negative exponent lands in the same error because there is no
// integer answer to two to the minus one.
f.run(&[b"JSON.SET", b"doc", b"$.big", b"9223372036854775807"]);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".big", b"1"]),
"-ERR numeric overflow\r\n"
);
f.run(&[b"JSON.SET", b"doc", b"$.p", b"2"]);
assert_eq!(
f.run(&[b"JSON.NUMPOWBY", b"doc", b".p", b"-1"]),
"-ERR numeric overflow\r\n"
);
// A double that leaves the finite numbers is the other error.
f.run(&[b"JSON.SET", b"doc", b"$.huge", b"1e308"]);
assert_eq!(
f.run(&[b"JSON.NUMMULTBY", b"doc", b".huge", b"1e10"]),
"-ERR result is not a number\r\n"
);
// A match that is not a number is a null inside the array on a
// JSONPath, and a legacy path that found no number at all is the error
// with the module's own typo in it.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.s", b"1"]),
bulk("[null]").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.nope", b"1"]),
bulk("[]").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".s", b"1"]),
"-ERR Path does not exist or does not contains a number\r\n"
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".nope", b"1"]),
"-ERR Path does not exist or does not contains a number\r\n"
);
// The operand is JSON and has to be a number. Valid JSON that is not
// one is a line of its own, and it goes out without a prefix.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".i", b"true"]),
"-bad input number\r\n"
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"nokey", b".i", b"1"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"nokey", b"$.i", b"1"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
}
/// `JSON.STRAPPEND` puts its path in the middle and makes it optional,
/// which nothing else in the group does.
#[test]
fn json_strappend_reads_its_shape_off_the_argument_count() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"s":"ab","n":1}"#]);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".s", br#""c""#]),
":3\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b"$.s", br#""d""#]),
"*1\r\n:4\r\n"
);
// The length is in bytes and not in characters, so one two byte letter
// takes it up by two.
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".s", br#""\u00e9""#]),
":6\r\n"
);
// Three arguments means the value is the last one and the path is the
// root, so this appends to a document that is a string on its own.
f.run(&[b"JSON.SET", b"str", b"$", br#""ab""#]);
assert_eq!(f.run(&[b"JSON.STRAPPEND", b"str", br#""c""#]), ":3\r\n");
assert_eq!(f.run(&[b"JSON.GET", b"str"]), bulk("\"abc\"").as_str());
// The value is JSON and has to be a JSON string. A number is a
// WRONGTYPE about a path value even though it was the value that was
// wrong, which is the module's wording and not a slip here.
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".s", b"5"]),
"-WRONGTYPE wrong type of path value - expected string\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b"$.n", br#""c""#]),
"*1\r\n$-1\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".n", br#""c""#]),
"-ERR Path does not exist or not a string\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b"$.nope", br#""c""#]),
"*0\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"nokey", br#""c""#]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
}
/// A legacy path can match more than one value, and which of them the one
/// answer comes from is not the same choice twice.
#[test]
fn a_legacy_wildcard_write_touches_every_match_and_answers_only_one() {
let mut f = Fixture::new();
// Three arrays of one, two and three elements, which tells the first
// match and the last match apart in a single command.
let three = br#"{"a":[[7],[7,7],[7,7,7]]}"#;
f.run(&[b"JSON.SET", b"doc", b"$", three]);
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b".a[*]", b"9"]),
":4\r\n"
);
f.run(&[b"JSON.SET", b"doc", b"$", three]);
assert_eq!(
f.run(&[b"JSON.ARRINSERT", b"doc", b".a[*]", b"0", b"9"]),
":2\r\n"
);
f.run(&[b"JSON.SET", b"doc", b"$", three]);
assert_eq!(
f.run(&[b"JSON.ARRTRIM", b"doc", b".a[*]", b"0", b"1"]),
":1\r\n"
);
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[[1,2,3],[4,5,6]]}"#]);
assert_eq!(
f.run(&[b"JSON.ARRPOP", b"doc", b".a[*]", b"0"]),
bulk("1").as_str()
);
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,2,3]}"#]);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".a[*]", b"10"]),
bulk("13").as_str()
);
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":["p","qq","rrr"]}"#]);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".a[*]", br#""z""#]),
":4\r\n"
);
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[true,false,true]}"#]);
assert_eq!(
f.run(&[b"JSON.TOGGLE", b"doc", b".a[*]"]),
bulk("false").as_str()
);
// Every one of them wrote to all three matches, whichever one it chose
// to answer about.
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".a"]),
bulk("[false,true,false]").as_str()
);
// A match of the wrong kind is skipped rather than being the answer, so
// a path that found a string and then two arrays still answers.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":["x",[1],[1,2]]}"#]);
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b".a[*]", b"9"]),
":3\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".a"]),
bulk(r#"["x",[1,9],[1,2,9]]"#).as_str()
);
// Nothing of the right kind anywhere is the error, and that is the only
// case that is.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":["x","y"]}"#]);
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b".a[*]", b"9"]),
"-ERR Path does not exist or not an array\r\n"
);
assert_eq!(
f.run(&[b"JSON.TOGGLE", b"doc", b".a[*]"]),
"-ERR Path does not exist or not a bool\r\n"
);
// The one array that was there and had nothing in it is an answer and
// not a skip, so the pop answers about it rather than about the array
// after it.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[[],[2,3]]}"#]);
assert_eq!(f.run(&[b"JSON.ARRPOP", b"doc", b".a[*]"]), "$-1\r\n");
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b".a"]),
bulk("[[],[2]]").as_str()
);
}
/// A path that matched a value and something inside that value writes to
/// both, which is what `$..` and a nested wildcard are for.
#[test]
fn a_write_reaches_a_match_that_sits_inside_another_match() {
let mut f = Fixture::new();
let nested = br#"{"a":[{"a":[7]},{"a":[7,7]}]}"#;
f.run(&[b"JSON.SET", b"doc", b"$", nested]);
assert_eq!(
f.run(&[b"JSON.ARRAPPEND", b"doc", b"$..a", b"9"]),
"*3\r\n:3\r\n:2\r\n:3\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[{"a":[7,9]},{"a":[7,7,9]},9]}]"#).as_str()
);
// The same for a trim, where the outer array keeps the two elements the
// inner writes landed in.
f.run(&[b"JSON.SET", b"doc", b"$", nested]);
assert_eq!(
f.run(&[b"JSON.ARRTRIM", b"doc", b"$..a", b"0", b"0"]),
"*3\r\n:1\r\n:1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[{"a":[7]}]}]"#).as_str()
);
// And for a number, where the first match is the object the outer array
// holds and only the two inside it are numbers.
f.run(&[b"JSON.SET", b"doc", b"$", nested]);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$..a[0]", b"1"]),
bulk("[null,8,8]").as_str()
);
}
/// The value a write is given is looked at only once the path has found
/// something of the right kind to use it on.
#[test]
fn a_bad_operand_is_not_the_answer_when_the_path_found_nothing_to_use_it_on() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"n":7,"s":"t"}"#]);
// A string is not a number, so the path answers first and the `"x"` is
// never looked at. Same for the value that is not JSON at all.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.s", br#""x""#]),
bulk("[null]").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.s", b"notjson"]),
bulk("[null]").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.missing", b"notjson"]),
bulk("[]").as_str()
);
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b".s", br#""x""#]),
"-ERR Path does not exist or does not contains a number\r\n"
);
// A number match anywhere and the value is looked at after all.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.n", br#""x""#]),
"-bad input number\r\n"
);
// JSON.STRAPPEND follows the same order with its own two answers.
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b"$.n", b"1"]),
"*1\r\n$-1\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b".n", b"1"]),
"-ERR Path does not exist or not a string\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"doc", b"$.s", b"1"]),
"-WRONGTYPE wrong type of path value - expected string\r\n"
);
// A key that is not there still comes before either of them.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"nope", b"$.a", br#""x""#]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.STRAPPEND", b"nope", b"$.a", b"1"]),
"-ERR could not perform this operation on a key that doesn't exist\r\n"
);
}
/// RFC 7386 in one test: a null deletes, everything else merges, and a
/// patch that is not an object replaces what it lands on.
#[test]
fn a_merge_patch_adds_replaces_and_deletes_in_one_write() {
let mut f = Fixture::new();
// A key that is not there is created at the root, nulls and all,
// because a deletion with nothing to delete is still what the client
// sent.
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$", br#"{"x":null,"y":1}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"x":null,"y":1}]"#).as_str()
);
// Onto something that is there, a null deletes the member of that name
// and the rest is merged one level at a time.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":{"b":1,"c":2},"d":3}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$", br#"{"a":{"b":null,"e":4}}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":{"c":2,"e":4},"d":3}]"#).as_str()
);
// A patch that is not an object replaces what it is merged onto.
assert_eq!(f.run(&[b"JSON.MERGE", b"doc", b"$.a", b"[1,2]"]), "+OK\r\n");
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[1,2],"d":3}]"#).as_str()
);
// A patch object onto a value that is not an object starts from an
// empty object, so this time the null has nothing to delete and is
// dropped rather than stored.
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.d", br#"{"p":null,"q":9}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[1,2],"d":{"q":9}}]"#).as_str()
);
// A member one level past the end of the document is created and keeps
// its nulls, two levels past it is a write that did not happen, and a
// path that would have to invent where it goes is the unprefixed line.
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.new", br#"{"z":null}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$.new"]),
bulk(r#"[{"z":null}]"#).as_str()
);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.no.deep", b"1"]),
"$-1\r\n"
);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.no.*", b"1"]),
"-Err wrong static path\r\n"
);
// A wildcard merges every match.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":{"n":1},"b":{"n":2}}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.*", br#"{"m":0}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":{"m":0,"n":1},"b":{"m":0,"n":2}}]"#).as_str()
);
// The three ways to get it wrong.
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$", b"{}", b"more"]),
"-ERR syntax error\r\n"
);
assert_eq!(
f.run(&[b"JSON.MERGE", b"gone", b"$.a", b"1"]),
"-ERR new objects must be created at the root\r\n"
);
f.run(&[b"SET", b"str", b"x"]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"str", b"$", b"1"]),
"-Existing key has wrong Redis type\r\n"
);
}
/// A descent is the one path that matches a value and something inside that
/// same value, and the inner merge has to survive the outer one.
#[test]
fn a_merge_down_a_descent_keeps_what_the_inner_match_did() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":{"b":1},"c":[2]}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$..*", br#"{"m":1}"#]),
"+OK\r\n"
);
// `a`, `a.b`, `c` and `c[0]` all match. `a.b` is merged first and `a` is
// merged onto the result, so the `{"m":1}` written into `a.b` is still
// there. Doing it the other way round would leave `{"a":{"b":1,"m":1}}`.
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":{"b":{"m":1},"m":1},"c":{"m":1}}]"#).as_str()
);
// A deletion down the same path, which is the case where the inner
// merge empties the object the outer one then copies.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":{"b":1},"c":[2]}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$..*", br#"{"a":null}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":{"b":{}},"c":{}}]"#).as_str()
);
}
/// A filter is a selector like any other, so every command that takes a path
/// takes one, reads and writes alike.
#[test]
fn a_filter_path_reads_and_writes_the_members_it_keeps() {
let mut f = Fixture::new();
let doc = br#"{"book":[{"t":"a","p":8},{"t":"b","p":13},{"t":"c","p":9}],"cap":10}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$.book[?(@.p < 10)].t"]),
bulk(r#"["a","c"]"#).as_str()
);
// `$` inside the expression is the document, so a member can be measured
// against something that is not inside it.
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$.book[?(@.p < $.cap)].t"]),
bulk(r#"["a","c"]"#).as_str()
);
// The legacy syntax takes one too, and answers the first match.
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"book[?(@.p < 10)].t"]),
bulk(r#""a""#).as_str()
);
assert_eq!(
f.run(&[b"JSON.TYPE", b"doc", b"$.book[?(@.p > 10)]"]),
"*1\r\n$6\r\nobject\r\n"
);
// A write goes through it as far as a value that is already there. A
// field that is not there yet has nowhere definite to go, which is the
// same refusal a wildcard gets.
assert_eq!(
f.run(&[b"JSON.NUMINCRBY", b"doc", b"$.book[?(@.p < 10)].p", b"1"]),
bulk("[9,10]").as_str()
);
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.book[?(@.p == 13)].t", br#""B""#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.book[?(@.p == 13)].n", b"1"]),
"-Err wrong static path\r\n"
);
assert_eq!(
f.run(&[b"JSON.DEL", b"doc", b"$.book[?(@.p > 9)]"]),
":2\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"cap":10,"book":[{"p":9,"t":"a"}]}]"#).as_str()
);
// A path that does not parse is refused before the document is read, so
// a key that is not there answers the same way.
assert!(
f.run(&[b"JSON.GET", b"doc", b"$.book[?(@.p <)]"])
.starts_with("-ERR")
);
assert!(
f.run(&[b"JSON.GET", b"nokey", b"$.book[?(@.p <)]"])
.starts_with("-ERR")
);
}
/// The operators past the comparisons, over the wire rather than in the
/// parser's own tests, so that a client can reach all of them.
#[test]
fn a_filter_takes_the_membership_operators_and_the_methods_too() {
let mut f = Fixture::new();
let doc = br#"{"box":[{"t":"a","n":[1,2],"g":"x"},{"t":"b","n":[9],"g":"y"}]}"#;
f.run(&[b"JSON.SET", b"doc", b"$", doc]);
for (path, want) in [
(&b"$.box[?(@.g in [\"x\"])].t"[..], r#"["a"]"#),
(b"$.box[?(@.g nin [\"x\"])].t", r#"["b"]"#),
(b"$.box[?(@.n anyof [2,3])].t", r#"["a"]"#),
(b"$.box[?(@.n subsetof [1,2,3])].t", r#"["a"]"#),
(b"$.box[?(@.n size 2)].t", r#"["a"]"#),
(b"$.box[?(@.n empty false)].t", r#"["a","b"]"#),
(b"$.box[?(@.n.length() == 1)].t", r#"["b"]"#),
(b"$.box[?(@.n.sum() > 5)].t", r#"["b"]"#),
(b"$.box[?(@.n[0] + 1 == 2)].t", r#"["a"]"#),
(b"$.box[?(@~ size 3)].t", r#"["a","b"]"#),
(b"$.box[?(@.n~)].t", "[]"),
(b"$.box[?(@.n sizeof 2)].t", r#"["a"]"#),
(b"$.box[?(-@.n[0] == -9)].t", r#"["b"]"#),
(b"$.box[?(1 in @.n)].t", r#"["a"]"#),
(b"$.box[?(\"g\" in @~)].t", r#"["a","b"]"#),
] {
assert_eq!(f.run(&[b"JSON.GET", b"doc", path]), bulk(want).as_str());
}
// A write goes through one of these the same way it goes through a
// comparison.
assert_eq!(
f.run(&[b"JSON.SET", b"doc", b"$.box[?(@.n size 1)].g", br#""z""#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$.box[?(@.g == \"z\")].t"]),
bulk(r#"["b"]"#).as_str()
);
}
/// D-41. RedisJSON refuses this one, and which document it refuses is
/// decided by how it happens to hold an array of numbers.
#[test]
fn a_merge_onto_a_number_inside_an_array_is_a_merge_and_not_an_error() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,2]}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.a[0]", br#"{"x":1}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[{"x":1},2]}]"#).as_str()
);
// The same document with one element that is not an integer is the one
// RedisJSON is happy with, and it goes the same way here.
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,"s"]}"#]);
assert_eq!(
f.run(&[b"JSON.MERGE", b"doc", b"$.a[0]", br#"{"x":1}"#]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"doc", b"$"]),
bulk(r#"[{"a":[{"x":1},"s"]}]"#).as_str()
);
}
/// `JSON.MSET` checks what it can before it writes anything and skips the
/// one thing it cannot, which is a path with nowhere to put its value.
#[test]
fn an_mset_writes_every_triple_it_can_and_checks_the_rest_up_front() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$", b"1", b"b", b"$", b"2"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"a", b"$"]), bulk("[1]").as_str());
assert_eq!(f.run(&[b"JSON.GET", b"b", b"$"]), bulk("[2]").as_str());
// A repeated key takes the last write.
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$", b"3", b"a", b"$", b"4"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"a", b"$"]), bulk("[4]").as_str());
// A triple whose path names nowhere is skipped, the others are still
// written and the reply turns into a nil. Both ways round, because a
// loop that gave up at the first skip would agree with this on one
// order and not on the other.
f.run(&[b"JSON.SET", b"a", b"$", br#"{"n":1}"#]);
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$.no.deep", b"9", b"b", b"$", b"5"]),
"$-1\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"b", b"$"]), bulk("[5]").as_str());
assert_eq!(
f.run(&[b"JSON.MSET", b"b", b"$", b"6", b"a", b"$.no.deep", b"9"]),
"$-1\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"b", b"$"]), bulk("[6]").as_str());
// A value that is not JSON, a key holding something else and a path
// that would have to create a document below its own root are all
// checked before anything is written, so the good triple next to them
// does not happen either.
f.run(&[b"SET", b"str", b"x"]);
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$.n", b"7", b"b", b"$", b"notjson"]),
"-this is not the start of a value, at byte 0 of the JSON text\r\n"
);
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$.n", b"7", b"str", b"$", b"1"]),
"-Existing key has wrong Redis type\r\n"
);
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$.n", b"7", b"gone", b"$.x", b"1"]),
"-ERR new objects must be created at the root\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"a", b"$.n"]), bulk("[1]").as_str());
// The two errors a path can be are checked up front as well, so the
// triple before them is not written either. A wildcard that matched
// nothing has nowhere to invent, and an index that is not in the array
// is out of range, and both of them stop the whole command.
assert_eq!(
f.run(&[b"JSON.MSET", b"b", b"$", b"8", b"a", b"$.no.*", b"9"]),
"-Err wrong static path\r\n"
);
assert_eq!(
f.run(&[b"JSON.MSET", b"b", b"$", b"8", b"a", b"$[0]", b"9"]),
"-ERR array index out of range\r\n"
);
assert_eq!(f.run(&[b"JSON.GET", b"b", b"$"]), bulk("[6]").as_str());
// Every triple is worked out against the keyspace as the command found
// it, so a second triple on the same key does not see the first one and
// the last write is the one that stays.
f.run(&[b"JSON.SET", b"c", b"$", br#"{"n":1}"#]);
assert_eq!(
f.run(&[b"JSON.MSET", b"c", b"$", br#"{"n":2}"#, b"c", b"$.n", b"3"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"JSON.GET", b"c", b"$"]),
bulk(r#"[{"n":3}]"#).as_str()
);
// An argument count that is not a run of key, path and value is the
// arity error rather than a syntax one.
assert_eq!(
f.run(&[b"JSON.MSET", b"a", b"$", b"1", b"b"]),
"-ERR wrong number of arguments for 'json.mset' command\r\n"
);
}
/// `JSON.RESP` hands back RESP types, and the marker element is what tells
/// an empty array and an empty object apart.
#[test]
fn json_resp_answers_the_document_as_resp_types() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":1,"b":[2,"c"]}"#]);
assert_eq!(
f.run(&[b"JSON.RESP", b"doc"]),
"*5\r\n+{\r\n$1\r\na\r\n:1\r\n$1\r\nb\r\n*3\r\n+[\r\n:2\r\n$1\r\nc\r\n"
);
// A JSONPath wraps the same answer in one more array.
assert_eq!(
f.run(&[b"JSON.RESP", b"doc", b"$.b"]),
"*1\r\n*3\r\n+[\r\n:2\r\n$1\r\nc\r\n"
);
f.run(&[
b"JSON.SET",
b"doc",
b"$",
br#"{"f":2.5,"t":true,"z":null,"e":[],"o":{}}"#,
]);
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b".e"]), "*1\r\n+[\r\n");
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b".o"]), "*1\r\n+{\r\n");
// A double goes out as its text, so a client reads the same digits
// `JSON.GET` would have given it.
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b".f"]), bulk("2.5").as_str());
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b".t"]), "+true\r\n");
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b".z"]), "$-1\r\n");
// A missing legacy path is an error, a missing JSONPath is an empty
// array, and a key that is not there is a nil on either.
assert_eq!(
f.run(&[b"JSON.RESP", b"doc", b".nope"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(f.run(&[b"JSON.RESP", b"doc", b"$.nope"]), "*0\r\n");
assert_eq!(f.run(&[b"JSON.RESP", b"gone"]), "$-1\r\n");
assert_eq!(f.run(&[b"JSON.RESP", b"gone", b"$"]), "$-1\r\n");
}
/// `JSON.DEBUG` answers a byte count that is this encoding's, so the test
/// pins the shapes and that the two syntaxes agree rather than a number
/// read off another server. That is D-42.
#[test]
fn json_debug_answers_a_byte_count_and_its_own_help() {
let mut f = Fixture::new();
f.run(&[b"JSON.SET", b"doc", b"$", br#"{"a":[1,2],"s":"hello"}"#]);
let one = f.run(&[b"JSON.DEBUG", b"MEMORY", b"doc", b".s"]);
assert!(one.starts_with(':'), "{one}");
assert_eq!(
f.run(&[b"JSON.DEBUG", b"memory", b"doc", b"$.s"]),
format!("*1\r\n{one}")
);
let whole = f.run(&[b"JSON.DEBUG", b"MEMORY", b"doc"]);
assert!(whole.starts_with(':') && whole.len() > one.len(), "{whole}");
// A key that is not there is a zero on a legacy path and an empty set
// on a JSONPath, which is the one reader here that does not answer nil
// for it.
assert_eq!(f.run(&[b"JSON.DEBUG", b"MEMORY", b"gone"]), ":0\r\n");
assert_eq!(f.run(&[b"JSON.DEBUG", b"MEMORY", b"gone", b"$"]), "*0\r\n");
assert_eq!(
f.run(&[b"JSON.DEBUG", b"MEMORY", b"doc", b".nope"]),
"-ERR Path does not exist\r\n"
);
assert_eq!(
f.run(&[b"JSON.DEBUG", b"MEMORY", b"doc", b"$.nope"]),
"*0\r\n"
);
assert_eq!(
f.run(&[b"JSON.DEBUG", b"HELP"]),
"*2\r\n$42\r\nMEMORY <key> [path] - reports memory usage\r\n\
$34\r\nHELP - this message\r\n"
);
assert_eq!(
f.run(&[b"JSON.DEBUG", b"NOPE"]),
"-ERR unknown subcommand - try `JSON.DEBUG HELP`\r\n"
);
assert_eq!(
f.run(&[b"JSON.DEBUG", b"MEMORY"]),
"-ERR wrong number of arguments for 'json.debug' command\r\n"
);
}
// ---------------------------------------------------------------- vector
/// The first `VADD` fixes the dimension and every one after it has to
/// agree, because there is no create command to say it earlier.
#[test]
fn the_first_vadd_decides_how_wide_the_set_is() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]),
":1\r\n"
);
assert_eq!(f.run(&[b"VDIM", b"v"]), ":2\r\n");
assert_eq!(f.run(&[b"VCARD", b"v"]), ":1\r\n");
// A second vector under the same name replaces it and says so with a
// zero, so an ingest can count what it created.
assert_eq!(
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"1", b"east"]),
":0\r\n"
);
assert_eq!(f.run(&[b"VCARD", b"v"]), ":1\r\n");
// Three dimensions into a two dimensional set names both numbers, since
// a client that gets this wrong needs to know which end is which.
assert_eq!(
f.run(&[b"VADD", b"v", b"VALUES", b"3", b"1", b"0", b"0", b"up"]),
"-ERR Vector dimension mismatch - got 3 but set has 2\r\n"
);
// A vector of zeros has no direction, so a cosine set has nowhere to
// put it.
assert_eq!(
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"0", b"nowhere"]),
"-ERR a cosine collection compares directions and a vector of length zero has none\r\n"
);
// Nothing above created a key, and a set that never took a vector has
// no dimension to report.
assert_eq!(f.run(&[b"EXISTS", b"fresh"]), ":0\r\n");
assert_eq!(f.run(&[b"VDIM", b"fresh"]), "-ERR key does not exist\r\n");
assert_eq!(f.run(&[b"VCARD", b"fresh"]), ":0\r\n");
}
/// What a client sent comes back out, and what a client asked for is a
/// similarity and not the distance underneath it.
#[test]
fn vemb_gives_back_the_vector_and_vsim_gives_back_a_similarity() {
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"3", b"4", b"a"]);
// The set stored the unit vector and the length is multiplied back on
// the way out, so `3 4` and not `0.6 0.8`.
assert_eq!(
f.run(&[b"VEMB", b"v", b"a"]),
"*2\r\n$1\r\n3\r\n$1\r\n4\r\n"
);
assert_eq!(f.run(&[b"VEMB", b"v", b"nobody"]), "*-1\r\n");
assert_eq!(f.run(&[b"VEMB", b"nokey", b"a"]), "*-1\r\n");
// On the axes, where the unit vector is exact and so is the dot
// product, both ends of the scale come out exact: the same direction is
// 1 and the opposite one is 0, with a right angle at a half.
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"3", b"0", b"a"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"-1", b"0", b"opposite"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"7", b"across"]);
assert_eq!(
f.run(&[b"VSIM", b"v", b"VALUES", b"2", b"2", b"0", b"WITHSCORES"]),
"*6\r\n$1\r\na\r\n$1\r\n1\r\n$6\r\nacross\r\n$3\r\n0.5\r\n\
$8\r\nopposite\r\n$1\r\n0\r\n"
);
// A search from an element leaves that element out, since it is always
// its own nearest neighbour.
assert_eq!(
f.run(&[b"VSIM", b"v", b"ELE", b"a"]),
"*2\r\n$6\r\nacross\r\n$8\r\nopposite\r\n"
);
// An element that is not there is an empty answer and not an error,
// which is what a missing key gives too.
assert_eq!(f.run(&[b"VSIM", b"v", b"ELE", b"nobody"]), "*0\r\n");
assert_eq!(f.run(&[b"VSIM", b"nokey", b"ELE", b"a"]), "*0\r\n");
// COUNT bounds it and TRUTH reads every vector rather than the codes,
// which has to agree with the index on a set this small.
assert_eq!(
f.run(&[b"VSIM", b"v", b"ELE", b"a", b"COUNT", b"1"]),
"*1\r\n$6\r\nacross\r\n"
);
assert_eq!(
f.run(&[b"VSIM", b"v", b"ELE", b"a", b"TRUTH"]),
"*2\r\n$6\r\nacross\r\n$8\r\nopposite\r\n"
);
// EF widens how much of the index is read and does not change how many
// answers come back, so a wide search still returns what COUNT asked
// for.
assert_eq!(
f.run(&[b"VSIM", b"v", b"ELE", b"a", b"COUNT", b"1", b"EF", b"500"]),
"*1\r\n$6\r\nacross\r\n"
);
// On RESP3 a scored search is a map, which is what the vector set
// module replies and is not what ZRANGE does here.
let mut g = Fixture::new();
g.run(&[b"HELLO", b"3"]);
g.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
assert_eq!(
g.run(&[b"VSIM", b"v", b"VALUES", b"2", b"1", b"0", b"WITHSCORES"]),
"%1\r\n$4\r\neast\r\n,1\r\n"
);
}
/// The attribute pair, and the one reply that means two things.
#[test]
fn an_attribute_is_bytes_and_an_empty_one_takes_it_off() {
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
assert_eq!(f.run(&[b"VGETATTR", b"v", b"east"]), "$-1\r\n");
assert_eq!(f.run(&[b"VSETATTR", b"v", b"east", b"{\"k\":1}"]), ":1\r\n");
assert_eq!(f.run(&[b"VGETATTR", b"v", b"east"]), "$7\r\n{\"k\":1}\r\n");
// Not parsed as JSON, because nothing reads into it yet and refusing a
// write for a rule nothing enforces would be the wrong trade.
assert_eq!(f.run(&[b"VSETATTR", b"v", b"east", b"not json"]), ":1\r\n");
assert_eq!(f.run(&[b"VGETATTR", b"v", b"east"]), "$8\r\nnot json\r\n");
// An empty string clears it, which is Redis's spelling of the removal.
assert_eq!(f.run(&[b"VSETATTR", b"v", b"east", b""]), ":1\r\n");
assert_eq!(f.run(&[b"VGETATTR", b"v", b"east"]), "$-1\r\n");
// An element that is not there answers zero rather than being created,
// since an attribute with no vector under it is not a thing this holds.
assert_eq!(f.run(&[b"VSETATTR", b"v", b"nobody", b"{}"]), ":0\r\n");
assert_eq!(f.run(&[b"VSETATTR", b"nokey", b"east", b"{}"]), ":0\r\n");
assert_eq!(f.run(&[b"EXISTS", b"nokey"]), ":0\r\n");
// A null for an element with no attribute and a null for one that is
// not there. VISMEMBER is how a client tells the two apart.
assert_eq!(f.run(&[b"VGETATTR", b"v", b"nobody"]), "$-1\r\n");
assert_eq!(f.run(&[b"VISMEMBER", b"v", b"east"]), ":1\r\n");
assert_eq!(f.run(&[b"VISMEMBER", b"v", b"nobody"]), ":0\r\n");
assert_eq!(f.run(&[b"VISMEMBER", b"nokey", b"east"]), ":0\r\n");
// WITHATTRIBS carries it alongside the answers.
f.run(&[b"VSETATTR", b"v", b"east", b"{\"k\":1}"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"1", b"north"]);
assert_eq!(
f.run(&[b"VSIM", b"v", b"VALUES", b"2", b"1", b"0", b"WITHATTRIBS"]),
"*4\r\n$4\r\neast\r\n$7\r\n{\"k\":1}\r\n$5\r\nnorth\r\n$-1\r\n"
);
}
/// The slot a removed element had is reused, and nothing that was beside it
/// comes back with the next element to get it.
#[test]
fn vrem_takes_the_attribute_with_it() {
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
f.run(&[b"VSETATTR", b"v", b"east", b"{\"k\":1}"]);
assert_eq!(f.run(&[b"VREM", b"v", b"east"]), ":1\r\n");
assert_eq!(f.run(&[b"VREM", b"v", b"east"]), ":0\r\n");
assert_eq!(f.run(&[b"VREM", b"nokey", b"east"]), ":0\r\n");
// The key went with the last element, the way every other collection
// here works.
assert_eq!(f.run(&[b"EXISTS", b"v"]), ":0\r\n");
// The next element is given the slot the removed one had, and it comes
// with no attribute on it.
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
f.run(&[b"VSETATTR", b"v", b"east", b"{\"k\":1}"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"1", b"north"]);
f.run(&[b"VREM", b"v", b"east"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"1", b"between"]);
assert_eq!(f.run(&[b"VGETATTR", b"v", b"between"]), "$-1\r\n");
}
/// `VINFO` says what the index is before it says anything a client could
/// mistake for a graph.
#[test]
fn vinfo_says_partition_first() {
let mut f = Fixture::new();
f.run(&[
b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east", b"M", b"32",
]);
f.run(&[b"VSETATTR", b"v", b"east", b"{}"]);
let info = f.run(&[b"VINFO", b"v"]);
assert!(info.starts_with("*24\r\n$10\r\nindex-type\r\n$9\r\npartition\r\n"));
// What the client asked for and not what happened to the tuning, which
// is `10` section 7: M is recorded and changes nothing.
assert!(info.contains("$6\r\nhnsw-m\r\n:32\r\n"), "{info}");
assert!(info.contains("$10\r\nvector-dim\r\n:2\r\n"), "{info}");
assert!(info.contains("$16\r\nattributes-count\r\n:1\r\n"), "{info}");
// The quantisation is recorded and not applied, which is D-32, so it
// reports back what was sent.
assert!(
info.contains("$10\r\nquant-type\r\n$3\r\nf32\r\n"),
"{info}"
);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"1", b"north", b"BIN"]);
assert!(
f.run(&[b"VINFO", b"v"])
.contains("$10\r\nquant-type\r\n$3\r\nbin\r\n")
);
assert_eq!(f.run(&[b"VINFO", b"nokey"]), "$-1\r\n");
}
/// The option that asks for something this index does not have says so
/// rather than doing something else quietly.
#[test]
fn reduce_is_refused_and_not_ignored() {
let mut f = Fixture::new();
let reduce = f.run(&[
b"VADD", b"v", b"REDUCE", b"1", b"VALUES", b"2", b"1", b"0", b"east",
]);
assert!(
reduce.starts_with("-ERR REDUCE is not supported."),
"{reduce}"
);
assert_eq!(f.run(&[b"EXISTS", b"v"]), ":0\r\n");
}
/// A filtered search answers with the nearest elements that match, and an
/// expression that is not one is an error before the key is looked at.
#[test]
fn vsim_filter_reads_the_attributes() {
let mut f = Fixture::new();
for (name, x, y, attr) in [
("a", "1", "0", r#"{"lang":"en","year":1999}"#),
("b", "9", "1", r#"{"lang":"fr","year":2005}"#),
("c", "8", "2", r#"{"lang":"en","year":1970}"#),
("d", "7", "3", r#"{"lang":"en","year":2020}"#),
] {
f.run(&[
b"VADD",
b"v",
b"VALUES",
b"2",
x.as_bytes(),
y.as_bytes(),
name.as_bytes(),
b"SETATTR",
attr.as_bytes(),
]);
}
// `b` is the nearest to the query and is the one the filter drops, so
// this is the answer a filter applied afterwards would have got wrong.
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"COUNT",
b"2",
b"FILTER",
b".lang == \"en\"",
]),
"*2\r\n$1\r\na\r\n$1\r\nc\r\n"
);
// A number is compared as a number, and the two halves of an `and` both
// have to hold.
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"FILTER",
b".lang == 'en' and .year > 1980",
]),
"*2\r\n$1\r\na\r\n$1\r\nd\r\n"
);
// A list, and a field an element does not have.
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"FILTER",
b".lang in ['fr', 'de']",
]),
"*1\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"FILTER",
b".rating > 3"
]),
"*0\r\n"
);
// TRUTH measures every vector, and the filter still decides which ones
// are measured.
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"TRUTH",
b"FILTER",
b".year < 1980",
]),
"*1\r\n$1\r\nc\r\n"
);
// VSETATTR moves an element in and out of a filter, which means the tag
// beside its code was rewritten and not just the string.
f.run(&[b"VSETATTR", b"v", b"b", r#"{"lang":"en"}"#.as_bytes()]);
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"COUNT",
b"1",
b"FILTER",
b".lang == \"en\"",
]),
"*1\r\n$1\r\nb\r\n"
);
// And a VADD that replaces the vector keeps the attribute and the tag,
// which is the same rewrite from the other end.
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"9", b"2", b"b"]);
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"COUNT",
b"1",
b"FILTER",
b".lang == \"en\"",
]),
"*1\r\n$1\r\nb\r\n"
);
// The expression is parsed before the key is read, so a bad one is an
// error whether or not the key is there.
let bad = f.run(&[b"VSIM", b"nokey", b"ELE", b"e", b"FILTER", b".k =="]);
assert_eq!(bad, "-ERR invalid FILTER expression\r\n");
assert_eq!(
f.run(&[b"VSIM", b"v", b"ELE", b"a", b"FILTER", b"junk"]),
"-ERR invalid FILTER expression\r\n"
);
// FILTER-EF raises the effort rather than capping it, and zero is
// Redis's word for no limit, so neither is an error.
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"COUNT",
b"1",
b"FILTER-EF",
b"500",
b"FILTER",
b".lang == 'en'",
]),
"*1\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"COUNT",
b"1",
b"FILTER-EF",
b"0"
]),
"*1\r\n$1\r\nb\r\n"
);
assert_eq!(
f.run(&[
b"VSIM",
b"v",
b"VALUES",
b"2",
b"9",
b"1",
b"FILTER-EF",
b"lots"
]),
"-ERR EF must be a positive integer\r\n"
);
}
/// A vector set key is a key, so the keyspace owns it the way it owns every
/// other one and none of those commands know what is inside it.
#[test]
fn the_keyspace_sees_a_vector_set_key_like_any_other() {
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
assert_eq!(f.run(&[b"TYPE", b"v"]), "+vectorset\r\n");
assert_eq!(f.run(&[b"EXISTS", b"v"]), ":1\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"v"]), "$6\r\nrabitq\r\n");
assert_eq!(f.run(&[b"KEYS", b"*"]), "*1\r\n$1\r\nv\r\n");
assert_eq!(f.run(&[b"DBSIZE"]), ":1\r\n");
assert_eq!(f.run(&[b"EXPIRE", b"v", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"TTL", b"v"]), ":100\r\n");
assert_eq!(f.run(&[b"PERSIST", b"v"]), ":1\r\n");
assert_eq!(f.run(&[b"DEL", b"v"]), ":1\r\n");
assert_eq!(f.run(&[b"EXISTS", b"v"]), ":0\r\n");
// And the wrong type is the wrong type in both directions.
f.run(&[b"SET", b"s", b"1"]);
assert_eq!(
f.run(&[b"VADD", b"s", b"VALUES", b"2", b"1", b"0", b"east"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
assert_eq!(
f.run(&[b"VCARD", b"s"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
assert_eq!(
f.run(&[b"GET", b"v"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
// A graph and a vector set share the escape in the record tag and are
// still two different types, which is the case the tag alone cannot
// decide.
f.run(&[b"G.NADD", b"social", b"ada"]);
assert_eq!(
f.run(&[b"VCARD", b"social"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
assert_eq!(
f.run(&[b"G.NGET", b"v", b"ada"]),
"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"
);
}
/// `VRANDMEMBER` is `SRANDMEMBER` over the element names, in both of its
/// shapes, off the database's own generator.
#[test]
fn vrandmember_has_the_two_shapes_srandmember_has() {
let mut f = Fixture::new();
for (i, name) in [&b"a"[..], b"b", b"c"].iter().enumerate() {
let x = (i + 1).to_string();
f.run(&[b"VADD", b"v", b"VALUES", b"2", x.as_bytes(), b"1", name]);
}
// One element is a bulk string and not an array of one.
let one = f.run(&[b"VRANDMEMBER", b"v"]);
assert!(one.starts_with("$1\r\n"), "{one}");
// A positive count is distinct and stops at the size of the set.
let mut all = f.run(&[b"VRANDMEMBER", b"v", b"9"]);
assert!(all.starts_with("*3\r\n"), "{all}");
for name in ["a", "b", "c"] {
assert!(all.contains(name), "{all} is missing {name}");
}
all = f.run(&[b"VRANDMEMBER", b"v", b"2"]);
assert!(all.starts_with("*2\r\n"), "{all}");
// A negative one draws that many and allows repeats.
let many = f.run(&[b"VRANDMEMBER", b"v", b"-5"]);
assert!(many.starts_with("*5\r\n"), "{many}");
// A key that is not there answers the shape that was asked for.
assert_eq!(f.run(&[b"VRANDMEMBER", b"nokey"]), "$-1\r\n");
assert_eq!(f.run(&[b"VRANDMEMBER", b"nokey", b"3"]), "*0\r\n");
}
/// `VLINKS` answers about the index that is here rather than the graph that
/// is not, which is D-2.
#[test]
fn vlinks_reports_one_layer_of_partition_neighbours() {
let mut f = Fixture::new();
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"1", b"0", b"east"]);
f.run(&[b"VADD", b"v", b"VALUES", b"2", b"0", b"1", b"north"]);
// One layer deep, because the index is one layer deep, so a client
// walking layers gets a short list and not a shape it cannot parse.
assert_eq!(
f.run(&[b"VLINKS", b"v", b"east"]),
"*1\r\n*1\r\n$5\r\nnorth\r\n"
);
assert_eq!(
f.run(&[b"VLINKS", b"v", b"east", b"WITHSCORES"]),
"*1\r\n*2\r\n$5\r\nnorth\r\n$3\r\n0.5\r\n"
);
assert_eq!(f.run(&[b"VLINKS", b"v", b"nobody"]), "*-1\r\n");
assert_eq!(f.run(&[b"VLINKS", b"nokey", b"east"]), "*-1\r\n");
}
/// A vector arrives either as digits or as bytes, and the two have to mean
/// the same thing.
#[test]
fn fp32_and_values_are_the_same_vector() {
let mut f = Fixture::new();
let mut blob = Vec::new();
for x in [3.0f32, 4.0] {
blob.extend_from_slice(&x.to_le_bytes());
}
assert_eq!(f.run(&[b"VADD", b"v", b"FP32", &blob, b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"VDIM", b"v"]), ":2\r\n");
assert_eq!(
f.run(&[b"VEMB", b"v", b"a"]),
"*2\r\n$1\r\n3\r\n$1\r\n4\r\n"
);
// RAW is the stored form and the number that turns it back into the
// client's, which is the unit vector and the length it arrived with.
let raw = f.run(&[b"VEMB", b"v", b"a", b"RAW"]);
assert!(raw.starts_with("*3\r\n$3\r\nf32\r\n$8\r\n"), "{raw}");
assert!(raw.ends_with("$1\r\n5\r\n"), "{raw}");
// A blob that is not a whole number of floats is not a vector.
assert_eq!(
f.run(&[b"VADD", b"w", b"FP32", b"abc", b"a"]),
"-ERR invalid vector specification\r\n"
);
// Neither is a count that promises more than arrived.
assert_eq!(
f.run(&[b"VADD", b"w", b"VALUES", b"4", b"1", b"0", b"a"]),
"-ERR syntax error\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"w"]), ":0\r\n");
}
// ----------------------------------------------------------------- bloom
/// The filter a client gets when it does not describe one, and the two
/// answers an add can give.
#[test]
fn bf_add_makes_the_filter_and_says_whether_it_was_new() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"BF.ADD", b"b", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"BF.ADD", b"b", b"hello"]), ":0\r\n");
assert_eq!(f.run(&[b"BF.EXISTS", b"b", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"BF.EXISTS", b"b", b"never"]), ":0\r\n");
assert_eq!(f.run(&[b"BF.CARD", b"b"]), ":1\r\n");
// The defaults are the module's configs and not anything the command
// said, which is 100 entries at a hundredth and a growth of 2.
assert_eq!(
f.run(&[b"BF.INFO", b"b"]),
"*10\r\n+Capacity\r\n:100\r\n+Size\r\n:240\r\n\
+Number of filters\r\n:1\r\n+Number of items inserted\r\n:1\r\n\
+Expansion rate\r\n:2\r\n"
);
assert_eq!(f.run(&[b"TYPE", b"b"]), "+MBbloom--\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"b"]), "$3\r\nraw\r\n");
// A key that is not there has no filter to report on, and answers two
// different ways about it depending on which command asked.
assert_eq!(f.run(&[b"BF.CARD", b"gone"]), ":0\r\n");
assert_eq!(f.run(&[b"BF.INFO", b"gone"]), "-ERR not found\r\n");
}
/// `BF.EXISTS` on a key holding something else answers a miss, and
/// everything else in the family answers `WRONGTYPE`.
///
/// The two halves of a check and set disagree about what that key is, which
/// is the module's behaviour and not a decision taken here.
#[test]
fn a_wrong_type_is_a_miss_to_the_two_that_only_read_bits() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"text"]);
assert_eq!(f.run(&[b"BF.EXISTS", b"s", b"x"]), ":0\r\n");
assert_eq!(f.run(&[b"BF.MEXISTS", b"s", b"x"]), "*1\r\n:0\r\n");
for cmd in [
vec![&b"BF.ADD"[..], b"s", b"x"],
vec![&b"BF.MADD"[..], b"s", b"x"],
vec![&b"BF.CARD"[..], b"s"],
vec![&b"BF.INFO"[..], b"s"],
vec![&b"BF.DEBUG"[..], b"s"],
vec![&b"BF.SCANDUMP"[..], b"s", b"0"],
] {
let name = String::from_utf8_lossy(cmd[0]).into_owned();
assert!(f.run(&cmd).starts_with("-WRONGTYPE"), "{name}");
}
// The arguments are read before the key is, so a reserve with a bad
// error rate complains about the rate and never learns about the string.
assert_eq!(
f.run(&[b"BF.RESERVE", b"s", b"abc", b"10"]),
"-ERR bad error rate\r\n"
);
assert!(
f.run(&[b"BF.RESERVE", b"s", b"0.01", b"10"])
.starts_with("-WRONGTYPE")
);
}
/// A chain grows by its expansion factor and each link is half as wrong as
/// the one before, which is what makes the whole filter hold its rate.
#[test]
fn a_full_filter_grows_a_link_and_a_fixed_one_says_no() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"BF.RESERVE", b"g", b"0.01", b"10"]), "+OK\r\n");
for i in 0..10u32 {
assert_eq!(
f.run(&[b"BF.ADD", b"g", i.to_string().as_bytes()]),
":1\r\n"
);
}
assert_eq!(f.run(&[b"BF.INFO", b"g", b"FILTERS"]), "*1\r\n:1\r\n");
assert_eq!(f.run(&[b"BF.ADD", b"g", b"11"]), ":1\r\n");
assert_eq!(f.run(&[b"BF.INFO", b"g", b"filters"]), "*1\r\n:2\r\n");
// Capacity is the sum of every link and not the number that was asked
// for, so it is 10 and then 10 plus 20.
assert_eq!(f.run(&[b"BF.INFO", b"g", b"CAPACITY"]), "*1\r\n:30\r\n");
assert_eq!(
f.run(&[b"BF.DEBUG", b"g"]),
"*3\r\n$7\r\nsize:11\r\n\
$71\r\nbytes:16 bits:128 hashes:8 hashwidth:64 capacity:10 size:10 ratio:0.005\r\n\
$71\r\nbytes:32 bits:256 hashes:9 hashwidth:64 capacity:20 size:1 ratio:0.0025\r\n"
);
// The same filter told not to grow fills instead.
assert_eq!(
f.run(&[b"BF.RESERVE", b"n", b"0.01", b"2", b"NONSCALING"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"BF.ADD", b"n", b"a"]), ":1\r\n");
assert_eq!(f.run(&[b"BF.ADD", b"n", b"b"]), ":1\r\n");
assert_eq!(
f.run(&[b"BF.ADD", b"n", b"c"]),
"-ERR non scaling filter is full\r\n"
);
// And an item that is already in it still answers, because membership
// is checked before fullness.
assert_eq!(f.run(&[b"BF.ADD", b"n", b"a"]), ":0\r\n");
// A filter that will not grow has no expansion rate to report, in
// either of the two spellings that make one.
assert_eq!(f.run(&[b"BF.INFO", b"n", b"EXPANSION"]), "*1\r\n$-1\r\n");
f.run(&[b"BF.RESERVE", b"z", b"0.01", b"2", b"EXPANSION", b"0"]);
assert_eq!(f.run(&[b"BF.INFO", b"z", b"EXPANSION"]), "*1\r\n$-1\r\n");
// Asking for both at once is refused, which is one of the module's
// errors that carries no prefix at all.
assert_eq!(
f.run(&[
b"BF.RESERVE",
b"q",
b"0.01",
b"2",
b"NONSCALING",
b"EXPANSION",
b"2"
]),
"-Nonscaling filters cannot expand\r\n"
);
}
/// A multi add stops where the filter did, so the reply can be shorter than
/// the argument list.
#[test]
fn madd_truncates_its_reply_at_the_item_that_did_not_fit() {
let mut f = Fixture::new();
f.run(&[b"BF.RESERVE", b"n", b"0.01", b"2", b"NONSCALING"]);
assert_eq!(
f.run(&[b"BF.MADD", b"n", b"a", b"b", b"c", b"d"]),
"*3\r\n:1\r\n:1\r\n-ERR non scaling filter is full\r\n"
);
assert_eq!(
f.run(&[b"BF.MEXISTS", b"n", b"a", b"c"]),
"*2\r\n:1\r\n:0\r\n"
);
}
/// `BF.INSERT` describes a filter and fills it in one command, with its own
/// spelling of every complaint.
#[test]
fn insert_is_a_reserve_and_a_madd_with_different_errors() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"BF.INSERT",
b"i",
b"CAPACITY",
b"50",
b"ERROR",
b"0.001",
b"ITEMS",
b"a",
b"b"
]),
"*2\r\n:1\r\n:1\r\n"
);
assert_eq!(f.run(&[b"BF.INFO", b"i", b"CAPACITY"]), "*1\r\n:50\r\n");
// NOCREATE is the only way to add without making the key.
assert_eq!(
f.run(&[b"BF.INSERT", b"gone", b"NOCREATE", b"ITEMS", b"a"]),
"-ERR not found\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"gone"]), ":0\r\n");
// The same mistakes as BF.RESERVE, in the sentences this command uses
// for them, and one sentence where BF.RESERVE has two.
assert_eq!(
f.run(&[b"BF.INSERT", b"i", b"CAPACITY", b"abc", b"ITEMS", b"a"]),
"-Bad capacity\r\n"
);
assert_eq!(
f.run(&[b"BF.INSERT", b"i", b"ERROR", b"2", b"ITEMS", b"a"]),
"-Bad error rate\r\n"
);
assert_eq!(
f.run(&[b"BF.INSERT", b"i", b"EXPANSION", b"99999", b"ITEMS", b"a"]),
"-Bad expansion\r\n"
);
// An option is matched on its first letter and not on the word, so a
// token nobody meant as an option is one anyway if it starts with the
// right letter. NOSUCHTHING is NONSCALING here, and the filter it
// builds says so.
assert_eq!(
f.run(&[b"BF.INSERT", b"ns", b"NOSUCHTHING", b"ITEMS", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(f.run(&[b"BF.INFO", b"ns", b"EXPANSION"]), "*1\r\n$-1\r\n");
// Only E and N need a second look, one for ERROR against EXPANSION and
// the other for NOCREATE against NONSCALING, and both stop as soon as
// they can tell the two apart.
assert_eq!(
f.run(&[b"BF.INSERT", b"e1", b"E", b"4", b"ITEMS", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(f.run(&[b"BF.INFO", b"e1", b"EXPANSION"]), "*1\r\n:4\r\n");
assert_eq!(
f.run(&[b"BF.INSERT", b"e2", b"ER", b"0.5", b"ITEMS", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"BF.INSERT", b"gone", b"NOC", b"ITEMS", b"a"]),
"-ERR not found\r\n"
);
// A letter that starts nothing is the one case that is refused.
assert_eq!(
f.run(&[b"BF.INSERT", b"i", b"ZZZ", b"ITEMS", b"a"]),
"-Unknown argument received\r\n"
);
// Everything after ITEMS is an item, even when it spells an option.
assert_eq!(
f.run(&[b"BF.INSERT", b"i", b"ITEMS", b"NOCREATE"]),
"*1\r\n:1\r\n"
);
// And ITEMS with nothing after it is the same as leaving it out.
assert!(
f.run(&[b"BF.INSERT", b"i", b"ITEMS"])
.contains("wrong number of arguments")
);
}
/// A filter dumped a chunk at a time and put back into another key is the
/// same filter.
#[test]
fn a_dump_replays_into_a_filter_that_answers_the_same() {
let mut f = Fixture::new();
f.run(&[b"BF.RESERVE", b"src", b"0.01", b"10"]);
for i in 0..25u32 {
f.run(&[b"BF.ADD", b"src", i.to_string().as_bytes()]);
}
assert_eq!(f.run(&[b"BF.INFO", b"src", b"FILTERS"]), "*1\r\n:2\r\n");
// Iterator zero asks for the header and every one after it is a running
// byte offset, and a chunk never spans two links.
let mut iter = b"0".to_vec();
let mut chunks = 0;
loop {
let raw = f.raw(&[b"BF.SCANDUMP", b"src", &iter]);
let text = String::from_utf8_lossy(&raw).into_owned();
let next = text
.split("\r\n")
.nth(1)
.and_then(|n| n.strip_prefix(':'))
.expect("a two element reply of an iterator and a chunk")
.to_owned();
let body = &raw[raw.iter().position(|&b| b == b'$').expect("a bulk chunk")..];
let data = &body[body
.windows(2)
.position(|w| w == b"\r\n")
.expect("a length line")
+ 2..body.len() - 2];
if next == "0" {
assert!(data.is_empty(), "the last chunk is empty");
break;
}
let put = f.run(&[b"BF.LOADCHUNK", b"dst", next.as_bytes(), data]);
assert_eq!(put, "+OK\r\n", "loading chunk {chunks}");
iter = next.into_bytes();
chunks += 1;
}
assert_eq!(chunks, 3, "a header and one chunk per link");
assert_eq!(f.run(&[b"BF.INFO", b"dst"]), f.run(&[b"BF.INFO", b"src"]));
assert_eq!(f.run(&[b"BF.DEBUG", b"dst"]), f.run(&[b"BF.DEBUG", b"src"]));
for i in 0..25u32 {
assert_eq!(
f.run(&[b"BF.EXISTS", b"dst", i.to_string().as_bytes()]),
":1\r\n"
);
}
// A header on top of a filter is refused rather than merged, and so is
// one that no filter wrote.
assert_eq!(
f.run(&[b"BF.LOADCHUNK", b"dst", b"1", b"anything"]),
"-ERR received bad data\r\n"
);
assert_eq!(
f.run(&[b"BF.LOADCHUNK", b"fresh", b"1", b"anything"]),
"-ERR received bad data\r\n"
);
// An offset past the end of the filter names itself.
assert_eq!(
f.run(&[b"BF.LOADCHUNK", b"dst", b"99999", b"x"]),
"-ERR invalid offset - no link found\r\n"
);
assert_eq!(
f.run(&[b"BF.LOADCHUNK", b"dst", b"nope", b"x"]),
"-ERR Second argument must be numeric\r\n"
);
// The same complaint without the prefix on the way out, which is the
// module's inconsistency and not a slip here.
assert_eq!(
f.run(&[b"BF.SCANDUMP", b"src", b"nope"]),
"-Second argument must be numeric\r\n"
);
}
/// The argument checks, which have a sentence each and read numbers the way
/// Redis reads them everywhere else.
#[test]
fn reserve_reads_its_numbers_the_way_string2ll_does() {
let mut f = Fixture::new();
for (args, want) in [
(vec![&b"abc"[..], b"10"], "-ERR bad error rate\r\n"),
(vec![&b"nan"[..], b"10"], "-ERR bad error rate\r\n"),
(
vec![&b"0"[..], b"10"],
"-ERR error rate must be in the range (0.000000, 1.000000)\r\n",
),
(
vec![&b"1"[..], b"10"],
"-ERR error rate must be in the range (0.000000, 1.000000)\r\n",
),
(
vec![&b"inf"[..], b"10"],
"-ERR error rate must be in the range (0.000000, 1.000000)\r\n",
),
(vec![&b"0.01"[..], b"+10"], "-ERR bad capacity\r\n"),
(vec![&b"0.01"[..], b"1e2"], "-ERR bad capacity\r\n"),
(vec![&b"0.01"[..], b"007"], "-ERR bad capacity\r\n"),
(
vec![&b"0.01"[..], b"0"],
"-ERR capacity must be in the range [1, 1073741824]\r\n",
),
(
vec![&b"0.01"[..], b"1073741825"],
"-ERR capacity must be in the range [1, 1073741824]\r\n",
),
] {
let mut cmd = vec![&b"BF.RESERVE"[..], b"k"];
cmd.extend(args.iter().copied());
assert_eq!(f.run(&cmd), want, "{}", String::from_utf8_lossy(args[0]));
}
assert_eq!(
f.run(&[b"BF.RESERVE", b"k", b"0.01", b"10", b"EXPANSION"]),
"-ERR no expansion\r\n"
);
assert_eq!(
f.run(&[b"BF.RESERVE", b"k", b"0.01", b"10", b"EXPANSION", b"abc"]),
"-ERR bad expansion\r\n"
);
assert_eq!(
f.run(&[b"BF.RESERVE", b"k", b"0.01", b"10", b"EXPANSION", b"32769"]),
"-ERR expansion must be in the range [0, 32768]\r\n"
);
// Trailing rubbish after the capacity is ignored rather than refused.
assert_eq!(
f.run(&[b"BF.RESERVE", b"k", b"0.01", b"10", b"junk"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"BF.RESERVE", b"k", b"0.01", b"10"]),
"-ERR item exists\r\n"
);
assert_eq!(
f.run(&[b"BF.INFO", b"k", b"nosuchfield"]),
"-Invalid information value\r\n"
);
assert!(
f.run(&[b"BF.INFO", b"k", b"CAPACITY", b"SIZE"])
.contains("wrong number of arguments")
);
}
/// The RESP3 shapes, which are where this family differs most from RESP2.
#[test]
fn the_bloom_family_answers_in_resp3_spelling_too() {
let mut f = Fixture::new();
f.out.set_proto(Proto::Resp3);
assert_eq!(f.run(&[b"BF.ADD", b"b", b"a"]), "#t\r\n");
assert_eq!(f.run(&[b"BF.ADD", b"b", b"a"]), "#f\r\n");
assert_eq!(f.run(&[b"BF.MADD", b"b", b"a", b"c"]), "*2\r\n#f\r\n#t\r\n");
assert_eq!(f.run(&[b"BF.EXISTS", b"b", b"a"]), "#t\r\n");
assert_eq!(
f.run(&[b"BF.MEXISTS", b"b", b"a", b"z"]),
"*2\r\n#t\r\n#f\r\n"
);
// The count stays an integer, because it counts rather than answers.
assert_eq!(f.run(&[b"BF.CARD", b"b"]), ":2\r\n");
assert_eq!(
f.run(&[b"BF.INFO", b"b"]),
"%5\r\n+Capacity\r\n:100\r\n+Size\r\n:240\r\n\
+Number of filters\r\n:1\r\n+Number of items inserted\r\n:2\r\n\
+Expansion rate\r\n:2\r\n"
);
// One field is a map of one here and a bare array of one on RESP2, so
// this is the reply where the two protocols carry different facts.
assert_eq!(
f.run(&[b"BF.INFO", b"b", b"CAPACITY"]),
"%1\r\n+Capacity\r\n:100\r\n"
);
}
// ---------------------------------------------------------------- cuckoo
/// A dump header, which is the four counts and the three widths a filter
/// writes in front of its fingerprints.
///
/// Written by hand rather than taken from a `CF.SCANDUMP`, because what the
/// tests below want out of it is the states a filter cannot be put into
/// from the wire.
fn cf_header(
items: u64,
buckets: u64,
deletes: u64,
filters: u64,
geometry: [u16; 3],
) -> Vec<u8> {
let mut out = Vec::with_capacity(38);
for n in [items, buckets, deletes, filters] {
out.extend_from_slice(&n.to_le_bytes());
}
for n in geometry {
out.extend_from_slice(&n.to_le_bytes());
}
out
}
/// The filter a client gets when it does not describe one, and the thing a
/// cuckoo filter does that a Bloom filter cannot, which is count copies and
/// take them out again.
#[test]
fn cf_add_makes_the_filter_and_counts_the_copies() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"CF.ADD", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.ADD", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.COUNT", b"d", b"hello"]), ":2\r\n");
// The NX form is the one that looks first, which is why it is a command
// of its own rather than an option.
assert_eq!(f.run(&[b"CF.ADDNX", b"d", b"hello"]), ":0\r\n");
assert_eq!(f.run(&[b"CF.ADDNX", b"d", b"other"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.EXISTS", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.EXISTS", b"d", b"no"]), ":0\r\n");
assert_eq!(
f.run(&[b"CF.MEXISTS", b"d", b"hello", b"no"]),
"*2\r\n:1\r\n:0\r\n"
);
// The defaults are the module's configs: 1024 entries over buckets of
// two, twenty kicks and a chain that grows by one.
assert_eq!(
f.run(&[b"CF.INFO", b"d"]),
"*16\r\n+Size\r\n:1080\r\n+Number of buckets\r\n:512\r\n\
+Number of filters\r\n:1\r\n+Number of items inserted\r\n:3\r\n\
+Number of items deleted\r\n:0\r\n+Bucket size\r\n:2\r\n\
+Expansion rate\r\n:1\r\n+Max iterations\r\n:20\r\n"
);
assert_eq!(
f.run(&[b"CF.DEBUG", b"d"]),
"$79\r\nbktsize:2 buckets:512 items:3 deletes:0 filters:1 \
max_iterations:20 expansion:1\r\n"
);
assert_eq!(f.run(&[b"TYPE", b"d"]), "+MBbloomCF\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"d"]), "$3\r\nraw\r\n");
// A delete takes one copy, so the same item goes twice and then stops.
assert_eq!(f.run(&[b"CF.DEL", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.COUNT", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.DEL", b"d", b"hello"]), ":1\r\n");
assert_eq!(f.run(&[b"CF.DEL", b"d", b"hello"]), ":0\r\n");
assert_eq!(f.run(&[b"CF.COMPACT", b"d"]), "+OK\r\n");
// A key with no filter under it gets three different sentences and one
// plain miss, depending on which command asked.
assert_eq!(f.run(&[b"CF.INFO", b"gone"]), "-ERR not found\r\n");
assert_eq!(f.run(&[b"CF.DEL", b"gone", b"x"]), "-Not found\r\n");
assert_eq!(
f.run(&[b"CF.COMPACT", b"gone"]),
"-Cuckoo filter was not found\r\n"
);
assert_eq!(f.run(&[b"CF.EXISTS", b"gone", b"x"]), ":0\r\n");
// And `CF.COMPACT` is declared as taking any number of keys and takes
// exactly one, which is the module's own arity being wrong rather than
// this table's.
assert!(
f.run(&[b"CF.COMPACT", b"a", b"b"])
.contains("wrong number of arguments")
);
}
/// The four that only read fingerprints treat a key holding something else
/// as a key with no filter, and everything else answers `WRONGTYPE`.
#[test]
fn a_wrong_type_is_a_miss_to_the_four_that_only_read_fingerprints() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"text"]);
assert_eq!(f.run(&[b"CF.EXISTS", b"s", b"x"]), ":0\r\n");
assert_eq!(f.run(&[b"CF.MEXISTS", b"s", b"x"]), "*1\r\n:0\r\n");
assert_eq!(f.run(&[b"CF.COUNT", b"s", b"x"]), ":0\r\n");
// `CF.DEL` writes and is still in that group, and `CF.COMPACT` writes
// and is declared read only, so neither of the two halves of the family
// is the same set as the flags say.
assert_eq!(f.run(&[b"CF.DEL", b"s", b"x"]), "-Not found\r\n");
assert_eq!(
f.run(&[b"CF.COMPACT", b"s"]),
"-Cuckoo filter was not found\r\n"
);
for cmd in [
vec![&b"CF.ADD"[..], b"s", b"x"],
vec![&b"CF.ADDNX"[..], b"s", b"x"],
vec![&b"CF.INSERT"[..], b"s", b"ITEMS", b"x"],
vec![&b"CF.INSERTNX"[..], b"s", b"ITEMS", b"x"],
vec![&b"CF.INFO"[..], b"s"],
vec![&b"CF.DEBUG"[..], b"s"],
vec![&b"CF.SCANDUMP"[..], b"s", b"0"],
vec![&b"CF.LOADCHUNK"[..], b"s", b"2", b"x"],
vec![&b"CF.RESERVE"[..], b"s", b"64"],
] {
let name = String::from_utf8_lossy(cmd[0]).into_owned();
assert!(f.run(&cmd).starts_with("-WRONGTYPE"), "{name}");
}
}
/// `CF.RESERVE` reads its options by name in an order of its own, and the
/// first pair with a given name is the only one it looks at.
#[test]
fn reserve_complains_about_its_options_in_the_order_it_looks_for_them() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[
b"CF.RESERVE",
b"r",
b"64",
b"BUCKETSIZE",
b"1",
b"MAXITERATIONS",
b"7",
b"EXPANSION",
b"4"
]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"CF.DEBUG", b"r"]),
"$77\r\nbktsize:1 buckets:64 items:0 deletes:0 filters:1 \
max_iterations:7 expansion:4\r\n"
);
assert_eq!(f.run(&[b"CF.RESERVE", b"r", b"64"]), "-ERR item exists\r\n");
assert_eq!(f.run(&[b"CF.RESERVE", b"q", b"abc"]), "-Bad capacity\r\n");
assert_eq!(
f.run(&[b"CF.RESERVE", b"q", b"1"]),
"-Capacity must be in the range [2 * BUCKETSIZE, 1073741824]\r\n"
);
// The range is the bucket size's and not a constant, so a capacity that
// was fine at two slots a bucket is not at four.
assert_eq!(
f.run(&[b"CF.RESERVE", b"q", b"7", b"BUCKETSIZE", b"4"]),
"-Capacity must be in the range [2 * BUCKETSIZE, 1073741824]\r\n"
);
assert_eq!(
f.run(&[b"CF.RESERVE", b"q", b"8", b"BUCKETSIZE", b"4"]),
"+OK\r\n"
);
// The capacity is checked last, so a command that is wrong twice
// answers about the option. Which option it answers about is the order
// the module looks for them in and not the order they were written, so
// a bad kick budget wins over a bad bucket size wherever the two sit.
assert_eq!(
f.run(&[b"CF.RESERVE", b"q2", b"64", b"BUCKETSIZE", b"0"]),
"-BUCKETSIZE: value must be in the range [1, 255]\r\n"
);
assert_eq!(
f.run(&[
b"CF.RESERVE",
b"q2",
b"64",
b"EXPANSION",
b"xx",
b"BUCKETSIZE",
b"0"
]),
"-BUCKETSIZE: value must be in the range [1, 255]\r\n"
);
assert_eq!(
f.run(&[
b"CF.RESERVE",
b"q2",
b"64",
b"MAXITERATIONS",
b"0",
b"BUCKETSIZE",
b"0"
]),
"-MAXITERATIONS: value must be in the range [1, 65535]\r\n"
);
// A second pair with a name that has already been read is not looked at
// at all, so this one is a filter with buckets of one rather than an
// error about a bucket size of zero.
assert_eq!(
f.run(&[
b"CF.RESERVE",
b"q3",
b"64",
b"BUCKETSIZE",
b"1",
b"BUCKETSIZE",
b"0"
]),
"+OK\r\n"
);
// A pair nobody knows is dropped, which is the opposite of what
// `CF.INSERT` does with the same mistake.
assert_eq!(
f.run(&[b"CF.RESERVE", b"q4", b"64", b"NOSUCH", b"9"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"CF.DEBUG", b"q4"]),
"$78\r\nbktsize:2 buckets:32 items:0 deletes:0 filters:1 \
max_iterations:20 expansion:1\r\n"
);
// And an option with nothing after it leaves an odd number of them,
// which is an arity error rather than a complaint about the option.
assert!(
f.run(&[b"CF.RESERVE", b"q5", b"64", b"BUCKETSIZE"])
.contains("wrong number of arguments")
);
}
/// `CF.INSERT` is a reserve and a multi add, with a grammar that agrees
/// with `CF.RESERVE` about nothing.
#[test]
fn insert_checks_every_occurrence_and_matches_on_the_first_letter() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"CAPACITY", b"64", b"ITEMS", b"a", b"b"]),
"*2\r\n:1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"CF.DEBUG", b"i"]),
"$78\r\nbktsize:2 buckets:32 items:2 deletes:0 filters:1 \
max_iterations:20 expansion:1\r\n"
);
// The NX form has three answers rather than two, which is why it stays
// integers on both protocols.
assert_eq!(
f.run(&[b"CF.INSERTNX", b"i", b"ITEMS", b"a", b"c"]),
"*2\r\n:0\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"CF.INSERT", b"gone", b"NOCREATE", b"ITEMS", b"a"]),
"-ERR not found\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"gone"]), ":0\r\n");
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"CAPACITY", b"abc", b"ITEMS", b"a"]),
"-Bad capacity\r\n"
);
// The bucket size cannot be given here, so the range names the config
// that holds it instead of the option `CF.RESERVE` names.
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"CAPACITY", b"2", b"ITEMS", b"a"]),
"-Capacity must be in the range [cf-bucket-size * 2, 1073741824]\r\n"
);
// Every occurrence is checked, which is where this differs from
// `CF.RESERVE`: the second `CAPACITY` is an error even though the first
// one is the one that would have been used.
assert_eq!(
f.run(&[
b"CF.INSERT",
b"i",
b"CAPACITY",
b"8",
b"CAPACITY",
b"2",
b"ITEMS",
b"a"
]),
"-Capacity must be in the range [cf-bucket-size * 2, 1073741824]\r\n"
);
// An option is one letter and not a word, so `NOSUCH` is `NOCREATE` and
// `ITEMSXYZ` is `ITEMS`, and only a letter that starts nothing is
// refused.
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"NOSUCH", b"ITEMS", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"ITEMSXYZ", b"a"]),
"*1\r\n:1\r\n"
);
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"ZZZ", b"ITEMS", b"a"]),
"-Unknown argument received\r\n"
);
// Everything after ITEMS is an item, even when it spells an option.
assert_eq!(
f.run(&[b"CF.INSERT", b"i", b"ITEMS", b"NOCREATE"]),
"*1\r\n:1\r\n"
);
// And the two ways of sending no items at all are the same complaint.
assert!(
f.run(&[b"CF.INSERT", b"i", b"ITEMS"])
.contains("wrong number of arguments")
);
assert!(
f.run(&[b"CF.INSERT", b"i", b"CAPACITY"])
.contains("wrong number of arguments")
);
}
/// The two walls a filter can hit, which say different things and are not
/// the same wall.
#[test]
fn a_full_filter_and_one_that_ran_out_of_filters_answer_differently() {
let mut f = Fixture::new();
f.run(&[
b"CF.RESERVE",
b"s",
b"4",
b"BUCKETSIZE",
b"1",
b"EXPANSION",
b"0",
]);
for i in 0..4u32 {
assert_eq!(
f.run(&[b"CF.ADD", b"s", i.to_string().as_bytes()]),
":1\r\n"
);
}
assert_eq!(f.run(&[b"CF.ADD", b"s", b"4"]), "-Filter is full\r\n");
assert_eq!(f.run(&[b"CF.ADDNX", b"s", b"zz"]), "-Filter is full\r\n");
// The add commands say it in a sentence and the insert commands say it
// in the array, one value per item, and the array is never short.
assert_eq!(
f.run(&[b"CF.INSERT", b"s", b"ITEMS", b"p", b"q"]),
"*2\r\n:-1\r\n:-1\r\n"
);
assert_eq!(
f.run(&[b"CF.INSERTNX", b"s", b"ITEMS", b"0", b"q"]),
"*2\r\n:0\r\n:-1\r\n"
);
// A chain that is allowed to grow stops for a different reason, and the
// count it stops at is the filter limit rather than the room: this one
// gives up with three slots free. Loading a chain that already has
// every filter it is allowed shows why, since it refuses an item
// straight into an empty one.
let full = cf_header(0, 4, 0, 32, [1, 20, 1]);
assert_eq!(f.run(&[b"CF.LOADCHUNK", b"g", b"1", &full]), "+OK\r\n");
assert_eq!(
f.run(&[b"CF.ADD", b"g", b"q"]),
"-Maximum expansions reached\r\n"
);
assert_eq!(
f.run(&[b"CF.INFO", b"g"]),
"*16\r\n+Size\r\n:680\r\n+Number of buckets\r\n:4\r\n\
+Number of filters\r\n:32\r\n+Number of items inserted\r\n:0\r\n\
+Number of items deleted\r\n:0\r\n+Bucket size\r\n:1\r\n\
+Expansion rate\r\n:1\r\n+Max iterations\r\n:20\r\n"
);
}
/// A filter dumped a chunk at a time and put back under another key is the
/// same filter, and the headers that describe one nobody could build are
/// refused on the way in.
#[test]
fn a_cuckoo_dump_replays_into_a_filter_that_answers_the_same() {
let mut f = Fixture::new();
f.run(&[
b"CF.RESERVE",
b"src",
b"8",
b"BUCKETSIZE",
b"2",
b"EXPANSION",
b"2",
]);
for i in 0..40u32 {
f.run(&[b"CF.ADD", b"src", i.to_string().as_bytes()]);
}
// Position zero asks for the header and every one after it is a byte
// offset across every filter laid end to end, and the walk ends on a
// zero and a nil rather than an empty chunk.
let mut pos = b"0".to_vec();
let mut chunks = 0;
loop {
let raw = f.raw(&[b"CF.SCANDUMP", b"src", &pos]);
let head = String::from_utf8_lossy(&raw[..raw.len().min(24)]).into_owned();
let next = head
.split("\r\n")
.nth(1)
.and_then(|n| n.strip_prefix(':'))
.expect("a two element reply of a position and a chunk")
.to_owned();
if next == "0" {
assert!(raw.ends_with(b"$-1\r\n"), "the walk ends on a nil");
break;
}
let body = &raw[raw.iter().position(|&b| b == b'$').expect("a bulk chunk")..];
let at = body
.windows(2)
.position(|w| w == b"\r\n")
.expect("a length line")
+ 2;
let data = &body[at..body.len() - 2];
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"dst", next.as_bytes(), data]),
"+OK\r\n",
"loading chunk {chunks}"
);
pos = next.into_bytes();
chunks += 1;
}
assert!(chunks >= 2, "a header and at least one chunk");
assert_eq!(f.run(&[b"CF.INFO", b"dst"]), f.run(&[b"CF.INFO", b"src"]));
assert_eq!(f.run(&[b"CF.DEBUG", b"dst"]), f.run(&[b"CF.DEBUG", b"src"]));
for i in 0..40u32 {
assert_eq!(
f.run(&[b"CF.EXISTS", b"dst", i.to_string().as_bytes()]),
":1\r\n"
);
}
// A filter with nothing in it hands out no header at all, so a client
// that dumps one has nothing to load back.
f.run(&[b"CF.RESERVE", b"empty", b"4", b"BUCKETSIZE", b"1"]);
assert_eq!(
f.run(&[b"CF.SCANDUMP", b"empty", b"0"]),
"*2\r\n:0\r\n$-1\r\n"
);
// The positions this end will not take, which are not the same set at
// both ends: a dump refuses a negative one and a load takes it as an
// offset and fails to find anything there.
assert_eq!(
f.run(&[b"CF.SCANDUMP", b"src", b"nope"]),
"-Invalid position\r\n"
);
assert_eq!(
f.run(&[b"CF.SCANDUMP", b"src", b"-1"]),
"-Invalid position\r\n"
);
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"dst", b"0", b"x"]),
"-Invalid position\r\n"
);
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"dst", b"99999", b"x"]),
"-Couldn't load chunk!\r\n"
);
// A header on top of a filter is refused rather than merged.
let good = cf_header(0, 8, 0, 1, [2, 20, 1]);
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"dst", b"1", &good]),
"-ERR item exists\r\n"
);
// A chunk that is not the size of a header where a header should have
// been is one sentence, and one that is the size of a header and
// describes a filter nobody could build is another.
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"n1", b"1", b"short"]),
"-Invalid header\r\n"
);
for (why, bad) in [
("no filters at all", cf_header(0, 8, 0, 0, [2, 20, 1])),
("no buckets", cf_header(0, 0, 0, 1, [2, 20, 1])),
(
"a bucket count that is not a power of two",
cf_header(0, 3, 0, 1, [2, 20, 1]),
),
("an empty bucket", cf_header(0, 8, 0, 1, [0, 20, 1])),
("no kicks", cf_header(0, 8, 0, 1, [2, 0, 1])),
(
"a growth nobody could reach",
cf_header(0, 8, 0, 1, [2, 20, 32769]),
),
(
"a chain that cannot grow and did",
cf_header(0, 8, 0, 2, [2, 20, 0]),
),
// The count is written in eight bytes and read into two, so a
// number that is a multiple of the second arrives as none.
(
"a filter count that wraps",
cf_header(0, 8, 0, 65_536, [2, 20, 1]),
),
] {
assert_eq!(
f.run(&[b"CF.LOADCHUNK", b"bad", b"1", &bad]),
"-Couldn't create filter!\r\n",
"{why}"
);
}
}
/// The RESP3 shapes, which are where this family differs most from RESP2
/// and where one of its answers stops being readable.
#[test]
fn the_cuckoo_family_answers_in_resp3_spelling_too() {
let mut f = Fixture::new();
f.out.set_proto(Proto::Resp3);
assert_eq!(f.run(&[b"CF.ADD", b"c", b"a"]), "#t\r\n");
assert_eq!(f.run(&[b"CF.ADD", b"c", b"a"]), "#t\r\n");
assert_eq!(f.run(&[b"CF.ADDNX", b"c", b"a"]), "#f\r\n");
assert_eq!(f.run(&[b"CF.EXISTS", b"c", b"a"]), "#t\r\n");
assert_eq!(
f.run(&[b"CF.MEXISTS", b"c", b"a", b"z"]),
"*2\r\n#t\r\n#f\r\n"
);
assert_eq!(f.run(&[b"CF.DEL", b"c", b"a"]), "#t\r\n");
assert_eq!(f.run(&[b"CF.DEL", b"c", b"z"]), "#f\r\n");
// The count stays an integer, because it counts rather than answers.
assert_eq!(f.run(&[b"CF.COUNT", b"c", b"a"]), ":1\r\n");
assert_eq!(
f.run(&[b"CF.INFO", b"c"]),
"%8\r\n+Size\r\n:1080\r\n+Number of buckets\r\n:512\r\n\
+Number of filters\r\n:1\r\n+Number of items inserted\r\n:1\r\n\
+Number of items deleted\r\n:1\r\n+Bucket size\r\n:2\r\n\
+Expansion rate\r\n:1\r\n+Max iterations\r\n:20\r\n"
);
// `CF.INSERT` writes a boolean per item here and an integer per item on
// RESP2, and minus one has nowhere to go in a boolean, so a RESP3
// client cannot tell an item that did not fit from one that is already
// there. `CF.INSERTNX` keeps its integers for exactly that reason.
f.run(&[
b"CF.RESERVE",
b"s",
b"4",
b"BUCKETSIZE",
b"1",
b"EXPANSION",
b"0",
]);
assert_eq!(
f.run(&[
b"CF.INSERT",
b"s",
b"ITEMS",
b"a",
b"b",
b"c",
b"d",
b"e",
b"f"
]),
"*6\r\n#t\r\n#t\r\n#t\r\n#f\r\n#f\r\n#f\r\n"
);
assert_eq!(
f.run(&[b"CF.INSERTNX", b"s", b"ITEMS", b"a", b"zz"]),
"*2\r\n:0\r\n:-1\r\n"
);
assert_eq!(f.run(&[b"CF.ADD", b"s", b"zzz"]), "-Filter is full\r\n");
// The end of a dump is a nil and not an empty chunk, which is one
// underscore here and a negative length on RESP2.
assert_eq!(f.run(&[b"CF.SCANDUMP", b"c", b"9999"]), "*2\r\n:0\r\n_\r\n");
}
// ------------------------------------------------------------------- cms
/// A sketch is made from either end, and both constructors look at the key
/// before they look at their arguments.
#[test]
fn a_sketch_is_made_from_a_size_or_from_an_error_rate() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"CMS.INITBYDIM", b"d", b"100", b"5"]), "+OK\r\n");
assert_eq!(
f.run(&[b"CMS.INFO", b"d"]),
"*6\r\n+width\r\n:100\r\n+depth\r\n:5\r\n+count\r\n:0\r\n"
);
assert_eq!(f.run(&[b"TYPE", b"d"]), "+CMSk-TYPE\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"d"]), "$3\r\nraw\r\n");
// Two over the error rounded up, and the log of the probability over the
// log of a half rounded up, which for these two is 200 by 6.
assert_eq!(
f.run(&[b"CMS.INITBYPROB", b"p", b"0.01", b"0.03"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"CMS.INFO", b"p"]),
"*6\r\n+width\r\n:200\r\n+depth\r\n:6\r\n+count\r\n:0\r\n"
);
// The key is checked first, so a width of zero at a key that is already
// there is about the key and not about the width.
assert_eq!(
f.run(&[b"CMS.INITBYDIM", b"d", b"0", b"2"]),
"-CMS: key already exists\r\n"
);
assert_eq!(
f.run(&[b"CMS.INITBYDIM", b"new", b"0", b"2"]),
"-CMS: invalid width\r\n"
);
assert_eq!(
f.run(&[b"CMS.INITBYDIM", b"new", b"2", b"0"]),
"-CMS: invalid depth\r\n"
);
assert_eq!(
f.run(&[b"CMS.INITBYPROB", b"new", b"0", b"0.5"]),
"-CMS: invalid overestimation value\r\n"
);
assert_eq!(
f.run(&[b"CMS.INITBYPROB", b"new", b"0.1", b"1"]),
"-CMS: invalid prob value\r\n"
);
// A probability whose float conversion is zero has no depth, and a width
// past a signed sixty four bit integer has no width, and both are the
// same sentence.
assert_eq!(
f.run(&[b"CMS.INITBYPROB", b"new", b"0.5", b"1e-46"]),
"-CMS: invalid init arguments\r\n"
);
// And a sketch bigger than a gibibyte of counters is refused here where
// the reference reserves address space nobody has touched, which is
// D-47.
assert_eq!(
f.run(&[b"CMS.INITBYDIM", b"new", b"268435457", b"1"]),
"-CMS: Insufficient memory to create the key\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"new"]), ":0\r\n");
}
/// Every pair is parsed before any of them lands, the counters saturate,
/// and the count is a signed total of what was asked for.
#[test]
fn increments_are_parsed_whole_and_the_counters_saturate() {
let mut f = Fixture::new();
f.run(&[b"CMS.INITBYDIM", b"c", b"100", b"4"]);
assert_eq!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"3", b"b", b"4"]),
"*2\r\n:3\r\n:4\r\n"
);
// An item that is incremented twice in one call sees its own first
// increment in the reply to the second.
assert_eq!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"1", b"a", b"1"]),
"*2\r\n:4\r\n:5\r\n"
);
// A bad number anywhere means nothing at all is applied.
assert_eq!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"9", b"b", b"x"]),
"-CMS: Cannot parse number\r\n"
);
assert_eq!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"9", b"b", b"-1"]),
"-CMS: Number cannot be negative\r\n"
);
assert_eq!(
f.run(&[b"CMS.QUERY", b"c", b"a", b"b"]),
"*2\r\n:5\r\n:4\r\n"
);
// The counters stop at four billion and the item that stopped says so in
// its own slot while the one beside it answers a number.
f.run(&[b"CMS.INCRBY", b"c", b"a", b"4294967295"]);
assert_eq!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"1", b"b", b"1"]),
"*2\r\n-CMS: INCRBY overflow\r\n:5\r\n"
);
assert_eq!(f.run(&[b"CMS.QUERY", b"c", b"a"]), "*1\r\n:4294967295\r\n");
// The count is what was asked for rather than what landed, and it is
// signed, so a big enough total comes back negative.
f.run(&[b"CMS.INITBYDIM", b"w", b"4", b"1"]);
f.run(&[b"CMS.INCRBY", b"w", b"x", b"9223372036854775807"]);
f.run(&[b"CMS.INCRBY", b"w", b"x", b"1"]);
assert_eq!(
f.run(&[b"CMS.INFO", b"w"]),
"*6\r\n+width\r\n:4\r\n+depth\r\n:1\r\n+count\r\n:-9223372036854775808\r\n"
);
// An odd number of arguments after the key is an arity error and not a
// syntax one.
assert!(
f.run(&[b"CMS.INCRBY", b"c", b"a", b"1", b"b"])
.contains("wrong number of arguments")
);
assert_eq!(
f.run(&[b"CMS.INCRBY", b"nope", b"a", b"1"]),
"-CMS: key does not exist\r\n"
);
assert_eq!(
f.run(&[b"CMS.QUERY", b"nope", b"a"]),
"-CMS: key does not exist\r\n"
);
}
/// A merge overwrites its destination, and it is worked out in full before
/// any of it is written.
#[test]
fn a_merge_lands_whole_or_not_at_all() {
let mut f = Fixture::new();
for name in [&b"m1"[..], b"m2", b"dst"] {
f.run(&[b"CMS.INITBYDIM", name, b"64", b"3"]);
}
f.run(&[b"CMS.INCRBY", b"m1", b"a", b"5"]);
f.run(&[b"CMS.INCRBY", b"m2", b"a", b"7"]);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"2", b"m1", b"m2"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"CMS.QUERY", b"dst", b"a"]), "*1\r\n:12\r\n");
// Overwritten and not added to, so the same merge twice is the same
// answer twice.
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"2", b"m1", b"m2"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"CMS.QUERY", b"dst", b"a"]), "*1\r\n:12\r\n");
assert_eq!(
f.run(&[
b"CMS.MERGE",
b"dst",
b"2",
b"m1",
b"m2",
b"WEIGHTS",
b"2",
b"3"
]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"CMS.QUERY", b"dst", b"a"]), "*1\r\n:31\r\n");
// A cell times a weight is checked wide rather than wrapped, so this is
// a refusal and the destination is left exactly as it was.
assert_eq!(
f.run(&[
b"CMS.MERGE",
b"dst",
b"1",
b"m1",
b"WEIGHTS",
b"4611686018427387904"
]),
"-CMS: MERGE overflow\r\n"
);
assert_eq!(f.run(&[b"CMS.QUERY", b"dst", b"a"]), "*1\r\n:31\r\n");
// The destination comes first, then the count, then the layout, then the
// weights, then the sources one at a time.
f.run(&[b"CMS.INITBYDIM", b"wide", b"128", b"3"]);
assert_eq!(
f.run(&[b"CMS.MERGE", b"gone", b"1", b"m1"]),
"-CMS: key does not exist\r\n"
);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"0", b"m1"]),
"-CMS: Number of keys must be positive\r\n"
);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"3", b"m1"]),
"-CMS: wrong number of keys\r\n"
);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"1", b"m1", b"WEIGHTS", b"1", b"2"]),
"-CMS: wrong number of keys/weights\r\n"
);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"1", b"wide"]),
"-CMS: width/depth is not equal\r\n"
);
assert_eq!(
f.run(&[b"CMS.MERGE", b"dst", b"1", b"gone"]),
"-CMS: key does not exist\r\n"
);
}
/// A key holding anything else is `WRONGTYPE` to all six, and a key holding
/// a sketch is refused by the two commands that would have to serialise it.
#[test]
fn a_sketch_is_a_module_key_to_the_rest_of_the_keyspace() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"text"]);
for cmd in [
vec![&b"CMS.INITBYDIM"[..], b"s", b"8", b"2"],
vec![&b"CMS.INCRBY"[..], b"s", b"a", b"1"],
vec![&b"CMS.QUERY"[..], b"s", b"a"],
vec![&b"CMS.INFO"[..], b"s"],
vec![&b"CMS.MERGE"[..], b"s", b"1", b"s"],
] {
let name = String::from_utf8_lossy(cmd[0]).into_owned();
let reply = f.run(&cmd);
// The two constructors see the key before anything else and say so
// in the module's own words, and the rest are `WRONGTYPE`.
assert!(
reply.starts_with("-WRONGTYPE") || reply == "-CMS: key already exists\r\n",
"{name}: {reply}"
);
}
f.run(&[b"CMS.INITBYDIM", b"c", b"64", b"2"]);
// Redis refuses to copy a module key that has no copy callback, and
// these are its words rather than ours. `DUMP` is the other half of
// D-48: the reference has a payload for one of these and we do not.
assert_eq!(
f.run(&[b"COPY", b"c", b"c2"]),
"-ERR not supported for this module key\r\n"
);
assert_eq!(
f.run(&[b"DUMP", b"c"]),
"-ERR DUMP is not supported for this module key\r\n"
);
// A graph is nobody's module and keeps its own sentence.
f.run(&[b"G.NADD", b"g", b"a"]);
assert_eq!(
f.run(&[b"COPY", b"g", b"g2"]),
"-ERR COPY is not supported for a graph\r\n"
);
assert_eq!(
f.run(&[b"DUMP", b"g"]),
"-ERR DUMP is not supported for a graph\r\n"
);
// Everything that does not need a byte shape works on a sketch key the
// way it works on any other.
assert_eq!(f.run(&[b"EXPIRE", b"c", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"PERSIST", b"c"]), ":1\r\n");
assert_eq!(f.run(&[b"RENAME", b"c", b"c3"]), "+OK\r\n");
assert_eq!(f.run(&[b"TYPE", b"c3"]), "+CMSk-TYPE\r\n");
assert_eq!(f.run(&[b"DEL", b"c3"]), ":1\r\n");
}
// ------------------------------------------------------------------ topk
/// `TOPK.RESERVE` takes three arguments or six, and looks at the key before
/// it looks at any of them.
#[test]
fn a_reserve_takes_three_arguments_or_six() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"TOPK.RESERVE", b"t", b"5"]), "+OK\r\n");
assert_eq!(
f.run(&[b"TOPK.INFO", b"t"]),
"*8\r\n+k\r\n:5\r\n+width\r\n:8\r\n+depth\r\n:7\r\n+decay\r\n$3\r\n0.9\r\n"
);
// Four arguments and five are an arity error rather than a defaulted
// depth or decay.
for cmd in [
vec![&b"TOPK.RESERVE"[..], b"u", b"5", b"8"],
vec![&b"TOPK.RESERVE"[..], b"u", b"5", b"8", b"7"],
] {
assert!(f.run(&cmd).contains("wrong number of arguments"));
}
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"u", b"5", b"8", b"7", b"0.5"]),
"+OK\r\n"
);
// The key is checked first, so a reserve with nothing else right at a
// key that is taken still says the key is taken.
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"u", b"0", b"0", b"0", b"9"]),
"-TopK: key already exists\r\n"
);
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"v", b"0"]),
"-TopK: invalid k\r\n"
);
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"v", b"1", b"0", b"7", b"0.9"]),
"-TopK: invalid width\r\n"
);
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"v", b"1", b"8", b"x", b"0.9"]),
"-TopK: invalid depth\r\n"
);
// Zero is out and one is in, which is the module's `> 0` and `<= 1`.
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"v", b"1", b"8", b"7", b"0"]),
"-TopK: invalid decay value. must be '<= 1' & '> 0'\r\n"
);
assert_eq!(
f.run(&[b"TOPK.RESERVE", b"v", b"1", b"8", b"7", b"1"]),
"+OK\r\n"
);
// Past the cap, with the one sentence in the family that has a prefix.
assert_eq!(
f.run(&[
b"TOPK.RESERVE",
b"w",
b"1",
b"4294967295",
b"4294967295",
b"0.9"
]),
"-ERR Insufficient memory to create topk data structure\r\n"
);
}
/// What the sketch keeps, and the three ways of asking about it.
#[test]
fn the_kept_set_is_what_query_and_list_answer_from() {
let mut f = Fixture::new();
f.run(&[b"TOPK.RESERVE", b"t", b"2", b"1000", b"5", b"0.9"]);
// A null an item while there is room, then the name of whatever was
// pushed out.
assert_eq!(
f.run(&[b"TOPK.ADD", b"t", b"a", b"b"]),
"*2\r\n$-1\r\n$-1\r\n"
);
assert_eq!(f.run(&[b"TOPK.INCRBY", b"t", b"a", b"10"]), "*1\r\n$-1\r\n");
// Two slots are full and `c` arrives with a count of one, which is not
// under the smallest kept count, so it takes that slot straight away.
assert_eq!(f.run(&[b"TOPK.ADD", b"t", b"c"]), "*1\r\n$1\r\nb\r\n");
assert_eq!(f.run(&[b"TOPK.INCRBY", b"t", b"c", b"5"]), "*1\r\n$-1\r\n");
assert_eq!(
f.run(&[b"TOPK.QUERY", b"t", b"a", b"b", b"c"]),
"*3\r\n:1\r\n:0\r\n:1\r\n"
);
// The table still counts what the kept set let go of.
assert_eq!(
f.run(&[b"TOPK.COUNT", b"t", b"a", b"b", b"c"]),
"*3\r\n:11\r\n:1\r\n:6\r\n"
);
assert_eq!(f.run(&[b"TOPK.LIST", b"t"]), "*2\r\n$1\r\na\r\n$1\r\nc\r\n");
assert_eq!(
f.run(&[b"TOPK.LIST", b"t", b"WITHCOUNT"]),
"*4\r\n$1\r\na\r\n:11\r\n$1\r\nc\r\n:6\r\n"
);
// Any prefix of the keyword turns the counts on, the empty string
// included, and only a longer word or a different one is refused.
assert_eq!(
f.run(&[b"TOPK.LIST", b"t", b"w"]),
f.run(&[b"TOPK.LIST", b"t", b"WITHCOUNT"])
);
assert_eq!(
f.run(&[b"TOPK.LIST", b"t", b""]),
f.run(&[b"TOPK.LIST", b"t", b"WITHCOUNT"])
);
assert_eq!(
f.run(&[b"TOPK.LIST", b"t", b"WITHCOUNTS"]),
"-WITHCOUNT keyword expected\r\n"
);
// And the keyword is looked at before the key, so a missing key with a
// bad keyword complains about the keyword.
assert_eq!(
f.run(&[b"TOPK.LIST", b"missing", b"nope"]),
"-WITHCOUNT keyword expected\r\n"
);
assert_eq!(
f.run(&[b"TOPK.LIST", b"missing"]),
"-TopK: key does not exist\r\n"
);
// An item counted zero times is kept and not listed.
f.run(&[b"TOPK.RESERVE", b"z", b"3"]);
assert_eq!(
f.run(&[b"TOPK.INCRBY", b"z", b"nothing", b"0"]),
"*1\r\n$-1\r\n"
);
assert_eq!(f.run(&[b"TOPK.QUERY", b"z", b"nothing"]), "*1\r\n:1\r\n");
assert_eq!(f.run(&[b"TOPK.LIST", b"z"]), "*0\r\n");
}
/// `TOPK.INCRBY` applies as it goes, so a bad increment leaves everything
/// before it counted, and the reply counts what it wrote.
#[test]
fn an_increment_is_applied_as_it_goes_and_stops_at_a_bad_one() {
let mut f = Fixture::new();
f.run(&[b"TOPK.RESERVE", b"t", b"5", b"1000", b"5", b"0.9"]);
// Three pairs, the middle one bad: two elements come back, one of them
// the error, and the array header says two rather than three. That last
// part is D-51 and it is why a client here stays in step.
assert_eq!(
f.run(&[b"TOPK.INCRBY", b"t", b"a", b"3", b"b", b"-1", b"c", b"4"]),
format!(
"*2\r\n$-1\r\n-{}\r\n",
"TopK: increment must be an integer greater or equal to 0 and smaller or equal to 100,000"
)
);
assert_eq!(
f.run(&[b"TOPK.COUNT", b"t", b"a", b"b", b"c"]),
"*3\r\n:3\r\n:0\r\n:0\r\n"
);
// A hundred thousand is in and one more is out.
assert_eq!(
f.run(&[b"TOPK.INCRBY", b"t", b"a", b"100000"]),
"*1\r\n$-1\r\n"
);
assert!(
f.run(&[b"TOPK.INCRBY", b"t", b"a", b"100001"])
.contains("smaller or equal to 100,000")
);
// Pairs have to be pairs.
assert!(
f.run(&[b"TOPK.INCRBY", b"t", b"a", b"1", b"b"])
.contains("wrong number of arguments")
);
assert_eq!(f.run(&[b"TOPK.COUNT", b"t", b"a"]), "*1\r\n:100003\r\n");
}
/// The RESP3 shapes, which are the two the protocols disagree about.
#[test]
fn a_query_is_a_bool_and_info_is_a_map_on_resp3() {
let mut f = Fixture::new();
f.run(&[b"HELLO", b"3"]);
f.run(&[b"TOPK.RESERVE", b"t", b"2", b"8", b"7", b"0.5"]);
f.run(&[b"TOPK.ADD", b"t", b"a"]);
assert_eq!(
f.run(&[b"TOPK.QUERY", b"t", b"a", b"b"]),
"*2\r\n#t\r\n#f\r\n"
);
// The count stays an integer on both protocols.
assert_eq!(f.run(&[b"TOPK.COUNT", b"t", b"a"]), "*1\r\n:1\r\n");
assert_eq!(
f.run(&[b"TOPK.INFO", b"t"]),
"%4\r\n+k\r\n:2\r\n+width\r\n:8\r\n+depth\r\n:7\r\n+decay\r\n,0.5\r\n"
);
assert_eq!(f.run(&[b"TOPK.ADD", b"t", b"a"]), "*1\r\n_\r\n");
}
/// A top k key answers the module sentences the other sketch families
/// answer, and its own word for its type.
#[test]
fn a_top_k_sketch_is_a_module_key_to_the_rest_of_the_keyspace() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"text"]);
for cmd in [
vec![&b"TOPK.RESERVE"[..], b"s", b"5"],
vec![&b"TOPK.ADD"[..], b"s", b"a"],
vec![&b"TOPK.INCRBY"[..], b"s", b"a", b"1"],
vec![&b"TOPK.QUERY"[..], b"s", b"a"],
vec![&b"TOPK.COUNT"[..], b"s", b"a"],
vec![&b"TOPK.LIST"[..], b"s"],
vec![&b"TOPK.INFO"[..], b"s"],
] {
let name = String::from_utf8_lossy(cmd[0]).into_owned();
let reply = f.run(&cmd);
assert!(
reply.starts_with("-WRONGTYPE") || reply == "-TopK: key already exists\r\n",
"{name}: {reply}"
);
}
f.run(&[b"TOPK.RESERVE", b"t", b"5"]);
assert_eq!(
f.run(&[b"COPY", b"t", b"t2"]),
"-ERR not supported for this module key\r\n"
);
assert_eq!(
f.run(&[b"DUMP", b"t"]),
"-ERR DUMP is not supported for this module key\r\n"
);
assert_eq!(f.run(&[b"EXPIRE", b"t", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"PERSIST", b"t"]), ":1\r\n");
assert_eq!(f.run(&[b"RENAME", b"t", b"t3"]), "+OK\r\n");
assert_eq!(f.run(&[b"TYPE", b"t3"]), "+TopK-TYPE\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"t3"]), "$3\r\nraw\r\n");
assert_eq!(f.run(&[b"DEL", b"t3"]), ":1\r\n");
// Every one of the six that is not the constructor says the same thing
// about a key that is not there.
assert_eq!(
f.run(&[b"TOPK.INFO", b"t3"]),
"-TopK: key does not exist\r\n"
);
}
// --------------------------------------------------------------- tdigest
/// `TDIGEST.CREATE` takes two arguments or four, and the keyword search is a
/// search rather than a lookup.
#[test]
fn a_create_takes_two_arguments_or_four_and_reads_the_last_one() {
let mut f = Fixture::new();
assert_eq!(f.run(&[b"TDIGEST.CREATE", b"t"]), "+OK\r\n");
// A hundred is the default and the capacity is six times it plus ten.
assert_eq!(
f.run(&[b"TDIGEST.INFO", b"t"]),
"*18\r\n+Compression\r\n:100\r\n+Capacity\r\n:610\r\n+Merged nodes\r\n:0\r\n\
+Unmerged nodes\r\n:0\r\n+Merged weight\r\n:0\r\n+Unmerged weight\r\n:0\r\n\
+Observations\r\n:0\r\n+Total compressions\r\n:0\r\n+Memory usage\r\n:9840\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"t"]),
"-ERR T-Digest: key already exists\r\n"
);
// Three arguments is an arity error and not a missing keyword.
assert!(
f.run(&[b"TDIGEST.CREATE", b"u", b"COMPRESSION"])
.contains("wrong number of arguments")
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"u", b"COMPRESSION", b"1000"]),
"+OK\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"v", b"compression", b"1"]),
"+OK\r\n"
);
// The word is looked for across both trailing arguments and the number
// is then read out of the last one whatever was found, so this looks for
// a number inside the word `COMPRESSION` and does not find one.
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"100", b"COMPRESSION"]),
"-ERR T-Digest: error parsing compression parameter\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"NOPE", b"100"]),
"-ERR T-Digest: wrong keyword\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"COMPRESSION", b"1.5"]),
"-ERR T-Digest: error parsing compression parameter\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"COMPRESSION", b"0"]),
"-ERR T-Digest: compression parameter needs to be a positive integer\r\n"
);
// The reference's own ceiling, which is where the capacity stops fitting
// in an int, and one past it.
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"COMPRESSION", b"357913942"]),
"-ERR T-Digest: allocation failed\r\n"
);
// And ours, which is a gibibyte of centroids and is D-52.
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"w", b"COMPRESSION", b"100000000"]),
"-ERR T-Digest: allocation failed\r\n"
);
// The key is checked before the arguments, so a bad compression at a key
// that is already a digest still says the key is taken.
assert_eq!(
f.run(&[b"TDIGEST.CREATE", b"t", b"COMPRESSION", b"0"]),
"-ERR T-Digest: key already exists\r\n"
);
}
/// The four samples every note about this family is written against, and the
/// answers a real 8.10.1 gives for them.
#[test]
fn the_quantile_family_answers_what_the_module_answers() {
let mut f = Fixture::new();
f.run(&[b"TDIGEST.CREATE", b"s"]);
assert_eq!(
f.run(&[b"TDIGEST.ADD", b"s", b"1", b"2", b"3", b"4"]),
"+OK\r\n"
);
assert_eq!(f.run(&[b"TDIGEST.MIN", b"s"]), "$1\r\n1\r\n");
assert_eq!(f.run(&[b"TDIGEST.MAX", b"s"]), "$1\r\n4\r\n");
// The cdf of a sample is the weight below it plus half its own.
assert_eq!(
f.run(&[b"TDIGEST.CDF", b"s", b"1", b"2", b"3", b"4"]),
"*4\r\n$5\r\n0.125\r\n$5\r\n0.375\r\n$5\r\n0.625\r\n$5\r\n0.875\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"s", b"0", b"0.5", b"1"]),
"*3\r\n$1\r\n1\r\n$1\r\n3\r\n$1\r\n4\r\n"
);
// Out of order, the walk restarts, and 0.5 answers 3 either way while
// the two after it are read from the front again.
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"s", b"0.5", b"0.1", b"0.9"]),
"*3\r\n$1\r\n3\r\n$1\r\n1\r\n$1\r\n4\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.RANK", b"s", b"0", b"1", b"3", b"4", b"5"]),
"*5\r\n:-1\r\n:0\r\n:2\r\n:3\r\n:4\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.REVRANK", b"s", b"0", b"1", b"3", b"4", b"5"]),
"*5\r\n:4\r\n:3\r\n:1\r\n:0\r\n:-1\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.BYRANK", b"s", b"0", b"1", b"3", b"4"]),
"*4\r\n$1\r\n1\r\n$1\r\n2\r\n$1\r\n4\r\n$3\r\ninf\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.BYREVRANK", b"s", b"0", b"1", b"3", b"4"]),
"*4\r\n$1\r\n4\r\n$1\r\n3\r\n$1\r\n1\r\n$4\r\n-inf\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"0", b"1"]),
"$3\r\n2.5\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"0.25", b"0.75"]),
"$3\r\n2.5\r\n"
);
// The ranges, which are separate sentences from the parse failures.
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"s", b"1.1"]),
"-ERR T-Digest: quantile should be in [0,1]\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"s", b"zzz"]),
"-ERR T-Digest: error parsing quantile\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.CDF", b"s", b"zzz"]),
"-ERR T-Digest: error parsing cdf\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.RANK", b"s", b"zzz"]),
"-ERR T-Digest: error parsing value\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.BYRANK", b"s", b"-1"]),
"-ERR T-Digest: rank needs to be non negative\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.BYRANK", b"s", b"1.5"]),
"-ERR T-Digest: error parsing rank\r\n"
);
// Both cuts have their own parse sentence and share the range one, and
// equal cuts are refused rather than answering nothing.
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"zzz", b"0.9"]),
"-ERR T-Digest: error parsing low_cut_percentile\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"0.1", b"zzz"]),
"-ERR T-Digest: error parsing high_cut_percentile\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"0.1", b"1.1"]),
"-ERR T-Digest: low_cut_percentile and high_cut_percentile should be in [0,1]\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"s", b"0.5", b"0.5"]),
"-ERR T-Digest: low_cut_percentile should be lower than high_cut_percentile\r\n"
);
}
/// An empty digest answers every question, and answers most of them with
/// something that is not a number.
#[test]
fn an_empty_digest_has_an_answer_for_everything() {
let mut f = Fixture::new();
f.run(&[b"TDIGEST.CREATE", b"e"]);
assert_eq!(f.run(&[b"TDIGEST.MIN", b"e"]), "$3\r\nnan\r\n");
assert_eq!(f.run(&[b"TDIGEST.MAX", b"e"]), "$3\r\nnan\r\n");
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"e", b"0", b"1"]),
"*2\r\n$3\r\nnan\r\n$3\r\nnan\r\n"
);
assert_eq!(f.run(&[b"TDIGEST.CDF", b"e", b"0"]), "*1\r\n$3\r\nnan\r\n");
assert_eq!(
f.run(&[b"TDIGEST.TRIMMED_MEAN", b"e", b"0.1", b"0.9"]),
"$3\r\nnan\r\n"
);
// Minus two, which is a number no rank on a digest with samples in it
// can ever be.
assert_eq!(
f.run(&[b"TDIGEST.RANK", b"e", b"0", b"1"]),
"*2\r\n:-2\r\n:-2\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.REVRANK", b"e", b"0", b"1"]),
"*2\r\n:-2\r\n:-2\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.BYRANK", b"e", b"0", b"5"]),
"*2\r\n$3\r\nnan\r\n$3\r\nnan\r\n"
);
// A reset puts a digest with samples back into exactly this state.
f.run(&[b"TDIGEST.ADD", b"e", b"1", b"2", b"3"]);
assert_eq!(f.run(&[b"TDIGEST.RESET", b"e"]), "+OK\r\n");
assert_eq!(f.run(&[b"TDIGEST.MIN", b"e"]), "$3\r\nnan\r\n");
// Down to the compression count, so a reset digest and a fresh one of
// the same compression report the same nine numbers.
f.run(&[b"TDIGEST.CREATE", b"e2"]);
assert_eq!(
f.run(&[b"TDIGEST.INFO", b"e"]),
f.run(&[b"TDIGEST.INFO", b"e2"])
);
}
/// The double parser is Redis's and not this engine's, and the two disagree
/// at both ends of the range.
#[test]
fn a_sample_is_read_the_way_redis_reads_a_double() {
let mut f = Fixture::new();
f.run(&[b"TDIGEST.CREATE", b"a"]);
// Overflow and underflow are parse failures rather than an infinity and
// a zero, which is where this parts company with the rest of the engine.
for bad in [
&b"nan"[..],
b"1e400",
b"-1e400",
b"1e309",
b"1e-400",
b"",
b" 1",
b"1 ",
b"1e",
b"--1",
] {
assert_eq!(
f.run(&[b"TDIGEST.ADD", b"a", bad]),
"-ERR T-Digest: error parsing val parameter\r\n",
"{}",
String::from_utf8_lossy(bad)
);
}
// An infinity spelled out parses and is then refused for being one, with
// a different sentence.
for word in [&b"inf"[..], b"-inf", b"+INF", b"Infinity"] {
assert_eq!(
f.run(&[b"TDIGEST.ADD", b"a", word]),
"-ERR T-Digest: val parameter needs to be a finite number\r\n",
"{}",
String::from_utf8_lossy(word)
);
}
// These all parse: hex, a bare point either side, and the smallest
// subnormal the reference will take.
for good in [&b"0x10"[..], b".5", b"1.", b"1e-320", b"-0", b"0"] {
assert_eq!(
f.run(&[b"TDIGEST.ADD", b"a", good]),
"+OK\r\n",
"{}",
String::from_utf8_lossy(good)
);
}
// Nothing landed from the failures, so six samples is what there is.
assert!(
f.run(&[b"TDIGEST.INFO", b"a"])
.contains("Observations\r\n:6\r\n")
);
// Every value is parsed before any is added, so this whole command is a
// no op.
assert_eq!(
f.run(&[b"TDIGEST.ADD", b"a", b"1", b"zzz"]),
"-ERR T-Digest: error parsing val parameter\r\n"
);
assert!(
f.run(&[b"TDIGEST.INFO", b"a"])
.contains("Observations\r\n:6\r\n")
);
}
/// What a merge does to its destination, to its inputs and to the buffer
/// split `TDIGEST.INFO` reports.
#[test]
fn a_merge_sweeps_the_destination_between_its_inputs() {
let mut f = Fixture::new();
f.run(&[b"TDIGEST.CREATE", b"m1", b"COMPRESSION", b"100"]);
f.run(&[b"TDIGEST.ADD", b"m1", b"1", b"2", b"3"]);
f.run(&[b"TDIGEST.CREATE", b"m2", b"COMPRESSION", b"200"]);
f.run(&[b"TDIGEST.ADD", b"m2", b"4", b"5", b"6"]);
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"d", b"2", b"m1", b"m2"]),
"+OK\r\n"
);
// The destination did not exist, so the compression is the largest of
// the inputs. The three from the first input were swept in before the
// three from the second arrived, which is the one visible effect of the
// reference folding one input at a time.
let info = f.run(&[b"TDIGEST.INFO", b"d"]);
assert!(info.contains("Compression\r\n:200\r\n"), "{info}");
assert!(info.contains("Merged nodes\r\n:3\r\n"), "{info}");
assert!(info.contains("Unmerged nodes\r\n:3\r\n"), "{info}");
assert!(info.contains("Total compressions\r\n:1\r\n"), "{info}");
assert_eq!(f.run(&[b"TDIGEST.MIN", b"d"]), "$1\r\n1\r\n");
assert_eq!(f.run(&[b"TDIGEST.MAX", b"d"]), "$1\r\n6\r\n");
// Reading a source sweeps it too, so a merge writes to keys it only
// reads from.
assert!(
f.run(&[b"TDIGEST.INFO", b"m1"])
.contains("Merged nodes\r\n:3\r\n")
);
// Without OVERRIDE the destination joins its own inputs, so this takes
// it to nine observations and keeps its own compression.
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"m1"]);
let info = f.run(&[b"TDIGEST.INFO", b"d"]);
assert!(info.contains("Observations\r\n:9\r\n"), "{info}");
assert!(info.contains("Compression\r\n:200\r\n"), "{info}");
// With OVERRIDE the old destination is dropped and the compression goes
// back to the largest of the inputs.
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"m1", b"OVERRIDE"]);
let info = f.run(&[b"TDIGEST.INFO", b"d"]);
assert!(info.contains("Observations\r\n:3\r\n"), "{info}");
assert!(info.contains("Compression\r\n:100\r\n"), "{info}");
// And COMPRESSION beats both.
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"m1", b"COMPRESSION", b"500"]);
assert!(
f.run(&[b"TDIGEST.INFO", b"d"])
.contains("Compression\r\n:500\r\n")
);
// Naming the destination as a source folds it in twice.
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"d"]);
assert!(
f.run(&[b"TDIGEST.INFO", b"d"])
.contains("Observations\r\n:12\r\n")
);
// The arguments, in the order the reference checks them.
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"d", b"zzz", b"m1"]),
"-ERR T-Digest: error parsing numkeys\r\n"
);
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"d", b"0", b"m1"]),
"-ERR T-Digest: numkeys needs to be a positive integer\r\n"
);
assert!(
f.run(&[b"TDIGEST.MERGE", b"d", b"3", b"m1", b"m2"])
.contains("wrong number of arguments")
);
assert!(
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"m1", b"COMPRESSION"])
.contains("wrong number of arguments")
);
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"m1", b"NOPE"]),
"-ERR T-Digest: wrong keyword\r\n"
);
// A source that is not there stops the whole thing, and the destination
// is left as it was.
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"d", b"2", b"m1", b"gone"]),
"-ERR T-Digest: key does not exist\r\n"
);
assert!(
f.run(&[b"TDIGEST.INFO", b"d"])
.contains("Observations\r\n:12\r\n")
);
// A destination that is not there and is also named as a source is the
// same sentence rather than an empty merge.
assert_eq!(
f.run(&[b"TDIGEST.MERGE", b"gone", b"1", b"gone"]),
"-ERR T-Digest: key does not exist\r\n"
);
}
/// The RESP3 shapes, which are the two the protocols disagree about.
#[test]
fn a_digest_answers_doubles_and_a_map_on_resp3() {
let mut f = Fixture::new();
f.run(&[b"HELLO", b"3"]);
f.run(&[b"TDIGEST.CREATE", b"s"]);
f.run(&[b"TDIGEST.ADD", b"s", b"1", b"2", b"3", b"4"]);
assert_eq!(f.run(&[b"TDIGEST.MIN", b"s"]), ",1\r\n");
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"s", b"0", b"1"]),
"*2\r\n,1\r\n,4\r\n"
);
assert_eq!(f.run(&[b"TDIGEST.CDF", b"s", b"1"]), "*1\r\n,0.125\r\n");
// The two infinities and the NaN go out as the bare words.
assert_eq!(f.run(&[b"TDIGEST.BYRANK", b"s", b"4"]), "*1\r\n,inf\r\n");
assert_eq!(
f.run(&[b"TDIGEST.BYREVRANK", b"s", b"4"]),
"*1\r\n,-inf\r\n"
);
f.run(&[b"TDIGEST.CREATE", b"e"]);
assert_eq!(f.run(&[b"TDIGEST.MIN", b"e"]), ",nan\r\n");
// The ranks stay integers on both protocols.
assert_eq!(f.run(&[b"TDIGEST.RANK", b"s", b"1"]), "*1\r\n:0\r\n");
// Every question above swept the buffer in, so the four samples are all
// merged by now and the compression count says it happened once.
assert_eq!(
f.run(&[b"TDIGEST.INFO", b"s"]),
"%9\r\n+Compression\r\n:100\r\n+Capacity\r\n:610\r\n+Merged nodes\r\n:4\r\n\
+Unmerged nodes\r\n:0\r\n+Merged weight\r\n:4\r\n+Unmerged weight\r\n:0\r\n\
+Observations\r\n:4\r\n+Total compressions\r\n:1\r\n+Memory usage\r\n:9840\r\n"
);
}
/// A t digest key answers the module sentences the other sketch families
/// answer, and its own word for its type.
#[test]
fn a_t_digest_is_a_module_key_to_the_rest_of_the_keyspace() {
let mut f = Fixture::new();
f.run(&[b"SET", b"s", b"text"]);
for cmd in [
vec![&b"TDIGEST.CREATE"[..], b"s"],
vec![&b"TDIGEST.RESET"[..], b"s"],
vec![&b"TDIGEST.ADD"[..], b"s", b"1"],
vec![&b"TDIGEST.MIN"[..], b"s"],
vec![&b"TDIGEST.MAX"[..], b"s"],
vec![&b"TDIGEST.QUANTILE"[..], b"s", b"0.5"],
vec![&b"TDIGEST.CDF"[..], b"s", b"1"],
vec![&b"TDIGEST.TRIMMED_MEAN"[..], b"s", b"0.1", b"0.9"],
vec![&b"TDIGEST.RANK"[..], b"s", b"1"],
vec![&b"TDIGEST.REVRANK"[..], b"s", b"1"],
vec![&b"TDIGEST.BYRANK"[..], b"s", b"0"],
vec![&b"TDIGEST.BYREVRANK"[..], b"s", b"0"],
vec![&b"TDIGEST.INFO"[..], b"s"],
] {
let name = String::from_utf8_lossy(cmd[0]).into_owned();
let reply = f.run(&cmd);
assert!(reply.starts_with("-WRONGTYPE"), "{name}: {reply}");
}
// The merge checks its destination the same way, and its sources too.
f.run(&[b"TDIGEST.CREATE", b"t"]);
assert!(
f.run(&[b"TDIGEST.MERGE", b"s", b"1", b"t"])
.starts_with("-WRONGTYPE")
);
assert!(
f.run(&[b"TDIGEST.MERGE", b"d", b"1", b"s"])
.starts_with("-WRONGTYPE")
);
assert_eq!(
f.run(&[b"COPY", b"t", b"t2"]),
"-ERR not supported for this module key\r\n"
);
assert_eq!(
f.run(&[b"DUMP", b"t"]),
"-ERR DUMP is not supported for this module key\r\n"
);
assert_eq!(f.run(&[b"EXPIRE", b"t", b"100"]), ":1\r\n");
assert_eq!(f.run(&[b"PERSIST", b"t"]), ":1\r\n");
assert_eq!(f.run(&[b"RENAME", b"t", b"t3"]), "+OK\r\n");
assert_eq!(f.run(&[b"TYPE", b"t3"]), "+TDIS-TYPE\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"t3"]), "$3\r\nraw\r\n");
assert_eq!(f.run(&[b"DEL", b"t3"]), ":1\r\n");
// An empty digest is still a key, so the twelve that are not the
// constructor all say the same thing once it is gone.
assert_eq!(
f.run(&[b"TDIGEST.INFO", b"t3"]),
"-ERR T-Digest: key does not exist\r\n"
);
// The key is looked at before the arguments, so a bad argument at a key
// that is not there still says the key is not there.
assert_eq!(
f.run(&[b"TDIGEST.QUANTILE", b"t3", b"zzz"]),
"-ERR T-Digest: key does not exist\r\n"
);
}
/// The three shapes an `XADD` id can take, and the one rule behind all of
/// them.
#[test]
fn xadd_ids_only_ever_go_up() {
let mut f = Fixture::new();
// A bare millisecond is that millisecond and sequence zero.
assert_eq!(f.run(&[b"XADD", b"s", b"5", b"a", b"1"]), "$3\r\n5-0\r\n");
// And `5-*` is the next free sequence inside it.
assert_eq!(f.run(&[b"XADD", b"s", b"5-*", b"a", b"2"]), "$3\r\n5-1\r\n");
assert_eq!(f.run(&[b"XADD", b"s", b"5-*", b"a", b"3"]), "$3\r\n5-2\r\n");
assert_eq!(f.run(&[b"XADD", b"s", b"6-9", b"a", b"4"]), "$3\r\n6-9\r\n");
assert_eq!(f.run(&[b"XLEN", b"s"]), ":4\r\n");
assert!(
f.run(&[b"XADD", b"s", b"6-9", b"a", b"5"])
.contains("equal or smaller")
);
assert!(
f.run(&[b"XADD", b"s", b"0-0", b"a", b"5"])
.contains("must be greater than 0-0")
);
assert!(
f.run(&[b"XADD", b"s", b"nonsense", b"a", b"5"])
.contains("Invalid stream ID")
);
// The pairs have to be pairs, and Redis calls an odd one an arity error
// rather than a syntax error even though the table has already passed.
assert!(
f.run(&[b"XADD", b"s", b"*", b"a"])
.contains("wrong number of arguments")
);
// `NOMKSTREAM` on a key that is not there is a null and not a zero, so a
// producer can tell nobody is consuming this yet from the write landed.
assert_eq!(
f.run(&[b"XADD", b"gone", b"NOMKSTREAM", b"*", b"a", b"1"]),
"$-1\r\n"
);
assert_eq!(f.run(&[b"EXISTS", b"gone"]), ":0\r\n");
assert_eq!(f.run(&[b"TYPE", b"s"]), "+stream\r\n");
assert_eq!(f.run(&[b"OBJECT", b"ENCODING", b"s"]), "$6\r\nstream\r\n");
}
/// The trim options, which are three keywords that disagree about how many
/// arguments they take.
#[test]
fn trimming_reads_its_options_the_way_redis_does() {
let mut f = Fixture::new();
for i in 1..=10u32 {
f.run(&[b"XADD", b"s", format!("{i}-1").as_bytes(), b"a", b"1"]);
}
assert_eq!(f.run(&[b"XTRIM", b"s", b"MAXLEN", b"4"]), ":6\r\n");
assert_eq!(f.run(&[b"XLEN", b"s"]), ":4\r\n");
assert_eq!(f.run(&[b"XTRIM", b"s", b"MINID", b"9"]), ":2\r\n");
assert_eq!(f.run(&[b"XLEN", b"s"]), ":2\r\n");
// One argument after the keyword and the `~` is read as the threshold,
// which is what a real server does and is the reason this is a number
// complaint and not a syntax one.
assert!(
f.run(&[b"XTRIM", b"s", b"MAXLEN", b"~"])
.contains("not an integer")
);
assert!(
f.run(&[b"XTRIM", b"s", b"MAXLEN", b"-1"])
.contains("MAXLEN argument must be >= 0")
);
// The strategy check runs before the approximation check, so a LIMIT
// with neither is told about the missing strategy.
assert!(
f.run(&[b"XTRIM", b"s", b"LIMIT", b"5"])
.contains("without specifying a trimming strategy")
);
assert!(
f.run(&[b"XTRIM", b"s", b"MAXLEN", b"5", b"LIMIT", b"5"])
.contains("without the special ~ option")
);
assert!(
f.run(&[b"XTRIM", b"s", b"MAXLEN", b"5", b"MINID", b"5"])
.contains("at the same time are not compatible")
);
// NOMKSTREAM is XADD's and XTRIM does not take it.
assert!(
f.run(&[b"XTRIM", b"s", b"NOMKSTREAM", b"MAXLEN", b"5"])
.contains("syntax error")
);
assert_eq!(f.run(&[b"XTRIM", b"missing", b"MAXLEN", b"5"]), ":0\r\n");
}
/// `XRANGE`, whose two kinds of nothing are the thing worth pinning.
#[test]
fn xrange_looks_the_key_up_before_it_reads_the_count() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"5-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"6-1", b"b", b"2"]);
assert_eq!(
f.run(&[b"XRANGE", b"s", b"-", b"+"]),
"*2\r\n*2\r\n$3\r\n5-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n\
*2\r\n$3\r\n6-1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
assert_eq!(
f.run(&[b"XREVRANGE", b"s", b"+", b"-", b"COUNT", b"1"]),
"*1\r\n*2\r\n$3\r\n6-1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
// The exclusive bound is stepped after the missing sequence is filled
// in, so `(6` is `6-` and the largest sequence there is, minus one, and
// `6-1` is still in the range.
assert_eq!(
f.run(&[b"XRANGE", b"s", b"-", b"(6"]),
"*2\r\n*2\r\n$3\r\n5-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n\
*2\r\n$3\r\n6-1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
assert_eq!(
f.run(&[b"XRANGE", b"s", b"(5-1", b"+"]),
"*1\r\n*2\r\n$3\r\n6-1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
assert!(
f.run(&[b"XRANGE", b"s", b"(-", b"+"])
.contains("Invalid stream ID")
);
// The two kinds of nothing. A key that is not there is an empty array
// and a key that is there with a count of zero is a null array, because
// the lookup happens first.
assert_eq!(
f.run(&[b"XRANGE", b"missing", b"-", b"+", b"COUNT", b"0"]),
"*0\r\n"
);
assert_eq!(
f.run(&[b"XRANGE", b"s", b"-", b"+", b"COUNT", b"0"]),
"*-1\r\n"
);
f.run(&[b"SET", b"str", b"v"]);
assert!(
f.run(&[b"XRANGE", b"str", b"-", b"+", b"COUNT", b"0"])
.starts_with("-WRONGTYPE")
);
// The count is read in a loop, so the last one wins.
assert_eq!(
f.run(&[b"XRANGE", b"s", b"-", b"+", b"COUNT", b"2", b"COUNT", b"1"]),
"*1\r\n*2\r\n$3\r\n5-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
}
/// `XDEL` and `XACK` check every id before they touch any of them.
#[test]
fn a_bad_id_late_in_the_list_stops_the_whole_command() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
assert!(
f.run(&[b"XDEL", b"s", b"1-1", b"nonsense"])
.contains("Invalid stream ID")
);
assert_eq!(f.run(&[b"XLEN", b"s"]), ":2\r\n");
assert_eq!(f.run(&[b"XDEL", b"s", b"1-1", b"9-9"]), ":1\r\n");
assert_eq!(f.run(&[b"XLEN", b"s"]), ":1\r\n");
assert_eq!(f.run(&[b"XDEL", b"missing", b"1-1"]), ":0\r\n");
assert_eq!(f.run(&[b"XACK", b"missing", b"g", b"1-1"]), ":0\r\n");
}
/// `XGROUP`, and the two different complaints it makes about arguments.
#[test]
fn xgroup_has_an_arity_per_subcommand() {
let mut f = Fixture::new();
assert!(
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"$"])
.contains("requires the key")
);
assert_eq!(
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"$", b"MKSTREAM"]),
"+OK\r\n"
);
// A second CREATE is BUSYGROUP and not an ordinary error, because a
// client racing another one to make a group branches on the prefix.
assert!(
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"$"])
.starts_with("-BUSYGROUP")
);
assert_eq!(
f.run(&[b"XGROUP", b"CREATECONSUMER", b"s", b"g", b"c"]),
":1\r\n"
);
assert_eq!(
f.run(&[b"XGROUP", b"CREATECONSUMER", b"s", b"g", b"c"]),
":0\r\n"
);
assert_eq!(
f.run(&[b"XGROUP", b"DELCONSUMER", b"s", b"g", b"c"]),
":0\r\n"
);
// Below the subcommand's own arity is an arity error naming the pair.
let short = f.run(&[b"XGROUP", b"DESTROY", b"s"]);
assert!(
short.contains("wrong number of arguments for 'xgroup|destroy' command"),
"{short}"
);
// At or above it in a shape the handler will not take is the other one.
let odd = f.run(&[b"XGROUP", b"SETID", b"s", b"g", b"0", b"ENTRIESREAD"]);
assert!(
odd.contains("unknown subcommand or wrong number of arguments for 'SETID'"),
"{odd}"
);
assert!(
f.run(&[b"XGROUP", b"NOSUCH", b"s"])
.contains("Try XGROUP HELP")
);
assert_eq!(f.run(&[b"XGROUP", b"SETID", b"s", b"g", b"0"]), "+OK\r\n");
assert!(
f.run(&[b"XGROUP", b"SETID", b"s", b"nogroup", b"0"])
.starts_with("-NOGROUP")
);
assert_eq!(f.run(&[b"XGROUP", b"DESTROY", b"s", b"g"]), ":1\r\n");
assert_eq!(f.run(&[b"XGROUP", b"DESTROY", b"s", b"g"]), ":0\r\n");
assert!(
f.run(&[b"XGROUP", b"DESTROY", b"missing", b"g"])
.contains("requires the key")
);
}
/// A group read, an acknowledgement, and what is left in between.
#[test]
fn xreadgroup_hands_out_and_xack_takes_back() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
let first = f.run(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c1",
b"COUNT",
b"1",
b"STREAMS",
b"s",
b">",
]);
assert_eq!(
first,
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// A history read names its stream even with nothing to show, which is
// the difference between it and a `>` read that found nothing.
assert_eq!(
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c2", b"STREAMS", b"s", b"0"]),
"*1\r\n*2\r\n$1\r\ns\r\n*0\r\n"
);
assert_eq!(
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b"0"]),
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g"]),
"*4\r\n:1\r\n$3\r\n1-1\r\n$3\r\n1-1\r\n*1\r\n*2\r\n$2\r\nc1\r\n$1\r\n1\r\n"
);
assert_eq!(f.run(&[b"XACK", b"s", b"g", b"1-1"]), ":1\r\n");
assert_eq!(f.run(&[b"XACK", b"s", b"g", b"1-1"]), ":0\r\n");
// Empty is four nulls and not a zero with three empty things.
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g"]),
"*4\r\n:0\r\n$-1\r\n$-1\r\n*-1\r\n"
);
// A history read of an entry that has since been deleted is the id with
// a null beside it, so the consumer can still acknowledge it.
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b">"]);
f.run(&[b"XDEL", b"s", b"2-1"]);
assert_eq!(
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b"0"]),
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n2-1\r\n$-1\r\n"
);
// The group lookup runs before the id parse, so a `+` at a stream with
// no such group is told about the group and not about the id.
assert!(
f.run(&[
b"XREADGROUP",
b"GROUP",
b"nope",
b"c",
b"STREAMS",
b"s",
b"+"
])
.starts_with("-NOGROUP")
);
assert!(
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c", b"STREAMS", b"s", b"$"])
.contains("meaningless in the context of XREADGROUP")
);
assert!(
f.run(&[b"XREAD", b"GROUP", b"g", b"c", b"STREAMS", b"s", b"0"])
.contains("only supported by XREADGROUP")
);
assert!(
f.run(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c",
b"STREAMS",
b"s",
b"a",
b"b"
])
.contains("Unbalanced 'xreadgroup' list of streams")
);
}
/// `XREAD` without `BLOCK`, which answers now and takes nothing for an
/// answer.
#[test]
fn xread_with_no_block_writes_the_null_itself() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
assert_eq!(
f.run(&[b"XREAD", b"STREAMS", b"s", b"0"]),
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// Nothing new is a null array and not an empty one, and a stream with
// nothing new is left out rather than sent with an empty list.
assert_eq!(f.run(&[b"XREAD", b"STREAMS", b"s", b"1-1"]), "*-1\r\n");
assert_eq!(f.run(&[b"XREAD", b"STREAMS", b"missing", b"0"]), "*-1\r\n");
f.run(&[b"XADD", b"other", b"1-1", b"b", b"2"]);
assert_eq!(
f.run(&[b"XREAD", b"STREAMS", b"s", b"other", b"1-1", b"0"]),
"*1\r\n*2\r\n$5\r\nother\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\nb\r\n$1\r\n2\r\n"
);
// `$` is the last id, so nothing that is already there comes back.
assert_eq!(f.run(&[b"XREAD", b"STREAMS", b"s", b"$"]), "*-1\r\n");
// And `+` is the last entry, whatever COUNT says.
assert_eq!(
f.run(&[b"XREAD", b"COUNT", b"5", b"STREAMS", b"s", b"+"]),
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// A count of zero means unlimited here, which is the opposite of what it
// means to XRANGE.
assert_eq!(
f.run(&[b"XREAD", b"COUNT", b"0", b"STREAMS", b"s", b"0"]),
"*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// Milliseconds as a whole number, where BLPOP takes seconds as a float.
assert!(
f.run(&[b"XREAD", b"BLOCK", b"0.5", b"STREAMS", b"s", b"$"])
.contains("not an integer")
);
assert!(
f.run(&[b"XREAD", b"BLOCK", b"-1", b"STREAMS", b"s", b"$"])
.contains("timeout is negative")
);
assert!(
f.run(&[b"XREAD", b"STREAMS", b"s", b"other", b"0"])
.contains("Unbalanced 'xread' list of streams")
);
}
/// A blocked reader, and the two ways it stops being blocked.
#[test]
fn a_blocked_xread_wakes_on_the_next_entry() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
let (flow, reply) = f.flow(&[b"XREAD", b"BLOCK", b"0", b"STREAMS", b"s", b"$"]);
assert_eq!(flow, Flow::Block);
assert!(reply.is_empty());
// Everybody parked on the stream gets the entry, because a read takes
// nothing away. That is the difference between this and BLPOP.
let (flow, _) = f.flow(&[b"XREAD", b"BLOCK", b"0", b"STREAMS", b"s", b"$"]);
assert_eq!(flow, Flow::Block);
assert_eq!(f.server.waiters().len(), 2);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
let want = "*1\r\n*2\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n2-1\r\n*2\r\n$1\r\na\r\n$1\r\n2\r\n";
for at in 0..2 {
let mut out = Out::new(Proto::Resp2);
assert!(f.server.serve_waiter(at, 0, &mut out));
assert_eq!(core::str::from_utf8(out.as_slice()).expect("ascii"), want);
}
// And a deadline that runs out is a null array, the same as a plain
// XREAD that found nothing.
f.server.waiters_mut().forget(7);
let (flow, _) = f.flow(&[b"XREAD", b"BLOCK", b"50", b"STREAMS", b"s", b"$"]);
assert_eq!(flow, Flow::Block);
let mut out = Out::new(Proto::Resp2);
assert!(!f.server.serve_waiter(0, 0, &mut out));
assert!(out.as_slice().is_empty());
assert!(f.server.serve_waiter(0, u64::MAX, &mut out));
assert_eq!(
core::str::from_utf8(out.as_slice()).expect("ascii"),
"*-1\r\n"
);
}
/// A blocked group reader whose group is destroyed under it.
#[test]
fn losing_a_group_while_blocked_is_the_ordinary_sentence() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"$"]);
let (flow, _) = f.flow(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c",
b"BLOCK",
b"0",
b"STREAMS",
b"s",
b">",
]);
assert_eq!(flow, Flow::Block);
f.run(&[b"XGROUP", b"DESTROY", b"s", b"g"]);
let mut out = Out::new(Proto::Resp2);
assert!(f.server.serve_waiter(0, 0, &mut out));
// The ordinary sentence and not a special one about having been parked,
// which is what a running 8.10 sends.
assert_eq!(
core::str::from_utf8(out.as_slice()).expect("ascii"),
"-NOGROUP No such key 's' or consumer group 'g' in XREADGROUP with GROUP option\r\n"
);
}
/// `XCLAIM`, whose argument shape is the odd one in the group.
#[test]
fn xclaim_reads_ids_until_one_will_not_parse() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b">"]);
// Everything after the first argument that is not an id is an option, so
// a `-` is an unrecognised option and not a bad id.
assert!(
f.run(&[b"XCLAIM", b"s", b"g", b"c2", b"0", b"-"])
.contains("Unrecognized XCLAIM option '-'")
);
assert_eq!(
f.run(&[b"XCLAIM", b"s", b"g", b"c2", b"0", b"1-1", b"JUSTID"]),
"*1\r\n$3\r\n1-1\r\n"
);
// An id that is pending but whose entry has gone is an empty answer, and
// it leaves the pending list on the way past.
f.run(&[b"XDEL", b"s", b"2-1"]);
assert_eq!(
f.run(&[b"XCLAIM", b"s", b"g", b"c2", b"0", b"2-1"]),
"*0\r\n"
);
assert!(
f.run(&[b"XPENDING", b"s", b"g"])
.starts_with("*4\r\n:1\r\n")
);
assert!(
f.run(&[b"XCLAIM", b"s", b"nope", b"c", b"0", b"1-1"])
.starts_with("-NOGROUP")
);
assert!(
f.run(&[b"XCLAIM", b"s", b"g", b"c", b"nan", b"1-1"])
.contains("Invalid min-idle-time argument for XCLAIM")
);
}
/// `XAUTOCLAIM`, and the third value nobody expects.
#[test]
fn xautoclaim_reports_what_it_dropped() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b">"]);
f.run(&[b"XDEL", b"s", b"1-1"]);
// The cursor, what was claimed, and what was dropped for no longer being
// in the stream. The third one is what makes a sweep converge.
assert_eq!(
f.run(&[b"XAUTOCLAIM", b"s", b"g", b"c2", b"0", b"-", b"JUSTID"]),
"*3\r\n$3\r\n0-0\r\n*1\r\n$3\r\n2-1\r\n*1\r\n$3\r\n1-1\r\n"
);
assert!(
f.run(&[b"XAUTOCLAIM", b"s", b"g", b"c2", b"0", b"-", b"COUNT", b"0"])
.contains("COUNT must be > 0")
);
assert!(
f.run(&[b"XAUTOCLAIM", b"s", b"nope", b"c", b"0", b"-"])
.starts_with("-NOGROUP")
);
}
/// `XDELEX`, which is `XDEL` with a say in what the groups keep.
#[test]
fn xdelex_answers_one_integer_an_id() {
let mut f = Fixture::new();
for i in 1..=4 {
f.run(&[b"XADD", b"s", format!("{i}-1").as_bytes(), b"a", b"1"]);
}
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c",
b"COUNT",
b"2",
b"STREAMS",
b"s",
b">",
]);
// One means gone and minus one means it was not there to start with.
assert_eq!(
f.run(&[b"XDELEX", b"s", b"IDS", b"2", b"1-1", b"9-9"]),
"*2\r\n:1\r\n:-1\r\n"
);
// `KEEPREF` leaves the pending entry behind, so the group still counts
// the one it was handed even though the entry has gone.
assert!(
f.run(&[b"XPENDING", b"s", b"g"])
.starts_with("*4\r\n:2\r\n")
);
// `DELREF` takes it out of every pending list on the way past.
assert_eq!(
f.run(&[b"XDELEX", b"s", b"DELREF", b"IDS", b"1", b"2-1"]),
"*1\r\n:1\r\n"
);
// `1-1` is still in the list, because the delete before it said KEEPREF.
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g"]),
"*4\r\n:1\r\n$3\r\n1-1\r\n$3\r\n1-1\r\n*1\r\n*2\r\n$1\r\nc\r\n$1\r\n1\r\n"
);
// Two means somebody still wants it, and the question is wider than the
// name: the group's bookmark is at `2-1`, so `4-1` is above it and is
// refused even though no consumer has ever been handed it.
assert_eq!(
f.run(&[b"XDELEX", b"s", b"ACKED", b"IDS", b"2", b"3-1", b"4-1"]),
"*2\r\n:2\r\n:2\r\n"
);
// A key that is not there answers minus ones without reading the IDs.
assert_eq!(
f.run(&[b"XDELEX", b"nope", b"IDS", b"2", b"bad", b"worse"]),
"*2\r\n:-1\r\n:-1\r\n"
);
// A key that is there validates every ID before deleting any of them.
assert!(
f.run(&[b"XDELEX", b"s", b"IDS", b"2", b"3-1", b"bad"])
.starts_with("-ERR Invalid stream ID")
);
assert_eq!(f.run(&[b"XLEN", b"s"]), ":2\r\n");
assert!(
f.run(&[b"XDELEX", b"s", b"IDS", b"0", b"1-1"])
.contains("Number of IDs must be a positive integer")
);
assert!(
f.run(&[b"XDELEX", b"s", b"IDS", b"2", b"1-1"])
.contains("The `numids` parameter must match the number of arguments")
);
// The condition is one word, so a second one is a syntax error, and so
// is one ID more than the count promised.
assert!(
f.run(&[b"XDELEX", b"s", b"KEEPREF", b"DELREF", b"IDS", b"1", b"1-1"])
.starts_with("-ERR syntax error")
);
assert!(
f.run(&[b"XDELEX", b"s", b"IDS", b"1", b"1-1", b"2-1"])
.starts_with("-ERR syntax error")
);
// The key is looked up first, so the wrong type beats the syntax.
f.run(&[b"SET", b"str", b"v"]);
assert!(
f.run(&[b"XDELEX", b"str", b"BOGUS", b"IDS", b"0", b"1-1"])
.starts_with("-WRONGTYPE")
);
}
/// `XACKDEL`, whose reply is about the pending list and not about the log.
#[test]
fn xackdel_reports_what_the_group_was_holding() {
let mut f = Fixture::new();
for i in 1..=3 {
f.run(&[b"XADD", b"s", format!("{i}-1").as_bytes(), b"a", b"1"]);
}
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c",
b"COUNT",
b"1",
b"STREAMS",
b"s",
b">",
]);
// Minus one is not about the stream: `2-1` is sitting there unread and
// still answers minus one, because the group was not holding it. It also
// stays, since only an ID that was acknowledged is deleted.
assert_eq!(
f.run(&[b"XACKDEL", b"s", b"g", b"IDS", b"2", b"1-1", b"2-1"]),
"*2\r\n:1\r\n:-1\r\n"
);
assert_eq!(f.run(&[b"XLEN", b"s"]), ":2\r\n");
// A missing group is minus one an ID and not a NOGROUP.
assert_eq!(
f.run(&[b"XACKDEL", b"s", b"nope", b"IDS", b"1", b"2-1"]),
"*1\r\n:-1\r\n"
);
assert_eq!(
f.run(&[b"XACKDEL", b"nope", b"g", b"IDS", b"1", b"2-1"]),
"*1\r\n:-1\r\n"
);
// The acknowledgement happens whatever the condition says, so an ACKED
// that answers two has still emptied the pending list.
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c", b"STREAMS", b"s", b">"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g2", b"0"]);
assert_eq!(
f.run(&[b"XACKDEL", b"s", b"g", b"ACKED", b"IDS", b"1", b"2-1"]),
"*1\r\n:2\r\n"
);
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g"]),
"*4\r\n:1\r\n$3\r\n3-1\r\n$3\r\n3-1\r\n*1\r\n*2\r\n$1\r\nc\r\n$1\r\n1\r\n"
);
assert_eq!(f.run(&[b"XLEN", b"s"]), ":2\r\n");
}
/// `XNACK`, which hands an entry back to nobody.
#[test]
fn xnack_releases_an_entry_for_the_next_claim() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b">"]);
// Twice, so the delivery count is two and the words have something to
// do with it.
f.run(&[b"XCLAIM", b"s", b"g", b"c1", b"0", b"1-1", b"2-1"]);
assert_eq!(
f.run(&[b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"1", b"1-1"]),
":1\r\n"
);
// No owner, no idle time, and the count left where it was. A released
// entry reads as idle for longer than any min-idle-time, which is what
// puts it at the front of the next claim.
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"]),
"*2\r\n*4\r\n$3\r\n1-1\r\n$0\r\n\r\n:-1\r\n:2\r\n*4\r\n$3\r\n2-1\r\n$2\r\nc1\r\n:0\r\n:2\r\n"
);
// The consumer no longer holds it, so a filtered XPENDING skips it.
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10", b"c1"]),
"*1\r\n*4\r\n$3\r\n2-1\r\n$2\r\nc1\r\n:0\r\n:2\r\n"
);
// The bookmark did not move, so a `>` read will not hand it out again.
assert_eq!(
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c2", b"STREAMS", b"s", b">"]),
"*-1\r\n"
);
// A claim at any min-idle-time takes it.
assert_eq!(
f.run(&[
b"XAUTOCLAIM",
b"s",
b"g",
b"c2",
b"99999999",
b"-",
b"JUSTID"
]),
"*3\r\n$3\r\n0-0\r\n*1\r\n$3\r\n1-1\r\n*0\r\n"
);
// `SILENT` takes one off the count rather than putting it back to zero,
// which only shows on an entry that has been handed out more than once.
// It was delivered and then claimed, so it is on two and goes to one.
f.run(&[b"XNACK", b"s", b"g", b"SILENT", b"IDS", b"1", b"1-1"]);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"])
.contains(":-1\r\n:1\r\n")
);
// And it stops at zero rather than wrapping.
f.run(&[b"XNACK", b"s", b"g", b"SILENT", b"IDS", b"1", b"1-1"]);
f.run(&[b"XNACK", b"s", b"g", b"SILENT", b"IDS", b"1", b"1-1"]);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"])
.contains(":-1\r\n:0\r\n")
);
// `FATAL` puts it at the ceiling, and `RETRYCOUNT` wins over the word.
f.run(&[b"XNACK", b"s", b"g", b"FATAL", b"IDS", b"1", b"1-1"]);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"])
.contains(":9223372036854775807\r\n")
);
f.run(&[
b"XNACK",
b"s",
b"g",
b"FATAL",
b"IDS",
b"1",
b"1-1",
b"RETRYCOUNT",
b"3",
]);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"])
.contains(":-1\r\n:3\r\n")
);
// Releasing something the group is not holding is zero, and `FORCE`
// makes the pending entry rather than answering zero. A forced entry
// starts at zero, since there was no earlier count to keep.
f.run(&[b"XACK", b"s", b"g", b"2-1"]);
assert_eq!(
f.run(&[b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"1", b"2-1"]),
":0\r\n"
);
assert_eq!(
f.run(&[
b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"1", b"2-1", b"FORCE"
]),
":1\r\n"
);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"])
.contains(":-1\r\n:0\r\n")
);
// `FORCE` on an ID the stream does not have is still zero.
assert_eq!(
f.run(&[
b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"1", b"9-9", b"FORCE"
]),
":0\r\n"
);
// The group is looked up before the mode word, and it raises rather
// than answering per ID the way the two delete commands do.
assert_eq!(
f.run(&[b"XNACK", b"s", b"nope", b"BOGUS", b"IDS", b"1", b"1-1"]),
"-NOGROUP No such key 's' or consumer group 'nope'\r\n"
);
assert!(
f.run(&[b"XNACK", b"s", b"g", b"BOGUS", b"IDS", b"1", b"1-1"])
.starts_with("-ERR")
);
// Its own sentences, which are not the ones XDELEX uses.
assert!(
f.run(&[b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"0", b"1-1"])
.contains("numids must be a positive integer")
);
assert!(
f.run(&[b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"2", b"1-1"])
.contains("number of IDs doesn't match numids")
);
// Everything past the counted IDs is an option, so one too many is an
// option nobody recognises and not a count that does not add up.
assert!(
f.run(&[b"XNACK", b"s", b"g", b"FAIL", b"IDS", b"1", b"1-1", b"2-1"])
.contains("Unrecognized XNACK option '2-1'")
);
}
/// `XINFO`, which is where the shape of the storage shows through.
#[test]
fn xinfo_reports_the_stream_the_groups_and_the_consumers() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XADD", b"s", b"2-1", b"a", b"2"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[
b"XREADGROUP",
b"GROUP",
b"g",
b"c1",
b"COUNT",
b"1",
b"STREAMS",
b"s",
b">",
]);
let info = f.run(&[b"XINFO", b"STREAM", b"s"]);
// Ten pairs, since the six idempotency fields have nothing behind them
// here and a zero would claim they had. That is D-27.
assert!(info.starts_with("*20\r\n"), "{info}");
assert!(info.contains("$6\r\nlength\r\n:2\r\n"), "{info}");
assert!(
info.contains("$17\r\nlast-generated-id\r\n$3\r\n2-1\r\n"),
"{info}"
);
assert!(info.contains("$13\r\nentries-added\r\n:2\r\n"), "{info}");
assert!(info.contains("$6\r\ngroups\r\n:1\r\n"), "{info}");
let groups = f.run(&[b"XINFO", b"GROUPS", b"s"]);
assert!(groups.starts_with("*1\r\n*12\r\n"), "{groups}");
assert!(groups.contains("$9\r\nconsumers\r\n:1\r\n"), "{groups}");
assert!(groups.contains("$7\r\npending\r\n:1\r\n"), "{groups}");
assert!(groups.contains("$3\r\nlag\r\n:1\r\n"), "{groups}");
// A consumer that has never been given anything reports minus one for
// inactive rather than the moment it turned up, which is what tells a
// worker that is stuck from one that has nothing to do.
f.run(&[b"XGROUP", b"CREATECONSUMER", b"s", b"g", b"c2"]);
let consumers = f.run(&[b"XINFO", b"CONSUMERS", b"s", b"g"]);
assert!(consumers.starts_with("*2\r\n"), "{consumers}");
assert!(
consumers.contains("$8\r\ninactive\r\n:-1\r\n"),
"{consumers}"
);
// And in name order, which the storage does not hold them in.
let c1 = consumers.find("c1").unwrap();
let c2 = consumers.find("c2").unwrap();
assert!(c1 < c2, "{consumers}");
let full = f.run(&[b"XINFO", b"STREAM", b"s", b"FULL"]);
assert!(full.starts_with("*18\r\n"), "{full}");
assert!(full.contains("$12\r\nnacked-count\r\n:0\r\n"), "{full}");
assert!(full.contains("$11\r\nactive-time\r\n"), "{full}");
assert!(
f.run(&[b"XINFO", b"STREAM", b"missing"])
.contains("no such key")
);
assert!(
f.run(&[b"XINFO", b"GROUPS", b"missing"])
.contains("no such key")
);
assert!(
f.run(&[b"XINFO", b"CONSUMERS", b"s", b"nope"])
.starts_with("-NOGROUP")
);
assert!(
f.run(&[b"XINFO", b"NOSUCH", b"s"])
.contains("Try XINFO HELP")
);
assert!(f.run(&[b"XINFO", b"HELP"]).contains("XINFO <subcommand>"));
assert!(f.run(&[b"XGROUP", b"HELP"]).contains("XGROUP <subcommand>"));
}
/// `XPENDING`'s long form, which reads its arguments by counting them.
#[test]
fn xpending_takes_the_consumer_only_when_the_count_comes_out_right() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
f.run(&[b"XGROUP", b"CREATE", b"s", b"g", b"0"]);
f.run(&[b"XREADGROUP", b"GROUP", b"g", b"c1", b"STREAMS", b"s", b">"]);
let list = f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10"]);
assert_eq!(list, "*1\r\n*4\r\n$3\r\n1-1\r\n$2\r\nc1\r\n:0\r\n:1\r\n");
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10", b"c1"]),
"*1\r\n*4\r\n$3\r\n1-1\r\n$2\r\nc1\r\n:0\r\n:1\r\n"
);
// A consumer nobody has heard of holds nothing rather than erroring.
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"10", b"nope"]),
"*0\r\n"
);
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"IDLE", b"0", b"-", b"+", b"10"]),
list
);
// IDLE is only read at position three.
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"IDLE", b"0"])
.contains("syntax error")
);
assert!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+"])
.contains("syntax error")
);
assert_eq!(
f.run(&[b"XPENDING", b"s", b"g", b"-", b"+", b"-1"]),
"*0\r\n"
);
assert!(
f.run(&[b"XPENDING", b"missing", b"g"])
.starts_with("-NOGROUP")
);
}
/// `XSETID`, which is three counters and two refusals.
#[test]
fn xsetid_will_not_go_below_what_is_there() {
let mut f = Fixture::new();
f.run(&[b"XADD", b"s", b"5-5", b"a", b"1"]);
assert_eq!(f.run(&[b"XSETID", b"s", b"9-9"]), "+OK\r\n");
assert_eq!(
f.run(&[
b"XSETID",
b"s",
b"10-1",
b"ENTRIESADDED",
b"7",
b"MAXDELETEDID",
b"9-1"
]),
"+OK\r\n"
);
let info = f.run(&[b"XINFO", b"STREAM", b"s"]);
assert!(info.contains("$13\r\nentries-added\r\n:7\r\n"), "{info}");
assert!(
info.contains("$20\r\nmax-deleted-entry-id\r\n$3\r\n9-1\r\n"),
"{info}"
);
assert!(
f.run(&[b"XSETID", b"s", b"1-1"])
.contains("smaller than the target stream top item")
);
assert!(
f.run(&[b"XSETID", b"s", b"10-1", b"ENTRIESADDED", b"-1"])
.contains("entries_added must be positive")
);
assert!(
f.run(&[b"XSETID", b"missing", b"1-1"])
.contains("no such key")
);
}
/// RESP3, where the two reads answer a map and the entries stay an array.
#[test]
fn xread_answers_a_map_on_resp3_and_the_fields_stay_flat() {
let mut f = Fixture::new();
f.run(&[b"HELLO", b"3"]);
f.run(&[b"XADD", b"s", b"1-1", b"a", b"1"]);
// A map header and then the key and the entries side by side, with no
// two element array wrapping the pair.
assert_eq!(
f.run(&[b"XREAD", b"STREAMS", b"s", b"0"]),
"%1\r\n$1\r\ns\r\n*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
// The fields are still one flat array and not a map, which is Redis's
// shape and is what every consumer written before RESP3 expects.
assert_eq!(
f.run(&[b"XRANGE", b"s", b"-", b"+"]),
"*1\r\n*2\r\n$3\r\n1-1\r\n*2\r\n$1\r\na\r\n$1\r\n1\r\n"
);
assert_eq!(f.run(&[b"XREAD", b"STREAMS", b"s", b"1-1"]), "_\r\n");
}
/// A store to migrate values into, so a test can watch the inversion.
///
/// A vector rather than a file for the same reason the tier's own tests use
/// one: the file work has not attached a real store yet, and what this is
/// checking is the policy above the store rather than the store.
struct Mem {
blobs: Vec<Vec<u8>>,
}
impl yo_kv::cold::Blocks for Mem {
fn put(&mut self, bytes: &[u8]) -> yo_common::Result<yo_common::Addr> {
self.blobs.push(bytes.to_vec());
Ok(yo_common::Addr::new(
yo_common::Space::Log,
(self.blobs.len() - 1) as u64,
))
}
fn get(&self, at: yo_common::Addr) -> yo_common::Result<&[u8]> {
self.blobs
.get(at.offset() as usize)
.map(Vec::as_slice)
.ok_or_else(|| {
yo_common::Error::new(yo_common::Code::Corrupt, "no chunk at that address")
})
}
fn bytes(&self) -> u64 {
self.blobs.iter().map(|b| b.len() as u64).sum()
}
}
/// A server holding several segments of strings, with somewhere to put them.
///
/// Answers the fixture and what it was holding when it stopped filling.
fn filled(attach: bool) -> (Fixture, usize) {
let mut f = Fixture::new();
if attach {
f.server.db(0).attach(Box::new(Mem { blobs: Vec::new() }));
}
let val = vec![b'v'; 256];
for i in 0..24000u32 {
let k = format!("key:{i:08}");
f.run(&[b"SET", k.as_bytes(), &val]);
}
let full = f.server.memory_bytes();
assert!(full > 3 * 1024 * 1024, "the arena is several segments");
(f, full)
}
/// Write until the server is under `limit` or the writes run out.
///
/// The same shape the eviction test uses. A memory limit is enforced in
/// front of a command, so nothing happens until something is written, and
/// the budget means one command does not do the whole job.
fn press(f: &mut Fixture, limit: usize) {
let val = vec![b'v'; 256];
for i in 0..3000u32 {
let k = format!("new:{i:08}");
assert_eq!(
f.run(&[b"SET", k.as_bytes(), &val]),
"+OK\r\n",
"write {i} was refused"
);
f.server.refresh_memory();
if f.server.memory_bytes() <= limit {
return;
}
}
panic!(
"it never got under: {} against {limit}",
f.server.memory_bytes()
);
}
#[test]
fn the_storage_limit_reads_back_and_minus_one_is_no_limit() {
let mut f = Fixture::new();
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxstore"]),
"*2\r\n$8\r\nmaxstore\r\n$2\r\n-1\r\n",
"no limit is the default"
);
// The same memory value parser `maxmemory` uses, and the same trap in
// it, plus the one spelling that means no limit at all.
for (typed, bytes) in [
(&b"0"[..], "0"),
(b"1024", "1024"),
(b"1k", "1000"),
(b"1gb", "1073741824"),
(b"-1", "-1"),
] {
assert_eq!(f.run(&[b"CONFIG", b"SET", b"maxstore", typed]), "+OK\r\n");
assert_eq!(
f.run(&[b"CONFIG", b"GET", b"maxstore"]),
format!("*2\r\n$8\r\nmaxstore\r\n${}\r\n{bytes}\r\n", bytes.len()),
"set {}",
String::from_utf8_lossy(typed)
);
}
for bad in [&b"1tb"[..], b"-2", b"", b"lots"] {
assert_eq!(
f.run(&[b"CONFIG", b"SET", b"maxstore", bad]),
"-ERR CONFIG SET failed (possibly related to argument 'maxstore') - argument must be a memory value or -1\r\n",
"refused {}",
String::from_utf8_lossy(bad)
);
}
// Nothing is attached, so the answer to a memory limit is still Redis's.
let info = f.run(&[b"INFO", b"memory"]);
assert!(info.contains("maxstore:-1"), "{info}");
assert!(info.contains("yo_memory_regime:evict"), "{info}");
assert!(info.contains("yo_store_bytes:0"), "{info}");
}
#[test]
fn a_memory_limit_moves_values_to_the_file_instead_of_dropping_keys() {
// The inversion. The same pressure that makes a Redis server throw keys
// away makes this one move values to the file, and afterwards every key
// is still there and still answers with what was stored in it.
let (mut f, full) = filled(true);
let keys = f.run(&[b"DBSIZE"]);
assert!(
f.run(&[b"INFO", b"memory"])
.contains("yo_memory_regime:migrate"),
"a database with somewhere to put values migrates"
);
let limit = full - 2 * 1024 * 1024;
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lru"]);
f.run(&[
b"CONFIG",
b"SET",
b"maxmemory",
limit.to_string().as_bytes(),
]);
press(&mut f, limit);
assert!(
f.run(&[b"INFO", b"stats"]).contains("evicted_keys:0"),
"nothing was thrown away"
);
let after: usize = f.run(&[b"DBSIZE"])[1..]
.trim_end()
.parse()
.expect("a count");
let before: usize = keys[1..].trim_end().parse().expect("a count");
assert!(after > before, "the keys that came in are all still here");
assert!(
f.server.store_bytes() > 0,
"and what came out of memory went to the file"
);
// And the values read back, which is the part that makes it a migration
// rather than a loss.
let val = format!("$256\r\n{}\r\n", "v".repeat(256));
assert_eq!(f.run(&[b"GET", b"key:00000000"]), val);
assert_eq!(f.run(&[b"GET", b"key:00023999"]), val);
}
#[test]
fn a_storage_limit_of_zero_restores_redis_behaviour_exactly() {
// The documented setting for a drop in cache. A file that may hold
// nothing cannot be migrated to, so eviction is all that is left, and
// the server behaves exactly as it did before any of this existed.
let (mut f, full) = filled(true);
f.run(&[b"CONFIG", b"SET", b"maxstore", b"0"]);
assert!(
f.run(&[b"INFO", b"memory"])
.contains("yo_memory_regime:evict"),
"nothing may go to the file"
);
let limit = full - 2 * 1024 * 1024;
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lru"]);
f.run(&[
b"CONFIG",
b"SET",
b"maxmemory",
limit.to_string().as_bytes(),
]);
press(&mut f, limit);
assert!(
!f.run(&[b"INFO", b"stats"]).contains("evicted_keys:0"),
"keys were thrown away, which is what was asked for"
);
assert_eq!(f.server.store_bytes(), 0, "and the file was never written");
}
#[test]
fn a_full_file_goes_back_to_evicting() {
// A storage limit reached is a storage limit, and eviction is the right
// answer to one. The budget here is a few kilobytes, so the first round
// of migration fills it and everything after that is evicted.
let (mut f, full) = filled(true);
f.run(&[b"CONFIG", b"SET", b"maxstore", b"64kb"]);
let limit = full - 2 * 1024 * 1024;
f.run(&[b"CONFIG", b"SET", b"maxmemory-policy", b"allkeys-lru"]);
f.run(&[
b"CONFIG",
b"SET",
b"maxmemory",
limit.to_string().as_bytes(),
]);
press(&mut f, limit);
assert!(f.server.store_bytes() >= 64 * 1024, "the file filled up");
assert!(
!f.run(&[b"INFO", b"stats"]).contains("evicted_keys:0"),
"and then it started evicting"
);
assert!(
f.run(&[b"INFO", b"memory"])
.contains("yo_memory_regime:evict"),
"and it says so"
);
}
}