kividb 1.2.2

A fast Redis®-compatible in-memory store written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
use ahash::AHashMap;
use parking_lot::RwLock;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::Instant;
use tokio::sync::mpsc;
use tokio::sync::oneshot;

static NEXT_CLIENT_ID: AtomicU64 = AtomicU64::new(1);

pub fn next_client_id() -> u64 {
    NEXT_CLIENT_ID.fetch_add(1, Ordering::Relaxed)
}

/// A monotonic clock the whole process shares, started at first use. Idle
/// time is measured against it, not the wall clock, so `idle=` cannot jump
/// when the system clock is set back or forwards.
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();

/// Whole seconds since the process's monotonic epoch. Non-decreasing.
fn now_seconds() -> u64 {
    EPOCH.get_or_init(Instant::now).elapsed().as_secs()
}

/// A handle the server loop holds to detect a CLIENT KILL.
/// When the kill command fires, the Receiver resolves and the loop breaks.
pub type KillRx = oneshot::Receiver<()>;

/// What a connection was last asked to do, for `CLIENT LIST`'s `cmd=` and
/// `db=`.
///
/// Written by the connection on every command, so it has to cost next to
/// nothing: a few words stored without a lock. The registry — one lock for
/// every worker thread — is not touched. Read only to list the clients; a
/// reader that catches the connection between two commands may see the name
/// of one with the subcommand of the other, and that is all that can go
/// wrong.
#[derive(Debug, Default)]
pub struct Activity {
    /// The command's name, as sent, cut to 24 bytes.
    name: [AtomicU64; 3],
    /// When the connection last interacted, in seconds on the monotonic
    /// clock [`now_seconds`] reads. Written once per socket read — see
    /// [`touch`](Activity::touch) — and read to print `idle=`. Nothing else
    /// reads it, so a torn view between the two is a second of error on that
    /// one field and nothing more.
    last_interaction: AtomicU64,
    /// Its first argument, if that is of 16 bytes or fewer: the subcommand,
    /// if the command has them.
    sub: [AtomicU64; 2],
    /// The two lengths.
    lens: AtomicU64,
    db: std::sync::atomic::AtomicUsize,
    /// What is to be written to the connection after the reply to the
    /// command it is running: a message that command gave rise to, for this
    /// same connection. See `tracking::tell`.
    after_reply: parking_lot::Mutex<Vec<u8>>,
    has_after_reply: std::sync::atomic::AtomicBool,
    /// The connection has killed itself (`CLIENT KILL … SKIPME no`): it is
    /// to be closed, but not before the reply to that command is written.
    closing_after_reply: std::sync::atomic::AtomicBool,
    /// Redis 8.10's per-client counters for `CLIENT LIST`: bytes read and
    /// written, commands run, reads, and commands per read (sum and count).
    /// Written only by the connection's own loop (or the script it is
    /// waiting on), so each is a load and a store, no locked instruction.
    io: [AtomicU64; 7],
    /// `CLIENT LIST`'s `multi` and `watch` (#158): the commands queued in the
    /// transaction, plus one (0 outside one), in the high half; the keys
    /// watched in the low. Written by the connection's loop as its replies go
    /// out, only when they changed.
    tx: AtomicU64,
}

/// Clients blocked in a command with a timeout: `clients_in_timeout_table`.
static IN_TIMEOUT_TABLE: AtomicU64 = AtomicU64::new(0);

const IO_NET_IN: usize = 0;
const IO_NET_OUT: usize = 1;
const IO_CMDS: usize = 2;
const IO_READS: usize = 3;
const IO_PIPE_SUM: usize = 4;
const IO_PIPE_CNT: usize = 5;
/// 1 from when a command starts until its read's replies are written. As
/// in Redis, a command counts once it has run: a `CLIENT INFO` does not count
/// itself, and a `BLPOP` that is blocked counts when it is answered. It is
/// in `IO_CMDS` from the start (one store more a command than that alone),
/// and `tot-cmds` is `IO_CMDS` less this.
const IO_RUNNING: usize = 6;

/// A connection's current RESP query buffer, published without taking the
/// registry lock. `free` is the spare capacity at the end of the backing Vec.
#[derive(Debug, Default)]
pub struct QueryBufferMetrics {
    /// The high and low halves hold qbuf and qbuf-free. Redis's maximum query
    /// buffer is below 2 GiB, so each value fits in 32 bits.
    values: AtomicU64,
}

impl QueryBufferMetrics {
    #[inline]
    pub fn update(&self, len: usize, free: usize, private: bool) {
        let len = len.min(u32::MAX as usize) as u64;
        let free = if private {
            free.min(u32::MAX as usize) as u64
        } else {
            0
        };
        self.values.store((len << 32) | free, Ordering::Relaxed);
    }

    #[inline]
    fn values(&self) -> (u64, u64) {
        let values = self.values.load(Ordering::Relaxed);
        (values >> 32, values & u32::MAX as u64)
    }
}

/// `CLIENT REPLY ON | OFF | SKIP`, as the connection loop keeps it.
///
/// The loop builds one buffer of replies for each batch of commands it
/// reads. [`begin`](Self::begin) is called as each command is about to run
/// and [`settle`](Self::settle) when the batch is over; between them they
/// take out of the buffer the replies the client asked not to be sent. A
/// connection that never uses the command pays one comparison per command.
#[derive(Default)]
pub struct ReplyGate {
    mode: ReplyMode,
    /// Where in the buffer the running command's reply starts.
    mark: usize,
    /// A command has begun whose reply has not been looked at.
    open: bool,
    /// That command is one whose output is not a reply: see `begin`.
    keep: bool,
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum ReplyMode {
    #[default]
    On,
    Off,
    /// `SKIP` was just given: no reply to it, nor to the command after it.
    SkipTwo,
    /// No reply to this command; then replies again.
    SkipOne,
}

impl ReplyGate {
    #[inline(always)]
    pub fn begin(&mut self, cmd: &[&[u8]], out: &mut Vec<u8>) {
        // Nearly always: replies are on, and this is not `CLIENT REPLY`.
        if self.mode == ReplyMode::On && !(cmd.len() == 3 && cmd[0].len() == 6) {
            return;
        }
        self.begin_gated(cmd, out);
    }

    #[cold]
    fn begin_gated(&mut self, cmd: &[&[u8]], out: &mut Vec<u8>) {
        if self.mode != ReplyMode::On {
            self.settle(out);
        }
        if cmd.len() == 3
            && cmd[0].len() == 6
            && cmd[0].eq_ignore_ascii_case(b"CLIENT")
            && cmd[1].eq_ignore_ascii_case(b"REPLY")
        {
            if cmd[2].eq_ignore_ascii_case(b"ON") {
                self.mode = ReplyMode::On;
            } else if cmd[2].eq_ignore_ascii_case(b"OFF") {
                self.mode = ReplyMode::Off;
            } else if cmd[2].eq_ignore_ascii_case(b"SKIP") && self.mode == ReplyMode::On {
                self.mode = ReplyMode::SkipTwo;
            }
        }
        if self.mode != ReplyMode::On {
            self.mark = out.len();
            self.open = true;
            // What the subscription commands write is not a reply but a
            // message — the first of those the subscription brings — and
            // messages are sent whatever was said about replies.
            self.keep =
                cmd[0].len() >= 9 && cmd[0][cmd[0].len() - 9..].eq_ignore_ascii_case(b"SUBSCRIBE");
        }
    }

