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
use crate::commands;
use crate::pubsub::PubSubHub;
use crate::resp;
use crate::store;
use crate::vector;
use crate::watch::WatchNotifier;
use commands::ctx::Ctx;
use parking_lot::RwLock;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, split};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
/// Hooks shared by plain TCP and TLS streams before `split`.
pub trait PrepareIoStream {
fn prepare_io(&mut self) -> std::io::Result<()>;
/// The socket underneath, where whether the client has gone can be asked
/// of the kernel (see `socket_says_gone`). Linux only; `None` elsewhere.
fn socket_fd(&self) -> Option<i32> {
None
}
/// The address the client connected to: `laddr` in `CLIENT LIST`.
fn local_address(&self) -> Option<std::net::SocketAddr> {
None
}
}
impl PrepareIoStream for TcpStream {
fn prepare_io(&mut self) -> std::io::Result<()> {
self.set_nodelay(true)
}
fn local_address(&self) -> Option<std::net::SocketAddr> {
self.local_addr().ok()
}
#[cfg(target_os = "linux")]
fn socket_fd(&self) -> Option<i32> {
Some(std::os::fd::AsRawFd::as_raw_fd(self))
}
}
#[cfg(feature = "tls")]
impl PrepareIoStream for tokio_rustls::server::TlsStream<TcpStream> {
fn prepare_io(&mut self) -> std::io::Result<()> {
self.get_mut().0.set_nodelay(true)
}
fn local_address(&self) -> Option<std::net::SocketAddr> {
self.get_ref().0.local_addr().ok()
}
#[cfg(target_os = "linux")]
fn socket_fd(&self) -> Option<i32> {
Some(std::os::fd::AsRawFd::as_raw_fd(self.get_ref().0))
}
}
/// Whether the kernel says the client at the other end of `fd` has gone:
/// closed its connection or its sending side, or reset it. Asked of `poll`,
/// for `POLLRDHUP`, which reports the end whatever is unread before it, and
/// which does not wait for the runtime's reactor to have taken the event in
/// (see `server_uring::peer_has_gone`).
#[cfg(target_os = "linux")]
fn socket_says_gone(fd: Option<i32>) -> bool {
let Some(fd) = fd else {
return false;
};
let mut look = libc::pollfd {
fd,
events: libc::POLLRDHUP,
revents: 0,
};
// SAFETY: one `pollfd` that outlives the call, on a descriptor the
// connection holds open; a timeout of 0 returns at once.
let ready = unsafe { libc::poll(&mut look, 1, 0) };
ready > 0
&& look.revents & (libc::POLLRDHUP | libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0
}
#[cfg(not(target_os = "linux"))]
fn socket_says_gone(_fd: Option<i32>) -> bool {
false
}
/// Whether what a waiting connection has read and not yet run has grown
/// past `client-query-buffer-limit` (1 GB unless set): the client is then
/// closed, as Redis closes one whose query buffer reaches the limit.
/// Otherwise a client that kept sending while it waited — in a blocking
/// command, a pause, `WAIT` — would be read into memory without end.
fn carried_too_much(carried: &[u8]) -> bool {
// Only past a megabyte, the least the limit can be set to, is the
// setting looked up.
if carried.len() <= 1 << 20 {
return false;
}
let limit = crate::commands::server::remembered_config("client-query-buffer-limit")
.and_then(|limit| limit.parse::<usize>().ok())
.unwrap_or(1 << 30);
if carried.len() <= limit {
return false;
}
log_warn!(
"Closing a client that sent {} bytes while it waited, past client-query-buffer-limit ({limit})",
carried.len()
);
true
}
#[inline(always)]
fn ascii_eq_ignore_case(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y))
}
/// Same first-byte filter as server_uring — avoids String allocation
/// on the fast path for GET/SET/DEL/INCR and all other normal commands.
#[inline(always)]
fn needs_slow_path(cmd0: &[u8]) -> bool {
let first = cmd0.first().copied().unwrap_or(0) | 0x20;
if !matches!(
first,
b's' | b'p' | b'm' | b'd' | b'w' | b'u' | b'e' | b'a' | b'h' | b'r'
) {
return false;
}
ascii_eq_ignore_case(cmd0, b"SUBSCRIBE")
|| ascii_eq_ignore_case(cmd0, b"PSUBSCRIBE")
|| ascii_eq_ignore_case(cmd0, b"SSUBSCRIBE")
// The UNSUBSCRIBE family only ever reached the RESP2 subscriber loop
// before, so it never needed the slow path. RESP3 clients now handle
// these inline in the main loop, which lives on the slow path. Each
// check is a length comparison first, so hot commands sharing the same
// first byte (SET, GET, ...) bail out immediately.
|| ascii_eq_ignore_case(cmd0, b"UNSUBSCRIBE")
|| ascii_eq_ignore_case(cmd0, b"PUNSUBSCRIBE")
|| ascii_eq_ignore_case(cmd0, b"SUNSUBSCRIBE")
|| ascii_eq_ignore_case(cmd0, b"PSYNC")
|| ascii_eq_ignore_case(cmd0, b"SYNC")
|| ascii_eq_ignore_case(cmd0, b"MULTI")
|| ascii_eq_ignore_case(cmd0, b"DISCARD")
|| ascii_eq_ignore_case(cmd0, b"WATCH")
|| ascii_eq_ignore_case(cmd0, b"UNWATCH")
|| ascii_eq_ignore_case(cmd0, b"EXEC")
|| ascii_eq_ignore_case(cmd0, b"AUTH")
|| ascii_eq_ignore_case(cmd0, b"RESET")
|| ascii_eq_ignore_case(cmd0, b"HELLO")
|| ascii_eq_ignore_case(cmd0, b"WAITAOF")
|| ascii_eq_ignore_case(cmd0, b"WAIT")
|| ascii_eq_ignore_case(cmd0, b"MONITOR")
}
/// Await a parked blocking command.
///
/// When a handler parks, the connection loop awaits the delivery and then
/// re-dispatches the *same* command — it simply does not advance `parse_offset`,
/// so the next turn of the parse loop re-reads the same bytes out of `buffer`.
/// That is what lets a single `Ctx` construction site serve both the initial
/// dispatch and the resume, with no extra allocation on the non-blocking path.
///
/// `Ok(())` means the delivery is stored and the caller should re-dispatch the
/// same command; `Err(reply)` means reply with this instead and move on.
#[allow(clippy::too_many_arguments)]
async fn park_blocking<S, R>(
mut wait: crate::commands::blocking::BlockingWait,
slot: &mut crate::commands::blocking::BlockingSlot,
writer: &Arc<Mutex<tokio::io::WriteHalf<S>>>,
combined: &mut Vec<u8>,
subscriptions: Option<&crate::pubsub::Subscriptions>,
waiter: &mut Waiter<'_, R>,
) -> Result<(), Vec<u8>>
where
S: AsyncWrite + Unpin + Send,
R: tokio::io::AsyncRead + Unpin,
{
// No wait: a write that got past a `CLIENT PAUSE` before it was set
// (`blocking::hold_for_pause`). Read again, and held by the pause check.
if wait.held_by_pause() {
slot.held_by_pause();
return Ok(());
}
if slot.in_resume() && !wait.may_repark() {
// A resumed handler parked again — it forgot its resume check. Reply
// as if the wait timed out rather than looping forever.
slot.clear_resume();
return Err(crate::resp::write::resp_null_array());
}
// Flush replies to anything pipelined ahead of this command before we go to
// sleep. Without this a client sending `SET a 1` and `BLPOP k 0` in one
// packet would not see the `+OK` until the BLPOP finally returned.
if write_tcp_batch(writer, combined).await.is_err() {
// Socket is gone. Don't park on a dead connection — return nothing and
// let the batch write at the end of the loop tear it down.
return Err(Vec::new());
}
if let Some(subs) = subscriptions {
subs.flushed();
}
let refused_on_replica = wait.refused_on_replica();
let park_epoch = wait.role_epoch();
let block_state = wait.take_state();
#[cfg(debug_assertions)]
if let Some(delay) = crate::commands::blocking::test_park_delay() {
tokio::time::sleep(delay).await;
}
let (unblock_tx, mut unblock_rx) = tokio::sync::oneshot::channel();
waiter
.client_registry
.set_blocked(waiter.client_id, Some(unblock_tx), wait.has_timeout());
let delivery = if crate::commands::blocking::ended_by_role_change(
park_epoch,
refused_on_replica,
waiter.repl_state,
) {
// This node became a replica before the client was listed as
// blocked, so the sweep that ends blocked clients passed it by.
waiter.interrupted.role_changed = true;
None
} else {
let waiting = wait.wait();
tokio::pin!(waiting);
let mut temp = [0u8; 4096];
let mut unblockable = true;
loop {
tokio::select! {
delivery = &mut waiting => {
// Woken: what it waited for may be there, for it to take
// on the dispatch that resumes it. A client that has
// gone in the meantime must not take it — and its end,
// ready at the same moment, may not have been the arm
// picked — so the socket is looked at now.
if gone_by_now(
waiter.reader,
waiter.carried,
waiter.activity,
waiter.socket_fd,
) {
waiter.interrupted.gone = true;
break None;
}
break delivery;
}
// The client's side of the connection, while it waits: more
// commands, which wait their turn — or the end of it. A
// client that has gone must not be left in line for an
// element nobody will receive.
read = waiter.reader.read(&mut temp) => match read {
Ok(n) if n > 0 => {
crate::stats::TOTAL_NET_INPUT_BYTES.fetch_add(n as u64, Ordering::Relaxed);
crate::stats::record_read();
waiter.carried.extend_from_slice(&temp[..n]);
// The client sent something while it was parked, so it
// is not idle: restart its idle clock.
waiter.activity.touch();
if carried_too_much(waiter.carried) {
waiter.interrupted.gone = true;
break None;
}
}
_ => {
waiter.interrupted.gone = true;
break None;
}
},
_ = &mut *waiter.kill_rx => {
waiter.interrupted.gone = true;
break None;
}
how = &mut unblock_rx, if unblockable => match how {
Ok(how) => {
waiter.interrupted.unblocked_with_error =
how == crate::commands::blocking::Unblock::Error;
waiter.interrupted.role_changed =
how == crate::commands::blocking::Unblock::RoleChange;
break None;
}
Err(_) => unblockable = false,
},
}
}
};
waiter
.client_registry
.set_blocked(waiter.client_id, None, false);
// Woken, or unblocked otherwise, at the moment this node became a
// replica: ended as the sweep ends it.
if !waiter.interrupted.gone
&& crate::commands::blocking::ended_by_role_change(
park_epoch,
refused_on_replica,
waiter.repl_state,
)
{
waiter.interrupted.unblocked_with_error = false;
waiter.interrupted.role_changed = true;
}
// However it ended, the command is dispatched again: with what it was
// waiting for, or as if its time had run out — which is also how it
// leaves the line it was standing in — or, its client gone or the role
// changed, only to leave that line, taking nothing: a look made as if
// its time had run out could take an element, on a node that is a
// master again by then, and the reply that carried it is not sent.
if waiter.interrupted.gone || waiter.interrupted.role_changed {
slot.set_gone(block_state);
} else {
slot.set_pending(delivery, block_state);
}
Ok(())
}
/// Whether the client has gone, as far as its socket says now, without
/// waiting for anything: asked of the kernel where there is a socket to ask
/// (`socket_fd`), which knows before the runtime's reactor has taken the
/// event in; otherwise of the stream, by reading what the client has sent
/// into `carried`, as the wait reads it, up to its end if that has arrived.
fn gone_by_now<R: tokio::io::AsyncRead + Unpin>(
reader: &mut R,
carried: &mut Vec<u8>,
activity: &crate::client_registry::Activity,
socket_fd: Option<i32>,
) -> bool {
// The kernel's word, where it can be had, is enough: what the client has
// sent stays for the connection to read.
if socket_fd.is_some() {
return socket_says_gone(socket_fd);
}
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
let mut temp = [0u8; 4096];
loop {
let mut read = tokio::io::ReadBuf::new(&mut temp);
match std::pin::Pin::new(&mut *reader).poll_read(&mut cx, &mut read) {
std::task::Poll::Pending => return false,
std::task::Poll::Ready(Ok(())) if !read.filled().is_empty() => {
let n = read.filled().len();
crate::stats::TOTAL_NET_INPUT_BYTES.fetch_add(n as u64, Ordering::Relaxed);
crate::stats::record_read();
carried.extend_from_slice(read.filled());
activity.touch();
if carried_too_much(carried) {
return true;
}
}
std::task::Poll::Ready(_) => return true,
}
}
}
/// Resolves once the client has gone — closed its connection, or been
/// killed — and never while it is there. What it sends meanwhile is kept in
/// `carried`, to be run after what the connection is waiting on. For the
/// waits that are not a blocking command's (which watches the same way, in
/// `park_blocking`): `WAIT`, `WAITAOF`, a pause, which a client that has
/// gone must not be left in, nor have its command run after it.
///
/// Boxed, so that it is polled out of line, as `server_uring::unless_gone`
/// is: the connection's own future, which every command goes through, is
/// compiled as it was without it.
fn until_gone<'a, R: tokio::io::AsyncRead + Unpin + Send>(
reader: &'a mut R,
carried: &'a mut Vec<u8>,
kill_rx: &'a mut crate::client_registry::KillRx,
activity: &'a crate::client_registry::Activity,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
Box::pin(async move {
let mut temp = [0u8; 4096];
loop {
tokio::select! {
read = reader.read(&mut temp) => match read {
Ok(n) if n > 0 => {
crate::stats::TOTAL_NET_INPUT_BYTES.fetch_add(n as u64, Ordering::Relaxed);
crate::stats::record_read();
carried.extend_from_slice(&temp[..n]);
activity.touch();
if carried_too_much(carried) {
return;
}
}
_ => return,
},
_ = &mut *kill_rx => return,
}
}
})
}
/// What a connection lends its parked command: the means of noticing that
/// the wait should end early.
struct Waiter<'a, R> {
reader: &'a mut R,
/// What the client sent while the command waited, to be parsed after it.
carried: &'a mut Vec<u8>,
kill_rx: &'a mut crate::client_registry::KillRx,
client_registry: &'a crate::client_registry::ClientRegistry,
client_id: u64,
interrupted: &'a mut crate::commands::blocking::Interrupted,
/// The waiting connection's activity, so bytes that arrive while it waits
/// restart its idle clock just as the main loop's reads do.
activity: &'a crate::client_registry::Activity,
/// The socket underneath, if there is one to ask (see `socket_says_gone`).
socket_fd: Option<i32>,
/// Whether this node is a replica now: a wait a replica refuses ends
/// on a demotion (#591).
repl_state: &'a crate::replication::ReplState,
}
/// A connection's buffer that has grown past this is given back once it is
/// empty, rather than kept.
const BIG_BUFFER: usize = 256 * 1024;
/// Write one response batch straight to TCP (normal client hot path).
#[inline]
async fn write_tcp_batch<S>(
w: &Arc<Mutex<tokio::io::WriteHalf<S>>>,
combined: &mut Vec<u8>,
) -> Result<(), std::io::Error>
where
S: AsyncWrite + Unpin + Send,
{
if combined.is_empty() {
return Ok(());
}
crate::stats::TOTAL_NET_OUTPUT_BYTES.fetch_add(combined.len() as u64, Ordering::Relaxed);
crate::stats::record_write();
let mut g = w.lock().await;
g.write_all(combined).await?;
combined.clear();
// Nor is one that grew to hold one large reply.
if combined.capacity() > BIG_BUFFER {
*combined = Vec::with_capacity(8192);
}
Ok(())
}
/// Write a subscribed connection's messages as they arrive. Ends when the
/// connection's subscriptions do, which stops it.
fn spawn_pubsub_forwarder<S>(
writer: Arc<Mutex<tokio::io::WriteHalf<S>>>,
mut outbox: crate::pubsub::Outbox,
client_registry: crate::client_registry::ClientRegistry,
client_id: u64,
) -> tokio::task::JoinHandle<()>
where
S: AsyncWrite + Unpin + Send + 'static,
{
tokio::spawn(async move {
while let Some(batch) = outbox.next().await {
let mut g = writer.lock().await;
// With the writer held: see `Batch::encode`.
let frames = batch.encode(client_registry.get_resp(client_id));
if frames.is_empty() {
continue;
}
crate::stats::TOTAL_NET_OUTPUT_BYTES.fetch_add(frames.len() as u64, Ordering::Relaxed);
crate::stats::record_write();
if g.write_all(&frames).await.is_err() {
break;
}
}
})
}
/// A connection's subscriptions, made at its first SUBSCRIBE, with the task
/// that writes its messages.
fn open_subscriptions<S>(
pubsub: &crate::pubsub::PubSubHub,
client_registry: &crate::client_registry::ClientRegistry,
client_id: u64,
writer: &Arc<Mutex<tokio::io::WriteHalf<S>>>,
) -> crate::pubsub::Subscriptions
where
S: AsyncWrite + Unpin + Send + 'static,
{
let (mut subs, outbox) = crate::pubsub::connect(pubsub, Arc::clone(client_registry), client_id);
subs.forwarded_by(spawn_pubsub_forwarder(
Arc::clone(writer),
outbox,
Arc::clone(client_registry),
client_id,
));
subs
}
/// Replica / monitor: channel-fed writer multiplexes onto `writer`.
fn spawn_mux_to_socket<S>(
writer: Arc<Mutex<tokio::io::WriteHalf<S>>>,
mut resp_rx: mpsc::Receiver<Vec<u8>>,
) -> tokio::task::JoinHandle<()>
where
S: AsyncWrite + Unpin + Send + 'static,
{
// A frame this large (a full sync's payload, as large as the dataset) is
// written as it is. Copied into the buffer, it was the dataset twice
// over, and the buffer kept that size for as long as the replica stayed
// connected: memory counted against `maxmemory`, which evictions could
// not give back (#284).
const WRITTEN_AS_IS: usize = 1 << 20;
/// A buffer grown past this by a burst of small frames is let go of.
const BUFFER_KEPT: usize = 4 << 20;
async fn write_out<S: AsyncWrite + Unpin>(
writer: &Mutex<tokio::io::WriteHalf<S>>,
bytes: &[u8],
) -> bool {
crate::stats::TOTAL_NET_OUTPUT_BYTES.fetch_add(bytes.len() as u64, Ordering::Relaxed);
crate::stats::record_write();
writer.lock().await.write_all(bytes).await.is_ok()
}
tokio::spawn(async move {
let mut out_buf = Vec::with_capacity(65536);
'frames: while let Some(first) = resp_rx.recv().await {
let mut next = Some(first);
while let Some(r) = next.take() {
if r.len() >= WRITTEN_AS_IS {
// In order: what came before it goes first.
if !out_buf.is_empty() {
if !write_out(&writer, &out_buf).await {
break 'frames;
}
out_buf.clear();
}
if !write_out(&writer, &r).await {
break 'frames;
}
} else {
out_buf.extend_from_slice(&r);
}
next = resp_rx.try_recv().ok();
}
if !out_buf.is_empty() {
if !write_out(&writer, &out_buf).await {
break;
}
out_buf.clear();
}
if out_buf.capacity() > BUFFER_KEPT {
out_buf = Vec::with_capacity(65536);
}
}
})
}
#[inline(always)]
fn now_us() -> u64 {
// For measuring how long a command took, so: a clock that does not go
// backwards. This was the wall clock, and the difference of two readings
// of it — a panic in a debug build, and in a release build a command
// logged as having taken five hundred thousand years, whenever the
// system clock was set back between them.
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
START
.get_or_init(std::time::Instant::now)
.elapsed()
.as_micros() as u64
}
/// Eligibility check for MULTI/EXEC's lock-held fast-apply path (see the EXEC arm in
/// `handle_client`). Returns the queued `(key, value)` pairs only when every queued command
/// is an unconditional `SET key value` (exactly 3 args) — the shape a WATCH+CAS retry loop
/// produces — there's at least one WATCHed key (nothing to protect otherwise), and neither
/// MONITOR nor CLIENT TRACKING is active (the fast path skips those side effects entirely
/// rather than risk getting them subtly wrong, so it declines instead when they matter).
/// Anything else falls back to the existing per-command dispatch loop, unchanged.
fn exec_fast_apply_sets(
watched_keys_empty: bool,
queue: &[Vec<Vec<u8>>],
) -> Option<Vec<(String, Vec<u8>)>> {
if watched_keys_empty
|| crate::monitor::MONITOR_COUNT.load(Ordering::Relaxed) > 0
|| crate::tracking::TRACKING_CLIENT_COUNT.load(Ordering::Relaxed) > 0
{
return None;
}
queue
.iter()
.map(|cmd| {
if cmd.len() == 3 && cmd[0].eq_ignore_ascii_case(b"SET") {
std::str::from_utf8(&cmd[1])
.ok()
.map(|k| (k.to_string(), cmd[2].clone()))
} else {
None
}
})
.collect()
}
#[allow(clippy::too_many_arguments)]
pub async fn handle_client<S>(
mut stream: S,
store: store::Store,
lastsave: Arc<RwLock<i64>>,
aof_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
aof_enabled: bool,
config: Arc<crate::config::Config>,
started_at: Arc<Instant>,
index_store: vector::IndexStore,
dict_store: vector::DictStore,
wait_table: Arc<crate::wait_table::WaitTable>,
ts_index: store::SharedTsIndex,
pubsub: PubSubHub,
hub_tx: crate::replication::HubTx,
repl_state: Arc<crate::replication::ReplState>,
watch_registry: crate::watch::WatchRegistry,
client_registry: crate::client_registry::ClientRegistry,
peer_addr: String,
acl_store: crate::acl::AclStore,
acl_log: crate::acl::SharedAclLog,
slowlog: crate::slowlog::SharedSlowLog,
latency: crate::latency::SharedLatencyTracker,
compaction_tx: crate::vector::CompactionTx,
cluster_state: Arc<crate::cluster::ClusterState>,
monitor_registry: crate::monitor::SharedMonitorRegistry,
tracking_table: crate::tracking::TrackingTable,
) -> Result<(), Box<dyn std::error::Error>>
where
S: AsyncRead + AsyncWrite + Unpin + Send + PrepareIoStream + 'static,
{
stream.prepare_io()?;
if let Some(denied) = crate::protected_mode::refusal(&acl_store, &peer_addr) {
let _ = stream.write_all(denied).await;
return Ok(());
}
// ── Client registry bookkeeping ──────────────────────────────────────
let client_id = crate::client_registry::next_client_id();
let (mut client_info, mut kill_rx) =
crate::client_registry::ClientInfo::new(client_id, peer_addr.clone());
// The socket's own address, as Redis shows it (#566): not the bind
// setting, which can be 0.0.0.0.
client_info.laddr = stream.local_address().map_or_else(
|| format!("{}:{}", config.bind, config.port),
|a| a.to_string(),
);
let activity = Arc::clone(&client_info.activity);
let query_buffer = Arc::clone(&client_info.query_buffer);
// `CLIENT REPLY`.
let mut reply_gate = crate::client_registry::ReplyGate::default();
client_registry.register(client_info);
// However the connection ends — the client leaving, an error, a kill —
// what was kept for it goes: the keys it was tracking, and its entry in
// the registry (which is where a tracking client stops being counted).
struct ClientGuard {
id: u64,
registry: crate::client_registry::ClientRegistry,
tracking: crate::tracking::TrackingTable,
}
impl Drop for ClientGuard {
fn drop(&mut self) {
self.tracking.unregister_client(self.id);
self.registry.unregister(self.id);
}
}
let _guard = ClientGuard {
id: client_id,
registry: Arc::clone(&client_registry),
tracking: Arc::clone(&tracking_table),
};
let socket_fd = stream.socket_fd();
let (mut reader, writer) = split(stream);
let writer = Arc::new(Mutex::new(writer));
// Push notifications (CLIENT TRACKING invalidations, etc.) need a dedicated
// forwarder task so they are delivered immediately — not held until the next
// client command arrives.
let (push_tx, mut push_rx) =
mpsc::channel::<Vec<u8>>(crate::client_registry::PUSH_QUEUE_FRAMES);
client_registry.register_push_tx(client_id, push_tx.clone());
let writer_for_push = Arc::clone(&writer);
let push_forwarder = tokio::spawn(async move {
while let Some(msg) = push_rx.recv().await {
let mut g = writer_for_push.lock().await;
crate::stats::TOTAL_NET_OUTPUT_BYTES.fetch_add(msg.len() as u64, Ordering::Relaxed);
crate::stats::record_write();
if g.write_all(&msg).await.is_err() {
break;
}
}
});
// ── Connection state ─────────────────────────────────────────────────
let mut buffer = Vec::with_capacity(4 * 1024);
let mut private_query_buffer = false;
query_buffer.update(0, buffer.capacity(), private_query_buffer);
let mut last_query_buffer_activity = Instant::now();
let mut last_query_buffer_resize_check = Instant::now();
let query_buffer_idle_resize_after =
std::time::Duration::from_millis(config.query_buffer_idle_resize_after_ms);
let mut query_buffer_peak = 0usize;
let mut temp = [0u8; 4096];
let mut read_start = 0usize;
// How far the request still arriving has been read.
let mut progress = resp::parse::Progress::default();
let mut selected_db: usize = 0;
// This connection's subscriptions, while it has any. `None` otherwise, so
// that a connection that never uses pub/sub allocates nothing for it.
let mut subscriptions: Option<crate::pubsub::Subscriptions> = None;
// Tracks whether the current authenticated user has a key/command restriction.
// Drives RESTRICTED_KEY_CLIENTS/RESTRICTED_CMD_CLIENTS so handler.rs can
// fast-exit on the common path. Kept in sync via acl::track_restriction_counters.
// Declared before authenticated_user below because the implicit-default-user
// path also needs to seed these from the "default" user's actual ACL rules.
let mut key_restricted = false;
let mut cmd_restricted = false;
// The ACL as of when those flags were worked out; see `acl::ACL_EPOCH`.
// Read first, so a change racing with the lookup below is noticed.
let mut acl_epoch_seen = crate::acl::ACL_EPOCH.load(std::sync::atomic::Ordering::Relaxed);
// None = not authenticated, Some(name) = authenticated as this user
let mut authenticated_user: Option<String> = if crate::acl::default_user_is_open(&acl_store) {
// Connections start implicitly authenticated as "default" when that
// user needs no password — asked of the user table, where a password
// from `--requirepass`, from the ACL file or from `ACL SETUSER` all
// end up, and not of `--requirepass` alone -- but "default" is a real
// ACL user and can carry
// its own command/key restrictions (`ACL SETUSER default ... -flushall`).
// Route through the same counter bookkeeping AUTH uses, or a restricted
// default user's rules are silently never enforced for connections that
// never explicitly call AUTH.
if let Some(user) = acl_store.read().get("default") {
crate::acl::track_restriction_counters(user, &mut key_restricted, &mut cmd_restricted);
}
Some("default".to_string())
} else {
None
};
use crate::commands::transaction::TxState;
let mut tx = TxState::new();
// A command of the batch being answered may have queued an AOF
// record: its reply waits for it (see `aof::written`).
let mut aof_wait = false;
let dirty_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let mut combined = Vec::with_capacity(8192);
// Negotiated RESP protocol version, updated by HELLO. Kept as local connection
// state (not read from client_registry per command) so execute_command's
// per-command null-encoding check doesn't hit the shared client_registry lock
// on every single command across every worker thread.
let mut resp_version: u8 = 2;
enum ConnectionHandoff {
Replica {
legacy_sync: bool,
/// What the replica asked to continue from, if anything.
psync: Option<crate::replication::PsyncRequest>,
},
}
// `MONITOR` mode, while the connection is in it.
let mut monitoring: Option<crate::monitor::Monitoring> = None;
// What a script run for this connection is given: see where it is made.
#[cfg(feature = "lua")]
let mut lua_env: Option<crate::lua_vm_blocking::ClientExecEnv> = None;
// What arrived while a blocking command of this connection waited, and
// how such a wait was cut short. See `park_blocking`.
let mut carried: Vec<u8> = Vec::new();
let mut interrupted = crate::commands::blocking::Interrupted::default();
loop {
let was_private_at_read = private_query_buffer;
if carried.is_empty() {
// Redis reclaims private query buffers from its client cron, and the
// maintenance step below is the equivalent. It can only do anything
// when the buffer is private and has spare capacity to reclaim, so
// the timer arm is only built then; every other read — including
// every read of a client that is not sitting on a private buffer —
// races just the socket and `kill_rx`.
let should_maintain_query_buffer = private_query_buffer
&& buffer.capacity().saturating_sub(buffer.len())
> resp::parse::QUERY_BUFFER_MIN_SPARE_FOR_RESIZE;
let n = if should_maintain_query_buffer {
let resize_deadline =
if buffer.capacity() > resp::parse::QUERY_BUFFER_RESIZE_THRESHOLD {
tokio::time::Instant::from_std(
last_query_buffer_resize_check
+ resp::parse::QUERY_BUFFER_PEAK_SAMPLE_INTERVAL,
)
} else {
tokio::time::Instant::from_std(
last_query_buffer_activity
+ query_buffer_idle_resize_after
+ tokio::time::Duration::from_millis(10),
)
};
tokio::select! {
// Normal case: data arrived from the client
result = reader.read(&mut temp) => {
match result? {
0 => break,
n => n,
}
}
// CLIENT KILL was called — close this connection immediately
_ = &mut kill_rx => {
// Send a final error so the client knows it was killed,
// then break. Redis sends no response on kill — we match that.
break;
}
// Tokio's socket read is cancellation-safe, so this deadline
// can be checked without abandoning an in-flight operation.
_ = tokio::time::sleep_until(resize_deadline) => {
let resized = resp::parse::resize_private_query_buffer_after(
&mut buffer,
read_start,
&mut private_query_buffer,
last_query_buffer_activity.elapsed(),
query_buffer_idle_resize_after,
query_buffer_peak,
progress.minimum_capacity(),
);
if resized {
read_start = 0;
query_buffer.update(
buffer.len(),
buffer.capacity().saturating_sub(buffer.len()),
private_query_buffer,
);
}
query_buffer_peak = buffer
.len()
.saturating_sub(read_start)
.max(progress.minimum_capacity());
last_query_buffer_resize_check = Instant::now();
continue;
}
}
} else {
tokio::select! {
// Normal case: data arrived from the client
result = reader.read(&mut temp) => {
match result? {
0 => break,
n => n,
}
}
// CLIENT KILL was called — close this connection immediately
_ = &mut kill_rx => {
// Send a final error so the client knows it was killed,
// then break. Redis sends no response on kill — we match that.
break;
}
}
};
// Bytes arrived from the socket: the client is active, so its idle
// clock restarts. Once per read, not once per command — a pipeline
// that arrives together is one interaction. The timer arm above
// `continue`s, so it never reaches here.
activity.touch();
if was_private_at_read {
last_query_buffer_activity = Instant::now();
}
crate::stats::TOTAL_NET_INPUT_BYTES
.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
crate::stats::record_read();
activity.note_read(n);
buffer.extend_from_slice(&temp[..n]);
} else {
buffer.append(&mut carried);
}
query_buffer_peak = query_buffer_peak.max(buffer.len().saturating_sub(read_start));
query_buffer.update(
buffer.len().saturating_sub(read_start),
buffer.capacity().saturating_sub(buffer.len()),
private_query_buffer,
);
let mut parse_offset = read_start;
let commands_before = activity.commands_run();
let mut connection_handoff: Option<ConnectionHandoff> = None;
let mut quit_requested = false;
// Outside the parse loop: a park in one turn hands its delivery to the
// re-dispatch on the next turn.
let mut blocking_slot = crate::commands::blocking::BlockingSlot::default();
// The next turn dispatches the command of this one again: a parked
// command resumed, or a write a pause sent back to be held. It is
// the same command: not recorded, settled or begun again.
let mut redispatch = false;
// What the client sent that no request can begin with, if it did.
let mut protocol_error: Option<String> = None;
let query_buffer_bytes = buffer.len();
let query_buffer_free = buffer.capacity().saturating_sub(buffer.len());
let was_private_query_buffer = private_query_buffer;
while let Some((consumed, cmd)) =
match progress.next_request(&mut buffer, parse_offset, authenticated_user.is_some()) {
Ok(request) => request,
Err(e) => {
protocol_error = Some(e);
None
}
}
{
private_query_buffer |= progress.take_private_query_buffer();
if cmd.is_empty() {
parse_offset += consumed;
query_buffer.update(
query_buffer_bytes.saturating_sub(parse_offset),
query_buffer_free,
private_query_buffer,
);
continue;
}
query_buffer.update(
query_buffer_bytes.saturating_sub(parse_offset + consumed),
query_buffer_free,
private_query_buffer,
);
// ── QUIT ─────────────────────────────────────────────────────────
// Reply +OK and close the connection. Handled in the connection
// loop rather than the dispatch table because closing the socket
// is a connection-level concern `execute_command` can't express.
//
// QUIT appeared in both the pre-auth allowlist and
// `is_always_allowed_bytes` — the server treated it as special —
// but had no dispatch arm anywhere, so it fell through to the
// generic fallback, returned `-ERR unknown command`, and left the
// connection open. A client pipelining `AUTH … / <cmd> / QUIT` got
// a spurious trailing `-ERR` and then blocked until its own
// client-side timeout.
//
// Anything pipelined after QUIT is intentionally not executed —
// the connection is closing, which is what Redis does too.
//
// The `len() == 4` gate keeps this off the hot path: it rejects
// GET/SET/DEL in a single compare, before the byte-wise loop.
if cmd[0].len() == 4 && ascii_eq_ignore_case(cmd[0], b"QUIT") {
combined.extend_from_slice(b"+OK\r\n");
parse_offset += consumed;
quit_requested = true;
break;
}
// For `CLIENT LIST`'s `cmd=` and `db=`, and `tot-cmds`. Not again
// for a blocked command dispatched once more with what it waited
// for: it is one command.
if !redispatch && !blocking_slot.resuming() {
activity.record(&cmd, selected_db);
}
if !aof_wait && crate::aof::acks_wait() && crate::aof::may_log(&cmd) {
aof_wait = true;
}
// The command before this one is over: its reply is settled, and
// what it left to tell tracking clients follows it.
if std::mem::take(&mut redispatch) {
// A `CLIENT REPLY SKIP` before it is for the dispatch that
// replies, not used up by the one that did not.
reply_gate.again(&combined);
} else {
reply_gate.settle(&mut combined);
crate::tracking::after_command(
&tracking_table,
&client_registry,
client_id,
&activity,
&mut combined,
);
reply_gate.begin(&cmd, &mut combined);
}
// ── ACL changes reach connections that are already open ──────────────
// One relaxed load per command when nothing has changed.
if crate::acl::ACL_EPOCH.load(std::sync::atomic::Ordering::Relaxed) != acl_epoch_seen
&& !crate::acl::resync_connection(
&acl_store,
authenticated_user.as_deref(),
&mut acl_epoch_seen,
&mut key_restricted,
&mut cmd_restricted,
)
{
// The user this connection authenticated as has been deleted.
quit_requested = true;
break;
}
// ── CLIENT PAUSE enforcement (async-safe) ────────────────────────────
// Must be done here, not in execute_command, because std::thread::sleep
// inside a tokio task blocks the worker thread and prevents UNPAUSE
// from being processed on another connection.
//
// A client that goes while its command is held is let go, and the
// command is not run: as in Redis, which goes on reading a client
// a pause holds. A blocking pop run for it once the pause ended
// would take an element for nobody (#384). Except the dispatch
// that resumes a command that waited: that one runs, only to
// leave the line it stood in and pass the turn on, and one whose
// client has already gone is not held at all — it writes nothing.
//
// Boxed, and so polled out of line, as `until_gone` is.
let _ran = if crate::pause::PAUSE_UNTIL_MS.load(std::sync::atomic::Ordering::Relaxed)
!= 0
&& !(blocking_slot.resuming() && (interrupted.gone || interrupted.role_changed))
{
let gated: std::pin::Pin<
Box<
dyn std::future::Future<Output = Option<Option<crate::pause::Ran>>>
+ Send
+ '_,
>,
> = Box::pin(crate::pause::gate(&cmd, &tx.queue, client_id, || {
until_gone(&mut reader, &mut carried, &mut kill_rx, &activity)
}));
match gated.await {
// See the matching arm in `server_uring`: the gate may
// have kept a woken resume waiting, and its client gone.
Some(ran)
if blocking_slot.resuming()
&& gone_by_now(&mut reader, &mut carried, &activity, socket_fd) =>
{
blocking_slot.make_gone();
interrupted.gone = true;
ran
}
Some(ran) => ran,
None if blocking_slot.resuming() => {
blocking_slot.make_gone();
interrupted.gone = true;
None
}
None => {
quit_requested = true;
break;
}
}
} else {
None
};
// ══════════════════════════════════════════════════════════════
// FAST PATH — identical to v0.1.10: parse → execute → append.
// Zero heap allocations for command name, zero string compares.
// ══════════════════════════════════════════════════════════════
// Read for each command — one atomic load — and not once per
// connection: `CONFIG SET slowlog-log-slower-than` has to reach the
// connections that are already open, the one that issued it included.
let slowlog_enabled = slowlog.threshold_us() < u64::MAX;
// A RESP2 connection with subscriptions may run next to nothing:
// that is decided on the slow path.
let subscriber_only = resp_version == 2 && subscriptions.is_some();
if authenticated_user.is_some()
&& !tx.active
&& !subscriber_only
&& !needs_slow_path(cmd[0])
{
#[cfg(feature = "lua")]
if crate::commands::lua_command_runs_long_sync_vm(cmd.as_slice()) {
// Made once for the connection and kept: it is two dozen shared
// handles, each counted up to copy and down to drop, and a script
// needs none of them copied to run on this thread. Made again if
// the connection has become another user since.
let user_now = authenticated_user.as_deref().unwrap_or("default");
if lua_env
.as_ref()
.is_some_and(|env| env.authenticated_user != user_now)
{
lua_env = None;
}
let env = &*lua_env.get_or_insert_with(|| {
crate::lua_vm_blocking::ClientExecEnv::snapshot(
&store,
&lastsave,
crate::lua_vm_blocking::AofBridge::Tokio(aof_tx.clone()),
&config,
&started_at,
&index_store,
&dict_store,
&wait_table,
&ts_index,
&pubsub,
&hub_tx,
&repl_state,
&watch_registry,
&client_registry,
&acl_store,
&acl_log,
&slowlog,
&latency,
&compaction_tx,
&cluster_state,
&monitor_registry,
&tracking_table,
&peer_addr,
client_id,
authenticated_user.as_deref().unwrap_or("default"),
)
});
let (response, elapsed_us) = crate::lua_vm_blocking::run_lua_vm_blocking(
cmd.as_slice(),
&mut selected_db,
env,
crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed),
resp_version,
)
.await;
// A script that got past a `CLIENT PAUSE` before it was
// set, and did not run (`pause::HELD_IN_GATE`): read
// again, and held by the pause check.
if crate::pause::is_held(&response) {
redispatch = true;
continue;
}
if slowlog_enabled && elapsed_us >= slowlog.threshold_us() {
let client_name = client_registry
.get(client_id)
.map(|info| info.name.clone())
.unwrap_or_default();
slowlog.record(&cmd, elapsed_us, &peer_addr, client_name);
}
combined.extend_from_slice(&response);
parse_offset += consumed;
continue;
}
if !slowlog_enabled {
let mut response = commands::execute_command(Ctx {
cmd,
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
tracking_table: &tracking_table,
blocking: Some(blocking_slot.prime()),
});
if let Some(wait) = blocking_slot.take_parked() {
if std::mem::take(&mut aof_wait) {
crate::aof::written(&aof_tx).await;
}
match park_blocking(
wait,
&mut blocking_slot,
&writer,
&mut combined,
subscriptions.as_ref(),
&mut Waiter {
reader: &mut reader,
carried: &mut carried,
kill_rx: &mut kill_rx,
client_registry: &client_registry,
client_id,
interrupted: &mut interrupted,
activity: &activity,
socket_fd,
repl_state: &repl_state,
},
)
.await
{
// `parse_offset` deliberately not advanced: the same
// command is re-dispatched, now carrying the delivery.
Ok(()) => {
redispatch = true;
continue;
}
Err(reply) => response = reply,
}
}
if interrupted.unblocked_with_error {
interrupted.unblocked_with_error = false;
response = crate::commands::blocking::UNBLOCKED.to_vec();
}
if interrupted.gone {
// It has left the line; there is nobody to reply to.
quit_requested = true;
break;
}
if std::mem::take(&mut interrupted.role_changed) {
// This node became a replica: told so, and closed.
combined.extend_from_slice(crate::commands::blocking::ROLE_CHANGED);
quit_requested = true;
break;
}
combined.extend_from_slice(&response);
parse_offset += consumed;
continue;
}
let mut waited_from: Option<u64> = None;
let mut response = commands::execute_command(Ctx {
cmd,
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
tracking_table: &tracking_table,
blocking: Some(blocking_slot.prime()),
});
if let Some(wait) = blocking_slot.take_parked() {
waited_from = Some(now_us());
if std::mem::take(&mut aof_wait) {
crate::aof::written(&aof_tx).await;
}
match park_blocking(
wait,
&mut blocking_slot,
&writer,
&mut combined,
subscriptions.as_ref(),
&mut Waiter {
reader: &mut reader,
carried: &mut carried,
kill_rx: &mut kill_rx,
client_registry: &client_registry,
client_id,
interrupted: &mut interrupted,
activity: &activity,
socket_fd,
repl_state: &repl_state,
},
)
.await
{
// See the note at the non-slowlog site above.
Ok(()) => {
redispatch = true;
continue;
}
Err(reply) => response = reply,
}
}
if interrupted.unblocked_with_error {
interrupted.unblocked_with_error = false;
response = crate::commands::blocking::UNBLOCKED.to_vec();
}
if interrupted.gone {
// It has left the line; there is nobody to reply to.
quit_requested = true;
break;
}
if std::mem::take(&mut interrupted.role_changed) {
// This node became a replica: told so, and closed.
combined.extend_from_slice(crate::commands::blocking::ROLE_CHANGED);
quit_requested = true;
break;
}
// What the handler measured, and for a command that waited
// (`BLPOP`) the wait as well: the clock is not read again
// around every command for this.
let elapsed_us = crate::cmdstats::last_command_us()
+ waited_from.map_or(0, |from| now_us().saturating_sub(from));
if elapsed_us >= slowlog.threshold_us() {
let client_name = client_registry
.get(client_id)
.map(|info| info.name.clone())
.unwrap_or_default();
// The command is still where it was read: it is read
// again for the log, now that it has turned out slow,
// where every command used to be copied in case it did.
if let Ok(Some((_, slow_cmd))) =
resp::parse::next_request(&mut buffer, parse_offset)
{
slowlog.record(&slow_cmd, elapsed_us, &peer_addr, client_name);
}
}
combined.extend_from_slice(&response);
parse_offset += consumed;
continue;
}
// ══════════════════════════════════════════════════════════════
// SLOW PATH — auth, transactions, subscribe, psync
// ══════════════════════════════════════════════════════════════
let cmd_name = String::from_utf8_lossy(cmd[0]).to_ascii_uppercase();
// ── Auth gate ─────────────────────────────────────────────────
if authenticated_user.is_none()
&& !matches!(cmd_name.as_str(), "AUTH" | "QUIT" | "HELLO" | "RESET")
{
// As in Redis, nothing goes to the ACL log: no user was
// refused anything.
combined.extend_from_slice(b"-NOAUTH Authentication required.\r\n");
parse_offset += consumed;
continue;
}
// ── Permission check: the command, its keys, its channels ─────
if let Some(ref username) = authenticated_user {
let denied = acl_store
.read()
.get(username.as_str())
.and_then(|user| crate::acl::check_permission(user, &cmd_name, &cmd).err());
if let Some(denied) = denied {
// As in Redis, a command there is no such command as, or
// with the wrong number of arguments, is refused for that
// before the user's rules are looked at.
let refusal = if !commands::server::is_command(&cmd_name) {
commands::handler::unknown_command(&cmd)
} else if let Some(wrong) = commands::arity::check(&cmd_name, &cmd) {
wrong
} else if tx.active && commands::transaction::not_allowed_in_multi(&cmd_name) {
crate::resp::write::resp_error(commands::transaction::NOT_IN_MULTI)
} else {
let _context = tx.active.then(|| crate::acl::log_context("multi"));
acl_log.record(
denied.reason(),
denied.object(),
username,
&crate::acl::log_client_info(&client_registry, client_id, &peer_addr),
);
format!("-{}\r\n", denied.message(username)).into_bytes()
};
// Refused inside MULTI, it is not queued, and EXEC runs nothing, as
// for a command refused for any other reason (#159). A refused
// EXEC discards the transaction, as in Redis.
let reply = commands::transaction::reject(
&mut tx,
&cmd,
watch_registry.as_ref(),
&dirty_flag,
commands::transaction::Monitored {
registry: &monitor_registry,
db: selected_db,
peer_addr: &peer_addr,
},
refusal,
);
combined.extend_from_slice(&reply);
parse_offset += consumed;
continue;
}
}
// ── Subscriptions ─────────────────────────────────────────────
// A subscribed connection stays in this loop, with a task of its
// own writing its messages. Under RESP3 that is all there is to
// it; under RESP2 it may run nothing but the commands below while
// it has subscriptions. Inside MULTI they are queued like any other
// command, and EXEC runs them (#23).
if crate::pubsub::is_subscription_command(cmd_name.as_str()) && !tx.active {
if let Some(refusal) =
crate::pubsub::shard_subscribe_refusal(cmd_name.as_str(), &cmd, &cluster_state)
{
combined.extend_from_slice(&refusal);
parse_offset += consumed;
continue;
}
let subs = subscriptions.get_or_insert_with(|| {
open_subscriptions(&pubsub, &client_registry, client_id, &writer)
});
combined.extend_from_slice(&subs.handle(&cmd, resp_version));
if subs.total() == 0 {
subscriptions = None;
}
parse_offset += consumed;
continue;
}
if resp_version == 2
&& subscriptions.is_some()
&& let Some(reply) = crate::pubsub::resp2_subscriber_reply(cmd_name.as_str(), &cmd)
{
combined.extend_from_slice(&reply);
parse_offset += consumed;
continue;
}
// ── Connection handoffs (break parse loop so `buffer` can be drained/moved) ──
// A replica whose dataset may already be this master's is first
// offered the fingerprint (see `replication::digest`), and the
// connection stays a client until it asks again; so is one of a
// master that lost its dataset (`ReplState::psync_offer`).
// A replica does not take replicas of its own (#144).
// Inside MULTI they are refused, as in Redis (`queue_refusal`), and
// the transaction with them: they do not hand the connection over.
if (cmd_name == "PSYNC" || cmd_name == "SYNC") && !tx.active && repl_state.is_slave() {
combined.extend_from_slice(&crate::resp::write::resp_error(
crate::replication::NOT_A_MASTER,
));
parse_offset += consumed;
continue;
}
if cmd_name == "PSYNC"
&& !tx.active
&& let Some(offer) =
repl_state.psync_offer(&cluster_state, &client_registry, client_id, &cmd)
{
combined.extend_from_slice(&offer);
parse_offset += consumed;
continue;
}
if (cmd_name == "PSYNC" || cmd_name == "SYNC") && !tx.active {
parse_offset += consumed;
connection_handoff = Some(ConnectionHandoff::Replica {
legacy_sync: cmd_name == "SYNC",
psync: crate::replication::PsyncRequest::parse(&cmd),
});
break;
}
// Inside MULTI it is queued, as in Redis, and refused when EXEC
// runs it (#550).
if cmd_name == "MONITOR" && !tx.active {
if monitoring.is_none() {
monitoring = Some(crate::monitor::Monitoring::start(
&monitor_registry,
push_tx.clone(),
));
client_registry.update(client_id, |info| info.flags = "O".to_string());
}
combined.extend_from_slice(b"+OK\r\n");
parse_offset += consumed;
continue;
}
// A transaction's own commands with the wrong number of
// arguments are refused before they do anything, as in Redis;
// and, like any command refused inside MULTI, they take the
// transaction with them. An EXEC refused so ends it (#550).
if matches!(
cmd_name.as_str(),
"MULTI" | "EXEC" | "DISCARD" | "WATCH" | "UNWATCH" | "RESET"
) && let Some(wrong) = commands::arity::check(&cmd_name, &cmd)
{
let reply = commands::transaction::reject(
&mut tx,
&cmd,
watch_registry.as_ref(),
&dirty_flag,
commands::transaction::Monitored {
registry: &monitor_registry,
db: selected_db,
peer_addr: &peer_addr,
},
wrong,
);
combined.extend_from_slice(&reply);
parse_offset += consumed;
continue;
}
// `MULTI` or `EXEC`, as the client wrote it: for MONITOR, below.
let transaction_word: Option<Vec<u8>> =
matches!(cmd_name.as_str(), "MULTI" | "EXEC").then(|| cmd[0].to_vec());
// ── Transaction + Auth commands ───────────────────────────────
// Queued, inside MULTI: counted when EXEC runs them.
let queued_here = tx.active && matches!(cmd_name.as_str(), "UNWATCH" | "AUTH");
let response = match cmd_name.as_str() {
"MULTI" => {
if tx.active {
b"-ERR MULTI calls can not be nested\r\n".to_vec()
} else {
tx.active = true;
b"+OK\r\n".to_vec()
}
}
"DISCARD" => {
if !tx.active {
b"-ERR DISCARD without MULTI\r\n".to_vec()
} else {
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
b"+OK\r\n".to_vec()
}
}
"WATCH" => {
if tx.active {
b"-ERR WATCH inside MULTI is not allowed\r\n".to_vec()
} else if cmd.len() < 2 {
b"-ERR wrong number of arguments for 'watch' command\r\n".to_vec()
} else {
for key in &cmd[1..] {
// A key that has already expired is watched as
// the absent key it is: its removal, when it
// comes, is not a change.
commands::helpers::lazy_expire_key(&store, selected_db, key);
tx.watched_keys
.push((selected_db, crate::store::Key::new(key)));
watch_registry.as_ref().watch(
selected_db,
key,
Arc::clone(&dirty_flag),
);
}
b"+OK\r\n".to_vec()
}
}
// Inside MULTI it is queued, as in Redis: run there, it
// dropped the watches, and EXEC ran after a watched key
// had changed (#550).
"UNWATCH" if !tx.active => {
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.watched_keys.clear();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
b"+OK\r\n".to_vec()
}
// RESET: the connection as it was when it was opened. The
// transaction and the watches are dropped, subscriptions and
// tracking ended, the database is 0, the protocol RESP2, the
// name gone — and the user is `default` again, if `default`
// needs no password, or nobody.
"RESET" => {
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
selected_db = 0;
resp_version = 2;
subscriptions = None;
if client_registry
.get(client_id)
.map(|i| i.tracking)
.unwrap_or(false)
{
tracking_table.disable_tracking();
}
tracking_table.unregister_client(client_id);
monitoring = None;
// `HIMPORT` fieldsets are the connection's state (#566).
crate::commands::hash_import::forget_client(client_id);
client_registry.update(client_id, |info| {
info.no_evict = false;
info.resp = 2;
info.name = String::new();
info.tracking = false;
info.tracking_bcast = false;
info.tracking_optin = false;
info.tracking_optout = false;
info.tracking_noloop = false;
info.tracking_caching_next = None;
info.tracking_prefixes.clear();
info.tracking_redirect = None;
info.tracking_redirect_broken = false;
info.flags = "N".to_string();
info.user = "default".to_string();
});
authenticated_user = if crate::acl::default_user_is_open(&acl_store) {
if let Some(user) = acl_store.read().get("default") {
crate::acl::track_restriction_counters(
user,
&mut key_restricted,
&mut cmd_restricted,
);
}
Some("default".to_string())
} else {
crate::acl::clear_restriction_counters(
&mut key_restricted,
&mut cmd_restricted,
);
None
};
b"+RESET\r\n".to_vec()
}
"EXEC" => {
// One watching transaction at a time, from its check to
// its last command. See `WATCHED_EXEC`.
let _one_at_a_time = if tx.active && !tx.watched_keys.is_empty() {
Some(commands::transaction::WATCHED_EXEC.lock().await)
} else {
None
};
// A watched key whose time ran out while it was watched
// has been modified, whether or not anything has got
// round to removing it. Removing it now says so.
for (db, key) in &tx.watched_keys {
commands::helpers::lazy_expire_key(&store, *db, key);
}
// When it was routed, for the check inside its gates.
let mut routed = crate::cluster::routing::Routed::default();
let refusal = if !tx.active {
None
} else if let Some(busy) =
commands::transaction::exec_refusal(&cmd, &tx.queue, &repl_state)
{
// Before anything else, as for any command: a
// script has the server.
Some(busy)
} else if tx.aborted {
Some(
b"-EXECABORT Transaction discarded because of previous errors.\r\n"
.to_vec(),
)
} else {
crate::cluster::routing::exec_refusal(
&crate::cluster::routing::Caller {
cluster: &cluster_state,
registry: &client_registry,
client_id,
store: &store,
db: selected_db,
},
&tx.queue,
&mut routed,
)
};
if !tx.active {
b"-ERR EXEC without MULTI\r\n".to_vec()
} else if let Some(refusal) = refusal {
// Nothing runs: the transaction is discarded whole.
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
refusal
} else {
// From the check of the watched keys to the last queued
// command, the transaction is alone: no other command —
// read or write — runs in between. See `command_gate`.
// A queued WAIT counts the replicas that have what was
// written before this EXEC: each one's target taken after
// a hub barrier, as WAIT takes it outside a transaction.
// Taken here, before the gates: nothing waits inside them.
let wait_targets = if commands::transaction::queues_wait(&tx.queue)
&& repl_state
.connected_replicas
.load(std::sync::atomic::Ordering::Relaxed)
> 0
{
let (barrier_tx, barrier_rx) = tokio::sync::oneshot::channel();
if hub_tx
.send(crate::replication::HubMsg::Barrier(barrier_tx))
.is_ok()
{
let _ = barrier_rx.await;
}
Some(repl_state.wait_targets())
} else {
None
};
// The test hook that holds a write up before its gates
// (`pause::test_stall_before_the_gate`).
#[cfg(debug_assertions)]
for queued in &tx.queue {
let queued: Vec<&[u8]> = queued.iter().map(Vec::as_slice).collect();
crate::pause::test_stall_before_the_gate(&queued);
}
let _alone = crate::command_gate::enter_alone();
// And as one write: a snapshot, a backup or a full sync cuts
// before it or after it, never between two of its commands
// (#148). The writes it runs are inside this one.
let _whole = crate::write_gate::enter();
// A `CLIENT PAUSE` set since it passed the pause
// check: out of the gates, read again, and held by
// that check, the transaction as it was (#629). See
// `pause::pause_clients`.
if crate::pause::writes_must_check(routed.at())
&& crate::pause::exec_held_in_gate(&tx.queue)
{
redispatch = true;
continue;
}
// And to replicas and the AOF as one: its writes in the
// stream between a `MULTI` and an `EXEC`, its records
// written together (#172). Dropped first, while the
// gates are still held.
let _propagation = crate::replication::PropagationGroup::begin(
&repl_state,
&hub_tx,
&aof_tx,
);
// A `MIGRATE` is moving one of its keys, or its keys
// have left since it was routed (#331): it is given up
// whole. See `routing::exec_refusal_in_gate`.
let refused = crate::cluster::routing::exec_refusal_in_gate(
&crate::cluster::routing::Caller {
cluster: &cluster_state,
registry: &client_registry,
client_id,
store: &store,
db: selected_db,
},
&tx.queue,
routed,
);
if refused.is_some()
|| dirty_flag.load(std::sync::atomic::Ordering::Acquire)
{
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
// RESP3 has a dedicated null type (`_`); a RESP2-style `*-1` null
// array is not guaranteed to be recognized as null by a strict RESP3
// parser (redis-py's, e.g., parses it as an empty array instead),
// which breaks WATCH-abort detection for RESP3 clients entirely.
if let Some(refusal) = refused {
refusal
} else if resp_version == 3 {
crate::resp::write::resp_null_resp3()
} else {
crate::resp::write::resp_null_array()
}
} else if let Some(sets) =
exec_fast_apply_sets(tx.watched_keys.is_empty(), &tx.queue)
// The fast path writes without going through the
// per-command ACL check. A user with any
// restriction takes the generic path, where each
// queued command is checked against the rules in
// force now — not the ones in force when it was
// queued.
.filter(|_| !key_restricted && !cmd_restricted)
{
// ── Lock-held fast-apply path ────────────────────────────────────
// The generic path checks `dirty_flag` unlocked, then dispatches the
// queued write through the normal per-command path, which re-acquires
// the shard lock internally — there's a real gap between "checked
// clean" and "committed" during which another connection's write (on
// a different worker thread) can land, get lost by neither side ever
// observing the other. That's the lost-update race this closes for the
// common single/simple-multi-key CAS shape: acquire every affected
// shard's write lock up front (sorted by address so two concurrent
// fast-apply EXECs can't deadlock on each other), verify `dirty_flag`
// *while holding them*, and only then mutate — so no other writer to
// any of these shards can possibly interleave between the check and
// the commit. We can't just hold the lock and call the normal
// per-command dispatch path here: it would try to re-acquire the same
// (non-reentrant) shard lock and deadlock against itself. So this path
// applies the mutation directly, then replays the exact same
// replication/AOF/watch-notify/monitor/tracking side effects via
// `apply_write_side_effects` (shared with the normal path, not a
// hand-duplicated copy) so nothing observable differs except the race
// being closed.
let mut shard_ptrs: Vec<usize> = Vec::new();
let mut shards: Vec<&store::Shard> = Vec::new();
for (db_idx, key) in tx.watched_keys.iter() {
let shard = store::get_shard(&store[*db_idx], key);
let ptr = Arc::as_ptr(shard) as usize;
if !shard_ptrs.contains(&ptr) {
shard_ptrs.push(ptr);
shards.push(shard);
}
}
for (key, _) in sets.iter() {
let shard = store::get_shard(&store[selected_db], key);
let ptr = Arc::as_ptr(shard) as usize;
if !shard_ptrs.contains(&ptr) {
shard_ptrs.push(ptr);
shards.push(shard);
}
}
let mut order: Vec<usize> = (0..shards.len()).collect();
order.sort_by_key(|&i| shard_ptrs[i]);
// Hold the write gate across the mutation and its side effects,
// like any other write (see `write_gate`). Taken before the
// shard locks: gate first, shards second, everywhere.
let _write_gate = crate::write_gate::enter();
// …and, ahead of the shard locks too, the order of
// these keys' writes in the stream (`write_order`).
let _write_order = crate::write_order::lock_keys(
selected_db,
sets.iter().map(|(key, _)| key.as_bytes()),
);
let mut guards: Vec<(usize, _)> = order
.iter()
.map(|&i| (shard_ptrs[i], shards[i].write()))
.collect();
// A handoff that set its pause before the gates were
// taken has refused this transaction already
// (`routing::exec_refusal_in_gate`); one set since waits
// for the write gate before it takes its cut.
if dirty_flag.load(Ordering::Acquire) {
drop(guards);
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, Ordering::Release);
if resp_version == 3 {
crate::resp::write::resp_null_resp3()
} else {
crate::resp::write::resp_null_array()
}
} else {
// Each SET is a use, and a modification, of its
// key, as the same SET is outside a transaction
// (it went unrecorded here).
let _access = crate::eviction::recording().then(|| {
crate::store::AccessScope::open(crate::eviction::write_stamp(
std::time::Instant::now(),
))
});
for (key, value) in sets.iter() {
let shard = store::get_shard(&store[selected_db], key);
let ptr = Arc::as_ptr(shard) as usize;
if let Some((_, guard)) =
guards.iter_mut().find(|(p, _)| *p == ptr)
{
drop(guard.set_str_expiring(key, value, None));
}
// Notify while STILL HOLDING this key's shard lock. Doing this
// after `drop(guards)` below would reopen the exact race this
// path exists to close: another fast-apply EXEC could acquire
// the now-free lock and check `dirty_flag` before this notify
// sets it, observe clean, and overwrite this write. notify()
// only touches the (separate) watch-registry lock, so calling
// it here cannot deadlock against the shard lock we're holding.
watch_registry.as_ref().notify(selected_db, key.as_bytes());
}
// A plain SET takes the key's time to live away, in
// the same step as it writes the value. Every
// shard is let go of before what a SET wrote over
// is announced (`store::unlock_together`).
store::unlock_together(guards.into_iter().map(|(_, guard)| guard));
let count = sets.len();
let mut exec_out = format!("*{count}\r\n").into_bytes();
for (key, value) in sets.iter() {
let raw_cmd =
[b"SET".to_vec(), key.clone().into_bytes(), value.clone()];
let cmd_ctx = Ctx {
cmd: raw_cmd.iter().map(|v| v.as_slice()).collect(),
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user
.as_deref()
.unwrap_or("default"),
tracking_table: &tracking_table,
blocking: None,
};
crate::keyspace_events::notify(
cmd_ctx.pubsub,
*cmd_ctx.selected_db,
crate::keyspace_events::KS_STRING,
"set",
key,
);
commands::handler::apply_write_side_effects(
&cmd_ctx, "SET", b"+OK\r\n",
);
exec_out.extend_from_slice(b"+OK\r\n");
}
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, Ordering::Release);
exec_out
}
} else {
let queued = std::mem::take(&mut tx.queue);
let count = queued.len();
let mut exec_out = format!("*{count}\r\n").into_bytes();
// A plain FLUSHALL here is not counted as lazily freed.
let _queued = crate::lazyfree::running_queued();
// What the queued commands write to the ACL log is
// in context `multi`, as in Redis.
let _context = crate::acl::log_context("multi");
for queued_cmd in queued {
let queued_name = queued_cmd
.first()
.map(|name| String::from_utf8_lossy(name).to_ascii_uppercase())
.unwrap_or_default();
// SUBSCRIBE and its kind, queued: run as they run
// outside a transaction, their reply this command's
// place in EXEC's, as in Redis (#23).
if crate::pubsub::is_subscription_command(&queued_name) {
let args: Vec<&[u8]> =
queued_cmd.iter().map(|b| b.as_slice()).collect();
let subs = subscriptions.get_or_insert_with(|| {
open_subscriptions(
&pubsub,
&client_registry,
client_id,
&writer,
)
});
exec_out.extend_from_slice(&subs.handle(&args, resp_version));
if subs.total() == 0 {
subscriptions = None;
}
continue;
}
// Those the connection loop answers itself outside a
// transaction, answered as Redis's EXEC answers them
// (#550, #499).
if matches!(
queued_name.as_str(),
"AUTH" | "HELLO" | "UNWATCH" | "MONITOR" | "WAIT" | "WAITAOF"
) {
let args: Vec<&[u8]> =
queued_cmd.iter().map(|b| b.as_slice()).collect();
let reply = if queued_name == "AUTH" {
commands::login::Login {
acl_store: &acl_store,
acl_log: &acl_log,
client_registry: &client_registry,
client_id,
peer_addr: &peer_addr,
user: &mut authenticated_user,
key_restricted: &mut key_restricted,
cmd_restricted: &mut cmd_restricted,
}
.auth(&args)
} else if queued_name == "HELLO" {
commands::login::Login {
acl_store: &acl_store,
acl_log: &acl_log,
client_registry: &client_registry,
client_id,
peer_addr: &peer_addr,
user: &mut authenticated_user,
key_restricted: &mut key_restricted,
cmd_restricted: &mut cmd_restricted,
}
.hello(
&args,
&mut resp_version,
&repl_state,
)
} else {
commands::transaction::connection_reply_in_exec(
&queued_name,
&args,
&commands::transaction::InExec {
acl_store: &acl_store,
acl_log: &acl_log,
user: authenticated_user
.as_deref()
.unwrap_or("default"),
peer_addr: &peer_addr,
client_registry: &client_registry,
client_id,
repl_state: &repl_state,
wait_targets: wait_targets.as_deref(),
},
)
.unwrap_or_default()
};
crate::cmdstats::record(
&queued_name,
&args,
&reply,
std::time::Duration::ZERO,
);
exec_out.extend_from_slice(&reply);
continue;
}
let raw_cmd = queued_cmd.clone();
#[cfg(feature = "lua")]
let exec_slices: Vec<&[u8]> =
queued_cmd.iter().map(|b| b.as_slice()).collect();
#[cfg(feature = "lua")]
let (resp, elapsed_us) = {
let cmd_start = std::time::Instant::now();
let r = commands::execute_command(Ctx {
cmd: exec_slices,
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user
.as_deref()
.unwrap_or("default"),
tracking_table: &tracking_table,
blocking: None,
});
(r, cmd_start.elapsed().as_micros() as u64)
};
#[cfg(not(feature = "lua"))]
let (resp, elapsed_us) = {
let cmd_start = std::time::Instant::now();
let r = commands::execute_command(Ctx {
cmd: queued_cmd.iter().map(|b| b.as_slice()).collect(),
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user
.as_deref()
.unwrap_or("default"),
tracking_table: &tracking_table,
blocking: None,
});
(r, cmd_start.elapsed().as_micros() as u64)
};
if elapsed_us >= slowlog.threshold_us() {
slowlog.record(
&raw_cmd,
elapsed_us,
&peer_addr,
// The name now: a queued CLIENT SETNAME
// or HELLO may have changed it.
client_registry
.get(client_id)
.map(|info| info.name.clone())
.unwrap_or_default(),
);
}
exec_out.extend_from_slice(&resp);
}
watch_registry.as_ref().unwatch_all(
&tx.watched_keys
.iter()
.map(|_| Arc::clone(&dirty_flag))
.collect::<Vec<_>>(),
);
tx.reset();
dirty_flag.store(false, std::sync::atomic::Ordering::Release);
exec_out
}
}
}
// AUTH and HELLO: inside MULTI they are queued, and run
// when EXEC runs the transaction, as in Redis (#550).
"AUTH" if !tx.active => commands::login::Login {
acl_store: &acl_store,
acl_log: &acl_log,
client_registry: &client_registry,
client_id,
peer_addr: &peer_addr,
user: &mut authenticated_user,
key_restricted: &mut key_restricted,
cmd_restricted: &mut cmd_restricted,
}
.auth(&cmd),
"HELLO" if !tx.active => {
let reply = commands::login::Login {
acl_store: &acl_store,
acl_log: &acl_log,
client_registry: &client_registry,
client_id,
peer_addr: &peer_addr,
user: &mut authenticated_user,
key_restricted: &mut key_restricted,
cmd_restricted: &mut cmd_restricted,
}
.hello(&cmd, &mut resp_version, &repl_state);
// Counted here: the commands below are not.
crate::cmdstats::record("HELLO", &cmd, &reply, std::time::Duration::ZERO);
combined.extend_from_slice(&reply);
parse_offset += consumed;
continue;
}
// WAITAOF and WAIT: inside MULTI they are queued, and EXEC
// answers them without waiting, as in Redis (#499).
"WAITAOF" if !tx.active => {
if cmd.len() < 4 {
b"-ERR wrong number of arguments for 'waitaof' command\r\n".to_vec()
} else if !aof_enabled
&& !crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
{
// Nothing goes to an AOF, so nothing is on disk by
// one: it answered that the write was (#137). On at
// the start, or turned on since by `CONFIG SET`.
let num_local = std::str::from_utf8(cmd[1])
.ok()
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(0);
if num_local != 0 {
b"-ERR WAITAOF cannot be used when numlocal is set but appendonly is disabled.\r\n"
.to_vec()
} else {
b"*2\r\n:0\r\n:0\r\n".to_vec()
}
} else {
let timeout_ms: u64 =
std::str::from_utf8(cmd.get(3).copied().unwrap_or(b"0"))
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
let target =
crate::aof::AOF_WRITTEN.load(std::sync::atomic::Ordering::Relaxed);
crate::aof::request_flush();
let deadline = tokio::time::Instant::now()
+ tokio::time::Duration::from_millis(if timeout_ms == 0 {
u64::MAX
} else {
timeout_ms
});
let role_epoch = crate::commands::blocking::role_changes(&repl_state);
let waited = tokio::select! {
biased;
reply = async {
loop {
// Ended, as every blocked client is, when
// this node becomes a replica (#591).
if crate::commands::blocking::role_changes(&repl_state)
!= role_epoch
{
break crate::commands::blocking::ROLE_CHANGED.to_vec();
}
let fsynced = crate::aof::AOF_FSYNCED
.load(std::sync::atomic::Ordering::Relaxed);
// As Redis: 1 once the write is on disk here,
// whatever `numlocal` asked for.
if fsynced >= target {
break b"*2\r\n:1\r\n:0\r\n".to_vec();
}
if tokio::time::Instant::now() >= deadline {
break b"*2\r\n:0\r\n:0\r\n".to_vec();
}
// Async sleep — yields to tokio scheduler, lets AOF writer task run
tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
}
} => Some(reply),
() = until_gone(&mut reader, &mut carried, &mut kill_rx, &activity) => None,
};
match waited {
Some(reply) if reply == crate::commands::blocking::ROLE_CHANGED => {
combined.extend_from_slice(&reply);
quit_requested = true;
break;
}
Some(reply) => reply,
// The client has gone: there is nobody to answer.
None => {
quit_requested = true;
break;
}
}
}
}
"WAIT" if !tx.active => {
match crate::replication::wait_args(&cmd, repl_state.is_slave()) {
Err(refusal) => refusal,
Ok((wanted, timeout_ms)) => {
// A blocked client while it waits, as in Redis:
// `b` in CLIENT LIST, counted in
// `blocked_clients`, and ended by CLIENT UNBLOCK.
let (unblock_tx, unblock_rx) = tokio::sync::oneshot::channel();
let _blocked = (wanted > 0).then(|| {
client_registry.blocked_in(client_id, unblock_tx, timeout_ms > 0)
});
let waited = tokio::select! {
biased;
reply = crate::replication::wait_for_replicas(
&repl_state,
&hub_tx,
wanted,
timeout_ms,
unblock_rx,
) => Some(reply),
() = until_gone(&mut reader, &mut carried, &mut kill_rx, &activity) => None,
};
match waited {
Some(end) if end.close => {
// This master became a replica: told so,
// and closed, as Redis closes it.
combined.extend_from_slice(&end.reply);
parse_offset += consumed;
quit_requested = true;
break;
}
Some(end) => end.reply,
// The client has gone: there is nobody to answer.
None => {
quit_requested = true;
break;
}
}
}
}
}
_ if tx.active => {
// Inside a transaction — queue, don't execute. In a
// cluster the command is routed now: one that belongs to
// another node is refused, and takes the transaction
// with it.
//
// So is one that is no command at all, or has the wrong
// number of arguments, or arrives while a script has the
// server busy.
let refusal =
commands::transaction::queue_refusal(&cmd_name, &cmd).or_else(|| {
crate::cluster::routing::queue_refusal(
&crate::cluster::routing::Caller {
cluster: &cluster_state,
registry: &client_registry,
client_id,
store: &store,
db: selected_db,
},
&cmd,
)
});
match refusal {
Some(refusal) => {
tx.aborted = true;
refusal
}
None => {
tx.queue.push(cmd.iter().map(|s| s.to_vec()).collect());
b"+QUEUED\r\n".to_vec()
}
}
}
_ => {
let raw_cmd = cmd.clone();
#[cfg(feature = "lua")]
let (result, elapsed_us) =
if crate::commands::lua_command_runs_long_sync_vm(cmd.as_slice()) {
// Made once for the connection and kept: it is two dozen shared
// handles, each counted up to copy and down to drop, and a script
// needs none of them copied to run on this thread. Made again if
// the connection has become another user since.
let user_now = authenticated_user.as_deref().unwrap_or("default");
if lua_env
.as_ref()
.is_some_and(|env| env.authenticated_user != user_now)
{
lua_env = None;
}
let env = &*lua_env.get_or_insert_with(|| {
crate::lua_vm_blocking::ClientExecEnv::snapshot(
&store,
&lastsave,
crate::lua_vm_blocking::AofBridge::Tokio(aof_tx.clone()),
&config,
&started_at,
&index_store,
&dict_store,
&wait_table,
&ts_index,
&pubsub,
&hub_tx,
&repl_state,
&watch_registry,
&client_registry,
&acl_store,
&acl_log,
&slowlog,
&latency,
&compaction_tx,
&cluster_state,
&monitor_registry,
&tracking_table,
&peer_addr,
client_id,
authenticated_user.as_deref().unwrap_or("default"),
)
});
crate::lua_vm_blocking::run_lua_vm_blocking(
cmd.as_slice(),
&mut selected_db,
env,
crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed),
resp_version,
)
.await
} else {
let cmd_start = std::time::Instant::now();
let r = commands::execute_command(Ctx {
cmd,
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user
.as_deref()
.unwrap_or("default"),
tracking_table: &tracking_table,
blocking: None,
});
(r, cmd_start.elapsed().as_micros() as u64)
};
#[cfg(not(feature = "lua"))]
let (result, elapsed_us) = {
let cmd_start = std::time::Instant::now();
let r = commands::execute_command(Ctx {
cmd,
store: &store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &aof_tx,
aof_enabled: crate::aof::AOF_ENABLED
.load(std::sync::atomic::Ordering::Relaxed),
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state: &repl_state,
watch_registry: watch_registry.as_ref(),
client_id,
client_registry: &client_registry,
resp: resp_version,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster_state,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: &peer_addr,
monitor_registry: &monitor_registry,
authenticated_user: authenticated_user.as_deref().unwrap_or("default"),
tracking_table: &tracking_table,
blocking: None,
});
(r, cmd_start.elapsed().as_micros() as u64)
};
// Not a write a pause sent back: it is timed when it runs.
if elapsed_us >= slowlog.threshold_us() && !crate::pause::is_held(&result) {
let client_name = client_registry
.get(client_id)
.map(|info| info.name.clone())
.unwrap_or_default();
slowlog.record(&raw_cmd, elapsed_us, &peer_addr, client_name);
}
result
}
};
// A write that got past a `CLIENT PAUSE` before it was set, and
// went no further (`pause::HELD_IN_GATE`): read again, and held.
if crate::pause::is_held(&response) {
redispatch = true;
continue;
}
// The other commands answered here, and not by `execute_command`,
// are counted as well (`HELLO` counts itself, as it replies in
// several places).
if !queued_here
&& matches!(
cmd_name.as_str(),
"DISCARD" | "WATCH" | "UNWATCH" | "RESET" | "AUTH"
)
{
// None of them has subcommands, so the name is all `record` needs.
crate::cmdstats::record(
&cmd_name,
&[cmd_name.as_bytes()],
&response,
std::time::Duration::ZERO,
);
}
// MONITOR sees a transaction as it ran: `MULTI`, the commands —
// each shown as it was run — and then `EXEC`.
if let Some(word) = &transaction_word {
crate::monitor::feed(
&monitor_registry,
&[word.as_slice()],
selected_db,
&peer_addr,
);
// And they are commands, to be counted.
crate::cmdstats::record(
&cmd_name,
&[word.as_slice()],
&response,
std::time::Duration::ZERO,
);
}
combined.extend_from_slice(&response);
parse_offset += consumed;
}
private_query_buffer |= progress.take_private_query_buffer();
if private_query_buffer && !was_private_query_buffer {
last_query_buffer_activity = Instant::now();
}
let reserve_hint = progress.take_reserve_hint();
if private_query_buffer
&& !was_private_query_buffer
&& buffer.capacity() < resp::parse::PRIVATE_QUERY_BUFFER_MIN_CAPACITY
{
buffer.reserve(
resp::parse::PRIVATE_QUERY_BUFFER_MIN_CAPACITY.saturating_sub(buffer.len()),
);
}
if reserve_hint > buffer.capacity() {
buffer.reserve(reserve_hint.saturating_sub(buffer.len()));
}
query_buffer_peak = query_buffer_peak.max(reserve_hint);
reply_gate.settle(&mut combined);
crate::tracking::after_command(
&tracking_table,
&client_registry,
client_id,
&activity,
&mut combined,
);
// Told what was wrong with it, and then the connection is closed:
// there is no telling where in this stream the next request starts.
if let Some(e) = protocol_error {
log_verbose!(
"Client id={client_id}: protocol error: {e} — closing the connection. The \
client sent something that is not RESP: often a wrong port, TLS on a \
plaintext port, or HTTP"
);
combined.extend_from_slice(format!("-ERR Protocol error: {e}\r\n").as_bytes());
quit_requested = true;
}
read_start = parse_offset;
// Only compact when we've consumed a meaningful chunk AND there's
// data left to preserve. This amortizes the memmove cost.
if read_start > 0 && read_start > buffer.len() / 2 {
buffer.drain(0..read_start);
read_start = 0;
}
// A buffer that grew to hold one large request is not kept at that
// size for the life of the connection.
query_buffer.update(
buffer.len().saturating_sub(read_start),
buffer.capacity().saturating_sub(buffer.len()),
private_query_buffer,
);
// One TCP write per read syscall batch (pipelining).
activity.note_flush(combined.len(), commands_before);
activity.note_tx(tx.active.then_some(tx.queue.len()), tx.watched_keys.len());
// Replies to writes go out once their records are in the AOF (#147).
if std::mem::take(&mut aof_wait) {
crate::aof::written(&aof_tx).await;
}
if write_tcp_batch(&writer, &mut combined).await.is_err() {
break;
}
// The replies to SUBSCRIBE are out: messages may follow them.
if let Some(subs) = &subscriptions {
subs.flushed();
}
// QUIT: the +OK is on the wire now, so drop the connection.
if quit_requested {
break;
}
match connection_handoff {
None => {}
Some(ConnectionHandoff::Replica { legacy_sync, psync }) => {
push_forwarder.abort();
let (resp_tx, resp_rx) = mpsc::channel::<Vec<u8>>(16384);
let write_task = spawn_mux_to_socket(Arc::clone(&writer), resp_rx);
buffer.drain(0..read_start);
let listening_port = client_registry
.get(client_id)
.map(|info| info.replica_listening_port)
.filter(|p| *p != 0);
// A replica's link from here: `flags=S`, `TYPE replica`, as
// Redis lists it (#595).
client_registry.update(client_id, |info| {
info.push_tx = None;
info.flags = "S".to_string();
});
crate::replication::replica_client::handle_replica_connection(
reader,
Arc::clone(&writer),
resp_tx,
write_task,
store,
lastsave,
aof_tx,
crate::aof::AOF_ENABLED.load(std::sync::atomic::Ordering::Relaxed),
config,
started_at,
index_store,
dict_store,
wait_table,
ts_index,
pubsub,
hub_tx,
repl_state,
peer_addr.clone(),
legacy_sync,
buffer,
listening_port,
psync,
kill_rx,
)
.await?;
return Ok(());
}
}
}
// If this connection held a key-restriction slot, release it.
if key_restricted {
crate::acl::RESTRICTED_KEY_CLIENTS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
if cmd_restricted {
crate::acl::RESTRICTED_CMD_CLIENTS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
push_forwarder.abort();
// What was kept for tracking goes with `_guard`.
Ok(())
}