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::boolean("no-auth").with_description(
357            "Hard-disable auth: anonymous access, ignores REDDB_USERNAME/PASSWORD/vault, \
358             prints a startup warning. Local-dev shortcut — NEVER use in production.",
359        ),
360        FlagSchema::boolean("dev")
361            .with_description("Alias for --no-auth (local development convenience)."),
362        FlagSchema::new("log-dir").with_description(
363            "Directory for rotating log files (defaults to the parent of --path / ./logs)",
364        ),
365        FlagSchema::new("log-level")
366            .with_description(
367                "Log level filter — trace / debug / info / warn / error, or a RUST_LOG expression",
368            )
369            .with_default("info"),
370        FlagSchema::new("log-format")
371            .with_description("Log output format")
372            .with_choices(&["pretty", "json"])
373            .with_default("pretty"),
374        FlagSchema::new("log-keep-days")
375            .with_description("Number of rotated log files to keep")
376            .with_default("14"),
377        FlagSchema::boolean("no-log-file")
378            .with_description("Disable rotating file logs (stderr only)"),
379        FlagSchema::new("http-max-handlers").with_description(
380            "Max concurrent HTTP handler threads (env: REDDB_HTTP_MAX_HANDLERS; \
381             red_config: red.http.max_handlers; default: (2 x num_cpus).clamp(8, 256))",
382        ),
383        FlagSchema::new("http-handler-timeout-ms")
384            .with_description(
385                "Per-handler total-time budget in ms (env: REDDB_HTTP_HANDLER_TIMEOUT_MS; \
386             red_config: red.http.handler_timeout_ms)",
387            )
388            .with_default("30000"),
389        FlagSchema::new("http-retry-after-secs")
390            .with_description(
391                "Retry-After seconds on limiter 503 (env: REDDB_HTTP_RETRY_AFTER_SECS; \
392             red_config: red.http.retry_after_secs; clamped to [1, 30])",
393            )
394            .with_default("5"),
395        FlagSchema::new("http-max-inflight-per-principal").with_description(
396            "Max concurrent in-flight HTTP requests per principal; over-cap requests \
397             get a structured 429 (env: REDDB_HTTP_MAX_INFLIGHT_PER_PRINCIPAL; \
398             red_config: red.http.max_inflight_per_principal; 0 disables; default: 64)",
399        ),
400    ]
401}
402
403fn replica_flags() -> Vec<FlagSchema> {
404    vec![
405        FlagSchema::new("primary-addr")
406            .with_short('p')
407            .with_description("Primary gRPC address (e.g. http://primary:50051)"),
408        FlagSchema::new("path")
409            .with_short('d')
410            .with_description("Local replica database file path")
411            .with_default("./data/reddb.rdb"),
412        FlagSchema::new("bind").with_short('b').with_description(
413            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
414        ),
415        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
416        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
417        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
418        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
419        FlagSchema::new("wire-bind")
420            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
421        FlagSchema::new("vault")
422            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
423            .with_default("false"),
424    ]
425}
426
427fn vcs_flags() -> Vec<FlagSchema> {
428    vec![
429        FlagSchema::new("path")
430            .with_short('d')
431            .with_description("Persistent database file path (omit for in-memory)"),
432        FlagSchema::new("connection")
433            .with_short('c')
434            .with_description("Connection id for workset scoping")
435            .with_default("1"),
436        FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
437        FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
438        FlagSchema::new("to").with_description("Upper bound for log range"),
439        FlagSchema::new("author")
440            .with_description("Commit author name")
441            .with_default("reddb"),
442        FlagSchema::new("email")
443            .with_description("Commit author email")
444            .with_default("reddb@localhost"),
445        FlagSchema::new("message")
446            .with_short('m')
447            .with_description("Commit message"),
448        FlagSchema::new("limit")
449            .with_description("Max log entries")
450            .with_default("20"),
451        FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
452        FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
453    ]
454}
455
456fn service_flags() -> Vec<FlagSchema> {
457    vec![
458        FlagSchema::new("binary")
459            .with_description("Path to the red binary")
460            .with_default("/usr/local/bin/red"),
461        FlagSchema::new("service-name")
462            .with_description("systemd unit name")
463            .with_default("reddb"),
464        FlagSchema::new("user")
465            .with_description("Service user")
466            .with_default("reddb"),
467        FlagSchema::new("group")
468            .with_description("Service group")
469            .with_default("reddb"),
470        FlagSchema::new("path")
471            .with_short('d')
472            .with_description("Persistent database file path")
473            .with_default("/var/lib/reddb/data.rdb"),
474        FlagSchema::new("bind").with_short('b').with_description(
475            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
476        ),
477        FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
478        FlagSchema::boolean("http").with_description("Install an HTTP service"),
479        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
480        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
481    ]
482}
483
484fn query_flags() -> Vec<FlagSchema> {
485    vec![
486        FlagSchema::new("bind")
487            .with_short('b')
488            .with_description("Server address")
489            .with_default("0.0.0.0:6380"),
490        FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode"),
491        FlagSchema::new("param")
492            .with_short('p')
493            .with_description("Positional parameter for $1, $2, ... (repeatable)"),
494        FlagSchema::new("param-type").with_description("Type override for the preceding --param"),
495    ]
496}
497
498fn insert_flags() -> Vec<FlagSchema> {
499    vec![FlagSchema::new("bind")
500        .with_short('b')
501        .with_description("Server address")
502        .with_default("0.0.0.0:6380")]
503}
504
505fn get_flags() -> Vec<FlagSchema> {
506    vec![FlagSchema::new("bind")
507        .with_short('b')
508        .with_description("Server address")
509        .with_default("0.0.0.0:6380")]
510}
511
512fn delete_flags() -> Vec<FlagSchema> {
513    vec![FlagSchema::new("bind")
514        .with_short('b')
515        .with_description("Server address")
516        .with_default("0.0.0.0:6380")]
517}
518
519fn health_flags() -> Vec<FlagSchema> {
520    vec![
521        FlagSchema::new("bind")
522            .with_short('b')
523            .with_description("Server address; defaults by transport"),
524        FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
525        FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
526    ]
527}
528
529fn bootstrap_flags() -> Vec<FlagSchema> {
530    vec![
531        FlagSchema::new("path")
532            .with_short('d')
533            .with_description("Persistent database file path"),
534        FlagSchema::boolean("vault")
535            .with_description("Required: seal credentials in the encrypted vault"),
536        FlagSchema::new("username")
537            .with_short('u')
538            .with_description("Admin username (defaults to REDDB_USERNAME)"),
539        FlagSchema::new("password")
540            .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
541        FlagSchema::boolean("password-stdin")
542            .with_description("Read the admin password from stdin (one line)"),
543        FlagSchema::boolean("print-certificate")
544            .with_description("Print only the certificate to stdout"),
545    ]
546}
547
548fn doctor_flags() -> Vec<FlagSchema> {
549    vec![
550        FlagSchema::new("bind")
551            .with_description("HTTP address of the server to probe")
552            .with_default("127.0.0.1:5055"),
553        FlagSchema::new("token")
554            .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
555        FlagSchema::boolean("json")
556            .with_description("Emit a single JSON object instead of human text"),
557        FlagSchema::new("backup-age-warn-secs")
558            .with_description("Warn when last successful backup is older than N seconds")
559            .with_default("600"),
560        FlagSchema::new("backup-age-crit-secs")
561            .with_description("Critical when last successful backup is older than N seconds")
562            .with_default("3600"),
563        FlagSchema::new("wal-lag-warn")
564            .with_description("Warn when WAL archive lag exceeds N records")
565            .with_default("1000"),
566        FlagSchema::new("wal-lag-crit")
567            .with_description("Critical when WAL archive lag exceeds N records")
568            .with_default("10000"),
569    ]
570}
571
572fn dump_flags() -> Vec<FlagSchema> {
573    vec![
574        FlagSchema::new("path")
575            .with_description("Local database file to dump from")
576            .with_default("./data/reddb.rdb"),
577        FlagSchema::new("collection")
578            .with_short('c')
579            .with_description("Single collection to dump (omit for all)"),
580        FlagSchema::new("output")
581            .with_short('o')
582            .with_description("Destination file (defaults to stdout)"),
583    ]
584}
585
586fn restore_flags() -> Vec<FlagSchema> {
587    vec![
588        FlagSchema::new("path")
589            .with_description("Local database file to restore into")
590            .with_default("./data/reddb.rdb"),
591        FlagSchema::new("input")
592            .with_short('i')
593            .with_description("Dump file to read (required)"),
594        FlagSchema::new("collection")
595            .with_short('c')
596            .with_description("Override target collection name"),
597    ]
598}
599
600fn pitr_list_flags() -> Vec<FlagSchema> {
601    vec![
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 pitr_restore_flags() -> Vec<FlagSchema> {
610    vec![
611        FlagSchema::new("target-time")
612            .with_description("Recovery target — UNIX ms (0 = latest available)"),
613        FlagSchema::new("dest")
614            .with_description("Destination database file path for the restored DB"),
615        FlagSchema::new("snapshot-prefix")
616            .with_description("Directory (or remote prefix) holding .snapshot files"),
617        FlagSchema::new("wal-prefix")
618            .with_description("Directory (or remote prefix) holding archived WAL segments"),
619    ]
620}
621
622fn tick_flags() -> Vec<FlagSchema> {
623    vec![
624        FlagSchema::new("bind")
625            .with_short('b')
626            .with_description("Server HTTP bind address")
627            .with_default("127.0.0.1:5055"),
628        FlagSchema::new("operations")
629            .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
630        FlagSchema::boolean("dry-run")
631            .with_description("Validate operations without applying changes"),
632    ]
633}
634
635fn migrate_from_redis_flags() -> Vec<FlagSchema> {
636    vec![
637        FlagSchema::boolean("dry-run")
638            .with_description("Validate Redis and RedDB connectivity without cache writes"),
639        FlagSchema::new("redis-url")
640            .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
641        FlagSchema::new("path")
642            .with_short('d')
643            .with_description("Local RedDB .rdb file to open for connectivity validation"),
644        FlagSchema::new("phase")
645            .with_description("Migration phase: dry-run | dual-write")
646            .with_default("dry-run"),
647        FlagSchema::new("namespace")
648            .with_description("Blob Cache namespace recorded in dry-run output")
649            .with_default("redis-migration"),
650    ]
651}
652
653fn status_flags() -> Vec<FlagSchema> {
654    vec![FlagSchema::new("bind")
655        .with_short('b')
656        .with_description("Server address")
657        .with_default("0.0.0.0:6380")]
658}
659
660fn inspect_flags() -> Vec<FlagSchema> {
661    vec![
662        FlagSchema::new("path")
663            .with_short('d')
664            .with_description("Path to the on-disk database file"),
665        FlagSchema::new("at")
666            .with_description("Catalog at snapshot sequence (requires metadata journal)"),
667    ]
668}
669
670fn mcp_flags() -> Vec<FlagSchema> {
671    vec![FlagSchema::new("path")
672        .with_short('d')
673        .with_description("Data directory path (omit for in-memory)")
674        .with_default("")]
675}
676
677fn connect_flags() -> Vec<FlagSchema> {
678    vec![
679        FlagSchema::new("token")
680            .with_short('t')
681            .with_description("Auth token (session or API key)"),
682        FlagSchema::new("query")
683            .with_short('q')
684            .with_description("Execute a single query and exit"),
685        FlagSchema::new("user")
686            .with_short('u')
687            .with_description("Username for login"),
688        FlagSchema::new("password")
689            .with_short('p')
690            .with_description("Password for login"),
691    ]
692}
693
694fn auth_flags() -> Vec<FlagSchema> {
695    vec![
696        FlagSchema::new("bind")
697            .with_short('b')
698            .with_description("Server address")
699            .with_default("0.0.0.0:6380"),
700        FlagSchema::new("password")
701            .with_short('p')
702            .with_description("User password"),
703        FlagSchema::new("role")
704            .with_short('r')
705            .with_description("User role")
706            .with_choices(&["read", "write", "admin"]),
707        FlagSchema::new("name")
708            .with_short('n')
709            .with_description("API key name"),
710        FlagSchema::new("user")
711            .with_short('u')
712            .with_description("Target username"),
713    ]
714}
715
716// ============================================================================
717// Completion data helpers
718// ============================================================================
719
720/// Return domain data for completion scripts.
721pub fn completion_domains() -> Vec<(String, Vec<String>)> {
722    vec![
723        ("server".to_string(), vec![]),
724        ("service".to_string(), vec![]),
725        ("replica".to_string(), vec![]),
726        ("tick".to_string(), vec![]),
727        ("query".to_string(), vec!["q".to_string()]),
728        ("insert".to_string(), vec!["i".to_string()]),
729        ("get".to_string(), vec![]),
730        ("delete".to_string(), vec!["del".to_string()]),
731        ("health".to_string(), vec![]),
732        ("status".to_string(), vec![]),
733        ("inspect".to_string(), vec![]),
734        ("migrate-from-redis".to_string(), vec![]),
735        ("mcp".to_string(), vec![]),
736        ("auth".to_string(), vec![]),
737        ("connect".to_string(), vec![]),
738        ("version".to_string(), vec![]),
739    ]
740}
741
742/// Return global flag data for completion scripts.
743pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
744    vec![
745        ("help", Some('h')),
746        ("json", Some('j')),
747        ("output", Some('o')),
748        ("verbose", Some('v')),
749        ("no-color", None),
750        ("version", None),
751    ]
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757
758    #[test]
759    fn test_all_commands_defined() {
760        let cmds = all_commands();
761        let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
762        assert!(names.contains(&"server"));
763        assert!(names.contains(&"query"));
764        assert!(names.contains(&"insert"));
765        assert!(names.contains(&"get"));
766        assert!(names.contains(&"delete"));
767        assert!(names.contains(&"health"));
768        assert!(names.contains(&"tick"));
769        assert!(names.contains(&"migrate-from-redis"));
770        assert!(names.contains(&"status"));
771        assert!(names.contains(&"inspect"));
772        assert!(names.contains(&"connect"));
773        assert!(names.contains(&"version"));
774    }
775
776    #[test]
777    fn test_inspect_has_flags() {
778        let cmds = all_commands();
779        let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
780        let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
781        assert!(flag_names.contains(&"path"));
782        assert!(flag_names.contains(&"at"));
783    }
784
785    #[test]
786    fn test_server_has_flags() {
787        let cmds = all_commands();
788        let server = cmds.iter().find(|c| c.name == "server").unwrap();
789        let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
790        assert!(flag_names.contains(&"path"));
791        assert!(flag_names.contains(&"bind"));
792        // Slice 5 of issue #574 — HTTP handler-pool knobs.
793        assert!(flag_names.contains(&"http-max-handlers"));
794        assert!(flag_names.contains(&"http-handler-timeout-ms"));
795        assert!(flag_names.contains(&"http-retry-after-secs"));
796    }
797
798    #[test]
799    fn test_server_help_text_lists_http_limit_flags() {
800        let help = command_help_text("server").unwrap();
801        assert!(help.contains("--http-max-handlers"));
802        assert!(help.contains("--http-handler-timeout-ms"));
803        assert!(help.contains("--http-retry-after-secs"));
804        assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
805    }
806
807    #[test]
808    fn test_replica_has_flags() {
809        let cmds = all_commands();
810        let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
811        let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
812        assert!(flag_names.contains(&"primary-addr"));
813        assert!(flag_names.contains(&"path"));
814        assert!(flag_names.contains(&"bind"));
815    }
816
817    #[test]
818    fn test_main_help_text() {
819        let help = main_help_text();
820        assert!(help.contains("reddb"));
821        assert!(help.contains("Usage: red"));
822        assert!(help.contains("Commands:"));
823        assert!(help.contains("server"));
824        assert!(help.contains("query"));
825        assert!(help.contains("Global flags:"));
826        assert!(help.contains("--help"));
827        assert!(help.contains("Examples:"));
828    }
829
830    #[test]
831    fn test_command_help_text() {
832        let help = command_help_text("server").unwrap();
833        assert!(help.contains("red server"));
834        assert!(help.contains("--path"));
835        assert!(help.contains("--bind"));
836    }
837
838    #[test]
839    fn test_replica_command_help() {
840        let help = command_help_text("replica").unwrap();
841        assert!(help.contains("red replica"));
842        assert!(help.contains("--primary-addr"));
843    }
844
845    #[test]
846    fn test_migrate_from_redis_command_help() {
847        let help = command_help_text("migrate-from-redis").unwrap();
848        assert!(help.contains("red migrate-from-redis"));
849        assert!(help.contains("--dry-run"));
850        assert!(help.contains("--redis-url"));
851        assert!(help.contains("application-owned helper"));
852    }
853
854    #[test]
855    fn test_command_help_text_unknown() {
856        assert!(command_help_text("nonexistent").is_none());
857    }
858
859    #[test]
860    fn test_flag_builder() {
861        let flag = Flag::new("output", "Output format")
862            .with_short('o')
863            .with_default("text")
864            .with_arg("FORMAT");
865
866        assert_eq!(flag.long, "output");
867        assert_eq!(flag.short, Some('o'));
868        assert_eq!(flag.description, "Output format");
869        assert_eq!(flag.default, Some("text".to_string()));
870        assert_eq!(flag.arg, Some("FORMAT".to_string()));
871    }
872
873    #[test]
874    fn test_completion_domains() {
875        let domains = completion_domains();
876        let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
877        assert!(names.contains(&"server"));
878        assert!(names.contains(&"query"));
879        assert!(names.contains(&"health"));
880    }
881
882    #[test]
883    fn test_completion_global_flags() {
884        let flags = completion_global_flags();
885        assert!(flags.contains(&("help", Some('h'))));
886        assert!(flags.contains(&("json", Some('j'))));
887        assert!(flags.contains(&("verbose", Some('v'))));
888        assert!(flags.contains(&("no-color", None)));
889    }
890}