    /// The command that began last is dispatched again (a parked command
    /// resumed, a write a pause sent back): not a new command, so neither
    /// settled nor begun again, which would use up a `CLIENT REPLY SKIP`
    /// on the dispatch that did not reply. Its reply starts where `out`
    /// ends now: what was before it may have been sent meanwhile.
    pub fn again(&mut self, out: &[u8]) {
        if self.open {
            self.mark = out.len();
        }
    }

    /// Drop the reply of the command that has just run, if it is not wanted.
    #[inline(always)]
    pub fn settle(&mut self, out: &mut Vec<u8>) {
        if self.open {
            self.settle_open(out);
        }
    }

    #[cold]
    fn settle_open(&mut self, out: &mut Vec<u8>) {
        self.open = false;
        // A push (RESP3's `>`) is not a reply: the confirmation of a
        // subscription still goes out.
        if !self.keep && out.get(self.mark) != Some(&b'>') {
            out.truncate(self.mark);
        }
        self.mode = match self.mode {
            ReplyMode::SkipTwo => ReplyMode::SkipOne,
            ReplyMode::SkipOne => ReplyMode::On,
            mode => mode,
        };
    }
}

/// What kind of client a connection is, as `CLIENT LIST TYPE` and
/// `CLIENT KILL TYPE` name them.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ClientKind {
    Normal,
    Master,
    Replica,
    PubSub,
}

impl ClientKind {
    pub fn parse(raw: &[u8]) -> Option<Self> {
        if raw.eq_ignore_ascii_case(b"normal") {
            Some(ClientKind::Normal)
        } else if raw.eq_ignore_ascii_case(b"master") {
            Some(ClientKind::Master)
        } else if raw.eq_ignore_ascii_case(b"replica") || raw.eq_ignore_ascii_case(b"slave") {
            Some(ClientKind::Replica)
        } else if raw.eq_ignore_ascii_case(b"pubsub") {
            Some(ClientKind::PubSub)
        } else {
            None
        }
    }
}

/// Which clients `CLIENT LIST` shows or `CLIENT KILL` closes: those that
/// match every condition given.
#[derive(Default)]
pub struct ClientFilter {
    pub ids: Option<Vec<u64>>,
    pub addr: Option<String>,
    pub laddr: Option<String>,
    pub user: Option<String>,
    pub kind: Option<ClientKind>,
    /// Connected for at least this many seconds.
    pub max_age: Option<u64>,
    /// Leave out the client that is asking.
    pub skip_me: bool,
}

impl ClientFilter {
    fn matches(&self, client: &ClientInfo, me: u64) -> bool {
        if self.skip_me && client.id == me {
            return false;
        }
        self.ids.as_ref().is_none_or(|ids| ids.contains(&client.id))
            && self.addr.as_ref().is_none_or(|addr| *addr == client.addr)
            && self.laddr.as_ref().is_none_or(|addr| *addr == client.laddr)
            && self.user.as_ref().is_none_or(|user| *user == client.user)
            && self.kind.is_none_or(|kind| kind == client.kind())
            && self
                .max_age
                .is_none_or(|age| client.connected_at.elapsed().as_secs() >= age)
    }
}

/// `bytes` — eight of them at most — as a number, the first the lowest.
#[inline(always)]
fn up_to_eight(bytes: &[u8]) -> u64 {
    let len = bytes.len();
    if len >= 8 {
        let mut all = [0u8; 8];
        all.copy_from_slice(&bytes[..8]);
        u64::from_le_bytes(all)
    } else if len >= 4 {
        // The first four and the last four, which overlap: where they do,
        // they agree.
        let mut head = [0u8; 4];
        head.copy_from_slice(&bytes[..4]);
        let mut tail = [0u8; 4];
        tail.copy_from_slice(&bytes[len - 4..]);
        u32::from_le_bytes(head) as u64 | (u32::from_le_bytes(tail) as u64) << (8 * (len - 4))
    } else if len == 0 {
        0
    } else {
        // One, two or three: the first, the middle and the last, which are
        // the same byte where there are fewer than three.
        (bytes[0] as u64)
            | (bytes[len / 2] as u64) << (8 * (len / 2))
            | (bytes[len - 1] as u64) << (8 * (len - 1))
    }
}

/// `word`'s first bytes, eight to a slot. Returns how many were kept.
///
/// Only the slots the word reaches are written: what an earlier, longer
/// word left in the others is past the length recorded with this one, and
/// is not read.
#[inline(always)]
fn pack<const N: usize>(word: &[u8], into: &[AtomicU64; N]) -> u64 {
    // Nearly always: a word of eight bytes or fewer.
    if word.len() <= 8 {
        into[0].store(up_to_eight(word), Ordering::Relaxed);
        return word.len() as u64;
    }
    // Often: a key of nine to sixteen bytes in the place of a subcommand.
    // Two stores, without the iterator the general case below goes through.
    if word.len() <= 16 && N >= 2 {
        into[0].store(up_to_eight(&word[..8]), Ordering::Relaxed);
        into[1].store(up_to_eight(&word[8..]), Ordering::Relaxed);
        return word.len() as u64;
    }
    let len = word.len().min(N * 8);
    for (slot, chunk) in into.iter().zip(word[..len].chunks(8)) {
        slot.store(up_to_eight(chunk), Ordering::Relaxed);
    }
    len as u64
}

fn unpack<const N: usize>(from: &[AtomicU64; N], len: usize) -> String {
    let bytes: Vec<u8> = from
        .iter()
        .flat_map(|slot| slot.load(Ordering::Relaxed).to_le_bytes())
        .take(len.min(N * 8))
        .collect();
    String::from_utf8_lossy(&bytes).into_owned()
}

impl Activity {
    /// The connection's transaction now: the commands queued if it is in
    /// one, and the keys it watches. See [`Activity::tx`].
    #[inline]
    pub fn note_tx(&self, queued: Option<usize>, watched: usize) {
        let multi = queued.map_or(0, |n| n as u64 + 1).min(u32::MAX as u64);
        let packed = (multi << 32) | (watched as u64).min(u32::MAX as u64);
        if self.tx.load(Ordering::Relaxed) != packed {
            self.tx.store(packed, Ordering::Relaxed);
        }
    }

