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
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};

pub struct SlowLogEntry {
    pub id: u64,
    pub timestamp: u64,    // Unix seconds when command started
    pub duration_us: u64,  // execution time in microseconds
    pub cmd: Vec<Vec<u8>>, // command tokens (truncated), as sent
    pub client_addr: String,
    pub client_name: String,
    /// The command's argument count before truncation, command name included
    /// (the seventh element of a `SLOWLOG GET` entry, Redis 8.10).
    pub argc: usize,
}

pub struct SlowLog {
    entries: parking_lot::RwLock<std::collections::VecDeque<SlowLogEntry>>,
    next_id: AtomicU64,
    max_len: AtomicU64,      // was usize — needs to be runtime-mutable too
    threshold_us: AtomicU64, // was u64
    /// `slowlog-entry-max-argc` / `slowlog-entry-max-string-len` (Redis 8.8).
    entry_max_argc: AtomicU64,
    entry_max_string_len: AtomicU64,
    /// Totals for `INFO stats` (Redis 8.8). They count every command that
    /// crossed the threshold, including ones since trimmed out of the log.
    commands_count: AtomicU64,
    commands_time_us_sum: AtomicU64,
    commands_time_us_max: AtomicU64,
    /// The same totals per command name (lowercase): `(count, sum µs, max µs)`.
    per_command: parking_lot::Mutex<std::collections::BTreeMap<String, (u64, u64, u64)>>,
}

pub type SharedSlowLog = Arc<SlowLog>;

/// Redis's defaults for `slowlog-entry-max-argc` and
/// `slowlog-entry-max-string-len`.
pub const DEFAULT_ENTRY_MAX_ARGC: usize = 32;
pub const DEFAULT_ENTRY_MAX_STRING_LEN: usize = 128;

pub fn new_slowlog(threshold_us: u64, max_len: usize) -> SharedSlowLog {
    Arc::new(SlowLog {
        entries: parking_lot::RwLock::new(std::collections::VecDeque::new()),
        next_id: AtomicU64::new(0),
        max_len: AtomicU64::new(max_len as u64),
        threshold_us: AtomicU64::new(threshold_us),
        entry_max_argc: AtomicU64::new(DEFAULT_ENTRY_MAX_ARGC as u64),
        entry_max_string_len: AtomicU64::new(DEFAULT_ENTRY_MAX_STRING_LEN as u64),
        commands_count: AtomicU64::new(0),
        commands_time_us_sum: AtomicU64::new(0),
        commands_time_us_max: AtomicU64::new(0),
        per_command: parking_lot::Mutex::new(std::collections::BTreeMap::new()),
    })
}

/// A slow log carrying the limits from `config`.
pub fn new_slowlog_from_config(config: &crate::config::Config) -> SharedSlowLog {
    let log = new_slowlog(config.slowlog_log_slower_than, config.slowlog_max_len);
    log.set_entry_max_argc(config.slowlog_entry_max_argc);
    log.set_entry_max_string_len(config.slowlog_entry_max_string_len);
    log
}

/// What `SLOWLOG` and `MONITOR` show in place of a secret, as Redis does.
pub const REDACTED: &[u8] = b"(redacted)";

/// The settings whose values are secrets: `CONFIG SET` of one is shown in
/// `SLOWLOG` and `MONITOR`, and written to the server log, without its value.
pub const SECRET_SETTINGS: &[&str] = &[
    "requirepass",
    "masterauth",
    "primaryauth",
    "cluster-bus-secret",
    "tls-key-file-pass",
    "tls-client-key-file-pass",
];

