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