    /// `(multi, watch)` as `CLIENT LIST` writes them: `multi` is -1 outside
    /// a transaction.
    fn tx(&self) -> (i64, u64) {
        let packed = self.tx.load(Ordering::Relaxed);
        ((packed >> 32) as i64 - 1, packed & u32::MAX as u64)
    }

    /// See [`Activity::closing_after_reply`].
    pub fn closes_after_reply(&self) -> bool {
        self.closing_after_reply.load(Ordering::Relaxed)
    }

    pub fn push_after_reply(&self, frame: &[u8]) {
        self.after_reply.lock().extend_from_slice(frame);
        self.has_after_reply.store(true, Ordering::Relaxed);
    }

    /// Move what was held to the end of `out`.
    #[inline]
    pub fn drain_after_reply(&self, out: &mut Vec<u8>) {
        if self.has_after_reply.swap(false, Ordering::Relaxed) {
            out.append(&mut self.after_reply.lock());
        }
    }

    /// The database the connection has selected.
    pub fn db(&self) -> usize {
        self.db.load(Ordering::Relaxed)
    }

    /// Note that the connection has just interacted, so `idle=` restarts
    /// from now. One relaxed store.
    ///
    /// Called once per socket read by the connection loop — not once per
    /// command — so a pipeline of many commands that arrives in a single read
    /// pays for one clock reading, and a client that is idle between reads
    /// keeps the idle time it has built up. Reading client information does
    /// not touch, so `CLIENT LIST` leaves every listed client's timer alone.
    #[inline]
    pub fn touch(&self) {
        self.last_interaction
            .store(now_seconds(), Ordering::Relaxed);
    }

    /// Whole seconds since the connection last interacted: what Redis prints
    /// as `idle=`. Reading it does not touch the connection, so `CLIENT LIST`
    /// leaves every listed client's idle timer where it was.
    pub fn idle_seconds(&self) -> u64 {
        self.idle_seconds_at(now_seconds())
    }

    /// [`idle_seconds`](Self::idle_seconds) for a given clock reading, so the
    /// elapsed-time arithmetic can be checked without waiting on a clock.
    fn idle_seconds_at(&self, now: u64) -> u64 {
        now.saturating_sub(self.last_interaction.load(Ordering::Relaxed))
    }

    /// The monotonic reading this activity last recorded, for tests and for
    /// anyone reasoning about the clock directly.
    #[cfg(test)]
    fn interaction_at(&self) -> u64 {
        self.last_interaction.load(Ordering::Relaxed)
    }

    #[inline]
    fn bump(&self, which: usize, by: u64) {
        let counter = &self.io[which];
        counter.store(
            counter.load(Ordering::Relaxed).wrapping_add(by),
            Ordering::Relaxed,
        );
    }

    /// `n` bytes read from the connection: one read event.
    #[inline]
    pub fn note_read(&self, n: usize) {
        self.bump(IO_NET_IN, n as u64);
        self.bump(IO_READS, 1);
    }

    /// Commands run so far: taken before a read's commands are parsed, for
    /// [`note_flush`](Self::note_flush) to see how many that read held.
    #[inline]
    pub fn commands_run(&self) -> u64 {
        self.io[IO_CMDS].load(Ordering::Relaxed)
    }

    /// The replies to one read's commands written, `out` bytes of them.
    #[inline]
    pub fn note_flush(&self, out: usize, commands_before: u64) {
        self.bump(IO_NET_OUT, out as u64);
        self.io[IO_RUNNING].store(0, Ordering::Relaxed);
        let ran = self.commands_run().wrapping_sub(commands_before);
        if ran > 0 {
            self.bump(IO_PIPE_SUM, ran);
            self.bump(IO_PIPE_CNT, 1);
        }
    }

    fn io(&self, which: usize) -> u64 {
        self.io[which].load(Ordering::Relaxed)
    }

    /// Commands a script it ran ran (`redis.call`): Redis counts them as
    /// the client's.
    pub fn add_commands(&self, n: u64) {
        self.bump(IO_CMDS, n);
    }

    #[inline]
    pub fn record(&self, cmd: &[&[u8]], db: usize) {
        self.bump(IO_CMDS, 1);
        self.io[IO_RUNNING].store(1, Ordering::Relaxed);
        self.db.store(db, Ordering::Relaxed);
        let name = pack(cmd[0], &self.name);
        // An argument too long to be the name of a subcommand is a key, or
        // a value: nothing that is shown.
        let sub = match cmd.get(1) {
            Some(sub) if sub.len() <= 16 => pack(sub, &self.sub),
            _ => 0,
        };
        self.lens.store(name | (sub << 8), Ordering::Relaxed);
    }

    /// The name as Redis prints it: lower case, and `client|list` for a
    /// command that has subcommands.
    pub fn last_cmd(&self) -> String {
        let lens = self.lens.load(Ordering::Relaxed);
        let name = unpack(&self.name, (lens & 0xff) as usize);
        let sub = unpack(&self.sub, (lens >> 8) as usize);
        if name.is_empty() {
            return "NULL".to_string();
        }
        if !sub.is_empty() && crate::commands::arity::is_container(&name.to_ascii_uppercase()) {
            format!("{name}|{sub}").to_ascii_lowercase()
        } else {
            name.to_ascii_lowercase()
        }
    }
}

/// How many out-of-band messages (invalidations, RESP3 pub/sub, MONITOR
/// lines) a connection's push queue holds before a client that does not read
/// them is closed (#161). Generous because it costs nothing until used: the
/// channel allocates as it fills. Redis puts no limit on a normal client's
/// output buffer at all.
pub const PUSH_QUEUE_FRAMES: usize = 65_536;