/// `cmd` as `SLOWLOG` and `MONITOR` may show it: passwords and secret
/// settings replaced by [`REDACTED`]. `None` when it holds none, which is
/// nearly always. As in Redis.
///
/// - `AUTH`: every argument.
/// - `HELLO ... AUTH username password`: the two after `AUTH`.
/// - `MIGRATE ... AUTH password` / `AUTH2 username password`: what follows.
/// - `ACL SETUSER name rule ...`: every rule, passwords and hashes among them.
/// - `CONFIG SET name value ...`: the value of a secret setting.
pub fn redact<A: AsRef<[u8]>>(cmd: &[A]) -> Option<Vec<Vec<u8>>> {
    let arg = |i: usize| cmd.get(i).map(AsRef::as_ref);
    let is = |i: usize, word: &str| arg(i).is_some_and(|a| a.eq_ignore_ascii_case(word.as_bytes()));
    // Nearly every command logged is none of these: it costs a look at its
    // name, and nothing is allocated for it, which matters when every
    // command is logged (`slowlog-log-slower-than 0`).
    if !["AUTH", "HELLO", "MIGRATE", "ACL", "CONFIG"]
        .iter()
        .any(|name| is(0, name))
    {
        return None;
    }
    let mut secret = vec![false; cmd.len()];
    let mut mark = |from: usize, count: usize| {
        for flag in secret.iter_mut().skip(from).take(count) {
            *flag = true;
        }
    };
    if is(0, "AUTH") {
        mark(1, cmd.len());
    } else if is(0, "HELLO") {
        for i in 2..cmd.len() {
            if is(i, "AUTH") {
                mark(i + 1, 2);
            }
        }
    } else if is(0, "MIGRATE") {
        // Past host, port, key, db and timeout.
        for i in 6..cmd.len() {
            if is(i, "KEYS") {
                break;
            }
            if is(i, "AUTH") {
                mark(i + 1, 1);
            } else if is(i, "AUTH2") {
                mark(i + 1, 2);
            }
        }
    } else if is(0, "ACL") && is(1, "SETUSER") {
        mark(3, cmd.len());
    } else if is(0, "CONFIG") && is(1, "SET") {
        let mut i = 2;
        while i + 1 < cmd.len() {
            if SECRET_SETTINGS.iter().any(|name| is(i, name)) {
                mark(i + 1, 1);
            }
            i += 2;
        }
    }
    if !secret.contains(&true) {
        return None;
    }
    Some(
        cmd.iter()
            .zip(secret)
            .map(|(a, hide)| {
                if hide {
                    REDACTED.to_vec()
                } else {
                    a.as_ref().to_vec()
                }
            })
            .collect(),
    )
}

/// The logged form of a command: at most `max_argc` arguments, each at most
/// `max_string_len` bytes, with what was cut described in place — the same
/// shape Redis logs.
///
/// A command with more arguments than the limit keeps `max_argc - 1` of them
/// and ends with `... (N more arguments)`. An argument longer than the limit
/// is cut and suffixed with `... (N more bytes)`.
pub fn truncate_command<A: AsRef<[u8]>>(
    cmd: &[A],
    max_argc: usize,
    max_string_len: usize,
) -> Vec<Vec<u8>> {
    // A limit of 0 would log nothing at all, not even the command name.
    let max_argc = max_argc.max(1);
    let kept = if cmd.len() > max_argc {
        max_argc - 1
    } else {
        cmd.len()
    };
    let mut out: Vec<Vec<u8>> = cmd[..kept]
        .iter()
        .map(|arg| {
            let arg = arg.as_ref();
            if arg.len() > max_string_len {
                let mut cut = arg[..max_string_len].to_vec();
                cut.extend_from_slice(
                    format!("... ({} more bytes)", arg.len() - max_string_len).as_bytes(),
                );
                cut
            } else {
                arg.to_vec()
            }
        })
        .collect();
    if cmd.len() > max_argc {
        out.push(format!("... ({} more arguments)", cmd.len() - kept).into_bytes());
    }
    out
}

impl SlowLog {
    pub fn threshold_us(&self) -> u64 {
        self.threshold_us.load(Ordering::Relaxed)
    }

    pub fn set_threshold_us(&self, v: u64) {
        self.threshold_us.store(v, Ordering::Relaxed);
    }

    pub fn set_max_len(&self, v: usize) {
        self.max_len.store(v as u64, Ordering::Relaxed);
        // Trim entries if the new limit is smaller than current size
        let mut e = self.entries.write();
        while e.len() > v {
            e.pop_back();
        }
    }

    pub fn entry_max_argc(&self) -> usize {
        self.entry_max_argc.load(Ordering::Relaxed) as usize
    }

    pub fn set_entry_max_argc(&self, v: usize) {
        self.entry_max_argc.store(v as u64, Ordering::Relaxed);
    }

    pub fn entry_max_string_len(&self) -> usize {
        self.entry_max_string_len.load(Ordering::Relaxed) as usize
    }

