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: &mut 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 &mut server.dbs {
296 db.clear();
297 }
298 out.ok();
299 }
300 "flushdb" => {
301 flush_mode(args)?;
302 server.dbs[session.db].clear();
303 out.ok();
304 }
305 // Two databases change places and no key moves. A database here is a
306 // value in a slice, so this is the slice's own swap and it costs two
307 // pointer sized writes whatever is in either of them, which is what
308 // makes `SWAPDB` fast and dangerous at the same time.
309 //
310 // No connection is told. A client on database zero is still on database
311 // zero and is now looking at what used to be database one, which is the
312 // whole point of the command and is why Redis calls it dangerous. A
313 // client parked in `BLPOP` remembers the database index it blocked on
314 // and not the database, so it wakes up against the swapped in one, which
315 // is Redis's behaviour and falls out of the index being what is stored.
316 "swapdb" => {
317 let first = db_index(args.get(1), "invalid first DB index")?;
318 let second = db_index(args.get(2), "invalid second DB index")?;
319 server.dbs.swap(first, second);
320 out.ok();
321 }
322 "time" => time(out),
323 "backup" => backup::execute(server, args, out)?,
324 "shutdown" => return shutdown(server, args),
325 _ => return Err(args::unknown_command(args)),
326 }
327 Ok(Flow::Continue)
328}
329
330/// `TIME`, which is two bulk strings and not one integer.
331///
332/// Seconds first and then microseconds within that second, both written out as
333/// decimal text, which is a shape nobody would choose today and is the shape
334/// every client library parses.
335///
336/// It reads the wall clock rather than the coarse clock the keyspace uses. The
337/// coarse one is a cached millisecond that a background tick refreshes, which is
338/// the right trade for deciding whether a key has expired and the wrong one for
339/// a command whose entire job is to say what time it is. A client that calls
340/// `TIME` twice in a row and gets the same microsecond has been lied to.
341fn time(out: &mut Out) {
342 let now = SystemTime::now()
343 .duration_since(UNIX_EPOCH)
344 .unwrap_or_default();
345 out.array(2);
346 out.bulk(now.as_secs().to_string().as_bytes());
347 out.bulk(now.subsec_micros().to_string().as_bytes());
348}
349
350// ---------------------------------------------------------------- SHUTDOWN
351
352/// `SHUTDOWN [NOSAVE | SAVE] [NOW] [FORCE] [ABORT]`.
353///
354/// On success this writes nothing at all and the connection closes under the
355/// client, which is what a server that has stopped looks like from the outside
356/// and is what every client library already expects. There is no `OK`, because
357/// an `OK` would be a promise made by a process that is about to not exist.
358///
359/// The flags are taken and none of them changes what happens, which is the same
360/// answer `SAVE` gets from `CONFIG GET`: this server has no save points and no
361/// snapshot to write, so saving and not saving are the same act. What durability
362/// there is belongs to the file underneath and is already on disk by the time a
363/// command returns, so there is nothing for `SAVE` to do and nothing for
364/// `NOSAVE` to skip. `NOW` and `FORCE` are about not waiting for replicas and
365/// about going anyway when a save failed, and neither has anything to wait for
366/// or to fail here.
367///
368/// # Errors
369///
370/// [`Code::Invalid`] for a word that is not one of the five, for `SAVE` and
371/// `NOSAVE` in the same call, and for `ABORT` alongside any other flag, all of
372/// which is what 8.10.1 says. `ABORT` on its own gets Redis's message for a
373/// cancel with nothing to cancel, and here that is not a state that can be
374/// reached rather than one that happens to be empty: a shutdown is decided and
375/// done inside one turn of the loop, so there is never a window in which one is
376/// in progress and a second client could call it off.
377fn shutdown(server: &mut Server, args: Args<'_>) -> Result<Flow> {
378 let (mut save, mut nosave, mut abort, mut other) = (false, false, false, false);
379 for at in 1..args.len() {
380 let arg = args.get(at);
381 match () {
382 () if is(arg, b"save") => save = true,
383 () if is(arg, b"nosave") => nosave = true,
384 () if is(arg, b"abort") => abort = true,
385 () if is(arg, b"now") || is(arg, b"force") => other = true,
386 () => return Err(args::syntax()),
387 }
388 }
389 // Repeating one is fine and contradicting yourself is not, and `ABORT` says
390 // to do nothing so it cannot be combined with a word about how to do it.
391 if (save && nosave) || (abort && (save || nosave || other)) {
392 return Err(args::syntax());
393 }
394 if abort {
395 return Err(Error::new(Code::Invalid, "No shutdown in progress."));
396 }
397 server.stop();
398 // Closing is what stops anything the client pipelined behind this from
399 // being answered by a server that is on its way out.
400 Ok(Flow::Close)
401}
402
403// ------------------------------------------------------------------- FLUSH
404
405/// Check the optional `ASYNC` or `SYNC` on `FLUSHALL` and `FLUSHDB`.
406///
407/// Both are accepted and neither changes anything. On a real server the choice
408/// is whether the freeing happens on the connection's thread or on the lazy
409/// free thread, and either way the keyspace is empty before the `OK` goes out.
410/// That is the whole of what a client can observe, and it is the same here,
411/// so taking the word and ignoring it is answering the question rather than
412/// pretending to.
413///
414/// # Errors
415///
416/// [`Code::Invalid`] for a third argument, or for a second that is neither
417/// word, which is what Redis says about both.
418fn flush_mode(args: Args<'_>) -> Result<()> {
419 if args.len() == 1 {
420 return Ok(());
421 }
422 if args.len() > 2 || !(is(args.get(1), b"async") || is(args.get(1), b"sync")) {
423 return Err(args::syntax());
424 }
425 Ok(())
426}
427
428/// One of `SWAPDB`'s two database indexes, with Redis's two different
429/// complaints about it.
430///
431/// A word that is not a number, or a number too big to be a database index on a
432/// server that stores the index in a C `int`, gets the caller's message, which
433/// says which of the two arguments was wrong. A number that is a plausible index
434/// and is not one of ours gets the same out of range message `SELECT` gives. The
435/// split looks arbitrary and it is Redis's, and the reason for it is that the
436/// first check happens while reading the argument and the second happens inside
437/// the swap, so only the first one knows which argument it was looking at.
438fn db_index(arg: &[u8], bad: &'static str) -> Result<usize> {
439 let n = parse_i64(arg)
440 .filter(|n| i32::try_from(*n).is_ok())
441 .ok_or_else(|| Error::new(Code::Invalid, bad))?;
442 usize::try_from(n)
443 .ok()
444 .filter(|n| *n < DATABASES)
445 .ok_or_else(|| Error::new(Code::Invalid, "DB index is out of range"))
446}
447
448// ------------------------------------------------------------------- HELLO
449
450/// `HELLO [protover [AUTH username password] [SETNAME name]]`.
451fn hello(session: &mut Session, args: Args<'_>, out: &mut Out) -> Result<()> {
452 if args.len() > 1 {
453 let v = parse_i64(args.get(1)).ok_or_else(|| {
454 Error::new(
455 Code::Invalid,
456 "Protocol version is not an integer or out of range",
457 )
458 })?;
459 let Some(proto) = Proto::from_version(v) else {
460 // `NOPROTO` rather than `ERR`, and it is the one error in this file
461 // written straight into the buffer: the prefix is part of what the
462 // client branches on, and it is the only place in the engine that
463 // needs this one.
464 out.error(b"NOPROTO unsupported protocol version");
465 return Ok(());
466 };
467 let mut i = 2;
468 while i < args.len() {
469 let o = args.get(i);
470 if is(o, b"AUTH") && i + 2 < args.len() {
471 // No password is configured, so the default user is `nopass`
472 // and any password for it is the right one, which is how a
473 // real server with no `requirepass` behaves. Any other user
474 // does not exist.
475 if !is(args.get(i + 1), b"default") {
476 out.error(b"WRONGPASS invalid username-password pair or user is disabled.");
477 return Ok(());
478 }
479 i += 3;
480 } else if is(o, b"SETNAME") && i + 1 < args.len() {
481 session.set_name(args.get(i + 1));
482 i += 2;
483 } else {
484 return Err(yo_alloc::allow(|| {
485 Error::fmt(
486 Code::Invalid,
487 format_args!(
488 "Syntax error in HELLO option '{}'",
489 String::from_utf8_lossy(o)
490 ),
491 )
492 }));
493 }
494 }
495 // The reply is written in the protocol that was just agreed, not the
496 // one the request arrived in.
497 out.set_proto(proto);
498 }
499
500 let proto = out.proto().version();
501 out.map(7);
502 out.bulk(b"server");
503 out.bulk(REPORTED_SERVER.as_bytes());
504 out.bulk(b"version");
505 out.bulk(REPORTED_VERSION.as_bytes());
506 out.bulk(b"proto");
507 out.int(proto);
508 out.bulk(b"id");
509 out.int(session.id as i64);
510 out.bulk(b"mode");
511 out.bulk(b"standalone");
512 out.bulk(b"role");
513 out.bulk(b"master");
514 out.bulk(b"modules");
515 out.array(0);
516 Ok(())
517}
518
519// ----------------------------------------------------------------- COMMAND
520
521/// `COMMAND [COUNT|LIST|INFO|DOCS|GETKEYS|HELP]`.
522fn command(args: Args<'_>, out: &mut Out) -> Result<()> {
523 if args.len() == 1 {
524 out.array(table::COMMANDS.len());
525 for spec in table::COMMANDS {
526 write_spec(out, spec);
527 }
528 return Ok(());
529 }
530 let sub = args.get(1);
531 if is(sub, b"COUNT") {
532 out.int(table::COMMANDS.len() as i64);
533 } else if is(sub, b"INFO") {
534 if args.len() == 2 {
535 out.array(table::COMMANDS.len());
536 for spec in table::COMMANDS {
537 write_spec(out, spec);
538 }
539 } else {
540 out.array(args.len() - 2);
541 for i in 2..args.len() {
542 match table::lookup(args.get(i)) {
543 Some(spec) => write_spec(out, spec),
544 // A name nobody has heard of is a null in the list rather
545 // than an error, so one bad name in a batch does not cost
546 // the client the other answers. It is the plain null and
547 // not the array one, which on RESP2 is the difference
548 // between `$-1` and `*-1` and is what a real server sends.
549 None => out.nil(),
550 }
551 }
552 }
553 } else if is(sub, b"LIST") {
554 list(args, out)?;
555 } else if is(sub, b"DOCS") {
556 docs(args, out);
557 } else if is(sub, b"GETKEYS") {
558 getkeys(args, out)?;
559 } else if is(sub, b"HELP") {
560 help(out, COMMAND_HELP);
561 } else {
562 return Err(args::unknown_subcommand(sub, "COMMAND"));
563 }
564 Ok(())
565}
566
567/// `COMMAND LIST [FILTERBY MODULE m|ACLCAT c|PATTERN p]`.
568fn list(args: Args<'_>, out: &mut Out) -> Result<()> {
569 if args.len() == 2 {
570 out.array(table::COMMANDS.len());
571 for spec in table::COMMANDS {
572 out.bulk(spec.name.as_bytes());
573 }
574 return Ok(());
575 }
576 if args.len() != 5 || !is(args.get(2), b"FILTERBY") {
577 return Err(args::syntax());
578 }
579 let (how, what) = (args.get(3), args.get(4));
580 let keep = |spec: &Spec| {
581 if is(how, b"MODULE") {
582 // Nothing here came from a module, so every filter by one is empty.
583 false
584 } else if is(how, b"ACLCAT") {
585 spec.acl
586 .iter()
587 .any(|c| c.len() == what.len() + 1 && c.as_bytes()[1..].eq_ignore_ascii_case(what))
588 } else {
589 glob::matches(what, spec.name.as_bytes())
590 }
591 };
592 if !is(how, b"MODULE") && !is(how, b"ACLCAT") && !is(how, b"PATTERN") {
593 return Err(args::syntax());
594 }
595 out.array(table::COMMANDS.iter().filter(|s| keep(s)).count());
596 for spec in table::COMMANDS.iter().filter(|s| keep(s)) {
597 out.bulk(spec.name.as_bytes());
598 }
599 Ok(())
600}
601
602/// `COMMAND DOCS [name ...]`.
603///
604/// The arguments field a real server sends is left out. It describes the shape
605/// of every option of every command in a form nothing but `redis-cli`'s hinting
606/// reads, and getting it wrong would be worse than not sending it, since a
607/// client that finds the field trusts it.
608fn docs(args: Args<'_>, out: &mut Out) {
609 if args.len() == 2 {
610 out.map(table::COMMANDS.len());
611 for spec in table::COMMANDS {
612 write_docs(out, spec);
613 }
614 return;
615 }
616 let found = (2..args.len())
617 .filter(|&i| table::lookup(args.get(i)).is_some())
618 .count();
619 out.map(found);
620 for i in 2..args.len() {
621 if let Some(spec) = table::lookup(args.get(i)) {
622 write_docs(out, spec);
623 }
624 }
625}
626
627/// One command's documentation, as the name and then the map about it.
628fn write_docs(out: &mut Out, spec: &Spec) {
629 out.bulk(spec.name.as_bytes());
630 out.map(4);
631 out.bulk(b"summary");
632 out.bulk(spec.summary.as_bytes());
633 out.bulk(b"since");
634 out.bulk(spec.since.as_bytes());
635 out.bulk(b"group");
636 out.bulk(spec.group.as_bytes());
637 out.bulk(b"complexity");
638 out.bulk(spec.complexity.as_bytes());
639}
640
641/// `COMMAND GETKEYS <full command>`.
642///
643/// This is how a cluster aware client routes a command it does not have a rule
644/// for, so a wrong answer here is a client that sends a write to the wrong
645/// node. The generic path is the first, last and step triple from the table.
646fn getkeys(args: Args<'_>, out: &mut Out) -> Result<()> {
647 if args.len() < 3 {
648 return Err(args::wrong_arity_sub("command", "getkeys"));
649 }
650 let inner = args.get(2);
651 let spec = table::lookup(inner)
652 .ok_or_else(|| Error::new(Code::Unsupported, "Invalid command specified"))?;
653 let argc = args.len() - 2;
654 if !table::arity_ok(spec, argc) {
655 return Err(Error::new(
656 Code::Invalid,
657 "Invalid number of arguments specified for command",
658 ));
659 }
660 // `MSETEX` is the one command here whose keys are not where the triple
661 // says. It carries its own count, which is why a real server marks it
662 // `movablekeys` and why a client has to ask this question about it at all.
663 if spec.name == "msetex" {
664 let n = parse_i64(args.get(3))
665 .filter(|&n| n > 0)
666 .and_then(|n| usize::try_from(n).ok())
667 .filter(|&n| 4 + 2 * n <= args.len())
668 .ok_or_else(|| Error::new(Code::Invalid, "Invalid arguments specified for command"))?;
669 out.array(n);
670 for i in 0..n {
671 out.bulk(args.get(4 + 2 * i));
672 }
673 return Ok(());
674 }
675 if spec.first_key == 0 {
676 return Err(Error::new(
677 Code::Invalid,
678 "The command has no key arguments",
679 ));
680 }
681 let last = if spec.last_key < 0 {
682 (argc as i64) + i64::from(spec.last_key)
683 } else {
684 i64::from(spec.last_key)
685 };
686 let step = i64::from(spec.step).max(1);
687 let first = i64::from(spec.first_key);
688 let count = if last < first {
689 0
690 } else {
691 ((last - first) / step + 1) as usize
692 };
693 out.array(count);
694 for i in 0..count {
695 out.bulk(args.get(2 + (first + (i as i64) * step) as usize));
696 }
697 Ok(())
698}
699
700/// One command, in the ten field shape `COMMAND INFO` has had since 7.0.
701///
702/// The tips, the key specs and the subcommands are all empty. The triple above
703/// them says where the keys are for everything in this table except `MSETEX`,
704/// which is what `COMMAND GETKEYS` is for, and divergence D-13 says so.
705fn write_spec(out: &mut Out, spec: &Spec) {
706 out.array(10);
707 out.bulk(spec.name.as_bytes());
708 out.int(i64::from(spec.arity));
709 out.array(spec.flags.len());
710 for f in spec.flags {
711 out.simple(f.as_bytes());
712 }
713 out.int(i64::from(spec.first_key));
714 out.int(i64::from(spec.last_key));
715 out.int(i64::from(spec.step));
716 out.array(spec.acl.len());
717 for a in spec.acl {
718 out.simple(a.as_bytes());
719 }
720 out.array(0);
721 out.array(0);
722 out.array(0);
723}
724
725// ------------------------------------------------------------------ CONFIG
726
727/// What a ladder setting is set to now.
728fn read_knob(db: &Keyspace, knob: Knob) -> usize {
729 match knob {
730 Knob::SetIntsetEntries => db.limits().max_intset_entries,
731 Knob::SetListpackEntries => db.limits().max_listpack_entries,
732 Knob::SetListpackValue => db.limits().max_listpack_value,
733 Knob::HashListpackEntries => db.hash_limits().max_listpack_entries,
734 Knob::HashListpackValue => db.hash_limits().max_listpack_value,
735 Knob::MaxmemorySamples => db.samples(),
736 Knob::LfuLogFactor => db.lfu().log_factor as usize,
737 Knob::LfuDecayTime => db.lfu().decay_minutes as usize,
738 }
739}
740
741/// Move one ladder setting on one database.
742fn write_knob(db: &mut Keyspace, knob: Knob, n: usize) {
743 let mut set = *db.limits();
744 let mut hash = *db.hash_limits();
745 let mut lfu = db.lfu();
746 match knob {
747 Knob::SetIntsetEntries => set.max_intset_entries = n,
748 Knob::SetListpackEntries => set.max_listpack_entries = n,
749 Knob::SetListpackValue => set.max_listpack_value = n,
750 Knob::HashListpackEntries => hash.max_listpack_entries = n,
751 Knob::HashListpackValue => hash.max_listpack_value = n,
752 Knob::MaxmemorySamples => db.set_samples(n),
753 // Saturating rather than wrapping, because these two are read as `u32`
754 // and a client is free to send a number that does not fit. Redis clamps
755 // `lfu-log-factor` and `lfu-decay-time` to the same width.
756 Knob::LfuLogFactor => lfu.log_factor = u32::try_from(n).unwrap_or(u32::MAX),
757 Knob::LfuDecayTime => lfu.decay_minutes = u32::try_from(n).unwrap_or(u32::MAX),
758 }
759 db.set_limits(set);
760 db.set_hash_limits(hash);
761 db.set_lfu(lfu);
762}
763
764/// The two things a real server says about a number it will not take.
765///
766/// Both name the setting the client typed and not the one it is an alias for,
767/// so `hash-max-ziplist-entries` comes back saying `hash-max-ziplist-entries`.
768/// A value past the range of an `i64` is the parse complaint and not the range
769/// one, which is upstream reading it before it checks it.
770fn bad_setting(name: &str, parsed: bool) -> Error {
771 if parsed {
772 Error::fmt(
773 Code::Invalid,
774 format_args!(
775 "CONFIG SET failed (possibly related to argument '{name}') - argument must be between 0 and 9223372036854775807 inclusive"
776 ),
777 )
778 } else {
779 Error::fmt(
780 Code::Invalid,
781 format_args!(
782 "CONFIG SET failed (possibly related to argument '{name}') - argument couldn't be parsed into an integer"
783 ),
784 )
785 }
786}
787
788/// `CONFIG GET|SET|RESETSTAT|REWRITE|HELP`.
789fn config(server: &mut Server, args: Args<'_>, out: &mut Out) -> Result<()> {
790 let sub = args.get(1);
791 if is(sub, b"GET") {
792 if args.len() < 3 {
793 return Err(args::wrong_arity_sub("config", "get"));
794 }
795 let wanted =
796 |name: &str| (2..args.len()).any(|i| glob::matches(args.get(i), name.as_bytes()));
797 // A setting that two patterns both ask for is sent once, which is what
798 // makes this a count of settings rather than a count of matches. The
799 // two spellings of a ladder setting are two settings by that rule, so
800 // `CONFIG GET hash-max-*` sends the listpack name and the ziplist name
801 // and the same number under both, which is what a real server does.
802 let fixed = SETTINGS.iter().filter(|(k, _)| wanted(k));
803 let ladder = LADDER.iter().filter(|(k, _)| wanted(k));
804 let policy = wanted(MAXMEMORY_POLICY);
805 let limit = wanted(MAXMEMORY);
806 let store = wanted(MAXSTORE);
807 let where_ = wanted(DIR);
808 let ttl = wanted(SEALED_TTL);
809 out.map(
810 fixed.clone().count()
811 + ladder.clone().count()
812 + usize::from(policy)
813 + usize::from(limit)
814 + usize::from(store)
815 + usize::from(where_)
816 + usize::from(ttl),
817 );
818 for (k, v) in fixed {
819 out.bulk(k.as_bytes());
820 out.bulk(v.as_bytes());
821 }
822 for (k, knob) in ladder {
823 out.bulk(k.as_bytes());
824 out.bulk_int(read_knob(server.db_ref(0), *knob) as i64);
825 }
826 if policy {
827 out.bulk(MAXMEMORY_POLICY.as_bytes());
828 out.bulk(server.db_ref(0).policy().name().as_bytes());
829 }
830 if limit {
831 // Back as a plain number of bytes whatever the client typed to set
832 // it, which is what a real server does: `CONFIG SET maxmemory 1gb`
833 // reads back as 1073741824.
834 out.bulk(MAXMEMORY.as_bytes());
835 out.bulk_int(server.maxmemory() as i64);
836 }
837 if store {
838 // Minus one for no limit, and a plain number of bytes otherwise.
839 // Zero cannot mean no limit here the way it does for `maxmemory`,
840 // because zero is the setting that says the file holds nothing.
841 out.bulk(MAXSTORE.as_bytes());
842 out.bulk_int(server.maxstore().map_or(-1, |n| n as i64));
843 }
844 if where_ {
845 // Absolute, which is what a real server answers too: it resolves the
846 // directory at startup and reports the resolved one, so a client can
847 // tell where the files are without knowing where the process was
848 // launched from.
849 out.bulk(DIR.as_bytes());
850 yo_alloc::allow(|| out.bulk(server.dir().to_string_lossy().as_bytes()));
851 }
852 if ttl {
853 out.bulk(SEALED_TTL.as_bytes());
854 out.bulk_int(server.backup.ttl() as i64);
855 }
856 } else if is(sub, b"SET") {
857 // Too few is a wrong number of arguments and an odd number is a syntax
858 // error, which is not the same sentence and is not the same rule. A
859 // real server counts the pairs after it has decided there is at least
860 // one, so `CONFIG SET appendonly` is an arity error and `CONFIG SET
861 // appendonly no maxmemory` is a syntax one.
862 if args.len() < 4 {
863 return Err(args::wrong_arity_sub("config", "set"));
864 }
865 if !args.len().is_multiple_of(2) {
866 return Err(args::syntax());
867 }
868 // Every pair is checked before any of them is applied, because a real
869 // server takes the whole `CONFIG SET` or none of it. `CONFIG SET
870 // hash-max-listpack-entries 7 set-max-listpack-entries abc` leaves the
871 // hash setting where it was, which was checked rather than assumed.
872 let mut writes = [None; 16];
873 let mut count = 0;
874 let mut policy = None;
875 let mut limit = None;
876 let mut store = None;
877 let mut ttl = None;
878 let mut i = 2;
879 while i < args.len() {
880 let (name, value) = (args.get(i), args.get(i + 1));
881 i += 2;
882 if is(name, MAXMEMORY.as_bytes()) {
883 let Some(bytes) = parse_memory(value) else {
884 return Err(Error::fmt(
885 Code::Invalid,
886 format_args!(
887 "CONFIG SET failed (possibly related to argument '{MAXMEMORY}') - argument must be a memory value"
888 ),
889 ));
890 };
891 limit = Some(bytes);
892 continue;
893 }
894 if is(name, MAXSTORE.as_bytes()) {
895 // `-1` before the memory parser sees it, because that parser
896 // refuses a sign and should keep refusing one: `maxmemory -1`
897 // is not a very large number and never was.
898 let parsed = if value == b"-1" {
899 Some(None)
900 } else {
901 parse_memory(value).map(Some)
902 };
903 let Some(bytes) = parsed else {
904 return Err(Error::fmt(
905 Code::Invalid,
906 format_args!(
907 "CONFIG SET failed (possibly related to argument '{MAXSTORE}') - argument must be a memory value or -1"
908 ),
909 ));
910 };
911 store = Some(bytes);
912 continue;
913 }
914 if is(name, MAXMEMORY_POLICY.as_bytes()) {
915 // Named twice in one command, the last one wins, which is the
916 // same rule the ladder settings follow and is what a real server
917 // does with any setting repeated in a single `CONFIG SET`.
918 let Some(p) = Policy::parse(value) else {
919 return Err(Error::fmt(
920 Code::Invalid,
921 format_args!(
922 "CONFIG SET failed (possibly related to argument '{MAXMEMORY_POLICY}') - argument(s) must be one of the following: {PolicyNames}"
923 ),
924 ));
925 };
926 policy = Some(p);
927 continue;
928 }
929 if is(name, DIR.as_bytes()) {
930 // Refused whatever the value is, including the one it is already
931 // set to, which is the one place a setting here does not take
932 // the write that changes nothing. That is the reference's
933 // answer: a protected config is refused before anybody looks at
934 // what was asked for.
935 return Err(Error::fmt(
936 Code::Unsupported,
937 format_args!(
938 "CONFIG SET failed (possibly related to argument '{DIR}') - can't set protected config"
939 ),
940 ));
941 }
942 if is(name, SEALED_TTL.as_bytes()) {
943 let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
944 return Err(bad_setting(SEALED_TTL, parse_i64(value).is_some()));
945 };
946 ttl = Some(n as u64);
947 continue;
948 }
949 if let Some((k, knob)) = LADDER.iter().find(|(k, _)| is(name, k.as_bytes())) {
950 let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
951 return Err(bad_setting(k, parse_i64(value).is_some()));
952 };
953 if count == writes.len() {
954 // Sixteen pairs is more than the ten names there are, so
955 // getting here means a name was given twice enough times to
956 // fill it, and the last one would have won anyway.
957 return Err(args::syntax());
958 }
959 writes[count] = Some((*knob, n as usize));
960 count += 1;
961 continue;
962 }
963 let Some((k, v)) = SETTINGS.iter().find(|(k, _)| is(name, k.as_bytes())) else {
964 return Err(yo_alloc::allow(|| {
965 Error::fmt(
966 Code::Invalid,
967 format_args!(
968 "Unknown option or number of arguments for CONFIG SET - '{}'",
969 String::from_utf8_lossy(name)
970 ),
971 )
972 }));
973 };
974 if value != v.as_bytes() {
975 return Err(Error::fmt(
976 Code::Unsupported,
977 format_args!(
978 "CONFIG SET failed (possibly related to argument '{k}') - can't set immutable config"
979 ),
980 ));
981 }
982 }
983 // Every database, because these are one server wide number in Redis and
984 // the fact that a `Keyspace` carries its own copy is ours and not the
985 // client's problem.
986 for (knob, n) in writes.iter().flatten() {
987 for at in 0..DATABASES {
988 write_knob(server.db(at), *knob, *n);
989 }
990 }
991 if let Some(p) = policy {
992 for at in 0..DATABASES {
993 server.db(at).set_policy(p);
994 }
995 }
996 if let Some(seconds) = ttl {
997 server.backup.set_ttl(seconds);
998 }
999 // Last, so that a `CONFIG SET maxmemory 1mb maxmemory-policy allkeys-lru`
1000 // has the policy in place before the limit that will act on it. The two
1001 // in the other order would run the first eviction under whatever the
1002 // policy used to be, which for a fresh server is `noeviction` and would
1003 // refuse the next write instead of making room for it.
1004 if let Some(bytes) = store {
1005 server.set_maxstore(bytes);
1006 }
1007 if let Some(bytes) = limit {
1008 server.set_maxmemory(bytes);
1009 }
1010 out.ok();
1011 } else if is(sub, b"RESETSTAT") {
1012 server.stats.commands = 0;
1013 server.stats.connections = 0;
1014 out.ok();
1015 } else if is(sub, b"REWRITE") {
1016 return Err(Error::new(
1017 Code::Unsupported,
1018 "The server is running without a config file",
1019 ));
1020 } else if is(sub, b"HELP") {
1021 help(out, CONFIG_HELP);
1022 } else {
1023 return Err(args::unknown_subcommand(sub, "CONFIG"));
1024 }
1025 Ok(())
1026}
1027
1028// -------------------------------------------------------------------- INFO
1029
1030/// `INFO [section ...]`.
1031///
1032/// Every number in here is one this layer can actually answer. There is no
1033/// `rdb_last_save_time` because there is no save, and a field that is not there
1034/// is a client falling back rather than a client believing a zero.
1035///
1036/// The `CPU` section used to be missing for the same reason and is here now,
1037/// because nothing measured it and then something did. It is one `getrusage`
1038/// call in [`super::cpu`], and the reason it went in is that Redis's own
1039/// `unit/info-command` tests fail without it: a monitoring tool graphs
1040/// processor time against wall clock to decide whether a server is busy or
1041/// waiting, so an absent field there is a real hole and not a tidy omission.
1042fn info(server: &Server, args: Args<'_>, out: &mut Out) {
1043 // Redis keeps two lists: the sections a bare `INFO` hands back, and the ones
1044 // that have to be asked for by name or by `all`. `commandstats` is in the
1045 // second, along with `latencystats` and `errorstats`, because they grow with
1046 // the number of distinct commands a server has seen and a monitoring tool
1047 // polling `INFO` every second does not want them.
1048 //
1049 // `unit/info-command` is exactly this distinction written down: it asks for
1050 // `INFO default` and insists `rejected_calls` is not in the answer, then
1051 // asks for `INFO all` and insists that it is.
1052 let named = |section: &str| (1..args.len()).any(|i| is(args.get(i), section.as_bytes()));
1053 let everything = (1..args.len()).any(|i| {
1054 let a = args.get(i);
1055 is(a, b"all") || is(a, b"everything")
1056 });
1057 let by_default = args.len() == 1 || (1..args.len()).any(|i| is(args.get(i), b"default"));
1058 let want = |section: &str| by_default || everything || named(section);
1059 let extra = |section: &str| everything || named(section);
1060 // One string, built once and written once. It allocates, which is allowed
1061 // here and nowhere near the commands that count: `INFO` is a monitoring
1062 // call and it is not on the path M2 is measured on.
1063 let text = yo_alloc::allow(|| {
1064 let mut s = String::with_capacity(1024);
1065 if want("server") {
1066 let _ = write!(
1067 s,
1068 "# Server\r\nredis_version:{REPORTED_VERSION}\r\nyo_version:{}\r\n\
1069 redis_mode:standalone\r\narch_bits:{}\r\nprocess_id:0\r\n\
1070 run_id:0000000000000000000000000000000000000000\r\ntcp_port:0\r\n\
1071 uptime_in_seconds:{}\r\nio_threads_active:0\r\n\r\n",
1072 env!("CARGO_PKG_VERSION"),
1073 usize::BITS,
1074 server.uptime_secs(),
1075 );
1076 }
1077 if want("clients") {
1078 let _ = write!(
1079 s,
1080 "# Clients\r\nconnected_clients:{}\r\nblocked_clients:{}\r\n\
1081 cluster_connections:0\r\n\r\n",
1082 server.stats.clients,
1083 server.waiters().len(),
1084 );
1085 }
1086 if want("memory") {
1087 // Both the cap and the quarter of it, because the quarter is an
1088 // empirical number and somebody surprised by it should be able to
1089 // see what it was a quarter of without reading the source. The
1090 // reasoning is written out in `cap`.
1091 let cap = crate::cap::cap();
1092 let compact = server.compaction();
1093 let _ = write!(
1094 s,
1095 "# Memory\r\nused_memory:{}\r\nused_memory_dataset:{}\r\n\
1096 used_memory_overhead:{}\r\nmem_arena_bytes:{}\r\n\
1097 mem_arena_segments:{}\r\nmem_compact_walked:{}\r\n\
1098 mem_compact_moved:{}\r\nmem_compact_bytes:{}\r\n\
1099 mem_index_bytes:{}\r\n\
1100 mem_client_buffers:{}\r\ntotal_system_memory:{}\r\n\
1101 mem_cgroup_limit:{}\r\nmem_limit:{}\r\nmem_budget:{}\r\n\
1102 maxmemory:{}\r\nmaxmemory_policy:{}\r\n\
1103 maxstore:{}\r\nyo_store_bytes:{}\r\nyo_memory_regime:{}\r\n\r\n",
1104 server.memory_bytes(),
1105 server.dataset_bytes(),
1106 server.memory_bytes() - server.dataset_bytes(),
1107 server.arena_bytes(),
1108 server.segment_count(),
1109 compact.walked,
1110 compact.moved,
1111 compact.bytes,
1112 server.index_bytes(),
1113 server.conn_bytes(),
1114 cap.host.unwrap_or(0),
1115 cap.cgroup.unwrap_or(0),
1116 cap.limit().unwrap_or(0),
1117 cap.budget(),
1118 server.maxmemory(),
1119 server.db_ref(0).policy().name(),
1120 server.maxstore().map_or(-1, |n| n as i64),
1121 server.store_bytes(),
1122 server.regime(),
1123 );
1124 }
1125 if want("stats") {
1126 // The cold counters live here and not in the memory section,
1127 // because they are totals since the server started and everything
1128 // in that section is a level right now. `yo_cold_faults` over the
1129 // point reads a run issued is the ratio G9 is a gate on, and it
1130 // cannot be worked out from outside the server.
1131 let cold = server.cold_stats();
1132 let _ = write!(
1133 s,
1134 "# Stats\r\ntotal_connections_received:{}\r\n\
1135 total_commands_processed:{}\r\nexpired_keys:{}\r\n\
1136 evicted_keys:{}\r\nyo_cold_demoted:{}\r\nyo_cold_promoted:{}\r\n\
1137 yo_cold_faults:{}\r\nyo_cold_served:{}\r\nyo_cold_bytes_out:{}\r\n\
1138 yo_cold_bytes_in:{}\r\n\r\n",
1139 server.stats.connections,
1140 server.stats.commands,
1141 server.expired_keys(),
1142 server.evicted_keys(),
1143 cold.demoted,
1144 cold.promoted,
1145 cold.faults,
1146 cold.served,
1147 cold.bytes_out,
1148 cold.bytes_in,
1149 );
1150 }
1151 if want("cpu") {
1152 // Two of Redis's six are not here. `used_cpu_sys_main_thread` and
1153 // `used_cpu_user_main_thread` need `RUSAGE_THREAD`, which is Linux
1154 // only, and reporting the process totals under a name that says
1155 // main thread would be right on a single threaded server and wrong
1156 // on the one this becomes.
1157 if let Some(u) = cpu::usage() {
1158 let _ = write!(
1159 s,
1160 "# CPU\r\nused_cpu_sys:{:.6}\r\nused_cpu_user:{:.6}\r\n\
1161 used_cpu_sys_children:{:.6}\r\nused_cpu_user_children:{:.6}\r\n\r\n",
1162 u.sys, u.user, u.sys_children, u.user_children,
1163 );
1164 }
1165 }
1166 if want("replication") {
1167 // Four fields out of Redis's dozen, and the eight that are missing
1168 // all describe the replication backlog, which is a thing that does
1169 // not exist here rather than a thing that is empty. The four that
1170 // are here are true of a server with no replica attached: it is the
1171 // master, nobody is following it, no failover is in progress and
1172 // nothing has been written to a stream that does not exist, which is
1173 // an offset of zero.
1174 s.push_str(
1175 "# Replication\r\nrole:master\r\nconnected_slaves:0\r\n\
1176 master_failover_state:no-failover\r\nmaster_repl_offset:0\r\n\r\n",
1177 );
1178 }
1179 if extra("commandstats") {
1180 s.push_str("# Commandstats\r\n");
1181 for (name, row) in server.command_stats() {
1182 let _ = write!(
1183 s,
1184 "cmdstat_{name}:calls={},rejected_calls={},failed_calls={}\r\n",
1185 row.calls, row.rejected, row.failed,
1186 );
1187 }
1188 s.push_str("\r\n");
1189 }
1190 if want("keyspace") {
1191 s.push_str("# Keyspace\r\n");
1192 for i in 0..DATABASES {
1193 let keys = server.dbs[i].len();
1194 if keys > 0 {
1195 // `avg_ttl` is still a zero, and Redis reports a zero there
1196 // too on a server that has never run its active expiry
1197 // cycle, because the number is a running estimate that cycle
1198 // produces rather than something anybody measures on demand.
1199 let expires = server.dbs[i].expires();
1200 let _ = write!(s, "db{i}:keys={keys},expires={expires},avg_ttl=0\r\n");
1201 }
1202 }
1203 s.push_str("\r\n");
1204 }
1205 s
1206 });
1207 out.verbatim(b"txt", text.as_bytes());
1208}
1209
1210// -------------------------------------------------------------------- help
1211
1212/// The `HELP` reply, which is an array of simple strings on both protocols.
1213pub(super) fn help(out: &mut Out, lines: &[&str]) {
1214 out.array(lines.len());
1215 for line in lines {
1216 out.simple(line.as_bytes());
1217 }
1218}
1219
1220/// What `COMMAND HELP` says.
1221const COMMAND_HELP: &[&str] = &[
1222 "COMMAND <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
1223 "(no subcommand)",
1224 " Return details about all commands.",
1225 "COUNT",
1226 " Return the total number of commands in this server.",
1227 "LIST [FILTERBY <MODULE <module-name>|ACLCAT <category>|PATTERN <pattern>>]",
1228 " Return a list of all commands in this server.",
1229 "INFO [<command-name> ...]",
1230 " Return details about multiple commands.",
1231 "DOCS [<command-name> ...]",
1232 " Return documentation details about multiple commands.",
1233 "GETKEYS <full-command>",
1234 " Return the keys from a full command.",
1235 "HELP",
1236 " Print this help.",
1237];
1238
1239/// What `CONFIG HELP` says.
1240const CONFIG_HELP: &[&str] = &[
1241 "CONFIG <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
1242 "GET <pattern>",
1243 " Return parameters matching the glob-like <pattern> and their values.",
1244 "SET <directive> <value>",
1245 " Set the configuration <directive> to <value>.",
1246 "RESETSTAT",
1247 " Reset statistics reported by the INFO command.",
1248 "REWRITE",
1249 " Rewrite the configuration file.",
1250 "HELP",
1251 " Print this help.",
1252];