#[derive(Debug)]
pub struct ClientInfo {
    pub id: u64,
    pub addr: String,
    /// The address the client connected to.
    pub laddr: String,
    /// The user it is authenticated as.
    pub user: String,
    pub name: String,
    pub db: usize,
    pub flags: String,
    pub connected_at: Instant,
    pub activity: Arc<Activity>,
    pub query_buffer: Arc<QueryBufferMetrics>,
    pub no_evict: bool,
    /// Waiting in a blocking command: `b` in `CLIENT LIST`.
    pub blocked: bool,
    /// True iff the client has issued ASKING for the next command.
    /// Single-shot: cleared after the next command runs (whatever the result).
    pub asking: bool,
    /// True iff the client has issued READONLY (cluster replica reads).
    /// Persistent until READWRITE clears it.
    pub readonly: bool,
    // Sending to this closes the connection. Wrapped in Option so we can
    // take() it exactly once inside kill(). None after the first kill call.
    kill_tx: Option<oneshot::Sender<()>>,
    /// While the client is blocked in a command: how `CLIENT UNBLOCK` ends
    /// its wait.
    unblock_tx: Option<oneshot::Sender<crate::commands::blocking::Unblock>>,
    /// Blocked with a timeout: counted in [`IN_TIMEOUT_TABLE`].
    blocked_with_timeout: bool,
    // Tracking state
    pub tracking: bool,
    pub tracking_bcast: bool,
    pub tracking_prefixes: Vec<Vec<u8>>,
    pub tracking_redirect: Option<u64>, // redirect invalidation to another client ID
    /// The client they were redirected to has gone.
    pub tracking_redirect_broken: bool,
    // Channel to push out-of-band messages (invalidations) to this client.
    // None until the connection registers it after setup.
    pub push_tx: Option<mpsc::Sender<Vec<u8>>>,
    /// OPTIN/OPTOUT tracking mode.
    pub tracking_optin: bool, // true = OPTIN mode
    pub tracking_optout: bool, // true = OPTOUT mode
    /// Single-shot flag set by CLIENT CACHING yes/no.
    /// Applies to the next read command only, then cleared in handler.rs.
    pub tracking_caching_next: Option<bool>, // Some(true)=yes, Some(false)=no, None=unset
    pub tracking_noloop: bool,
    pub lib_name: String,
    pub lib_ver: String,
    /// Negotiated Redis protocol version per connection (`HELLO`): 2 or 3.
    pub resp: u8,
    /// Port announced with `REPLCONF listening-port`, 0 if none. Read when the
    /// connection turns into a replica link, so the master can list the
    /// replica by the port it serves clients on.
    pub replica_listening_port: u16,
    /// A replica that said `REPLCONF capa dataset-digest`, and has not yet
    /// been offered the fingerprint: see `replication::digest`.
    pub replica_takes_digest: bool,
    /// A replica that said `REPLCONF capa lost-data`: 1, or 2 once it has
    /// been told `+LOSTDATA`; 0 if it did not. See
    /// `ReplState::psync_offer`.
    pub replica_lost_data: u8,
    /// Channels, patterns and shard channels this client is subscribed to.
    pub subscriptions: [usize; 3],
}

impl ClientInfo {
    /// Create a new ClientInfo. Returns the paired kill receiver for the
    /// connection loop to select on.
    pub fn new(id: u64, addr: String) -> (Self, KillRx) {
        let (kill_tx, kill_rx) = oneshot::channel();
        let activity = Activity::default();
        activity.touch();
        let info = Self {
            id,
            addr,
            laddr: String::new(),
            user: "default".to_string(),
            name: String::new(),
            db: 0,
            flags: "N".to_string(),
            connected_at: Instant::now(),
            activity: Arc::new(activity),
            query_buffer: Arc::default(),
            no_evict: false,
            blocked: false,
            asking: false,
            readonly: false,
            tracking: false,
            tracking_bcast: false,
            tracking_prefixes: Vec::new(),
            tracking_redirect: None,
            tracking_redirect_broken: false,
            kill_tx: Some(kill_tx),
            unblock_tx: None,
            blocked_with_timeout: false,
            push_tx: None,
            tracking_optin: false,
            tracking_optout: false,
            tracking_caching_next: None,
            tracking_noloop: false,
            lib_name: String::new(),
            lib_ver: String::new(),
            resp: 2,
            replica_listening_port: 0,
            replica_takes_digest: false,
            replica_lost_data: 0,
            subscriptions: [0; 3],
        };
        (info, kill_rx)
    }

    pub fn kind(&self) -> ClientKind {
        if self.flags.contains('S') {
            ClientKind::Replica
        } else if self.flags.contains('M') {
            ClientKind::Master
        } else if self.subscriptions.iter().any(|n| *n > 0) {
            ClientKind::PubSub
        } else {
            ClientKind::Normal
        }
    }

    /// One line of `CLIENT LIST`, in Redis's layout. Query-buffer counters
    /// describe RESP bytes awaiting parsing and spare Vec capacity; other
    /// Redis-specific buffer and memory counters remain zero.
    pub fn to_list_line(&self) -> String {
        let age = self.connected_at.elapsed().as_secs();
        let idle = self.activity.idle_seconds();
        let (qbuf, qbuf_free) = self.query_buffer.values();
        let mut flags = String::new();
        if self.flags != "N" {
            flags.push_str(&self.flags);
        }
        if self.subscriptions.iter().any(|n| *n > 0) {
            flags.push('P');
        }
        if self.blocked {
            flags.push('b');
        }
        if self.tracking {
            flags.push('t');
        }
        if self.no_evict {
            flags.push('e');
        }
        if flags.is_empty() {
            flags.push('N');
        }
        format!(
            "id={} addr={} laddr={} fd=0 name={} age={} idle={} flags={} db={} sub={} psub={} \
            ssub={} multi={} watch={} qbuf={} qbuf-free={} argv-mem=0 multi-mem=0 \
            rbs=0 rbp=0 obl=0 oll=0 omem=0 omem-shared=0 omem-unshared=0 tot-mem={} events=r cmd={} \
            user={} redir={} resp={} lib-name={} lib-ver={} io-thread=0 tot-net-in={} \
            tot-net-out={} tot-cmds={} read-events={} avg-pipeline-len-sum={} \
            avg-pipeline-len-cnt={}\n",
            self.id,
            self.addr,
            self.laddr,
            self.name,
            age,
            idle,
            flags,
            self.activity.db(),
            self.subscriptions[0],
            self.subscriptions[1],
            self.subscriptions[2],
            self.activity.tx().0,
            self.activity.tx().1,
            qbuf,
            qbuf_free,
            // What KiviDB measures of a client's memory: its query buffer.
            qbuf + qbuf_free,
            self.activity.last_cmd(),
            self.user,
            self.tracking_redirect.map_or(-1, |id| id as i64),
            self.resp,
            self.lib_name,
            self.lib_ver,
            self.activity.io(IO_NET_IN),
            self.activity.io(IO_NET_OUT),
            self.activity
                .io(IO_CMDS)
                .saturating_sub(self.activity.io(IO_RUNNING)),
            self.activity.io(IO_READS),
            self.activity.io(IO_PIPE_SUM),
            self.activity.io(IO_PIPE_CNT),
        )
    }
}

// ClientInfo is stored in an Arc<RwLock<HashMap>> so it needs to be Send.
// oneshot::Sender<()> is Send, so this is automatic — but we note it explicitly.

pub type ClientRegistry = Arc<ClientRegistryInner>;

pub struct ClientRegistryInner {
    clients: RwLock<AHashMap<u64, ClientInfo>>,
    /// Connections holding a [`Slot`]: clients, and TLS ones still in their
    /// handshake.
    slots: AtomicUsize,
}

/// `maxclients`; 10000 is its default in `CONFIG GET`.
static MAX_CLIENTS: AtomicUsize = AtomicUsize::new(10_000);

pub fn set_max_clients(n: usize) {
    MAX_CLIENTS.store(n, Ordering::Relaxed);
}

pub fn max_clients() -> usize {
    MAX_CLIENTS.load(Ordering::Relaxed)
}

