Skip to main content

reddb_server/cli/
commands.rs

1/// RedDB command definitions.
2///
3/// Defines the command tree, Flag and Route types used by help and completion
4/// generators, and the schema for each built-in command.
5use super::types::FlagSchema;
6
7// ============================================================================
8// Help-layer types (used by help.rs and complete.rs)
9// ============================================================================
10
11/// Lightweight flag descriptor used by the help generator.
12#[derive(Debug, Clone)]
13pub struct Flag {
14    pub short: Option<char>,
15    pub long: String,
16    pub description: String,
17    pub default: Option<String>,
18    pub arg: Option<String>,
19}
20
21impl Flag {
22    pub fn new(long: &str, desc: &str) -> Self {
23        Self {
24            short: None,
25            long: long.to_string(),
26            description: desc.to_string(),
27            default: None,
28            arg: None,
29        }
30    }
31
32    pub fn with_short(mut self, short: char) -> Self {
33        self.short = Some(short);
34        self
35    }
36
37    pub fn with_default(mut self, default: &str) -> Self {
38        self.default = Some(default.to_string());
39        self
40    }
41
42    pub fn with_arg(mut self, arg: &str) -> Self {
43        self.arg = Some(arg.to_string());
44        self
45    }
46}
47
48/// A single routable verb within a resource.
49#[derive(Debug, Clone)]
50pub struct Route {
51    pub verb: &'static str,
52    pub summary: &'static str,
53    pub usage: &'static str,
54}
55
56// ============================================================================
57// RedDB command definitions
58// ============================================================================
59
60/// Command descriptor for a top-level RedDB command.
61pub struct CommandDef {
62    pub name: &'static str,
63    pub summary: &'static str,
64    pub usage: &'static str,
65    pub flags: Vec<FlagSchema>,
66}
67
68/// Return all RedDB commands.
69pub fn all_commands() -> Vec<CommandDef> {
70    vec![
71    CommandDef {
72      name: "server",
73      summary: "Start the database server (router/HTTP/gRPC/wire)",
74      usage: "red server [--grpc] [--http] [--grpc-bind 127.0.0.1:5555] [--http-bind 127.0.0.1:5055] [--wire-bind 127.0.0.1:5050] [--path ./data/reddb.rdb]",
75      flags: server_flags(),
76    },
77    CommandDef {
78      name: "service",
79      summary: "Install or inspect a systemd service",
80      usage: "red service <install|print-unit> [--binary /usr/local/bin/red] [--grpc-bind 0.0.0.0:5555] [--http-bind 0.0.0.0:5055] [--path /var/lib/reddb/data.rdb]",
81      flags: service_flags(),
82    },
83    CommandDef {
84      name: "query",
85      summary: "Execute a query against the database",
86      usage: "red query \"SELECT * FROM users WHERE age > $1\" -p 21",
87      flags: query_flags(),
88    },
89    CommandDef {
90      name: "insert",
91      summary: "Insert an entity into a collection",
92      usage: "red insert users '{\"name\": \"Alice\", \"age\": 30}'",
93      flags: insert_flags(),
94    },
95    CommandDef {
96      name: "get",
97      summary: "Get an entity by ID from a collection",
98      usage: "red get users abc123",
99      flags: get_flags(),
100    },
101    CommandDef {
102      name: "delete",
103      summary: "Delete an entity by ID from a collection",
104      usage: "red delete users abc123",
105      flags: delete_flags(),
106    },
107    CommandDef {
108      name: "health",
109      summary: "Run a health check against the server",
110      usage: "red health [--bind 127.0.0.1:5050] [--grpc|--http]",
111      flags: health_flags(),
112    },
113    CommandDef {
114      name: "tick",
115      summary: "Run maintenance/reclaim tick operations",
116      usage: "red tick [--bind 127.0.0.1:5055] [--operations maintenance,retention,checkpoint] [--dry-run]",
117      flags: tick_flags(),
118    },
119    CommandDef {
120      name: "migrate-from-redis",
121      summary: "Validate Redis to Blob Cache migration readiness; dual-write uses the documented application-owned helper pattern",
122      usage: "red migrate-from-redis --dry-run --redis-url redis://127.0.0.1:6379/0 [--path ./data/reddb.rdb]",
123      flags: migrate_from_redis_flags(),
124    },
125    CommandDef {
126      name: "replica",
127      summary: "Start as a read replica connected to a primary",
128      usage: "red replica --primary-addr http://primary:5555 [--grpc] [--http] [--grpc-bind 127.0.0.1:5555] [--http-bind 127.0.0.1:5055] [--path ./data/reddb.rdb]",
129      flags: replica_flags(),
130    },
131    CommandDef {
132      name: "status",
133      summary: "Show replication status",
134      usage: "red status [--bind 0.0.0.0:6380]",
135      flags: status_flags(),
136    },
137    CommandDef {
138      name: "inspect",
139      summary: "Inspect on-disk database state (catalog snapshot)",
140      usage: "red inspect catalog --path <FILE> [--at <SEQ>] [--json]",
141      flags: inspect_flags(),
142    },
143    CommandDef {
144      name: "mcp",
145      summary: "Start MCP server for AI agent integration",
146      usage: "red mcp [--path /data]",
147      flags: mcp_flags(),
148    },
149    CommandDef {
150      name: "auth",
151      summary: "Manage authentication (users, tokens, roles)",
152      usage: "red auth <subcommand>",
153      flags: auth_flags(),
154    },
155    CommandDef {
156      name: "connect",
157      summary: "Connect to a remote RedDB server (interactive REPL)",
158      usage: "red connect [--token <token>] [--query <sql>] <addr>",
159      flags: connect_flags(),
160    },
161    CommandDef {
162      name: "dump",
163      summary: "Export one or all collections as JSONL for backup/migration",
164      usage: "red dump [--path file] [--collection NAME] [-o FILE]",
165      flags: dump_flags(),
166    },
167    CommandDef {
168      name: "restore",
169      summary: "Import a previously dumped JSONL file into the database",
170      usage: "red restore [--path file] -i FILE [--collection NAME]",
171      flags: restore_flags(),
172    },
173    CommandDef {
174      name: "pitr-list",
175      summary: "List available point-in-time restore points from a snapshot archive",
176      usage: "red pitr-list --snapshot-prefix DIR --wal-prefix DIR",
177      flags: pitr_list_flags(),
178    },
179    CommandDef {
180      name: "pitr-restore",
181      summary: "Restore a database to a specific point in time from snapshots + WAL archive",
182      usage: "red pitr-restore --target-time UNIX_MS --dest PATH --snapshot-prefix DIR --wal-prefix DIR",
183      flags: pitr_restore_flags(),
184    },
185    CommandDef {
186      name: "doctor",
187      summary: "Health-check a running server against operator thresholds (PLAN.md Phase 5.5)",
188      usage: "red doctor [--bind 127.0.0.1:5055] [--token <admin>] [--json] [--backup-age-warn-secs 600] [--backup-age-crit-secs 3600] [--wal-lag-warn 1000] [--wal-lag-crit 10000]",
189      flags: doctor_flags(),
190    },
191    CommandDef {
192      name: "bootstrap",
193      summary: "One-shot first-admin bootstrap for headless containers / K8s Jobs",
194      usage: "red bootstrap --path PATH --vault [--username USER] [--password-stdin] [--print-certificate] [--json]",
195      flags: bootstrap_flags(),
196    },
197    CommandDef {
198      name: "version",
199      summary: "Show RedDB version information",
200      usage: "red version",
201      flags: vec![],
202    },
203    CommandDef {
204      name: "vcs",
205      summary: "Version-control operations (Git for Data)",
206      usage: "red vcs <commit|branch|branches|tag|tags|checkout|merge|log|status|lca|resolve> [args] [flags]",
207      flags: vcs_flags(),
208    },
209  ]
210}
211
212/// Return the help text for the main `red` command.
213pub fn main_help_text() -> String {
214    let mut out = String::with_capacity(1024);
215
216    out.push_str("reddb -- unified multi-model database engine\n");
217    out.push('\n');
218    out.push_str("Usage: red <command> [args] [flags]\n");
219    out.push('\n');
220
221    out.push_str("Commands:\n");
222    for cmd in all_commands() {
223        out.push_str(&format!("  {:<14} {}\n", cmd.name, cmd.summary));
224    }
225    out.push_str(&format!("  {:<14} {}\n", "help", "Show help for a command"));
226    out.push('\n');
227
228    out.push_str("Global flags:\n");
229    out.push_str(&format!("  {:<24} {}\n", "-h, --help", "Show help"));
230    out.push_str(&format!("  {:<24} {}\n", "-j, --json", "Force JSON output"));
231    out.push_str(&format!(
232        "  {:<24} {}\n",
233        "-o, --output FORMAT", "Output format [text|json|yaml]"
234    ));
235    out.push_str(&format!("  {:<24} {}\n", "-v, --verbose", "Verbose output"));
236    out.push_str(&format!(
237        "  {:<24} {}\n",
238        "    --no-color", "Disable colors"
239    ));
240    out.push_str(&format!("  {:<24} {}\n", "    --version", "Show version"));
241    out.push('\n');
242
243    out.push_str("Examples:\n");
244    out.push_str("  red server --path ./data/reddb.rdb\n");
245    out.push_str("  red server --grpc-bind 127.0.0.1:5555 --http-bind 127.0.0.1:5055 --path ./data/reddb.rdb\n");
246    out.push_str("  red server --wire-bind 127.0.0.1:5050 --path ./data/reddb.rdb\n");
247    out.push_str("  sudo red service install --binary /usr/local/bin/red --grpc-bind 0.0.0.0:5555 --http-bind 0.0.0.0:5055 --path /var/lib/reddb/data.rdb\n");
248    out.push_str("  red replica --primary-addr http://primary:5555 --path ./data/replica.rdb\n");
249    out.push_str("  red query \"SELECT * FROM users\"\n");
250    out.push_str("  red insert users '{\"name\": \"Alice\"}'\n");
251    out.push_str("  red get users abc123\n");
252    out.push_str("  red health\n");
253    out.push_str(
254        "  red tick --bind 127.0.0.1:5055 --operations maintenance,retention,checkpoint\n",
255    );
256    out.push_str("  red auth create-user alice --password secret --role admin\n");
257    out.push_str("  red auth create-api-key alice --name \"ci-token\" --role write\n");
258    out.push_str("  red auth list-users\n");
259    out.push_str("  red auth login alice --password secret\n");
260    out.push_str("  red connect 127.0.0.1:5050\n");
261    out.push_str("  red connect --query \"SELECT * FROM users\" 127.0.0.1:5050\n");
262    out.push('\n');
263
264    out.push_str("Run 'red <command> --help' for more information on a command.\n");
265    out
266}
267
268/// Return help text for a specific command.
269pub fn command_help_text(name: &str) -> Option<String> {
270    let cmds = all_commands();
271    let cmd = cmds.iter().find(|c| c.name == name)?;
272
273    let mut out = String::with_capacity(512);
274
275    out.push_str(&format!("red {} -- {}\n", cmd.name, cmd.summary));
276    out.push('\n');
277    out.push_str(&format!("Usage: {}\n", cmd.usage));
278    out.push('\n');
279
280    if !cmd.flags.is_empty() {
281        out.push_str("Flags:\n");
282        for flag in &cmd.flags {
283            let short_part = match flag.short {
284                Some(ch) => format!("-{}, ", ch),
285                None => "    ".to_string(),
286            };
287            let value_part = if flag.expects_value {
288                format!(" <{}>", flag.long.to_uppercase())
289            } else {
290                String::new()
291            };
292            let label = format!("{}--{}{}", short_part, flag.long, value_part);
293            let padding = if label.len() < 24 {
294                24 - label.len()
295            } else {
296                2
297            };
298            let default_text = match &flag.default {
299                Some(d) => format!(" (default: {})", d),
300                None => String::new(),
301            };
302            out.push_str(&format!(
303                "  {}{}{}{}\n",
304                label,
305                " ".repeat(padding),
306                flag.description,
307                default_text,
308            ));
309        }
310        out.push('\n');
311    }
312
313    Some(out)
314}
315
316// ============================================================================
317// Per-command flag schemas
318// ============================================================================
319
320fn server_flags() -> Vec<FlagSchema> {
321    vec![
322        FlagSchema::new("path")
323            .with_short('d')
324            .with_description("Persistent database file path (omit for in-memory)")
325            .with_default("./data/reddb.rdb"),
326        FlagSchema::new("bind").with_short('b').with_description(
327            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
328        ),
329        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
330        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
331        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
332        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
333        FlagSchema::new("wire-bind")
334            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
335        FlagSchema::new("wire-tls-bind")
336            .with_description("Explicit wire TLS bind address (host:port)"),
337        FlagSchema::new("wire-tls-cert")
338            .with_description("Path to TLS certificate PEM for wire TLS"),
339        FlagSchema::new("wire-tls-key")
340            .with_description("Path to TLS private key PEM for wire TLS"),
341        FlagSchema::new("pg-bind").with_description(
342            "PostgreSQL wire protocol bind address (enables psql / JDBC / DBeaver clients)",
343        ),
344        FlagSchema::new("role")
345            .with_short('r')
346            .with_description("Replication role")
347            .with_choices(&["standalone", "primary", "replica"])
348            .with_default("standalone"),
349        FlagSchema::new("primary-addr").with_description("Primary gRPC address for replica mode"),
350        FlagSchema::boolean("read-only").with_description("Open the database in read-only mode"),
351        FlagSchema::boolean("no-create-if-missing")
352            .with_description("Fail instead of creating the database file"),
353        FlagSchema::new("vault")
354            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
355            .with_default("false"),
356        FlagSchema::new("log-dir").with_description(
357            "Directory for rotating log files (defaults to the parent of --path / ./logs)",
358        ),
359        FlagSchema::new("log-level")
360            .with_description(
361                "Log level filter — trace / debug / info / warn / error, or a RUST_LOG expression",
362            )
363            .with_default("info"),
364        FlagSchema::new("log-format")
365            .with_description("Log output format")
366            .with_choices(&["pretty", "json"])
367            .with_default("pretty"),
368        FlagSchema::new("log-keep-days")
369            .with_description("Number of rotated log files to keep")
370            .with_default("14"),
371        FlagSchema::boolean("no-log-file")
372            .with_description("Disable rotating file logs (stderr only)"),
373        FlagSchema::new("http-max-handlers").with_description(
374            "Max concurrent HTTP handler threads (env: REDDB_HTTP_MAX_HANDLERS; \
375             red_config: red.http.max_handlers; default: (2 x num_cpus).clamp(8, 256))",
376        ),
377        FlagSchema::new("http-handler-timeout-ms").with_description(
378            "Per-handler total-time budget in ms (env: REDDB_HTTP_HANDLER_TIMEOUT_MS; \
379             red_config: red.http.handler_timeout_ms)",
380        )
381            .with_default("30000"),
382        FlagSchema::new("http-retry-after-secs").with_description(
383            "Retry-After seconds on limiter 503 (env: REDDB_HTTP_RETRY_AFTER_SECS; \
384             red_config: red.http.retry_after_secs; clamped to [1, 30])",
385        )
386            .with_default("5"),
387    ]
388}
389
390fn replica_flags() -> Vec<FlagSchema> {
391    vec![
392        FlagSchema::new("primary-addr")
393            .with_short('p')
394            .with_description("Primary gRPC address (e.g. http://primary:50051)"),
395        FlagSchema::new("path")
396            .with_short('d')
397            .with_description("Local replica database file path")
398            .with_default("./data/reddb.rdb"),
399        FlagSchema::new("bind").with_short('b').with_description(
400            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
401        ),
402        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
403        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
404        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
405        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
406        FlagSchema::new("wire-bind")
407            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
408        FlagSchema::new("vault")
409            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
410            .with_default("false"),
411    ]
412}
413
414fn vcs_flags() -> Vec<FlagSchema> {
415    vec![
416        FlagSchema::new("path")
417            .with_short('d')
418            .with_description("Persistent database file path (omit for in-memory)"),
419        FlagSchema::new("connection")
420            .with_short('c')
421            .with_description("Connection id for workset scoping")
422            .with_default("1"),
423        FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
424        FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
425        FlagSchema::new("to").with_description("Upper bound for log range"),
426        FlagSchema::new("author")
427            .with_description("Commit author name")
428            .with_default("reddb"),
429        FlagSchema::new("email")
430            .with_description("Commit author email")
431            .with_default("reddb@localhost"),
432        FlagSchema::new("message")
433            .with_short('m')
434            .with_description("Commit message"),
435        FlagSchema::new("limit")
436            .with_description("Max log entries")
437            .with_default("20"),
438        FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
439        FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
440    ]
441}
442
443fn service_flags() -> Vec<FlagSchema> {
444    vec![
445        FlagSchema::new("binary")
446            .with_description("Path to the red binary")
447            .with_default("/usr/local/bin/red"),
448        FlagSchema::new("service-name")
449            .with_description("systemd unit name")
450            .with_default("reddb"),
451        FlagSchema::new("user")
452            .with_description("Service user")
453            .with_default("reddb"),
454        FlagSchema::new("group")
455            .with_description("Service group")
456            .with_default("reddb"),
457        FlagSchema::new("path")
458            .with_short('d')
459            .with_description("Persistent database file path")
460            .with_default("/var/lib/reddb/data.rdb"),
461        FlagSchema::new("bind").with_short('b').with_description(
462            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
463        ),
464        FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
465        FlagSchema::boolean("http").with_description("Install an HTTP service"),
466        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
467        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
468    ]
469}
470
471fn query_flags() -> Vec<FlagSchema> {
472    vec![
473        FlagSchema::new("bind")
474            .with_short('b')
475            .with_description("Server address")
476            .with_default("0.0.0.0:6380"),
477        FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode"),
478        FlagSchema::new("param")
479            .with_short('p')
480            .with_description("Positional parameter for $1, $2, ... (repeatable)"),
481        FlagSchema::new("param-type").with_description("Type override for the preceding --param"),
482    ]
483}
484
485fn insert_flags() -> Vec<FlagSchema> {
486    vec![FlagSchema::new("bind")
487        .with_short('b')
488        .with_description("Server address")
489        .with_default("0.0.0.0:6380")]
490}
491
492fn get_flags() -> Vec<FlagSchema> {
493    vec![FlagSchema::new("bind")
494        .with_short('b')
495        .with_description("Server address")
496        .with_default("0.0.0.0:6380")]
497}
498
499fn delete_flags() -> Vec<FlagSchema> {
500    vec![FlagSchema::new("bind")
501        .with_short('b')
502        .with_description("Server address")
503        .with_default("0.0.0.0:6380")]
504}
505
506fn health_flags() -> Vec<FlagSchema> {
507    vec![
508        FlagSchema::new("bind")
509            .with_short('b')
510            .with_description("Server address; defaults by transport"),
511        FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
512        FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
513    ]
514}
515
516fn bootstrap_flags() -> Vec<FlagSchema> {
517    vec![
518        FlagSchema::new("path")
519            .with_short('d')
520            .with_description("Persistent database file path"),
521        FlagSchema::boolean("vault")
522            .with_description("Required: seal credentials in the encrypted vault"),
523        FlagSchema::new("username")
524            .with_short('u')
525            .with_description("Admin username (defaults to REDDB_USERNAME)"),
526        FlagSchema::new("password")
527            .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
528        FlagSchema::boolean("password-stdin")
529            .with_description("Read the admin password from stdin (one line)"),
530        FlagSchema::boolean("print-certificate")
531            .with_description("Print only the certificate to stdout"),
532    ]
533}
534
535fn doctor_flags() -> Vec<FlagSchema> {
536    vec![
537        FlagSchema::new("bind")
538            .with_description("HTTP address of the server to probe")
539            .with_default("127.0.0.1:5055"),
540        FlagSchema::new("token")
541            .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
542        FlagSchema::boolean("json")
543            .with_description("Emit a single JSON object instead of human text"),
544        FlagSchema::new("backup-age-warn-secs")
545            .with_description("Warn when last successful backup is older than N seconds")
546            .with_default("600"),
547        FlagSchema::new("backup-age-crit-secs")
548            .with_description("Critical when last successful backup is older than N seconds")
549            .with_default("3600"),
550        FlagSchema::new("wal-lag-warn")
551            .with_description("Warn when WAL archive lag exceeds N records")
552            .with_default("1000"),
553        FlagSchema::new("wal-lag-crit")
554            .with_description("Critical when WAL archive lag exceeds N records")
555            .with_default("10000"),
556    ]
557}
558
559fn dump_flags() -> Vec<FlagSchema> {
560    vec![
561        FlagSchema::new("path")
562            .with_description("Local database file to dump from")
563            .with_default("./data/reddb.rdb"),
564        FlagSchema::new("collection")
565            .with_short('c')
566            .with_description("Single collection to dump (omit for all)"),
567        FlagSchema::new("output")
568            .with_short('o')
569            .with_description("Destination file (defaults to stdout)"),
570    ]
571}
572
573fn restore_flags() -> Vec<FlagSchema> {
574    vec![
575        FlagSchema::new("path")
576            .with_description("Local database file to restore into")
577            .with_default("./data/reddb.rdb"),
578        FlagSchema::new("input")
579            .with_short('i')
580            .with_description("Dump file to read (required)"),
581        FlagSchema::new("collection")
582            .with_short('c')
583            .with_description("Override target collection name"),
584    ]
585}
586
587fn pitr_list_flags() -> Vec<FlagSchema> {
588    vec![
589        FlagSchema::new("snapshot-prefix")
590            .with_description("Directory (or remote prefix) holding .snapshot files"),
591        FlagSchema::new("wal-prefix")
592            .with_description("Directory (or remote prefix) holding archived WAL segments"),
593    ]
594}
595
596fn pitr_restore_flags() -> Vec<FlagSchema> {
597    vec![
598        FlagSchema::new("target-time")
599            .with_description("Recovery target — UNIX ms (0 = latest available)"),
600        FlagSchema::new("dest")
601            .with_description("Destination database file path for the restored DB"),
602        FlagSchema::new("snapshot-prefix")
603            .with_description("Directory (or remote prefix) holding .snapshot files"),
604        FlagSchema::new("wal-prefix")
605            .with_description("Directory (or remote prefix) holding archived WAL segments"),
606    ]
607}
608
609fn tick_flags() -> Vec<FlagSchema> {
610    vec![
611        FlagSchema::new("bind")
612            .with_short('b')
613            .with_description("Server HTTP bind address")
614            .with_default("127.0.0.1:5055"),
615        FlagSchema::new("operations")
616            .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
617        FlagSchema::boolean("dry-run")
618            .with_description("Validate operations without applying changes"),
619    ]
620}
621
622fn migrate_from_redis_flags() -> Vec<FlagSchema> {
623    vec![
624        FlagSchema::boolean("dry-run")
625            .with_description("Validate Redis and RedDB connectivity without cache writes"),
626        FlagSchema::new("redis-url")
627            .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
628        FlagSchema::new("path")
629            .with_short('d')
630            .with_description("Local RedDB .rdb file to open for connectivity validation"),
631        FlagSchema::new("phase")
632            .with_description("Migration phase: dry-run | dual-write")
633            .with_default("dry-run"),
634        FlagSchema::new("namespace")
635            .with_description("Blob Cache namespace recorded in dry-run output")
636            .with_default("redis-migration"),
637    ]
638}
639
640fn status_flags() -> Vec<FlagSchema> {
641    vec![FlagSchema::new("bind")
642        .with_short('b')
643        .with_description("Server address")
644        .with_default("0.0.0.0:6380")]
645}
646
647fn inspect_flags() -> Vec<FlagSchema> {
648    vec![
649        FlagSchema::new("path")
650            .with_short('d')
651            .with_description("Path to the on-disk database file"),
652        FlagSchema::new("at")
653            .with_description("Catalog at snapshot sequence (requires metadata journal)"),
654    ]
655}
656
657fn mcp_flags() -> Vec<FlagSchema> {
658    vec![FlagSchema::new("path")
659        .with_short('d')
660        .with_description("Data directory path (omit for in-memory)")
661        .with_default("")]
662}
663
664fn connect_flags() -> Vec<FlagSchema> {
665    vec![
666        FlagSchema::new("token")
667            .with_short('t')
668            .with_description("Auth token (session or API key)"),
669        FlagSchema::new("query")
670            .with_short('q')
671            .with_description("Execute a single query and exit"),
672        FlagSchema::new("user")
673            .with_short('u')
674            .with_description("Username for login"),
675        FlagSchema::new("password")
676            .with_short('p')
677            .with_description("Password for login"),
678    ]
679}
680
681fn auth_flags() -> Vec<FlagSchema> {
682    vec![
683        FlagSchema::new("bind")
684            .with_short('b')
685            .with_description("Server address")
686            .with_default("0.0.0.0:6380"),
687        FlagSchema::new("password")
688            .with_short('p')
689            .with_description("User password"),
690        FlagSchema::new("role")
691            .with_short('r')
692            .with_description("User role")
693            .with_choices(&["read", "write", "admin"]),
694        FlagSchema::new("name")
695            .with_short('n')
696            .with_description("API key name"),
697        FlagSchema::new("user")
698            .with_short('u')
699            .with_description("Target username"),
700    ]
701}
702
703// ============================================================================
704// Completion data helpers
705// ============================================================================
706
707/// Return domain data for completion scripts.
708pub fn completion_domains() -> Vec<(String, Vec<String>)> {
709    vec![
710        ("server".to_string(), vec![]),
711        ("service".to_string(), vec![]),
712        ("replica".to_string(), vec![]),
713        ("tick".to_string(), vec![]),
714        ("query".to_string(), vec!["q".to_string()]),
715        ("insert".to_string(), vec!["i".to_string()]),
716        ("get".to_string(), vec![]),
717        ("delete".to_string(), vec!["del".to_string()]),
718        ("health".to_string(), vec![]),
719        ("status".to_string(), vec![]),
720        ("inspect".to_string(), vec![]),
721        ("migrate-from-redis".to_string(), vec![]),
722        ("mcp".to_string(), vec![]),
723        ("auth".to_string(), vec![]),
724        ("connect".to_string(), vec![]),
725        ("version".to_string(), vec![]),
726    ]
727}
728
729/// Return global flag data for completion scripts.
730pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
731    vec![
732        ("help", Some('h')),
733        ("json", Some('j')),
734        ("output", Some('o')),
735        ("verbose", Some('v')),
736        ("no-color", None),
737        ("version", None),
738    ]
739}
740
741#[cfg(test)]
742mod tests {
743    use super::*;
744
745    #[test]
746    fn test_all_commands_defined() {
747        let cmds = all_commands();
748        let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
749        assert!(names.contains(&"server"));
750        assert!(names.contains(&"query"));
751        assert!(names.contains(&"insert"));
752        assert!(names.contains(&"get"));
753        assert!(names.contains(&"delete"));
754        assert!(names.contains(&"health"));
755        assert!(names.contains(&"tick"));
756        assert!(names.contains(&"migrate-from-redis"));
757        assert!(names.contains(&"status"));
758        assert!(names.contains(&"inspect"));
759        assert!(names.contains(&"connect"));
760        assert!(names.contains(&"version"));
761    }
762
763    #[test]
764    fn test_inspect_has_flags() {
765        let cmds = all_commands();
766        let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
767        let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
768        assert!(flag_names.contains(&"path"));
769        assert!(flag_names.contains(&"at"));
770    }
771
772    #[test]
773    fn test_server_has_flags() {
774        let cmds = all_commands();
775        let server = cmds.iter().find(|c| c.name == "server").unwrap();
776        let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
777        assert!(flag_names.contains(&"path"));
778        assert!(flag_names.contains(&"bind"));
779        // Slice 5 of issue #574 — HTTP handler-pool knobs.
780        assert!(flag_names.contains(&"http-max-handlers"));
781        assert!(flag_names.contains(&"http-handler-timeout-ms"));
782        assert!(flag_names.contains(&"http-retry-after-secs"));
783    }
784
785    #[test]
786    fn test_server_help_text_lists_http_limit_flags() {
787        let help = command_help_text("server").unwrap();
788        assert!(help.contains("--http-max-handlers"));
789        assert!(help.contains("--http-handler-timeout-ms"));
790        assert!(help.contains("--http-retry-after-secs"));
791        assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
792    }
793
794    #[test]
795    fn test_replica_has_flags() {
796        let cmds = all_commands();
797        let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
798        let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
799        assert!(flag_names.contains(&"primary-addr"));
800        assert!(flag_names.contains(&"path"));
801        assert!(flag_names.contains(&"bind"));
802    }
803
804    #[test]
805    fn test_main_help_text() {
806        let help = main_help_text();
807        assert!(help.contains("reddb"));
808        assert!(help.contains("Usage: red"));
809        assert!(help.contains("Commands:"));
810        assert!(help.contains("server"));
811        assert!(help.contains("query"));
812        assert!(help.contains("Global flags:"));
813        assert!(help.contains("--help"));
814        assert!(help.contains("Examples:"));
815    }
816
817    #[test]
818    fn test_command_help_text() {
819        let help = command_help_text("server").unwrap();
820        assert!(help.contains("red server"));
821        assert!(help.contains("--path"));
822        assert!(help.contains("--bind"));
823    }
824
825    #[test]
826    fn test_replica_command_help() {
827        let help = command_help_text("replica").unwrap();
828        assert!(help.contains("red replica"));
829        assert!(help.contains("--primary-addr"));
830    }
831
832    #[test]
833    fn test_migrate_from_redis_command_help() {
834        let help = command_help_text("migrate-from-redis").unwrap();
835        assert!(help.contains("red migrate-from-redis"));
836        assert!(help.contains("--dry-run"));
837        assert!(help.contains("--redis-url"));
838        assert!(help.contains("application-owned helper"));
839    }
840
841    #[test]
842    fn test_command_help_text_unknown() {
843        assert!(command_help_text("nonexistent").is_none());
844    }
845
846    #[test]
847    fn test_flag_builder() {
848        let flag = Flag::new("output", "Output format")
849            .with_short('o')
850            .with_default("text")
851            .with_arg("FORMAT");
852
853        assert_eq!(flag.long, "output");
854        assert_eq!(flag.short, Some('o'));
855        assert_eq!(flag.description, "Output format");
856        assert_eq!(flag.default, Some("text".to_string()));
857        assert_eq!(flag.arg, Some("FORMAT".to_string()));
858    }
859
860    #[test]
861    fn test_completion_domains() {
862        let domains = completion_domains();
863        let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
864        assert!(names.contains(&"server"));
865        assert!(names.contains(&"query"));
866        assert!(names.contains(&"health"));
867    }
868
869    #[test]
870    fn test_completion_global_flags() {
871        let flags = completion_global_flags();
872        assert!(flags.contains(&("help", Some('h'))));
873        assert!(flags.contains(&("json", Some('j'))));
874        assert!(flags.contains(&("verbose", Some('v'))));
875        assert!(flags.contains(&("no-color", None)));
876    }
877}