    pub fn set_entry_max_string_len(&self, v: usize) {
        self.entry_max_string_len.store(v as u64, Ordering::Relaxed);
    }

    /// `(count, total microseconds, max microseconds)` over every command that
    /// has crossed the threshold since startup or `CONFIG RESETSTAT`.
    pub fn totals(&self) -> (u64, u64, u64) {
        (
            self.commands_count.load(Ordering::Relaxed),
            self.commands_time_us_sum.load(Ordering::Relaxed),
            self.commands_time_us_max.load(Ordering::Relaxed),
        )
    }

    pub fn reset_totals(&self) {
        self.commands_count.store(0, Ordering::Relaxed);
        self.commands_time_us_sum.store(0, Ordering::Relaxed);
        self.commands_time_us_max.store(0, Ordering::Relaxed);
        self.per_command.lock().clear();
    }

    /// The same three numbers per command name (lowercase), for
    /// `INFO commandstats`. Only commands that have been logged appear.
    pub fn per_command_totals(&self) -> Vec<(String, (u64, u64, u64))> {
        self.per_command
            .lock()
            .iter()
            .map(|(name, totals)| (name.clone(), *totals))
            .collect()
    }

    /// Log one command that ran for `duration_us`.
    ///
    /// The single place an entry is built, so the truncation limits and the
    /// totals apply to every path that logs — there used to be eight copies of
    /// this, each with its own hardcoded limits.
    pub fn record<A: AsRef<[u8]>>(
        &self,
        cmd: &[A],
        duration_us: u64,
        client_addr: &str,
        client_name: String,
    ) {
        self.commands_count.fetch_add(1, Ordering::Relaxed);
        self.commands_time_us_sum
            .fetch_add(duration_us, Ordering::Relaxed);
        self.commands_time_us_max
            .fetch_max(duration_us, Ordering::Relaxed);
        // Only slow commands get here, so a lock per call is affordable.
        if let Some(name) = cmd.first() {
            let name = String::from_utf8_lossy(name.as_ref()).to_ascii_lowercase();
            let mut per_command = self.per_command.lock();
            let totals = per_command.entry(name).or_insert((0, 0, 0));
            totals.0 += 1;
            totals.1 += duration_us;
            totals.2 = totals.2.max(duration_us);
        }

        self.push(SlowLogEntry {
            id: self.next_id(),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            duration_us,
            cmd: match redact(cmd) {
                Some(shown) => {
                    truncate_command(&shown, self.entry_max_argc(), self.entry_max_string_len())
                }
                None => truncate_command(cmd, self.entry_max_argc(), self.entry_max_string_len()),
            },
            client_addr: client_addr.to_string(),
            client_name,
            argc: cmd.len(),
        });
    }

    pub fn push(&self, entry: SlowLogEntry) {
        let max = self.max_len.load(Ordering::Relaxed) as usize;
        if max == 0 {
            // `slowlog-max-len 0` keeps nothing; without this the entry below
            // would be pushed after a pop from an empty log and stay forever.
            return;
        }
        let mut e = self.entries.write();
        while e.len() >= max {
            e.pop_back();
        }
        e.push_front(entry);
    }

    pub fn get(&self, count: usize) -> Vec<SlowLogEntry> {
        // VecDeque doesn't impl Clone on entries directly; collect manually
        let e = self.entries.read();
        e.iter()
            .take(count)
            .map(|x| SlowLogEntry {
                id: x.id,
                timestamp: x.timestamp,
                duration_us: x.duration_us,
                cmd: x.cmd.clone(),
                client_addr: x.client_addr.clone(),
                client_name: x.client_name.clone(),
                argc: x.argc,
            })
            .collect()
    }

    pub fn reset(&self) {
        self.entries.write().clear();
    }

    pub fn len(&self) -> usize {
        self.entries.read().len()
    }

    pub fn next_id(&self) -> u64 {
        // fetch_add returns the value BEFORE incrementing — exactly what we want
        self.next_id.fetch_add(1, Ordering::Relaxed)
    }

    pub fn len_cap(&self) -> usize {
        self.max_len.load(Ordering::Relaxed) as usize
    }

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

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

    fn shown(cmd: &[&str]) -> Vec<String> {
        match redact(cmd) {
            Some(r) => r
                .into_iter()
                .map(|a| String::from_utf8(a).unwrap())
                .collect(),
            None => cmd.iter().map(|a| a.to_string()).collect(),
        }
    }