/// io_uring workers, set at startup: each holds open files of its own.
static URING_WORKERS: AtomicUsize = AtomicUsize::new(0);

/// Open files kept for everything but clients: Redis's 32, about twice what
/// the tokio loop holds. io_uring holds 7 more, and 7 a worker (its ring,
/// epolls, eventfd and listener), so it keeps 8 more and 8 a worker.
fn reserved_fds() -> usize {
    match URING_WORKERS.load(Ordering::Relaxed) {
        0 => 32,
        workers => workers.saturating_mul(8).saturating_add(40),
    }
}

/// How many of `max` clients a soft open-file limit of `soft` leaves room
/// for, with `reserved` kept back.
#[cfg(unix)]
fn clients_for(soft: libc::rlim_t, max: usize, reserved: usize) -> usize {
    let reserved = libc::rlim_t::try_from(reserved).unwrap_or(libc::RLIM_INFINITY);
    // Not `saturating_sub` alone: `rlim_t` is signed on FreeBSD, where it
    // goes below zero, and the conversion below then fails and gives `max`
    // (#288).
    if soft <= reserved {
        return 0;
    }
    usize::try_from(soft - reserved).map_or(max, |n| n.min(max))
}

/// Raises the soft open-file limit toward what `max` clients need, never past
/// the hard limit, and gives how many of them it then leaves room for.
#[cfg(unix)]
pub fn clients_that_fit(max: usize) -> std::io::Result<usize> {
    let mut limit = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: `limit` is a valid rlimit for getrlimit to fill in.
    if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
        return Err(std::io::Error::last_os_error());
    }
    let reserved = reserved_fds();
    let wanted =
        libc::rlim_t::try_from(max.saturating_add(reserved)).unwrap_or(libc::RLIM_INFINITY);
    // The most that is taken: macOS refuses more than kern.maxfilesperproc,
    // whatever the hard limit says.
    let (mut soft, mut high) = (limit.rlim_cur, wanted.min(limit.rlim_max));
    while soft < high {
        // Half the gap, rounded up. Not `div_ceil`: `rlim_t` is signed on
        // FreeBSD, where `div_ceil` is not stable (#288).
        let gap = high - soft;
        let next = soft + gap / 2 + gap % 2;
        let raised = libc::rlimit {
            rlim_cur: next,
            rlim_max: limit.rlim_max,
        };
        // SAFETY: `raised` is a valid rlimit.
        if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raised) } == 0 {
            soft = next;
        } else {
            high = next - 1;
        }
    }
    Ok(clients_for(soft, max, reserved))
}

#[cfg(not(unix))]
pub fn clients_that_fit(max: usize) -> std::io::Result<usize> {
    Ok(max)
}

/// At startup, makes room under the open-file limit for `maxclients`, or
/// lowers it to what fits. `Err` when not even one client would, or the
/// limit can't be read.
pub fn fit_max_clients(uring_workers: usize) -> Result<(), String> {
    URING_WORKERS.store(uring_workers, Ordering::Relaxed);
    let max = max_clients();
    let reserved = reserved_fds();
    let fits = clients_that_fit(max).map_err(|e| format!("Can't read the open-file limit: {e}"))?;
    if fits == 0 {
        return Err(format!(
            "The open-file limit (ulimit -n) is too low: KiviDB needs at least {}",
            reserved + 1
        ));
    }
    if fits < max {
        crate::log_warn!(
            "maxclients {max} needs {} open files, but the limit (ulimit -n) allows {}: \
             maxclients is {fits}",
            max.saturating_add(reserved),
            fits + reserved
        );
        crate::commands::server::config_set_global("maxclients", &fits.to_string());
    }
    Ok(())
}

/// What a plaintext client turned away for `maxclients` is told, as Redis
/// tells it.
pub const TOO_MANY_CLIENTS: &[u8] = b"-ERR max number of clients reached\r\n";

/// Tell a plaintext client turned away for `maxclients` why, and close it.
pub fn turn_away(mut socket: tokio::net::TcpStream) {
    tokio::spawn(async move {
        use tokio::io::AsyncWriteExt;
        let _ = socket.write_all(TOO_MANY_CLIENTS).await;
    });
}

/// A replica's link to its master, listed among its clients as Redis lists
/// it: `flags=M`, `TYPE master`, by the master's address. `CLIENT KILL` ends
/// the link, and the replica connects again and continues from where it
/// stands (#595). Taken off the list when dropped.
pub struct MasterLink {
    registry: ClientRegistry,
    id: u64,
    activity: Arc<Activity>,
    kill_rx: KillRx,
    /// Until it is known to have been taken off the list other than by a
    /// kill: its `kill_rx` is then done with.
    listed: bool,
}

impl MasterLink {
    pub fn register(registry: &ClientRegistry, addr: String, laddr: String) -> Self {
        let id = next_client_id();
        let (mut info, killed) = ClientInfo::new(id, addr);
        info.laddr = laddr;
        info.flags = "M".to_string();
        // Redis's master client has no ACL user.
        info.user = "(superuser)".to_string();
        let activity = Arc::clone(&info.activity);
        registry.register(info);
        Self {
            registry: Arc::clone(registry),
            id,
            activity,
            kill_rx: killed,
            listed: true,
        }
    }

    /// Resolves when the link is killed (`CLIENT KILL`), and never
    /// otherwise. Cancel-safe: it may be raced and dropped again and again.
    pub async fn killed(&mut self) {
        if self.listed {
            if (&mut self.kill_rx).await.is_ok() {
                return;
            }
            self.listed = false;
        }
        std::future::pending::<()>().await;
    }

    /// The master has sent something: the link is not idle.
    pub fn touch(&self) {
        self.activity.touch();
    }
}

impl Drop for MasterLink {
    fn drop(&mut self) {
        self.registry.unregister(self.id);
    }
}

/// A connection's place under `maxclients`, given back when dropped.
pub struct Slot(ClientRegistry);

impl Drop for Slot {
    fn drop(&mut self) {
        self.0.slots.fetch_sub(1, Ordering::Relaxed);
    }
}

/// A place for a connection just accepted, or `None` when `maxclients` are
/// connected and it is to be closed. Never waits.
pub fn admit(registry: &ClientRegistry) -> Option<Slot> {
    let max = MAX_CLIENTS.load(Ordering::Relaxed);
    let slot = ClientRegistryInner::admit_up_to(registry, max);
    if slot.is_none() {
        crate::stats::REJECTED_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
        crate::log_throttled!(
            10,
            crate::loglevel::WARN,
            "{max} clients connected (maxclients); closing new connections"
        );
    }
    slot
}

impl ClientRegistryInner {
    pub fn new() -> Self {
        Self {
            clients: RwLock::new(AHashMap::new()),
            slots: AtomicUsize::new(0),
        }
    }

