Skip to main content

kevy_cli/
lib.rs

1//! CLI-shaped Reply formatter for the kevy-cli REPL.
2//!
3//! Only `format_reply` lives here — the protocol pieces (TCP connect, request
4//! loop) live in the [`kevy-resp-client`](https://crates.io/crates/kevy-resp-client)
5//! crate so they're reusable by integration tests / scripts / other tools.
6//! This file is the CLI-specific bit (how a redis-cli user expects bulk
7//! strings quoted, arrays numbered, nil shown as `(nil)`).
8//!
9//! ```
10//! use kevy_cli::{DEFAULT_HOST, format_reply};
11//! # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
12//! let mut client = kevy_resp_client::RespClient::connect(DEFAULT_HOST, port)?;
13//! client.request_borrowed(&[b"RPUSH", b"langs", b"rust", b"zig"])?;
14//! let reply = client.request_borrowed(&[b"LRANGE", b"langs", b"0", b"-1"])?;
15//! assert_eq!(format_reply(&reply, 0), "1) \"rust\"\n2) \"zig\"");
16//! # Ok::<(), Box<dyn std::error::Error>>(())
17//! ```
18
19#![forbid(unsafe_code)]
20#![warn(missing_docs)]
21
22pub use kevy_resp::Reply;
23
24/// Backup / restore container support. See
25/// [`backup::pack`] and [`backup::unpack`].
26pub mod backup;
27
28/// Migration toolchain (`export` / `import`). See
29/// [`migrate::run_export`] and [`migrate::run_import`].
30pub mod migrate;
31
32/// kevy-cli's own tools, the second half of `--help`.
33pub(crate) const TOOLS_HELP: &str = "\
34KEVY TOOLS: kevy-cli [connection options] --kevy <tool> [args]
35    (in the REPL: \\<tool> [args]; a bare word is always a server command)
36
37  catalog
38    tables [pattern]                            TABLE.LIST as rows
39    indexes [table|pattern]                     IDX.LIST, with each index's table
40    views [pattern]                             VIEW.LIST
41    describe[+] <table|index|view>              columns and access paths, an
42                                                index's fields, a view's tree
43                                                (+ runs its VERIFY)
44    show-create <name> [--as kevy|sql]          the declaration that recreates it
45
46  query
47    query [--all] [--max-rows n] <IDX.QUERY|VIEW.QUERY …>
48                                                rows, following the cursor
49    explain <index> <shape…> | view <name>      the path a query takes
50    explain --analyze <query…>                  run it; measured by this client
51    advise                                      paths refused queries asked for
52    sql run [--max-rows n] 'SELECT …'           one SELECT over declared paths,
53                                                sent as the IDX.QUERY for it
54    sql compile <file.sql> [--apply]            CREATE TABLE/INDEX/VIEW as
55                                                TABLE.DECLARE / VIEW.CREATE and
56                                                query cards (--apply declares)
57    sql plan <file.sql>                         what becomes of every query
58    sql eval '<SELECT …>' [--at <ts>]           fold a table-free SELECT
59
60  data, one level per pair
61    backup --data-dir <d> --to <f>              a data directory, offline
62    restore --from <f> --to <d>
63    export [--prefix p] <file>                  the keyspace as RESP, online
64    import [--resume] [--strict] <file>
65    dump --schema [--table t]… [--as kevy|sql]  declarations as a script
66    dump --all <dir>                            + each table's declared columns
67    load <dir>                                  rows, declarations, wait-ready,
68                                                doctor
69    export-csv (--prefix p --columns a,b | --table t) [--via \"IDX.QUERY …\"] <f|->
70    import-csv <f> (--prefix p --pk c | --table t | --key-column c)
71               (--header|--columns a,b)
72    copy-prefix [--rate n] <from> <to>
73    delete-prefix [--rate n] [--dry-run] <prefix>
74
75  checks
76    digest <prefix>                             hash a prefix
77    diff <other host:port|redis://…> <prefix>…  compare it with another server
78    inspect <prefix>                            sample keys: types and sizes
79    doctor [--warn-is-failure] [--indexes] [--views]
80                                                VERIFY every table (and bare
81                                                index, view); exit code answers
82    lint overlap --prefix <p:>                  a name under more than one owner?
83    lint columns <table>                        column pairs that agree on most rows
84    backfill-keys --from-index <k> --from-prefix <p:> --from-file <f>
85                                                the union of every source
86    shadow --old <cmd> --new <cmd>              old and new read paths, compared
87                                                in membership and order
88    wait-ready [--index n|--table t|--all] [--timeout s]
89    status                                      server, role, keys, catalogs
90
91  running
92    run [-f file]… [-c cmd]… [--force] [--echo] [--atomic]
93                                                exit 3 on an error reply, 2 on a
94                                                lost link
95    watch <seconds> [count] <command…>
96    feed follow [--prefix p]… [--shard n|all] [--from tail|gen:off]
97                [--checkpoint f] [--as json|resp] [--on-resync stop|jump]
98
99  Rows: --format table|tsv|csv|json, --no-header, --null s, --expanded,
100        --timing (a table on a terminal, tsv when piped).
101
102EXAMPLES:
103    kevy-cli                            # REPL against 127.0.0.1:6379
104    kevy-cli -p 6004                    # REPL against kevy default port
105    kevy-cli -h prod.internal ping      # one-shot PING
106    kevy-cli -p 6004 set greet hello    # one-shot SET, exits 0
107
108    # move a keyspace, and prove it arrived
109    kevy-cli -p 6379 --kevy export --prefix user: dump.resp
110    kevy-cli -p 6380 --kevy import --strict dump.resp
111    kevy-cli -p 6379 --kevy diff 127.0.0.1:6380 user:
112
113Docs: https://github.com/goliajp/kevy
114";
115
116/// `kevy-cli [options] [command]`: the redis-cli half of the binary.
117///
118/// # Examples
119///
120/// ```
121/// // Parsing refuses what redis-cli refuses, with redis-cli's exit code.
122/// assert_eq!(kevy_cli::rcli::run(&[b"-2".to_vec(), b"-3".to_vec()]), 1);
123/// ```
124pub mod rcli;
125
126/// Where a subcommand connects when the caller says nothing. Shared
127/// rather than repeated: two copies of a default is a drift waiting to
128/// be reported as a bug.
129///
130/// ```
131/// use kevy_cli::DEFAULT_HOST;
132/// // loopback, the same default redis-cli has
133/// let ip: std::net::IpAddr = DEFAULT_HOST.parse()?;
134/// assert!(ip.is_loopback());
135/// # Ok::<(), Box<dyn std::error::Error>>(())
136/// ```
137pub const DEFAULT_HOST: &str = "127.0.0.1";
138/// The port half of the same default.
139///
140/// ```
141/// use kevy_cli::{DEFAULT_HOST, DEFAULT_PORT};
142/// // what `kevy-cli` with no -h / -p connects to
143/// assert_eq!(format!("{DEFAULT_HOST}:{DEFAULT_PORT}"), "127.0.0.1:6379");
144/// ```
145pub const DEFAULT_PORT: u16 = 6379;
146
147/// Prefix bulk ops + diagnostics (`copy-prefix` /
148/// `delete-prefix` / `digest` / `diff` / `inspect`).
149pub mod bulk;
150
151/// `shadow` — run the old query and the new one side by side and
152/// report where they disagree, in membership AND in order.
153///
154/// ```
155/// use kevy_cli::shadow::{Shape, run};
156/// # let port = include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/doc_server/serve.rs"));
157/// let mut client = kevy_resp_client::RespClient::connect("127.0.0.1", port)?;
158/// client.request_borrowed(&[b"ZADD", b"feed", b"1", b"a", b"2", b"b", b"3", b"c"])?;
159/// client.request_borrowed(&[b"RPUSH", b"feed:new", b"a", b"c"])?;
160/// let argv = |s: &str| s.split(' ').map(|w| w.as_bytes().to_vec()).collect::<Vec<_>>();
161/// let r = run(&mut client, &argv("ZRANGE feed 0 -1"), &argv("LRANGE feed:new 0 -1"),
162///     Shape::Flat, Shape::Flat, 3)?;
163/// assert_eq!((r.samples, r.diverged), (3, 3));
164/// let (_, first) = r.first.as_ref().expect("the paths disagree");
165/// assert_eq!(first.missing, [b"b".to_vec()], "the writer that never updated feed:new");
166/// # Ok::<(), Box<dyn std::error::Error>>(())
167/// ```
168pub mod shadow;
169
170pub mod backfill_keys;
171pub(crate) mod collections;
172/// `doctor` — every table's VERIFY counters, turned into an exit code
173/// a cron can act on.
174pub mod doctor;
175pub mod link;
176pub mod lint;
177mod tools;
178
179/// Pretty-print a reply roughly the way `redis-cli` does. Arrays are
180/// numbered + indented; bulk strings are quoted; nil shows as `(nil)`.
181///
182/// ```
183/// use kevy_cli::{Reply, format_reply};
184/// assert_eq!(format_reply(&Reply::Nil, 0), "(nil)");
185/// assert_eq!(format_reply(&Reply::Int(3), 0), "(integer) 3");
186/// let nested = Reply::Array(vec![Reply::Bulk(b"a".to_vec()), Reply::Array(vec![Reply::Int(1)])]);
187/// assert_eq!(format_reply(&nested, 0), "1) \"a\"\n2)    1) (integer) 1");
188/// ```
189pub fn format_reply(reply: &Reply, indent: usize) -> String {
190    match reply {
191        Reply::Simple(s) => String::from_utf8_lossy(s).into_owned(),
192        Reply::Error(s) | Reply::BlobError(s) => {
193            format!("(error) {}", String::from_utf8_lossy(s))
194        }
195        Reply::Int(n) => format!("(integer) {n}"),
196        Reply::Bulk(b) => format!("\"{}\"", String::from_utf8_lossy(b)),
197        Reply::Nil | Reply::Null => "(nil)".to_string(),
198        Reply::Array(items) if items.is_empty() => "(empty array)".to_string(),
199        Reply::Array(items) | Reply::Set(items) | Reply::Push(items) => {
200            let pad = "   ".repeat(indent);
201            items
202                .iter()
203                .enumerate()
204                .map(|(i, it)| format!("{pad}{}) {}", i + 1, format_reply(it, indent + 1)))
205                .collect::<Vec<_>>()
206                .join("\n")
207        }
208        // RESP3 additions: format the same way redis-cli does today.
209        Reply::Map(pairs) if pairs.is_empty() => "(empty map)".to_string(),
210        Reply::Map(pairs) => {
211            let pad = "   ".repeat(indent);
212            pairs
213                .iter()
214                .enumerate()
215                .map(|(i, (k, v))| {
216                    format!(
217                        "{pad}{}) {} => {}",
218                        i + 1,
219                        format_reply(k, indent + 1),
220                        format_reply(v, indent + 1)
221                    )
222                })
223                .collect::<Vec<_>>()
224                .join("\n")
225        }
226        Reply::Double(v) => format!("(double) {v}"),
227        Reply::Boolean(b) => format!("(boolean) {}", if *b { "t" } else { "f" }),
228        Reply::Verbatim { fmt, data } => format!(
229            "(verbatim/{}) \"{}\"",
230            String::from_utf8_lossy(fmt),
231            String::from_utf8_lossy(data)
232        ),
233        Reply::BigNumber(s) => format!("(bignum) {}", String::from_utf8_lossy(s)),
234    }
235}
236
237// Send and Sync are part of the public contract: a change that loses
238// either fails to compile here rather than in a caller.
239const _: () = {
240    const fn send_sync<T: Send + Sync>() {}
241    send_sync::<backfill_keys::Source>();
242    send_sync::<backfill_keys::SourceReport>();
243    send_sync::<backfill_keys::Union>();
244    send_sync::<bulk::DeleteMode>();
245    send_sync::<bulk::RateLimiter>();
246    send_sync::<doctor::Health>();
247    send_sync::<doctor::OnWarning>();
248    send_sync::<doctor::Scope>();
249    send_sync::<doctor::TableHealth>();
250    send_sync::<lint::Coincidence>();
251    send_sync::<lint::Overlap>();
252    send_sync::<migrate::Export>();
253    send_sync::<migrate::ImportReport>();
254    send_sync::<migrate::ImportStart>();
255    send_sync::<migrate::OnErrorReply>();
256    send_sync::<shadow::Compared>();
257    send_sync::<shadow::Divergence>();
258    send_sync::<shadow::ShadowReport>();
259    send_sync::<shadow::Shape>();
260};
261
262#[cfg(test)]
263mod format_reply_tests {
264    use super::format_reply;
265    use kevy_resp::Reply;
266
267    fn f(r: &Reply) -> String {
268        format_reply(r, 0)
269    }
270
271    /// One case per `Reply` variant. `format_reply` carried 79 never-executed
272    /// regions — the largest single symbol in this crate — while being a pure
273    /// function from a reply to a string, which is as cheap to test as code
274    /// gets. The expectations are redis-cli's rendering, which is what the
275    /// function's own comment says it follows.
276    #[test]
277    fn every_reply_variant_renders() {
278        assert_eq!(f(&Reply::Simple(b"OK".to_vec())), "OK");
279        assert_eq!(f(&Reply::Error(b"ERR nope".to_vec())), "(error) ERR nope");
280        assert_eq!(f(&Reply::Int(-7)), "(integer) -7");
281        assert_eq!(f(&Reply::Bulk(b"hi".to_vec())), "\"hi\"");
282        assert_eq!(f(&Reply::Nil), "(nil)");
283        assert_eq!(f(&Reply::Array(vec![])), "(empty array)");
284        assert_eq!(f(&Reply::Double(1.5)), "(double) 1.5");
285        assert_eq!(f(&Reply::Boolean(true)), "(boolean) t");
286        assert_eq!(f(&Reply::Boolean(false)), "(boolean) f");
287        assert_eq!(
288            f(&Reply::BigNumber(b"123456789012345678901".to_vec())),
289            "(bignum) 123456789012345678901"
290        );
291
292        // RESP3's second null and second error spelling render as their
293        // RESP2 counterparts — a client must not be able to tell which
294        // wire form it got from the printed line.
295        assert_eq!(f(&Reply::Null), "(nil)");
296        assert_eq!(f(&Reply::BlobError(b"ERR nope".to_vec())), "(error) ERR nope");
297
298        assert_eq!(
299            f(&Reply::Verbatim { fmt: *b"txt", data: b"hello".to_vec() }),
300            "(verbatim/txt) \"hello\""
301        );
302
303        // Set and Push share the array arm; a set of one is still numbered.
304        assert_eq!(f(&Reply::Set(vec![Reply::Int(4)])), "1) (integer) 4");
305        assert_eq!(f(&Reply::Push(vec![Reply::Bulk(b"message".to_vec())])), "1) \"message\"");
306    }
307
308    /// Arrays number from one and nest by indent — the recursive arm, which
309    /// a single flat array would leave unexercised.
310    #[test]
311    fn arrays_number_from_one_and_nest() {
312        let flat = Reply::Array(vec![Reply::Int(1), Reply::Bulk(b"x".to_vec())]);
313        assert_eq!(f(&flat), "1) (integer) 1\n2) \"x\"");
314
315        let nested = Reply::Array(vec![Reply::Array(vec![Reply::Int(9)])]);
316        // The inner element is padded by one level; the outer is not.
317        assert_eq!(f(&nested), "1)    1) (integer) 9");
318    }
319
320    /// An empty map is not an empty array, and a populated one renders
321    /// `key => value` rather than as two flat elements.
322    #[test]
323    fn maps_render_as_pairs() {
324        assert_eq!(f(&Reply::Map(vec![])), "(empty map)");
325        let m = Reply::Map(vec![(Reply::Bulk(b"k".to_vec()), Reply::Int(1))]);
326        assert_eq!(f(&m), "1) \"k\" => (integer) 1");
327    }
328}