    /// Passwords and secret settings never reach `SLOWLOG` or `MONITOR`;
    /// everything else is shown as sent.
    #[test]
    fn secrets_are_redacted_and_nothing_else() {
        let r = "(redacted)";
        assert_eq!(shown(&["AUTH", "pw"]), ["AUTH", r]);
        assert_eq!(shown(&["auth", "alice", "pw"]), ["auth", r, r]);
        assert_eq!(
            shown(&["HELLO", "3", "AUTH", "alice", "pw", "SETNAME", "app"]),
            ["HELLO", "3", "AUTH", r, r, "SETNAME", "app"]
        );
        assert_eq!(
            shown(&[
                "MIGRATE", "h", "6379", "", "0", "5000", "AUTH", "pw", "KEYS", "k"
            ]),
            [
                "MIGRATE", "h", "6379", "", "0", "5000", "AUTH", r, "KEYS", "k"
            ]
        );
        assert_eq!(
            shown(&[
                "MIGRATE", "h", "6379", "k", "0", "5000", "COPY", "AUTH2", "u", "pw"
            ]),
            [
                "MIGRATE", "h", "6379", "k", "0", "5000", "COPY", "AUTH2", r, r
            ]
        );
        // A key called AUTH is a key.
        assert!(redact(&["MIGRATE", "h", "6379", "", "0", "5000", "KEYS", "AUTH"]).is_none());
        assert_eq!(
            shown(&["ACL", "SETUSER", "alice", "on", ">pw", "~*"]),
            ["ACL", "SETUSER", "alice", r, r, r]
        );
        assert_eq!(
            shown(&[
                "CONFIG",
                "SET",
                "maxmemory",
                "1gb",
                "requirepass",
                "pw",
                "MASTERAUTH",
                "x"
            ]),
            [
                "CONFIG",
                "SET",
                "maxmemory",
                "1gb",
                "requirepass",
                r,
                "MASTERAUTH",
                r
            ]
        );
        assert_eq!(
            shown(&[
                "CONFIG",
                "SET",
                "tls-key-file-pass",
                "a",
                "tls-client-key-file-pass",
                "b"
            ]),
            [
                "CONFIG",
                "SET",
                "tls-key-file-pass",
                r,
                "tls-client-key-file-pass",
                r
            ]
        );
        let plain_commands: [&[&str]; 5] = [
            &["SET", "AUTH", "pw"],
            &["CONFIG", "SET", "maxmemory", "1gb"],
            &["CONFIG", "GET", "requirepass"],
            &["ACL", "GETUSER", "alice"],
            &["HELLO", "3"],
        ];
        for plain in plain_commands {
            assert!(redact(plain).is_none(), "{plain:?}");
        }
    }

    /// What `SLOWLOG GET` keeps of a command with a password.
    #[test]
    fn the_slowlog_keeps_no_password() {
        let log = new_slowlog(0, 10);
        log.record(
            &["ACL", "SETUSER", "alice", ">hunter2"],
            5,
            "127.0.0.1:1",
            String::new(),
        );
        log.record(
            &["CONFIG", "SET", "requirepass", "hunter2"],
            5,
            "127.0.0.1:1",
            String::new(),
        );
        for entry in log.get(10) {
            assert!(
                !entry
                    .cmd
                    .iter()
                    .any(|a| a.windows(7).any(|w| w == b"hunter2")),
                "{:?}",
                entry.cmd
            );
        }
    }

    /// An argument that is not text is logged as the bytes it is.
    #[test]
    fn arguments_are_logged_as_their_bytes() {
        let cmd: [&[u8]; 3] = [b"GET", b"\xff\x00k", b"\xfe"];
        assert_eq!(truncate_command(&cmd, 32, 128), cmd.map(<[u8]>::to_vec));
    }

    /// The worked example on the SLOWLOG GET reference page: 33 arguments
    /// against the default limit of 32.
    #[test]
    fn truncation_matches_the_reference_example() {
        let mut cmd: Vec<String> = vec!["SADD".into(), "myset".into()];
        cmd.extend((3..=33).map(|n| n.to_string()));
        assert_eq!(cmd.len(), 33);

        let logged = truncate_command(&cmd, 32, 128);
        assert_eq!(logged.len(), 32);
        assert_eq!(logged[0], b"SADD");
        assert_eq!(logged[30], b"31");
        assert_eq!(logged[31], b"... (2 more arguments)");
    }