    fn admit_up_to(registry: &ClientRegistry, max: usize) -> Option<Slot> {
        let mut n = registry.slots.load(Ordering::Relaxed);
        loop {
            if n >= max {
                return None;
            }
            match registry.slots.compare_exchange_weak(
                n,
                n + 1,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return Some(Slot(Arc::clone(registry))),
                Err(now) => n = now,
            }
        }
    }

    #[cfg(test)]
    pub(crate) fn slots_held(&self) -> usize {
        self.slots.load(Ordering::Relaxed)
    }

    pub fn register(&self, info: ClientInfo) {
        log_verbose!("Client id={} connected from {}", info.id, info.addr);
        self.clients.write().insert(info.id, info);
    }

    pub fn unregister(&self, id: u64) {
        let gone = self.clients.write().remove(&id);
        if gone.as_ref().is_some_and(|info| info.blocked_with_timeout) {
            IN_TIMEOUT_TABLE.fetch_sub(1, Ordering::Relaxed);
        }
        if let Some(info) = gone.as_ref() {
            log_verbose!(
                "Client id={} ({}{}) disconnected after {:.1}s",
                id,
                info.addr,
                if info.name.is_empty() {
                    String::new()
                } else {
                    format!(", name={}", info.name)
                },
                info.connected_at.elapsed().as_secs_f64()
            );
        }
        Self::no_longer_tracking(gone);
        // Per-connection state kept outside the registry goes with it.
        crate::commands::hash_import::forget_client(id);
    }

    /// Connected client count without cloning every `ClientInfo` (INFO used to
    /// call `list().len()`, which copied addr/name/last_cmd and the push
    /// channel handle on every scrape).
    pub fn len(&self) -> usize {
        self.clients.read().len()
    }

    pub fn is_empty(&self) -> bool {
        self.clients.read().is_empty()
    }

    /// `connected_clients`: the clients less the replicas' links, as Redis
    /// counts them.
    pub fn connected_clients(&self) -> usize {
        self.clients
            .read()
            .values()
            .filter(|info| !info.flags.contains('S'))
            .count()
    }

    /// The client has begun to wait in a blocking command (`Some`), or has
    /// stopped (`None`).
    pub fn set_blocked(
        &self,
        id: u64,
        unblock: Option<oneshot::Sender<crate::commands::blocking::Unblock>>,
        with_timeout: bool,
    ) {
        let blocked = unblock.is_some();
        if let Some(info) = self.clients.write().get_mut(&id) {
            info.unblock_tx = unblock;
            info.blocked = blocked;
            let counted = blocked && with_timeout;
            if counted != info.blocked_with_timeout {
                if counted {
                    IN_TIMEOUT_TABLE.fetch_add(1, Ordering::Relaxed);
                } else {
                    IN_TIMEOUT_TABLE.fetch_sub(1, Ordering::Relaxed);
                }
                info.blocked_with_timeout = counted;
            }
        }
        if blocked {
            crate::pause::went_on(id);
        }
    }

