Skip to main content

yo_resp/dispatch/
server.rs

1//! The connection and server commands.
2//!
3//! None of these touch a key. They are here because a client library sends most
4//! of them before it sends anything else: a driver opens a socket, says `HELLO
5//! 3`, maybe `SELECT 4`, asks `COMMAND DOCS` or `COMMAND COUNT` to build its
6//! own routing table, and only then does any work. A server that answers `GET`
7//! perfectly and `HELLO` badly is a server no client library can talk to, which
8//! is why these land in the same milestone as the string commands rather than
9//! after them.
10//!
11//! The replies were read off a running Redis 8.8 in both protocols. The shapes
12//! are not obvious from the documentation: `HELLO` is a map on RESP3 and the
13//! same pairs flattened on RESP2, `CONFIG GET` is the same, `INFO` is a
14//! verbatim string on RESP3 and a bulk string on RESP2, and the flags in
15//! `COMMAND INFO` are simple strings inside an array rather than bulk strings.
16
17use super::args::{self, Args, is};
18use super::table::{self, Spec};
19use super::{DATABASES, Flow, Server, Session, backup, cpu};
20use crate::proto::Proto;
21use crate::reply::Out;
22use core::fmt::Write;
23use std::time::{SystemTime, UNIX_EPOCH};
24use yo_common::num::parse_i64;
25use yo_common::{Code, Error, Result, glob};
26use yo_kv::Keyspace;
27use yo_kv::access::Policy;
28
29/// What we tell a client we are.
30///
31/// It is a lie and it is a deliberate one. Every client library in the world
32/// branches on this pair to decide which commands exist, and a driver that
33/// reads `yo` here falls back to its oldest code path or refuses to connect.
34/// Divergence D-12 in `divergences.toml` says so, and the honest answer is in
35/// the `yo_version` field of `INFO` next to this one.
36const REPORTED_SERVER: &str = "redis";
37/// The Redis version we answer 100 percent of, which is what `HELLO` reports.
38///
39/// [`super::backup`] writes it into the `redis-ver` aux field of the base file
40/// it produces, so a server told to load one reads the same version out of the
41/// file that a client reads off the connection.
42pub(super) const REPORTED_VERSION: &str = "8.8.0";
43
44/// The settings that are fixed for the life of the process.
45///
46/// `CONFIG SET` accepts a write to one of these that changes nothing and
47/// refuses everything else rather than pretending to have taken it. A client
48/// that sets `appendonly no` on a server that already has no append only file
49/// gets an `OK` and is telling the truth; one that sets `appendonly yes` gets
50/// told it cannot, which is better than an `OK` and no file.
51const SETTINGS: &[(&str, &str)] = &[
52    ("appendonly", "no"),
53    ("appendfsync", "everysec"),
54    // Where `BACKUP` writes, under `dir`. Fixed here where a real server takes
55    // it at startup, because nothing in this build reads it from a file.
56    ("backupdirname", backup::DIR_NAME),
57    ("databases", "16"),
58    ("io-threads", "1"),
59    ("proto-max-bulk-len", "536870912"),
60    ("save", ""),
61    ("timeout", "0"),
62];
63
64/// Which number on the size ladder a settings name refers to.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66enum Knob {
67    SetIntsetEntries,
68    SetListpackEntries,
69    SetListpackValue,
70    HashListpackEntries,
71    HashListpackValue,
72    MaxmemorySamples,
73    LfuLogFactor,
74    LfuDecayTime,
75}
76
77/// The settings that move the size ladder, which are the ones that really move.
78///
79/// These decide where a collection stops being a packed blob and becomes an
80/// element table, so they decide what `OBJECT ENCODING` answers, and a client
81/// that reads `OBJECT ENCODING` after setting one of these expects the two to
82/// agree. That is the whole reason they are writable when nothing else here is.
83///
84/// The `ziplist` spellings are the names these had before Redis renamed them
85/// and it still answers to both, so this does too. Two names, one number: a
86/// `CONFIG SET hash-max-ziplist-entries 4` shows up under the listpack name
87/// too, which was checked against 8.10.1 rather than assumed.
88///
89/// Moving one of these leaves every collection that already exists exactly as
90/// it is, and only decides what the next write builds. Redis does the same, and
91/// it is the reason `CONFIG SET set-max-listpack-entries 0` does not rewrite
92/// the keyspace.
93///
94/// The three eviction numbers are in here too, which stretches the name a
95/// little. They belong with these rather than with the immutable settings for
96/// the same reason: a client that sets one and then reads `OBJECT FREQ` or
97/// watches `evicted_keys` expects the two to agree. `maxmemory-samples` says how
98/// many keys a round of sampling looks at, and the two `lfu` numbers set what
99/// the counter under an LFU policy actually measures.
100const LADDER: &[(&str, Knob)] = &[
101    ("hash-max-listpack-entries", Knob::HashListpackEntries),
102    ("hash-max-listpack-value", Knob::HashListpackValue),
103    ("hash-max-ziplist-entries", Knob::HashListpackEntries),
104    ("hash-max-ziplist-value", Knob::HashListpackValue),
105    ("lfu-decay-time", Knob::LfuDecayTime),
106    ("lfu-log-factor", Knob::LfuLogFactor),
107    ("maxmemory-samples", Knob::MaxmemorySamples),
108    ("set-max-intset-entries", Knob::SetIntsetEntries),
109    ("set-max-listpack-entries", Knob::SetListpackEntries),
110    ("set-max-listpack-value", Knob::SetListpackValue),
111];
112
113/// The setting that decides which way the access field on every record is read.
114///
115/// It is on its own rather than in [`SETTINGS`] or [`LADDER`] because it is the
116/// only writable setting that is not a number, and rather than immutable because
117/// it really moves: a client that sets it and then reads `OBJECT FREQ` expects
118/// the two to agree, which is the same argument the size ladder makes.
119///
120/// Setting it changes nothing about the keys already stored. Whatever is in
121/// their access field stays there and means something different from the moment
122/// the policy changes, which is what the `OBJECT FREQ` error text warns about.
123const MAXMEMORY_POLICY: &str = "maxmemory-policy";
124
125/// How much the server is allowed to hold before it starts evicting.
126///
127/// Also on its own, and for the third different reason. It is not immutable,
128/// it is not on the size ladder and it is the only setting whose value is not a
129/// plain integer: a client writes `maxmemory 100mb` and means a hundred and
130/// four million bytes, so it needs a parser of its own.
131///
132/// Zero means no limit, which is the default and is what makes the check in
133/// front of every write one comparison. Setting it to a number smaller than
134/// what the server is already holding is allowed and is a real thing to do: the
135/// next write that would allocate evicts until it fits or is refused, which is
136/// what the `maxmemory-policy` decides between.
137const MAXMEMORY: &str = "maxmemory";
138
139/// How much the server is allowed to keep on the file before it starts evicting.
140///
141/// The other half of the eviction inversion `14` section 4.1 describes, and the
142/// only setting here that has no counterpart in Redis. `maxmemory` is a limit on
143/// memory, and the right answer to a memory limit on a system with a file under
144/// it is to move data to the file. Throwing data away is the right answer to a
145/// limit on the file, and this is that limit.
146///
147/// Minus one is no limit and is the default, so a server that never sets this
148/// grows until the disk is full and then refuses writes, which is what a
149/// database does. Zero is a real setting and it means the file may hold nothing,
150/// so migration cannot make room and eviction is all that is left, which is
151/// Redis exactly and is the documented setting for a drop in cache.
152const MAXSTORE: &str = "maxstore";
153
154/// Where the server writes, which `BACKUP LIST` answers paths under.
155///
156/// On its own for a fourth reason: it is readable and not writable, and it is
157/// not writable in a way of its own. Redis calls it a protected config, which
158/// means `CONFIG SET dir` is refused with a sentence about protection rather
159/// than about immutability unless the server was started with protected configs
160/// enabled. That distinction is copied, because the two messages are what an
161/// operator reads when a `CONFIG SET` does not take.
162const DIR: &str = "dir";
163
164/// How long a sealed backup is kept before it cleans itself up.
165///
166/// Seconds, and zero is the default and means it is kept until somebody says
167/// `BACKUP CLEANUP`. Writable, since a backup taken by a script that then died
168/// is exactly the thing this is for and setting it afterwards has to work.
169const SEALED_TTL: &str = "backup-sealed-ttl";
170
171/// Read a byte count the way `CONFIG SET maxmemory` reads one.
172///
173/// This is Redis's `memtoull`. Digits, then an optional unit that is not case
174/// sensitive: nothing or `b` is bytes, `k` is a thousand and `kb` is a kibibyte,
175/// and the same pairing again for `m` and `g`. The two spellings meaning
176/// different numbers is a trap and it is Redis's trap, so it is repeated here
177/// rather than tidied up.
178///
179/// A unit that overflows clamps rather than failing, which is upstream's
180/// `ULLONG_MAX` arm. There is no sign: a leading minus is refused before the
181/// digits are read, so `maxmemory -1` is not a very large number.
182///
183/// Public because `yodb serve` takes the same limits on the command line that
184/// `CONFIG SET` takes at runtime, and a server that accepts `100mb` from one and
185/// not the other, or reads it as a different number, is a server that gets
186/// misconfigured. One parser, one answer.
187#[must_use]
188pub fn parse_memory(value: &[u8]) -> Option<u64> {
189    let split = value
190        .iter()
191        .position(|b| !b.is_ascii_digit())
192        .unwrap_or(value.len());
193    let (digits, unit) = value.split_at(split);
194    if digits.is_empty() {
195        return None;
196    }
197    let mul: u64 = match unit {
198        [] => 1,
199        u if u.eq_ignore_ascii_case(b"b") => 1,
200        u if u.eq_ignore_ascii_case(b"k") => 1000,
201        u if u.eq_ignore_ascii_case(b"kb") => 1024,
202        u if u.eq_ignore_ascii_case(b"m") => 1000 * 1000,
203        u if u.eq_ignore_ascii_case(b"mb") => 1024 * 1024,
204        u if u.eq_ignore_ascii_case(b"g") => 1000 * 1000 * 1000,
205        u if u.eq_ignore_ascii_case(b"gb") => 1024 * 1024 * 1024,
206        _ => return None,
207    };
208    let mut n: u64 = 0;
209    for d in digits {
210        n = n.saturating_mul(10).saturating_add(u64::from(d - b'0'));
211    }
212    Some(n.saturating_mul(mul))
213}
214
215/// Every policy name, joined the way `CONFIG SET` lists them when it refuses one.
216///
217/// This is a formatter and not a string because the error path should not touch
218/// the allocator, and it walks [`Policy::ALL`] rather than spelling the ten names
219/// out again so the two cannot drift apart. The order is the order in Redis's own
220/// enum table, which is the whole reason `Policy::ALL` is written down.
221struct PolicyNames;
222
223impl core::fmt::Display for PolicyNames {
224    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
225        for (at, policy) in Policy::ALL.iter().enumerate() {
226            if at > 0 {
227                f.write_str(", ")?;
228            }
229            f.write_str(policy.name())?;
230        }
231        Ok(())
232    }
233}
234
235/// Run one connection or server command.
236pub(super) fn execute(
237    server: &Server,
238    session: &mut Session,
239    spec: &Spec,
240    args: Args<'_>,
241    out: &mut Out,
242) -> Result<Flow> {
243    match spec.name {
244        // The arity in the table is a minimum of one, and a real server then
245        // refuses a second argument as a wrong number of them.
246        "ping" => {
247            if args.len() > 2 {
248                return Err(args::wrong_arity("ping"));
249            }
250            if args.len() == 2 {
251                out.bulk(args.get(1));
252            } else {
253                out.simple(b"PONG");
254            }
255        }
256        "echo" => out.bulk(args.get(1)),
257        "hello" => hello(session, args, out)?,
258        "select" => {
259            let n = args.int(1)?;
260            let ok = usize::try_from(n).is_ok_and(|n| n < DATABASES);
261            if !ok {
262                return Err(Error::new(Code::Invalid, "DB index is out of range"));
263            }
264            session.db = n as usize;
265            out.ok();
266        }
267        "reset" => {
268            // Everything a connection carries goes back to what it was when it
269            // was opened, and that includes the protocol: a connection that
270            // said `HELLO 3` is speaking RESP2 again after this.
271            session.reset();
272            out.set_proto(Proto::Resp2);
273            out.simple(b"RESET");
274        }
275        // The reply goes out before the socket closes, which is why this is a
276        // flow answer and not something the body does to the connection.
277        "quit" => {
278            out.ok();
279            return Ok(Flow::Close);
280        }
281        "command" => command(args, out)?,
282        "config" => config(server, args, out)?,
283        "info" => info(server, args, out),
284        // A key that is past its deadline and has not been read since is still
285        // counted, which is what Redis does too: `DBSIZE` is the size of the
286        // dictionary and not a walk over it. Redis has an active expiry cycle
287        // that takes those keys out within a tick or so and we do not yet, so
288        // the two servers disagree for as long as a dead key sits unread. That
289        // gap closes with the maintenance slice rather than with a count here,
290        // because a count here would be O(N) on a command that is O(1)
291        // everywhere else.
292        "dbsize" => out.int(server.dbs[session.db].len() as i64),
293        "flushall" => {
294            flush_mode(args)?;
295            for db in &server.dbs {
296                db.clear();
297            }
298            server.search.lock().clear();
299            out.ok();
300        }
301        // The search indexes go too, and they go whichever database this is.
302        // An index that only ever followed keys on database zero is dropped by
303        // a `FLUSHDB` on database nine, which is measured against a real server
304        // rather than reasoned about: the module hangs its callback on the
305        // flush event without looking at which database flushed.
306        "flushdb" => {
307            flush_mode(args)?;
308            server.dbs[session.db].clear();
309            server.search.lock().clear();
310            out.ok();
311        }
312        // Two databases change places and no key moves. What is in the stripes
313        // is exchanged and the databases stay where they are, so this costs two
314        // pointer sized writes per stripe whatever is in either of them, which
315        // is what makes `SWAPDB` fast and dangerous at the same time.
316        //
317        // No connection is told. A client on database zero is still on database
318        // zero and is now looking at what used to be database one, which is the
319        // whole point of the command and is why Redis calls it dangerous. A
320        // client parked in `BLPOP` remembers the database index it blocked on
321        // and not the database, so it wakes up against the swapped in one, which
322        // is Redis's behaviour and falls out of the index being what is stored.
323        "swapdb" => {
324            let first = db_index(args.get(1), "invalid first DB index")?;
325            let second = db_index(args.get(2), "invalid second DB index")?;
326            server.striped(first).swap_with(server.striped(second));
327            out.ok();
328        }
329        "time" => time(out),
330        "backup" => backup::execute(server, args, out)?,
331        "shutdown" => return shutdown(server, args),
332        _ => return Err(args::unknown_command(args)),
333    }
334    Ok(Flow::Continue)
335}
336
337/// `TIME`, which is two bulk strings and not one integer.
338///
339/// Seconds first and then microseconds within that second, both written out as
340/// decimal text, which is a shape nobody would choose today and is the shape
341/// every client library parses.
342///
343/// It reads the wall clock rather than the coarse clock the keyspace uses. The
344/// coarse one is a cached millisecond that a background tick refreshes, which is
345/// the right trade for deciding whether a key has expired and the wrong one for
346/// a command whose entire job is to say what time it is. A client that calls
347/// `TIME` twice in a row and gets the same microsecond has been lied to.
348fn time(out: &mut Out) {
349    let now = SystemTime::now()
350        .duration_since(UNIX_EPOCH)
351        .unwrap_or_default();
352    out.array(2);
353    out.bulk(now.as_secs().to_string().as_bytes());
354    out.bulk(now.subsec_micros().to_string().as_bytes());
355}
356
357// ---------------------------------------------------------------- SHUTDOWN
358
359/// `SHUTDOWN [NOSAVE | SAVE] [NOW] [FORCE] [ABORT]`.
360///
361/// On success this writes nothing at all and the connection closes under the
362/// client, which is what a server that has stopped looks like from the outside
363/// and is what every client library already expects. There is no `OK`, because
364/// an `OK` would be a promise made by a process that is about to not exist.
365///
366/// The flags are taken and none of them changes what happens, which is the same
367/// answer `SAVE` gets from `CONFIG GET`: this server has no save points and no
368/// snapshot to write, so saving and not saving are the same act. What durability
369/// there is belongs to the file underneath and is already on disk by the time a
370/// command returns, so there is nothing for `SAVE` to do and nothing for
371/// `NOSAVE` to skip. `NOW` and `FORCE` are about not waiting for replicas and
372/// about going anyway when a save failed, and neither has anything to wait for
373/// or to fail here.
374///
375/// # Errors
376///
377/// [`Code::Invalid`] for a word that is not one of the five, for `SAVE` and
378/// `NOSAVE` in the same call, and for `ABORT` alongside any other flag, all of
379/// which is what 8.10.1 says. `ABORT` on its own gets Redis's message for a
380/// cancel with nothing to cancel, and here that is not a state that can be
381/// reached rather than one that happens to be empty: a shutdown is decided and
382/// done inside one turn of the loop, so there is never a window in which one is
383/// in progress and a second client could call it off.
384fn shutdown(server: &Server, args: Args<'_>) -> Result<Flow> {
385    let (mut save, mut nosave, mut abort, mut other) = (false, false, false, false);
386    for at in 1..args.len() {
387        let arg = args.get(at);
388        match () {
389            () if is(arg, b"save") => save = true,
390            () if is(arg, b"nosave") => nosave = true,
391            () if is(arg, b"abort") => abort = true,
392            () if is(arg, b"now") || is(arg, b"force") => other = true,
393            () => return Err(args::syntax()),
394        }
395    }
396    // Repeating one is fine and contradicting yourself is not, and `ABORT` says
397    // to do nothing so it cannot be combined with a word about how to do it.
398    if (save && nosave) || (abort && (save || nosave || other)) {
399        return Err(args::syntax());
400    }
401    if abort {
402        return Err(Error::new(Code::Invalid, "No shutdown in progress."));
403    }
404    server.stop();
405    // Closing is what stops anything the client pipelined behind this from
406    // being answered by a server that is on its way out.
407    Ok(Flow::Close)
408}
409
410// ------------------------------------------------------------------- FLUSH
411
412/// Check the optional `ASYNC` or `SYNC` on `FLUSHALL` and `FLUSHDB`.
413///
414/// Both are accepted and neither changes anything. On a real server the choice
415/// is whether the freeing happens on the connection's thread or on the lazy
416/// free thread, and either way the keyspace is empty before the `OK` goes out.
417/// That is the whole of what a client can observe, and it is the same here,
418/// so taking the word and ignoring it is answering the question rather than
419/// pretending to.
420///
421/// # Errors
422///
423/// [`Code::Invalid`] for a third argument, or for a second that is neither
424/// word, which is what Redis says about both.
425fn flush_mode(args: Args<'_>) -> Result<()> {
426    if args.len() == 1 {
427        return Ok(());
428    }
429    if args.len() > 2 || !(is(args.get(1), b"async") || is(args.get(1), b"sync")) {
430        return Err(args::syntax());
431    }
432    Ok(())
433}
434
435/// One of `SWAPDB`'s two database indexes, with Redis's two different
436/// complaints about it.
437///
438/// A word that is not a number, or a number too big to be a database index on a
439/// server that stores the index in a C `int`, gets the caller's message, which
440/// says which of the two arguments was wrong. A number that is a plausible index
441/// and is not one of ours gets the same out of range message `SELECT` gives. The
442/// split looks arbitrary and it is Redis's, and the reason for it is that the
443/// first check happens while reading the argument and the second happens inside
444/// the swap, so only the first one knows which argument it was looking at.
445fn db_index(arg: &[u8], bad: &'static str) -> Result<usize> {
446    let n = parse_i64(arg)
447        .filter(|n| i32::try_from(*n).is_ok())
448        .ok_or_else(|| Error::new(Code::Invalid, bad))?;
449    usize::try_from(n)
450        .ok()
451        .filter(|n| *n < DATABASES)
452        .ok_or_else(|| Error::new(Code::Invalid, "DB index is out of range"))
453}
454
455// ------------------------------------------------------------------- HELLO
456
457/// `HELLO [protover [AUTH username password] [SETNAME name]]`.
458fn hello(session: &mut Session, args: Args<'_>, out: &mut Out) -> Result<()> {
459    if args.len() > 1 {
460        let v = parse_i64(args.get(1)).ok_or_else(|| {
461            Error::new(
462                Code::Invalid,
463                "Protocol version is not an integer or out of range",
464            )
465        })?;
466        let Some(proto) = Proto::from_version(v) else {
467            // `NOPROTO` rather than `ERR`, and it is the one error in this file
468            // written straight into the buffer: the prefix is part of what the
469            // client branches on, and it is the only place in the engine that
470            // needs this one.
471            out.error(b"NOPROTO unsupported protocol version");
472            return Ok(());
473        };
474        let mut i = 2;
475        while i < args.len() {
476            let o = args.get(i);
477            if is(o, b"AUTH") && i + 2 < args.len() {
478                // No password is configured, so the default user is `nopass`
479                // and any password for it is the right one, which is how a
480                // real server with no `requirepass` behaves. Any other user
481                // does not exist.
482                if !is(args.get(i + 1), b"default") {
483                    out.error(b"WRONGPASS invalid username-password pair or user is disabled.");
484                    return Ok(());
485                }
486                i += 3;
487            } else if is(o, b"SETNAME") && i + 1 < args.len() {
488                session.set_name(args.get(i + 1));
489                i += 2;
490            } else {
491                return Err(yo_alloc::allow(|| {
492                    Error::fmt(
493                        Code::Invalid,
494                        format_args!(
495                            "Syntax error in HELLO option '{}'",
496                            String::from_utf8_lossy(o)
497                        ),
498                    )
499                }));
500            }
501        }
502        // The reply is written in the protocol that was just agreed, not the
503        // one the request arrived in.
504        out.set_proto(proto);
505    }
506
507    let proto = out.proto().version();
508    out.map(7);
509    out.bulk(b"server");
510    out.bulk(REPORTED_SERVER.as_bytes());
511    out.bulk(b"version");
512    out.bulk(REPORTED_VERSION.as_bytes());
513    out.bulk(b"proto");
514    out.int(proto);
515    out.bulk(b"id");
516    out.int(session.id as i64);
517    out.bulk(b"mode");
518    out.bulk(b"standalone");
519    out.bulk(b"role");
520    out.bulk(b"master");
521    out.bulk(b"modules");
522    out.array(0);
523    Ok(())
524}
525
526// ----------------------------------------------------------------- COMMAND
527
528/// `COMMAND [COUNT|LIST|INFO|DOCS|GETKEYS|HELP]`.
529fn command(args: Args<'_>, out: &mut Out) -> Result<()> {
530    if args.len() == 1 {
531        out.array(table::COMMANDS.len());
532        for spec in table::COMMANDS {
533            write_spec(out, spec);
534        }
535        return Ok(());
536    }
537    let sub = args.get(1);
538    if is(sub, b"COUNT") {
539        out.int(table::COMMANDS.len() as i64);
540    } else if is(sub, b"INFO") {
541        if args.len() == 2 {
542            out.array(table::COMMANDS.len());
543            for spec in table::COMMANDS {
544                write_spec(out, spec);
545            }
546        } else {
547            out.array(args.len() - 2);
548            for i in 2..args.len() {
549                match table::lookup(args.get(i)) {
550                    Some(spec) => write_spec(out, spec),
551                    // A name nobody has heard of is a null in the list rather
552                    // than an error, so one bad name in a batch does not cost
553                    // the client the other answers. It is the plain null and
554                    // not the array one, which on RESP2 is the difference
555                    // between `$-1` and `*-1` and is what a real server sends.
556                    None => out.nil(),
557                }
558            }
559        }
560    } else if is(sub, b"LIST") {
561        list(args, out)?;
562    } else if is(sub, b"DOCS") {
563        docs(args, out);
564    } else if is(sub, b"GETKEYS") {
565        getkeys(args, out)?;
566    } else if is(sub, b"HELP") {
567        help(out, COMMAND_HELP);
568    } else {
569        return Err(args::unknown_subcommand(sub, "COMMAND"));
570    }
571    Ok(())
572}
573
574/// `COMMAND LIST [FILTERBY MODULE m|ACLCAT c|PATTERN p]`.
575fn list(args: Args<'_>, out: &mut Out) -> Result<()> {
576    if args.len() == 2 {
577        out.array(table::COMMANDS.len());
578        for spec in table::COMMANDS {
579            out.bulk(spec.name.as_bytes());
580        }
581        return Ok(());
582    }
583    if args.len() != 5 || !is(args.get(2), b"FILTERBY") {
584        return Err(args::syntax());
585    }
586    let (how, what) = (args.get(3), args.get(4));
587    let keep = |spec: &Spec| {
588        if is(how, b"MODULE") {
589            // Nothing here came from a module, so every filter by one is empty.
590            false
591        } else if is(how, b"ACLCAT") {
592            spec.acl
593                .iter()
594                .any(|c| c.len() == what.len() + 1 && c.as_bytes()[1..].eq_ignore_ascii_case(what))
595        } else {
596            glob::matches(what, spec.name.as_bytes())
597        }
598    };
599    if !is(how, b"MODULE") && !is(how, b"ACLCAT") && !is(how, b"PATTERN") {
600        return Err(args::syntax());
601    }
602    out.array(table::COMMANDS.iter().filter(|s| keep(s)).count());
603    for spec in table::COMMANDS.iter().filter(|s| keep(s)) {
604        out.bulk(spec.name.as_bytes());
605    }
606    Ok(())
607}
608
609/// `COMMAND DOCS [name ...]`.
610///
611/// The arguments field a real server sends is left out. It describes the shape
612/// of every option of every command in a form nothing but `redis-cli`'s hinting
613/// reads, and getting it wrong would be worse than not sending it, since a
614/// client that finds the field trusts it.
615fn docs(args: Args<'_>, out: &mut Out) {
616    if args.len() == 2 {
617        out.map(table::COMMANDS.len());
618        for spec in table::COMMANDS {
619            write_docs(out, spec);
620        }
621        return;
622    }
623    let found = (2..args.len())
624        .filter(|&i| table::lookup(args.get(i)).is_some())
625        .count();
626    out.map(found);
627    for i in 2..args.len() {
628        if let Some(spec) = table::lookup(args.get(i)) {
629            write_docs(out, spec);
630        }
631    }
632}
633
634/// One command's documentation, as the name and then the map about it.
635fn write_docs(out: &mut Out, spec: &Spec) {
636    out.bulk(spec.name.as_bytes());
637    out.map(4);
638    out.bulk(b"summary");
639    out.bulk(spec.summary.as_bytes());
640    out.bulk(b"since");
641    out.bulk(spec.since.as_bytes());
642    out.bulk(b"group");
643    out.bulk(spec.group.as_bytes());
644    out.bulk(b"complexity");
645    out.bulk(spec.complexity.as_bytes());
646}
647
648/// `COMMAND GETKEYS <full command>`.
649///
650/// This is how a cluster aware client routes a command it does not have a rule
651/// for, so a wrong answer here is a client that sends a write to the wrong
652/// node. The generic path is the first, last and step triple from the table.
653fn getkeys(args: Args<'_>, out: &mut Out) -> Result<()> {
654    if args.len() < 3 {
655        return Err(args::wrong_arity_sub("command", "getkeys"));
656    }
657    let inner = args.get(2);
658    let spec = table::lookup(inner)
659        .ok_or_else(|| Error::new(Code::Unsupported, "Invalid command specified"))?;
660    let argc = args.len() - 2;
661    if !table::arity_ok(spec, argc) {
662        return Err(Error::new(
663            Code::Invalid,
664            "Invalid number of arguments specified for command",
665        ));
666    }
667    // Three commands here keep their keys somewhere the triple cannot describe,
668    // behind a count of how many there are. That is why a real server marks them
669    // `movablekeys` and why a client has to ask this question about them at all.
670    // `MSETEX` counts pairs and the two joined time series reads count single
671    // keys, so the step is the only thing that differs between them.
672    if let Some(step) = match spec.name {
673        "msetex" => Some(2),
674        "ts.nrange" | "ts.nrevrange" => Some(1),
675        _ => None,
676    } {
677        let n = parse_i64(args.get(3))
678            .filter(|&n| n > 0)
679            .and_then(|n| usize::try_from(n).ok())
680            .filter(|&n| 4 + step * n <= args.len())
681            .ok_or_else(|| Error::new(Code::Invalid, "Invalid arguments specified for command"))?;
682        out.array(n);
683        for i in 0..n {
684            out.bulk(args.get(4 + step * i));
685        }
686        return Ok(());
687    }
688    if spec.first_key == 0 {
689        return Err(Error::new(
690            Code::Invalid,
691            "The command has no key arguments",
692        ));
693    }
694    let last = if spec.last_key < 0 {
695        (argc as i64) + i64::from(spec.last_key)
696    } else {
697        i64::from(spec.last_key)
698    };
699    let step = i64::from(spec.step).max(1);
700    let first = i64::from(spec.first_key);
701    let count = if last < first {
702        0
703    } else {
704        ((last - first) / step + 1) as usize
705    };
706    out.array(count);
707    for i in 0..count {
708        out.bulk(args.get(2 + (first + (i as i64) * step) as usize));
709    }
710    Ok(())
711}
712
713/// One command, in the ten field shape `COMMAND INFO` has had since 7.0.
714///
715/// The tips, the key specs and the subcommands are all empty. The triple above
716/// them says where the keys are for everything in this table except `MSETEX`,
717/// `TS.NRANGE` and `TS.NREVRANGE`, which is what `COMMAND GETKEYS` is for, and
718/// divergence D-13 says so.
719fn write_spec(out: &mut Out, spec: &Spec) {
720    out.array(10);
721    out.bulk(spec.name.as_bytes());
722    out.int(i64::from(spec.arity));
723    out.array(spec.flags.len());
724    for f in spec.flags {
725        out.simple(f.as_bytes());
726    }
727    out.int(i64::from(spec.first_key));
728    out.int(i64::from(spec.last_key));
729    out.int(i64::from(spec.step));
730    out.array(spec.acl.len());
731    for a in spec.acl {
732        out.simple(a.as_bytes());
733    }
734    out.array(0);
735    out.array(0);
736    out.array(0);
737}
738
739// ------------------------------------------------------------------ CONFIG
740
741/// What a ladder setting is set to now.
742fn read_knob(db: &Keyspace, knob: Knob) -> usize {
743    match knob {
744        Knob::SetIntsetEntries => db.limits().max_intset_entries,
745        Knob::SetListpackEntries => db.limits().max_listpack_entries,
746        Knob::SetListpackValue => db.limits().max_listpack_value,
747        Knob::HashListpackEntries => db.hash_limits().max_listpack_entries,
748        Knob::HashListpackValue => db.hash_limits().max_listpack_value,
749        Knob::MaxmemorySamples => db.samples(),
750        Knob::LfuLogFactor => db.lfu().log_factor as usize,
751        Knob::LfuDecayTime => db.lfu().decay_minutes as usize,
752    }
753}
754
755/// Move one ladder setting on one database.
756fn write_knob(db: &mut Keyspace, knob: Knob, n: usize) {
757    let mut set = *db.limits();
758    let mut hash = *db.hash_limits();
759    let mut lfu = db.lfu();
760    match knob {
761        Knob::SetIntsetEntries => set.max_intset_entries = n,
762        Knob::SetListpackEntries => set.max_listpack_entries = n,
763        Knob::SetListpackValue => set.max_listpack_value = n,
764        Knob::HashListpackEntries => hash.max_listpack_entries = n,
765        Knob::HashListpackValue => hash.max_listpack_value = n,
766        Knob::MaxmemorySamples => db.set_samples(n),
767        // Saturating rather than wrapping, because these two are read as `u32`
768        // and a client is free to send a number that does not fit. Redis clamps
769        // `lfu-log-factor` and `lfu-decay-time` to the same width.
770        Knob::LfuLogFactor => lfu.log_factor = u32::try_from(n).unwrap_or(u32::MAX),
771        Knob::LfuDecayTime => lfu.decay_minutes = u32::try_from(n).unwrap_or(u32::MAX),
772    }
773    db.set_limits(set);
774    db.set_hash_limits(hash);
775    db.set_lfu(lfu);
776}
777
778/// The two things a real server says about a number it will not take.
779///
780/// Both name the setting the client typed and not the one it is an alias for,
781/// so `hash-max-ziplist-entries` comes back saying `hash-max-ziplist-entries`.
782/// A value past the range of an `i64` is the parse complaint and not the range
783/// one, which is upstream reading it before it checks it.
784fn bad_setting(name: &str, parsed: bool) -> Error {
785    if parsed {
786        Error::fmt(
787            Code::Invalid,
788            format_args!(
789                "CONFIG SET failed (possibly related to argument '{name}') - argument must be between 0 and 9223372036854775807 inclusive"
790            ),
791        )
792    } else {
793        Error::fmt(
794            Code::Invalid,
795            format_args!(
796                "CONFIG SET failed (possibly related to argument '{name}') - argument couldn't be parsed into an integer"
797            ),
798        )
799    }
800}
801
802/// `CONFIG GET|SET|RESETSTAT|REWRITE|HELP`.
803fn config(server: &Server, args: Args<'_>, out: &mut Out) -> Result<()> {
804    let sub = args.get(1);
805    if is(sub, b"GET") {
806        if args.len() < 3 {
807            return Err(args::wrong_arity_sub("config", "get"));
808        }
809        let wanted =
810            |name: &str| (2..args.len()).any(|i| glob::matches(args.get(i), name.as_bytes()));
811        // A setting that two patterns both ask for is sent once, which is what
812        // makes this a count of settings rather than a count of matches. The
813        // two spellings of a ladder setting are two settings by that rule, so
814        // `CONFIG GET hash-max-*` sends the listpack name and the ziplist name
815        // and the same number under both, which is what a real server does.
816        let fixed = SETTINGS.iter().filter(|(k, _)| wanted(k));
817        let ladder = LADDER.iter().filter(|(k, _)| wanted(k));
818        let policy = wanted(MAXMEMORY_POLICY);
819        let limit = wanted(MAXMEMORY);
820        let store = wanted(MAXSTORE);
821        let where_ = wanted(DIR);
822        let ttl = wanted(SEALED_TTL);
823        out.map(
824            fixed.clone().count()
825                + ladder.clone().count()
826                + usize::from(policy)
827                + usize::from(limit)
828                + usize::from(store)
829                + usize::from(where_)
830                + usize::from(ttl),
831        );
832        for (k, v) in fixed {
833            out.bulk(k.as_bytes());
834            out.bulk(v.as_bytes());
835        }
836        for (k, knob) in ladder {
837            out.bulk(k.as_bytes());
838            out.bulk_int(read_knob(&server.settings(), *knob) as i64);
839        }
840        if policy {
841            out.bulk(MAXMEMORY_POLICY.as_bytes());
842            out.bulk(server.settings().policy().name().as_bytes());
843        }
844        if limit {
845            // Back as a plain number of bytes whatever the client typed to set
846            // it, which is what a real server does: `CONFIG SET maxmemory 1gb`
847            // reads back as 1073741824.
848            out.bulk(MAXMEMORY.as_bytes());
849            out.bulk_int(server.maxmemory() as i64);
850        }
851        if store {
852            // Minus one for no limit, and a plain number of bytes otherwise.
853            // Zero cannot mean no limit here the way it does for `maxmemory`,
854            // because zero is the setting that says the file holds nothing.
855            out.bulk(MAXSTORE.as_bytes());
856            out.bulk_int(server.maxstore().map_or(-1, |n| n as i64));
857        }
858        if where_ {
859            // Absolute, which is what a real server answers too: it resolves the
860            // directory at startup and reports the resolved one, so a client can
861            // tell where the files are without knowing where the process was
862            // launched from.
863            out.bulk(DIR.as_bytes());
864            yo_alloc::allow(|| out.bulk(server.dir().to_string_lossy().as_bytes()));
865        }
866        if ttl {
867            out.bulk(SEALED_TTL.as_bytes());
868            out.bulk_int(server.backup().ttl() as i64);
869        }
870    } else if is(sub, b"SET") {
871        // Too few is a wrong number of arguments and an odd number is a syntax
872        // error, which is not the same sentence and is not the same rule. A
873        // real server counts the pairs after it has decided there is at least
874        // one, so `CONFIG SET appendonly` is an arity error and `CONFIG SET
875        // appendonly no maxmemory` is a syntax one.
876        if args.len() < 4 {
877            return Err(args::wrong_arity_sub("config", "set"));
878        }
879        if !args.len().is_multiple_of(2) {
880            return Err(args::syntax());
881        }
882        // Every pair is checked before any of them is applied, because a real
883        // server takes the whole `CONFIG SET` or none of it. `CONFIG SET
884        // hash-max-listpack-entries 7 set-max-listpack-entries abc` leaves the
885        // hash setting where it was, which was checked rather than assumed.
886        let mut writes = [None; 16];
887        let mut count = 0;
888        let mut policy = None;
889        let mut limit = None;
890        let mut store = None;
891        let mut ttl = None;
892        let mut i = 2;
893        while i < args.len() {
894            let (name, value) = (args.get(i), args.get(i + 1));
895            i += 2;
896            if is(name, MAXMEMORY.as_bytes()) {
897                let Some(bytes) = parse_memory(value) else {
898                    return Err(Error::fmt(
899                        Code::Invalid,
900                        format_args!(
901                            "CONFIG SET failed (possibly related to argument '{MAXMEMORY}') - argument must be a memory value"
902                        ),
903                    ));
904                };
905                limit = Some(bytes);
906                continue;
907            }
908            if is(name, MAXSTORE.as_bytes()) {
909                // `-1` before the memory parser sees it, because that parser
910                // refuses a sign and should keep refusing one: `maxmemory -1`
911                // is not a very large number and never was.
912                let parsed = if value == b"-1" {
913                    Some(None)
914                } else {
915                    parse_memory(value).map(Some)
916                };
917                let Some(bytes) = parsed else {
918                    return Err(Error::fmt(
919                        Code::Invalid,
920                        format_args!(
921                            "CONFIG SET failed (possibly related to argument '{MAXSTORE}') - argument must be a memory value or -1"
922                        ),
923                    ));
924                };
925                store = Some(bytes);
926                continue;
927            }
928            if is(name, MAXMEMORY_POLICY.as_bytes()) {
929                // Named twice in one command, the last one wins, which is the
930                // same rule the ladder settings follow and is what a real server
931                // does with any setting repeated in a single `CONFIG SET`.
932                let Some(p) = Policy::parse(value) else {
933                    return Err(Error::fmt(
934                        Code::Invalid,
935                        format_args!(
936                            "CONFIG SET failed (possibly related to argument '{MAXMEMORY_POLICY}') - argument(s) must be one of the following: {PolicyNames}"
937                        ),
938                    ));
939                };
940                policy = Some(p);
941                continue;
942            }
943            if is(name, DIR.as_bytes()) {
944                // Refused whatever the value is, including the one it is already
945                // set to, which is the one place a setting here does not take
946                // the write that changes nothing. That is the reference's
947                // answer: a protected config is refused before anybody looks at
948                // what was asked for.
949                return Err(Error::fmt(
950                    Code::Unsupported,
951                    format_args!(
952                        "CONFIG SET failed (possibly related to argument '{DIR}') - can't set protected config"
953                    ),
954                ));
955            }
956            if is(name, SEALED_TTL.as_bytes()) {
957                let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
958                    return Err(bad_setting(SEALED_TTL, parse_i64(value).is_some()));
959                };
960                ttl = Some(n as u64);
961                continue;
962            }
963            if let Some((k, knob)) = LADDER.iter().find(|(k, _)| is(name, k.as_bytes())) {
964                let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
965                    return Err(bad_setting(k, parse_i64(value).is_some()));
966                };
967                if count == writes.len() {
968                    // Sixteen pairs is more than the ten names there are, so
969                    // getting here means a name was given twice enough times to
970                    // fill it, and the last one would have won anyway.
971                    return Err(args::syntax());
972                }
973                writes[count] = Some((*knob, n as usize));
974                count += 1;
975                continue;
976            }
977            let Some((k, v)) = SETTINGS.iter().find(|(k, _)| is(name, k.as_bytes())) else {
978                return Err(yo_alloc::allow(|| {
979                    Error::fmt(
980                        Code::Invalid,
981                        format_args!(
982                            "Unknown option or number of arguments for CONFIG SET - '{}'",
983                            String::from_utf8_lossy(name)
984                        ),
985                    )
986                }));
987            };
988            if value != v.as_bytes() {
989                return Err(Error::fmt(
990                    Code::Unsupported,
991                    format_args!(
992                        "CONFIG SET failed (possibly related to argument '{k}') - can't set immutable config"
993                    ),
994                ));
995            }
996        }
997        // Every stripe of every database, because these are one server wide
998        // number in Redis and the fact that a `Keyspace` carries its own copy is
999        // ours and not the client's problem. A stripe that missed one would put
1000        // a key in a different shape from the same key on the stripe next to it,
1001        // which `OBJECT ENCODING` would then answer differently for depending on
1002        // where the key happened to land.
1003        // The whole database is held while its stripes are set rather than one
1004        // stripe at a time, for the same reason they all get the same number: a
1005        // client that read `OBJECT ENCODING` in the middle of a half done change
1006        // would be told two different things about two keys depending on nothing
1007        // it can see.
1008        for (knob, n) in writes.iter().flatten() {
1009            for at in 0..DATABASES {
1010                let db = server.striped(at);
1011                let mut held = db.hold_many(0..db.width());
1012                for i in 0..db.width() {
1013                    write_knob(held.stripe_mut(i), *knob, *n);
1014                }
1015            }
1016        }
1017        if let Some(p) = policy {
1018            for at in 0..DATABASES {
1019                let db = server.striped(at);
1020                let mut held = db.hold_many(0..db.width());
1021                for i in 0..db.width() {
1022                    held.stripe_mut(i).set_policy(p);
1023                }
1024            }
1025        }
1026        if let Some(seconds) = ttl {
1027            server.backup().set_ttl(seconds);
1028        }
1029        // Last, so that a `CONFIG SET maxmemory 1mb maxmemory-policy allkeys-lru`
1030        // has the policy in place before the limit that will act on it. The two
1031        // in the other order would run the first eviction under whatever the
1032        // policy used to be, which for a fresh server is `noeviction` and would
1033        // refuse the next write instead of making room for it.
1034        if let Some(bytes) = store {
1035            server.set_maxstore(bytes);
1036        }
1037        if let Some(bytes) = limit {
1038            server.set_maxmemory(bytes);
1039        }
1040        out.ok();
1041    } else if is(sub, b"RESETSTAT") {
1042        server.reset_stats();
1043        out.ok();
1044    } else if is(sub, b"REWRITE") {
1045        return Err(Error::new(
1046            Code::Unsupported,
1047            "The server is running without a config file",
1048        ));
1049    } else if is(sub, b"HELP") {
1050        help(out, CONFIG_HELP);
1051    } else {
1052        return Err(args::unknown_subcommand(sub, "CONFIG"));
1053    }
1054    Ok(())
1055}
1056
1057// -------------------------------------------------------------------- INFO
1058
1059/// `INFO [section ...]`.
1060///
1061/// Every number in here is one this layer can actually answer. There is no
1062/// `rdb_last_save_time` because there is no save, and a field that is not there
1063/// is a client falling back rather than a client believing a zero.
1064///
1065/// The `CPU` section used to be missing for the same reason and is here now,
1066/// because nothing measured it and then something did. It is one `getrusage`
1067/// call in [`super::cpu`], and the reason it went in is that Redis's own
1068/// `unit/info-command` tests fail without it: a monitoring tool graphs
1069/// processor time against wall clock to decide whether a server is busy or
1070/// waiting, so an absent field there is a real hole and not a tidy omission.
1071fn info(server: &Server, args: Args<'_>, out: &mut Out) {
1072    // Redis keeps two lists: the sections a bare `INFO` hands back, and the ones
1073    // that have to be asked for by name or by `all`. `commandstats` is in the
1074    // second, along with `latencystats` and `errorstats`, because they grow with
1075    // the number of distinct commands a server has seen and a monitoring tool
1076    // polling `INFO` every second does not want them.
1077    //
1078    // `unit/info-command` is exactly this distinction written down: it asks for
1079    // `INFO default` and insists `rejected_calls` is not in the answer, then
1080    // asks for `INFO all` and insists that it is.
1081    let named = |section: &str| (1..args.len()).any(|i| is(args.get(i), section.as_bytes()));
1082    let everything = (1..args.len()).any(|i| {
1083        let a = args.get(i);
1084        is(a, b"all") || is(a, b"everything")
1085    });
1086    let by_default = args.len() == 1 || (1..args.len()).any(|i| is(args.get(i), b"default"));
1087    let want = |section: &str| by_default || everything || named(section);
1088    let extra = |section: &str| everything || named(section);
1089    // One string, built once and written once. It allocates, which is allowed
1090    // here and nowhere near the commands that count: `INFO` is a monitoring
1091    // call and it is not on the path M2 is measured on.
1092    let text = yo_alloc::allow(|| {
1093        let mut s = String::with_capacity(1024);
1094        if want("server") {
1095            let _ = write!(
1096                s,
1097                "# Server\r\nredis_version:{REPORTED_VERSION}\r\nyo_version:{}\r\n\
1098                 redis_mode:standalone\r\narch_bits:{}\r\nprocess_id:0\r\n\
1099                 run_id:0000000000000000000000000000000000000000\r\ntcp_port:0\r\n\
1100                 uptime_in_seconds:{}\r\nio_threads_active:0\r\n\r\n",
1101                env!("CARGO_PKG_VERSION"),
1102                usize::BITS,
1103                server.uptime_secs(),
1104            );
1105        }
1106        if want("clients") {
1107            let _ = write!(
1108                s,
1109                "# Clients\r\nconnected_clients:{}\r\nblocked_clients:{}\r\n\
1110                 cluster_connections:0\r\n\r\n",
1111                server.totals().clients,
1112                server.parked(),
1113            );
1114        }
1115        if want("memory") {
1116            // Both the cap and the quarter of it, because the quarter is an
1117            // empirical number and somebody surprised by it should be able to
1118            // see what it was a quarter of without reading the source. The
1119            // reasoning is written out in `cap`.
1120            let cap = crate::cap::cap();
1121            let compact = server.compaction();
1122            // Read out of its stripe before the write, because an argument list
1123            // keeps every temporary in it alive until the whole call is over
1124            // and one of the other arguments walks that same stripe.
1125            let policy = server.settings().policy().name();
1126            let _ = write!(
1127                s,
1128                "# Memory\r\nused_memory:{}\r\nused_memory_dataset:{}\r\n\
1129                 used_memory_overhead:{}\r\nmem_arena_bytes:{}\r\n\
1130                 mem_arena_segments:{}\r\nmem_compact_walked:{}\r\n\
1131                 mem_compact_moved:{}\r\nmem_compact_bytes:{}\r\n\
1132                 mem_index_bytes:{}\r\n\
1133                 mem_client_buffers:{}\r\ntotal_system_memory:{}\r\n\
1134                 mem_cgroup_limit:{}\r\nmem_limit:{}\r\nmem_budget:{}\r\n\
1135                 maxmemory:{}\r\nmaxmemory_policy:{}\r\n\
1136                 maxstore:{}\r\nyo_store_bytes:{}\r\nyo_memory_regime:{}\r\n\r\n",
1137                server.memory_bytes(),
1138                server.dataset_bytes(),
1139                server.memory_bytes() - server.dataset_bytes(),
1140                server.arena_bytes(),
1141                server.segment_count(),
1142                compact.walked,
1143                compact.moved,
1144                compact.bytes,
1145                server.index_bytes(),
1146                server.conn_bytes(),
1147                cap.host.unwrap_or(0),
1148                cap.cgroup.unwrap_or(0),
1149                cap.limit().unwrap_or(0),
1150                cap.budget(),
1151                server.maxmemory(),
1152                policy,
1153                server.maxstore().map_or(-1, |n| n as i64),
1154                server.store_bytes(),
1155                server.regime(),
1156            );
1157        }
1158        if want("stats") {
1159            // The cold counters live here and not in the memory section,
1160            // because they are totals since the server started and everything
1161            // in that section is a level right now. `yo_cold_faults` over the
1162            // point reads a run issued is the ratio G9 is a gate on, and it
1163            // cannot be worked out from outside the server.
1164            let cold = server.cold_stats();
1165            let totals = server.totals();
1166            let _ = write!(
1167                s,
1168                "# Stats\r\ntotal_connections_received:{}\r\n\
1169                 total_commands_processed:{}\r\nexpired_keys:{}\r\n\
1170                 evicted_keys:{}\r\nyo_cold_demoted:{}\r\nyo_cold_promoted:{}\r\n\
1171                 yo_cold_faults:{}\r\nyo_cold_served:{}\r\nyo_cold_bytes_out:{}\r\n\
1172                 yo_cold_bytes_in:{}\r\n\r\n",
1173                totals.connections,
1174                totals.commands,
1175                server.expired_keys(),
1176                server.evicted_keys(),
1177                cold.demoted,
1178                cold.promoted,
1179                cold.faults,
1180                cold.served,
1181                cold.bytes_out,
1182                cold.bytes_in,
1183            );
1184        }
1185        if want("cpu") {
1186            // Two of Redis's six are not here. `used_cpu_sys_main_thread` and
1187            // `used_cpu_user_main_thread` need `RUSAGE_THREAD`, which is Linux
1188            // only, and reporting the process totals under a name that says
1189            // main thread would be right on a single threaded server and wrong
1190            // on the one this becomes.
1191            if let Some(u) = cpu::usage() {
1192                let _ = write!(
1193                    s,
1194                    "# CPU\r\nused_cpu_sys:{:.6}\r\nused_cpu_user:{:.6}\r\n\
1195                     used_cpu_sys_children:{:.6}\r\nused_cpu_user_children:{:.6}\r\n\r\n",
1196                    u.sys, u.user, u.sys_children, u.user_children,
1197                );
1198            }
1199        }
1200        if want("replication") {
1201            // Four fields out of Redis's dozen, and the eight that are missing
1202            // all describe the replication backlog, which is a thing that does
1203            // not exist here rather than a thing that is empty. The four that
1204            // are here are true of a server with no replica attached: it is the
1205            // master, nobody is following it, no failover is in progress and
1206            // nothing has been written to a stream that does not exist, which is
1207            // an offset of zero.
1208            s.push_str(
1209                "# Replication\r\nrole:master\r\nconnected_slaves:0\r\n\
1210                 master_failover_state:no-failover\r\nmaster_repl_offset:0\r\n\r\n",
1211            );
1212        }
1213        if extra("commandstats") {
1214            s.push_str("# Commandstats\r\n");
1215            for (name, row) in server.command_stats() {
1216                let _ = write!(
1217                    s,
1218                    "cmdstat_{name}:calls={},rejected_calls={},failed_calls={}\r\n",
1219                    row.calls, row.rejected, row.failed,
1220                );
1221            }
1222            s.push_str("\r\n");
1223        }
1224        if want("keyspace") {
1225            s.push_str("# Keyspace\r\n");
1226            for i in 0..DATABASES {
1227                let keys = server.dbs[i].len();
1228                if keys > 0 {
1229                    // `avg_ttl` is still a zero, and Redis reports a zero there
1230                    // too on a server that has never run its active expiry
1231                    // cycle, because the number is a running estimate that cycle
1232                    // produces rather than something anybody measures on demand.
1233                    let expires = server.dbs[i].expires();
1234                    let _ = write!(s, "db{i}:keys={keys},expires={expires},avg_ttl=0\r\n");
1235                }
1236            }
1237            s.push_str("\r\n");
1238        }
1239        s
1240    });
1241    out.verbatim(b"txt", text.as_bytes());
1242}
1243
1244// -------------------------------------------------------------------- help
1245
1246/// The `HELP` reply, which is an array of simple strings on both protocols.
1247pub(super) fn help(out: &mut Out, lines: &[&str]) {
1248    out.array(lines.len());
1249    for line in lines {
1250        out.simple(line.as_bytes());
1251    }
1252}
1253
1254/// What `COMMAND HELP` says.
1255const COMMAND_HELP: &[&str] = &[
1256    "COMMAND <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
1257    "(no subcommand)",
1258    "    Return details about all commands.",
1259    "COUNT",
1260    "    Return the total number of commands in this server.",
1261    "LIST [FILTERBY <MODULE <module-name>|ACLCAT <category>|PATTERN <pattern>>]",
1262    "    Return a list of all commands in this server.",
1263    "INFO [<command-name> ...]",
1264    "    Return details about multiple commands.",
1265    "DOCS [<command-name> ...]",
1266    "    Return documentation details about multiple commands.",
1267    "GETKEYS <full-command>",
1268    "    Return the keys from a full command.",
1269    "HELP",
1270    "    Print this help.",
1271];
1272
1273/// What `CONFIG HELP` says.
1274const CONFIG_HELP: &[&str] = &[
1275    "CONFIG <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
1276    "GET <pattern>",
1277    "    Return parameters matching the glob-like <pattern> and their values.",
1278    "SET <directive> <value>",
1279    "    Set the configuration <directive> to <value>.",
1280    "RESETSTAT",
1281    "    Reset statistics reported by the INFO command.",
1282    "REWRITE",
1283    "    Rewrite the configuration file.",
1284    "HELP",
1285    "    Print this help.",
1286];