    #[test]
    fn a_command_within_the_limits_is_logged_verbatim() {
        let cmd = ["SET", "k", "v"];
        assert_eq!(
            truncate_command(&cmd, 32, 128),
            vec![b"SET".to_vec(), b"k".to_vec(), b"v".to_vec()]
        );
        // Exactly at the argument limit: nothing is cut.
        let cmd: Vec<String> = (0..32).map(|n| n.to_string()).collect();
        assert_eq!(truncate_command(&cmd, 32, 128).len(), 32);
        assert!(!truncate_command(&cmd, 32, 128)[31].starts_with(b"..."));
    }

    #[test]
    fn long_arguments_are_cut_with_a_byte_count() {
        let big = "x".repeat(200);
        let logged = truncate_command(&["SET", "k", big.as_str()], 32, 128);
        assert_eq!(
            logged[2],
            format!("{}... (72 more bytes)", "x".repeat(128)).into_bytes()
        );
    }

    #[test]
    fn record_keeps_the_original_argument_count_and_totals() {
        let sl = new_slowlog(0, 128);
        sl.set_entry_max_argc(4);
        let cmd = ["MSET", "a", "1", "b", "2", "c", "3"];
        sl.record(&cmd, 1_500, "127.0.0.1:1", String::new());
        sl.record(&["PING"], 500, "127.0.0.1:1", String::new());

        let entries = sl.get(10);
        assert_eq!(entries.len(), 2);
        // Newest first.
        assert_eq!(entries[0].argc, 1);
        assert_eq!(entries[1].argc, 7);
        assert_eq!(
            entries[1].cmd,
            ["MSET", "a", "1", "... (4 more arguments)"].map(|a| a.as_bytes().to_vec())
        );
        assert_eq!(sl.totals(), (2, 2_000, 1_500));
    }

    #[test]
    fn max_len_zero_keeps_nothing() {
        let sl = new_slowlog(0, 0);
        sl.record(&["PING"], 1, "a", String::new());
        assert_eq!(sl.len(), 0);
        // ...but the command still counts toward the totals.
        assert_eq!(sl.totals().0, 1);
    }

    #[test]
    fn test_default_threshold_is_disabled() {
        // The default threshold must be u64::MAX (disabled).
        // If this fails, the fast path will call now_us() and latency.record()
        // on every command, causing a ~25x throughput regression.
        let config_default = u64::MAX; // mirrors Config::default slowlog_log_slower_than
        let sl = new_slowlog(config_default, 128);
        assert_eq!(
            sl.threshold_us(),
            u64::MAX,
            "Default slowlog threshold must be u64::MAX (disabled). \
             A lower value causes latency.record() on every fast-path command."
        );
        assert!(
            !sl.threshold_us() < u64::MAX, // i.e. slowlog_enabled = false
            "slowlog_enabled must be false with default config"
        );
    }

    #[test]
    fn test_slowlog_disabled_when_threshold_max() {
        let sl = new_slowlog(u64::MAX, 128);
        // Simulate what server.rs computes per connection
        let slowlog_enabled = sl.threshold_us() < u64::MAX;
        assert!(
            !slowlog_enabled,
            "slowlog_enabled must be false with threshold=u64::MAX"
        );
    }

    #[test]
    fn test_config_default_threshold_is_max() {
        // Directly test the Config struct default
        use crate::config::Config;
        use clap::Parser;
        // Parse with no args — should get all defaults
        let config = Config::parse_from(["kividb"]);
        assert_eq!(
            config.slowlog_log_slower_than,
            u64::MAX,
            "Config default slowlog_log_slower_than must be u64::MAX. \
             Changing this to any lower value (e.g. 10_000) causes a ~25x \
             throughput regression because latency.record() acquires a \
             RwLock write on every command on the fast path."
        );
    }
}

// Compile-time guard: ensure the default threshold constant is sane.
// This doesn't catch Config::parse() defaults but catches hardcoded changes.
#[allow(clippy::assertions_on_constants)]
const _: () = assert!(
    u64::MAX > 10_000_000,
    "slowlog threshold sentinel value looks wrong"
);