    /// Client `id` waits in a command that is no key's (`WAIT`): blocked,
    /// counted in `blocked_clients`, and ended by `CLIENT UNBLOCK` through
    /// `unblock`, until what this returns is dropped.
    pub fn blocked_in(
        &self,
        id: u64,
        unblock: oneshot::Sender<crate::commands::blocking::Unblock>,
        with_timeout: bool,
    ) -> BlockedIn<'_> {
        self.set_blocked(id, Some(unblock), with_timeout);
        crate::stats::BLOCKED_CLIENTS.fetch_add(1, Ordering::Relaxed);
        BlockedIn { registry: self, id }
    }

    /// `CLIENT UNBLOCK`: end the client's wait, if it is waiting.
    pub fn unblock(&self, id: u64, how: crate::commands::blocking::Unblock) -> bool {
        let sender = self
            .clients
            .write()
            .get_mut(&id)
            .and_then(|info| info.unblock_tx.take());
        sender.is_some_and(|tx| tx.send(how).is_ok())
    }

    /// `clients_in_timeout_table` (#158): clients blocked with a timeout.
    pub fn in_timeout_table() -> u64 {
        IN_TIMEOUT_TABLE.load(Ordering::Relaxed)
    }

    /// This node has become a replica: every client waiting in a blocking
    /// command is answered `-UNBLOCKED … (master -> replica?)` and its
    /// connection closed, as Redis's `disconnectAllBlockedClients` does
    /// (#591). A client paused by `CLIENT PAUSE` is not blocked, and is let
    /// be, as in Redis. Returns how many were ended.
    pub fn end_blocked_for_role_change(&self) -> usize {
        let senders: Vec<_> = self
            .clients
            .write()
            .values_mut()
            .filter_map(|info| info.unblock_tx.take())
            .collect();
        senders
            .into_iter()
            .filter_map(|tx| tx.send(crate::commands::blocking::Unblock::RoleChange).ok())
            .count()
    }

    /// What the clients' query buffers hold, the replicas' apart:
    /// `(mem_clients_normal, mem_clients_slaves)` (#152).
    pub fn buffer_totals(&self) -> (u64, u64) {
        let (mut normal, mut replicas) = (0u64, 0u64);
        for info in self.clients.read().values() {
            let (len, free) = info.query_buffer.values();
            if info.flags.contains('S') {
                replicas += len + free;
            } else {
                normal += len + free;
            }
        }
        (normal, replicas)
    }

    pub fn register_push_tx(&self, id: u64, tx: mpsc::Sender<Vec<u8>>) {
        if let Some(info) = self.clients.write().get_mut(&id) {
            info.push_tx = Some(tx);
        }
    }

    /// `n` commands run by a script client `id` ran: see
    /// [`Activity::add_commands`].
    pub fn add_commands(&self, id: u64, n: u64) {
        if let Some(info) = self.clients.read().get(&id) {
            info.activity.add_commands(n);
        }
    }

    /// Send the kill signal to a client. Returns true if the client was found
    /// and the signal was sent, false if no such client exists or was already killed.
    pub fn kill(&self, id: u64) -> bool {
        let mut clients = self.clients.write();
        let should_remove = if let Some(info) = clients.get_mut(&id) {
            if let Some(tx) = info.kill_tx.take() {
                let _ = tx.send(());
                true
            } else {
                false
            }
        } else {
            false
        };
        if should_remove {
            clients.remove(&id);
        }
        should_remove
    }

    pub fn update(&self, id: u64, f: impl FnOnce(&mut ClientInfo)) {
        if let Some(info) = self.clients.write().get_mut(&id) {
            f(info);
        }
    }

    pub fn list(&self) -> Vec<ClientInfo> {
        // ClientInfo no longer derives Clone (kill_tx isn't Clone).
        // Build list lines directly instead of cloning.
        self.clients
            .read()
            .values()
            .map(|c| ClientInfo {
                id: c.id,
                addr: c.addr.clone(),
                laddr: c.laddr.clone(),
                user: c.user.clone(),
                name: c.name.clone(),
                db: c.db,
                flags: c.flags.clone(),
                connected_at: c.connected_at,
                activity: Arc::clone(&c.activity),
                query_buffer: Arc::clone(&c.query_buffer),
                no_evict: c.no_evict,
                blocked: c.blocked,
                asking: c.asking,
                readonly: c.readonly,
                tracking: c.tracking,
                tracking_bcast: c.tracking_bcast,
                tracking_prefixes: c.tracking_prefixes.clone(),
                tracking_redirect: c.tracking_redirect,
                tracking_redirect_broken: c.tracking_redirect_broken,
                push_tx: c.push_tx.clone(),
                kill_tx: None,
                unblock_tx: None,
                blocked_with_timeout: false,
                tracking_optin: c.tracking_optin,
                tracking_optout: c.tracking_optout,
                tracking_caching_next: c.tracking_caching_next,
                tracking_noloop: c.tracking_noloop,
                lib_name: c.lib_name.clone(),
                lib_ver: c.lib_ver.clone(),
                resp: c.resp,
                replica_listening_port: c.replica_listening_port,
                replica_takes_digest: c.replica_takes_digest,
                replica_lost_data: c.replica_lost_data,
                subscriptions: c.subscriptions,
            })
            .collect()
    }

    pub fn get(&self, id: u64) -> Option<ClientInfo> {
        self.clients.read().get(&id).map(|c| ClientInfo {
            id: c.id,
            addr: c.addr.clone(),
            laddr: c.laddr.clone(),
            user: c.user.clone(),
            name: c.name.clone(),
            db: c.db,
            flags: c.flags.clone(),
            connected_at: c.connected_at,
            activity: Arc::clone(&c.activity),
            query_buffer: Arc::clone(&c.query_buffer),
            no_evict: c.no_evict,
            blocked: c.blocked,
            asking: c.asking,
            readonly: c.readonly,
            kill_tx: None,
            unblock_tx: None,
            blocked_with_timeout: false,
            tracking: c.tracking,
            tracking_bcast: c.tracking_bcast,
            tracking_prefixes: c.tracking_prefixes.clone(),
            tracking_redirect: c.tracking_redirect,
            tracking_redirect_broken: c.tracking_redirect_broken,
            push_tx: c.push_tx.clone(),
            tracking_optin: c.tracking_optin,
            tracking_optout: c.tracking_optout,
            tracking_caching_next: c.tracking_caching_next,
            tracking_noloop: c.tracking_noloop,
            lib_name: c.lib_name.clone(),
            lib_ver: c.lib_ver.clone(),
            resp: c.resp,
            replica_listening_port: c.replica_listening_port,
            replica_takes_digest: c.replica_takes_digest,
            replica_lost_data: c.replica_lost_data,
            subscriptions: c.subscriptions,
        })
    }

    /// Whether the client has issued `READONLY` (cluster replica reads).
    #[inline]
    pub fn get_readonly(&self, id: u64) -> bool {
        self.clients
            .read()
            .get(&id)
            .map(|c| c.readonly)
            .unwrap_or(false)
    }

    #[inline]
    pub fn get_resp(&self, id: u64) -> u8 {
        self.clients.read().get(&id).map(|c| c.resp).unwrap_or(2)
    }

    /// Hot-path accessor for the cluster routing layer. Returns just the
    /// asking flag without cloning the entire ClientInfo. Called on every
    /// command, so it must avoid allocation.
    pub fn get_asking(&self, id: u64) -> bool {
        self.clients
            .read()
            .get(&id)
            .map(|c| c.asking)
            .unwrap_or(false)
    }

    /// `CLIENT LIST`: the lines of the clients `filter` matches, oldest
    /// connection first.
    pub fn list_lines(&self, filter: &ClientFilter, me: u64) -> String {
        let clients = self.clients.read();
        let mut matching: Vec<&ClientInfo> = clients
            .values()
            .filter(|client| filter.matches(client, me))
            .collect();
        matching.sort_by_key(|client| client.id);
        matching
            .iter()
            .map(|client| client.to_list_line())
            .collect()
    }

    /// `CLIENT KILL`: close the clients `filter` matches. Returns how many,
    /// and whether the client that asked is one of them — its connection
    /// closes once it has had its reply.
    /// A client has left the registry: if it had tracking on, there is one
    /// tracking client fewer. Counted here, where the client goes, and not
    /// at the end of its connection's loop — which a connection that ends
    /// on an error, or is killed, does not reach with the client still
    /// listed.
    fn no_longer_tracking(gone: Option<ClientInfo>) {
        if gone.is_some_and(|client| client.tracking) {
            crate::tracking::TRACKING_CLIENT_COUNT.fetch_sub(1, Ordering::Relaxed);
        }
    }

    pub fn kill_matching(&self, filter: &ClientFilter, me: u64) -> (usize, bool) {
        let mut clients = self.clients.write();
        let ids: Vec<u64> = clients
            .values()
            .filter(|client| filter.matches(client, me))
            .map(|client| client.id)
            .collect();
        let mut killed = 0;
        for id in &ids {
            if let Some(client) = clients.get_mut(id)
                && let Some(tx) = client.kill_tx.take()
            {
                // The one asking still has a reply to be sent: its
                // connection closes once that is written.
                if *id == me {
                    client
                        .activity
                        .closing_after_reply
                        .store(true, Ordering::Relaxed);
                }
                let _ = tx.send(());
                killed += 1;
            }
            // And it stays listed until its connection has closed.
            if *id != me {
                Self::no_longer_tracking(clients.remove(id));
            }
        }
        (killed, ids.contains(&me))
    }

    /// The clients with tracking on.
    pub fn tracking_ids(&self) -> Vec<u64> {
        self.clients
            .read()
            .values()
            .filter(|client| client.tracking)
            .map(|client| client.id)
            .collect()
    }

    pub fn find_by_addr(&self, addr: &str) -> Option<u64> {
        self.clients
            .read()
            .values()
            .find(|c| c.addr == addr)
            .map(|c| c.id)
    }
}

pub fn new_client_registry() -> ClientRegistry {
    Arc::new(ClientRegistryInner::new())
}

impl Default for ClientRegistryInner {
    fn default() -> Self {
        Self::new()
    }
}

/// See [`ClientRegistry::blocked_in`]: the client stops being blocked when
/// this is dropped.
pub struct BlockedIn<'a> {
    registry: &'a ClientRegistryInner,
    id: u64,
}

impl Drop for BlockedIn<'_> {
    fn drop(&mut self) {
        self.registry.set_blocked(self.id, None, false);
        crate::stats::BLOCKED_CLIENTS.fetch_sub(1, Ordering::Relaxed);
    }
}

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

    #[test]
    fn slots_stop_at_the_limit_and_come_back_when_dropped() {
        let registry = new_client_registry();
        let held: Vec<_> = std::iter::from_fn(|| ClientRegistryInner::admit_up_to(&registry, 3))
            .take(10)
            .collect();
        assert_eq!(held.len(), 3);
        assert_eq!(registry.slots_held(), 3);
        drop(held);
        assert_eq!(registry.slots_held(), 0);
        assert!(ClientRegistryInner::admit_up_to(&registry, 3).is_some());
        assert!(ClientRegistryInner::admit_up_to(&registry, 0).is_none());
    }

    /// Taken at once from many threads, no more than the limit are given.
    #[test]
    fn slots_taken_at_once_never_pass_the_limit() {
        let registry = new_client_registry();
        let held = std::thread::scope(|s| {
            let threads: Vec<_> = (0..8)
                .map(|_| {
                    s.spawn(|| {
                        (0..100)
                            .filter_map(|_| ClientRegistryInner::admit_up_to(&registry, 50))
                            .collect::<Vec<_>>()
                    })
                })
                .collect();
            threads
                .into_iter()
                .flat_map(|t| t.join().unwrap())
                .collect::<Vec<_>>()
        });
        assert_eq!(held.len(), 50);
        drop(held);
        assert_eq!(registry.slots_held(), 0);
    }

    #[cfg(unix)]
    #[test]
    fn clients_fit_under_the_open_file_limit_less_what_is_reserved() {
        use super::clients_for;
        assert_eq!(clients_for(10_032, 10_000, 32), 10_000);
        assert_eq!(clients_for(1_024, 10_000, 32), 992);
        assert_eq!(clients_for(1_024, 10_000, 72), 952);
        assert_eq!(clients_for(33, 10_000, 32), 1);
        assert_eq!(clients_for(32, 10_000, 32), 0);
        assert_eq!(clients_for(0, 10_000, 32), 0);
        assert_eq!(
            clients_for(libc::RLIM_INFINITY, u32::MAX as usize, 32),
            u32::MAX as usize
        );
        assert_eq!(clients_for(1_024, 10_000, usize::MAX), 0);
    }

    fn after(commands: &[&[&str]]) -> String {
        let activity = Activity::default();
        for command in commands {
            let cmd: Vec<&[u8]> = command.iter().map(|word| word.as_bytes()).collect();
            activity.record(&cmd, 3);
        }
        assert_eq!(activity.db(), 3);
        activity.last_cmd()
    }

    #[test]
    fn the_last_command_is_the_one_shown() {
        assert_eq!(Activity::default().last_cmd(), "NULL");
        assert_eq!(after(&[&["GET", "key"]]), "get");
        assert_eq!(after(&[&["Client", "LIST"]]), "client|list");
        assert_eq!(after(&[&["PING"]]), "ping");
    }

    /// A shorter name after a longer one: nothing of the longer one is left
    /// showing, though its later bytes are still where they were written.
    #[test]
    fn a_shorter_command_after_a_longer_one() {
        assert_eq!(
            after(&[
                &["GEORADIUSBYMEMBER_RO", "a-long-key-name-here"],
                &["GET", "k"]
            ]),
            "get"
        );
        assert_eq!(
            after(&[&["CLIENT", "NO-EVICT-AND-MORE"], &["CONFIG", "GET"]]),
            "config|get"
        );
        assert_eq!(after(&[&["CLIENT", "TRACKINGINFO"], &["CLIENT"]]), "client");
        // Names are kept to their first 24 bytes; a subcommand is of 16 at
        // most.
        assert_eq!(
            after(&[&["ABCDEFGHIJKLMNOPQRSTUVWXYZ0123"]]),
            "abcdefghijklmnopqrstuvwx"
        );
        assert_eq!(
            after(&[&["CLIENT", "ABCDEFGHIJKLMNOP"]]),
            "client|abcdefghijklmnop"
        );
        assert_eq!(after(&[&["CLIENT", "ABCDEFGHIJKLMNOPQ"]]), "client");
    }

    /// A client that has just been created is idle only for the instant since.
    #[test]
    fn a_new_client_has_hardly_been_idle() {
        let activity = Activity::default();
        activity.touch();
        assert!(activity.idle_seconds() <= 1);
    }

    /// Idle time is the gap between the last interaction and now, and it
    /// grows as that gap widens.
    #[test]
    fn idle_time_grows_with_the_clock() {
        let activity = Activity::default();
        activity.touch();
        let at = activity.interaction_at();
        assert_eq!(activity.idle_seconds_at(at), 0);
        assert_eq!(activity.idle_seconds_at(at + 5), 5);
        assert_eq!(activity.idle_seconds_at(at + 30), 30);
    }

    /// An interaction from now clears the idle time.
    #[test]
    fn interacting_resets_the_idle_clock() {
        let activity = Activity::default();
        activity.touch();
        let at = activity.interaction_at();
        assert_eq!(activity.idle_seconds_at(at + 42), 42);
        // A later interaction moves the recorded point to that later time.
        activity.last_interaction.store(at + 42, Ordering::Relaxed);
        assert_eq!(activity.idle_seconds_at(at + 42), 0);
        assert_eq!(activity.idle_seconds_at(at + 45), 3);
    }

    /// Reading the idle time does not itself count as an interaction, so a
    /// `CLIENT LIST` of a client leaves its timer running.
    #[test]
    fn reading_the_idle_time_does_not_reset_it() {
        let activity = Activity::default();
        activity.touch();
        let at = activity.interaction_at();
        // Several reads at the same clock reading keep the same interaction
        // point, so the reported idle never falls back to zero by being read.
        assert_eq!(activity.interaction_at(), at);
        assert_eq!(activity.idle_seconds_at(at + 7), 7);
        assert_eq!(activity.interaction_at(), at);
        assert_eq!(activity.idle_seconds_at(at + 7), 7);
        assert_eq!(activity.interaction_at(), at);
    }

    /// A socket read is the interaction: `touch` restarts the idle clock.
    /// `record` — the per-command bookkeeping — must not, so a pipeline of
    /// commands that arrived in one read does not keep pushing the clock.
    #[test]
    fn a_socket_read_resets_the_idle_clock_but_a_command_does_not() {
        let activity = Activity::default();
        activity.touch();
        let read_at = activity.interaction_at();
        assert_eq!(activity.idle_seconds_at(read_at + 20), 20);

        // Commands arrive from one read: recording them leaves the clock alone.
        activity.record(&[b"PING"], 0);
        activity.record(&[b"GET", b"k"], 0);
        assert_eq!(activity.interaction_at(), read_at);
        assert_eq!(activity.idle_seconds_at(read_at + 20), 20);

        // The next socket read is the interaction, and it restarts the clock.
        activity
            .last_interaction
            .store(read_at + 20, Ordering::Relaxed);
        assert_eq!(activity.idle_seconds_at(read_at + 20), 0);
        assert_eq!(activity.idle_seconds_at(read_at + 23), 3);
    }
}