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    CommandDef {
210      name: "ui",
211      summary: "Open a graphical UI against a local .rdb or a remote red:///reds:// instance over a RedWire-over-WS bridge",
212      usage: "red ui file://./data.rdb | red ui red://host:port [--token TOKEN] [--ui-dir DIR] [--port N] [--tls-ca PEM] [--no-browser]",
213      flags: ui_flags(),
214    },
215  ]
216}
217
218/// Return the help text for the main `red` command.
219pub fn main_help_text() -> String {
220    let mut out = String::with_capacity(1024);
221
222    out.push_str("reddb -- unified multi-model database engine\n");
223    out.push('\n');
224    out.push_str("Usage: red <command> [args] [flags]\n");
225    out.push('\n');
226
227    out.push_str("Commands:\n");
228    for cmd in all_commands() {
229        out.push_str(&format!("  {:<14} {}\n", cmd.name, cmd.summary));
230    }
231    out.push_str(&format!("  {:<14} {}\n", "help", "Show help for a command"));
232    out.push('\n');
233
234    out.push_str("Global flags:\n");
235    out.push_str(&format!("  {:<24} {}\n", "-h, --help", "Show help"));
236    out.push_str(&format!("  {:<24} {}\n", "-j, --json", "Force JSON output"));
237    out.push_str(&format!(
238        "  {:<24} {}\n",
239        "-o, --output FORMAT", "Output format [text|json|yaml]"
240    ));
241    out.push_str(&format!("  {:<24} {}\n", "-v, --verbose", "Verbose output"));
242    out.push_str(&format!(
243        "  {:<24} {}\n",
244        "    --no-color", "Disable colors"
245    ));
246    out.push_str(&format!("  {:<24} {}\n", "    --version", "Show version"));
247    out.push('\n');
248
249    out.push_str("Examples:\n");
250    out.push_str("  red server --path ./data/reddb.rdb\n");
251    out.push_str("  red server --grpc-bind 127.0.0.1:5555 --http-bind 127.0.0.1:5055 --path ./data/reddb.rdb\n");
252    out.push_str("  red server --wire-bind 127.0.0.1:5050 --path ./data/reddb.rdb\n");
253    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");
254    out.push_str("  red replica --primary-addr http://primary:5555 --path ./data/replica.rdb\n");
255    out.push_str("  red query \"SELECT * FROM users\"\n");
256    out.push_str("  red insert users '{\"name\": \"Alice\"}'\n");
257    out.push_str("  red get users abc123\n");
258    out.push_str("  red health\n");
259    out.push_str(
260        "  red tick --bind 127.0.0.1:5055 --operations maintenance,retention,checkpoint\n",
261    );
262    out.push_str("  red auth create-user alice --password secret --role admin\n");
263    out.push_str("  red auth create-api-key alice --name \"ci-token\" --role write\n");
264    out.push_str("  red auth list-users\n");
265    out.push_str("  red auth login alice --password secret\n");
266    out.push_str("  red connect 127.0.0.1:5050\n");
267    out.push_str("  red connect --query \"SELECT * FROM users\" 127.0.0.1:5050\n");
268    out.push('\n');
269
270    out.push_str("Run 'red <command> --help' for more information on a command.\n");
271    out
272}
273
274/// Return help text for a specific command.
275pub fn command_help_text(name: &str) -> Option<String> {
276    let cmds = all_commands();
277    let cmd = cmds.iter().find(|c| c.name == name)?;
278
279    let mut out = String::with_capacity(512);
280
281    out.push_str(&format!("red {} -- {}\n", cmd.name, cmd.summary));
282    out.push('\n');
283    out.push_str(&format!("Usage: {}\n", cmd.usage));
284    out.push('\n');
285
286    if !cmd.flags.is_empty() {
287        out.push_str("Flags:\n");
288        for flag in &cmd.flags {
289            let short_part = match flag.short {
290                Some(ch) => format!("-{}, ", ch),
291                None => "    ".to_string(),
292            };
293            let value_part = if flag.expects_value {
294                format!(" <{}>", flag.long.to_uppercase())
295            } else {
296                String::new()
297            };
298            let label = format!("{}--{}{}", short_part, flag.long, value_part);
299            let padding = if label.len() < 24 {
300                24 - label.len()
301            } else {
302                2
303            };
304            let default_text = match &flag.default {
305                Some(d) => format!(" (default: {})", d),
306                None => String::new(),
307            };
308            out.push_str(&format!(
309                "  {}{}{}{}\n",
310                label,
311                " ".repeat(padding),
312                flag.description,
313                default_text,
314            ));
315        }
316        out.push('\n');
317    }
318
319    Some(out)
320}
321
322// ============================================================================
323// Per-command flag schemas
324// ============================================================================
325
326fn server_flags() -> Vec<FlagSchema> {
327    vec![
328        FlagSchema::new("path")
329            .with_short('d')
330            .with_description("Persistent database file path (omit for in-memory)")
331            .with_default("./data/reddb.rdb"),
332        FlagSchema::new("bind").with_short('b').with_description(
333            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
334        ),
335        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
336        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
337        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
338        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
339        FlagSchema::new("wire-bind")
340            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
341        FlagSchema::new("wire-tls-bind")
342            .with_description("Explicit wire TLS bind address (host:port)"),
343        FlagSchema::new("wire-tls-cert")
344            .with_description("Path to TLS certificate PEM for wire TLS"),
345        FlagSchema::new("wire-tls-key")
346            .with_description("Path to TLS private key PEM for wire TLS"),
347        FlagSchema::new("pg-bind").with_description(
348            "PostgreSQL wire protocol bind address (enables psql / JDBC / DBeaver clients)",
349        ),
350        FlagSchema::new("role")
351            .with_short('r')
352            .with_description("Replication role")
353            .with_choices(&["standalone", "primary", "replica"])
354            .with_default("standalone"),
355        FlagSchema::new("primary-addr").with_description("Primary gRPC address for replica mode"),
356        FlagSchema::boolean("read-only").with_description("Open the database in read-only mode"),
357        FlagSchema::boolean("no-create-if-missing")
358            .with_description("Fail instead of creating the database file"),
359        FlagSchema::new("vault")
360            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
361            .with_default("false"),
362        FlagSchema::boolean("no-auth").with_description(
363            "Hard-disable auth: anonymous access, ignores REDDB_USERNAME/PASSWORD/vault, \
364             prints a startup warning. Local-dev shortcut — NEVER use in production.",
365        ),
366        FlagSchema::boolean("dev")
367            .with_description("Alias for --no-auth (local development convenience)."),
368        FlagSchema::new("log-dir").with_description(
369            "Directory for rotating log files (defaults to the parent of --path / ./logs)",
370        ),
371        FlagSchema::new("log-level")
372            .with_description(
373                "Log level filter — trace / debug / info / warn / error, or a RUST_LOG expression",
374            )
375            .with_default("info"),
376        FlagSchema::new("log-format")
377            .with_description("Log output format")
378            .with_choices(&["pretty", "json"])
379            .with_default("pretty"),
380        FlagSchema::new("log-keep-days")
381            .with_description("Number of rotated log files to keep")
382            .with_default("14"),
383        FlagSchema::boolean("no-log-file")
384            .with_description("Disable rotating file logs (stderr only)"),
385        FlagSchema::new("http-max-handlers").with_description(
386            "Max concurrent HTTP handler threads (env: REDDB_HTTP_MAX_HANDLERS; \
387             red_config: red.http.max_handlers; default: (2 x num_cpus).clamp(8, 256))",
388        ),
389        FlagSchema::new("http-handler-timeout-ms")
390            .with_description(
391                "Per-handler total-time budget in ms (env: REDDB_HTTP_HANDLER_TIMEOUT_MS; \
392             red_config: red.http.handler_timeout_ms)",
393            )
394            .with_default("30000"),
395        FlagSchema::new("http-retry-after-secs")
396            .with_description(
397                "Retry-After seconds on limiter 503 (env: REDDB_HTTP_RETRY_AFTER_SECS; \
398             red_config: red.http.retry_after_secs; clamped to [1, 30])",
399            )
400            .with_default("5"),
401        FlagSchema::new("http-max-inflight-per-principal").with_description(
402            "Max concurrent in-flight HTTP requests per principal; over-cap requests \
403             get a structured 429 (env: REDDB_HTTP_MAX_INFLIGHT_PER_PRINCIPAL; \
404             red_config: red.http.max_inflight_per_principal; 0 disables; default: 64)",
405        ),
406    ]
407}
408
409fn replica_flags() -> Vec<FlagSchema> {
410    vec![
411        FlagSchema::new("primary-addr")
412            .with_short('p')
413            .with_description("Primary gRPC address (e.g. http://primary:50051)"),
414        FlagSchema::new("path")
415            .with_short('d')
416            .with_description("Local replica database file path")
417            .with_default("./data/reddb.rdb"),
418        FlagSchema::new("bind").with_short('b').with_description(
419            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
420        ),
421        FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
422        FlagSchema::boolean("http").with_description("Serve the HTTP API"),
423        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
424        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
425        FlagSchema::new("wire-bind")
426            .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
427        FlagSchema::new("vault")
428            .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)")
429            .with_default("false"),
430    ]
431}
432
433fn ui_flags() -> Vec<FlagSchema> {
434    vec![
435        FlagSchema::boolean("server")
436            .with_description("Force the browser-served bridge path (skip the desktop deep link)"),
437        FlagSchema::boolean("desktop").with_description(
438            "Force the desktop app via the redui:// deep link (no browser fallback)",
439        ),
440        FlagSchema::new("ui-dir").with_description(
441            "Directory to serve the UI bundle from (defaults to the built-in fixture)",
442        ),
443        FlagSchema::new("port")
444            .with_description("Loopback port for the bridge (0 / omit picks an ephemeral port)"),
445        FlagSchema::new("tls-ca").with_description(
446            "PEM CA bundle to trust for a reds:// target (on top of system roots)",
447        ),
448        FlagSchema::new("token").with_short('t').with_description(
449            "Bearer token (session/API key). Held by red and injected into the \
450             RedWire handshake — the UI never sees it (env: RED_UI_TOKEN)",
451        ),
452        FlagSchema::boolean("no-browser").with_description(
453            "Do not open the default browser (also honoured via RED_UI_NO_BROWSER)",
454        ),
455    ]
456}
457
458fn vcs_flags() -> Vec<FlagSchema> {
459    vec![
460        FlagSchema::new("path")
461            .with_short('d')
462            .with_description("Persistent database file path (omit for in-memory)"),
463        FlagSchema::new("connection")
464            .with_short('c')
465            .with_description("Connection id for workset scoping")
466            .with_default("1"),
467        FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
468        FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
469        FlagSchema::new("to").with_description("Upper bound for log range"),
470        FlagSchema::new("author")
471            .with_description("Commit author name")
472            .with_default("reddb"),
473        FlagSchema::new("email")
474            .with_description("Commit author email")
475            .with_default("reddb@localhost"),
476        FlagSchema::new("message")
477            .with_short('m')
478            .with_description("Commit message"),
479        FlagSchema::new("limit")
480            .with_description("Max log entries")
481            .with_default("20"),
482        FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
483        FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
484    ]
485}
486
487fn service_flags() -> Vec<FlagSchema> {
488    vec![
489        FlagSchema::new("binary")
490            .with_description("Path to the red binary")
491            .with_default("/usr/local/bin/red"),
492        FlagSchema::new("service-name")
493            .with_description("systemd unit name")
494            .with_default("reddb"),
495        FlagSchema::new("user")
496            .with_description("Service user")
497            .with_default("reddb"),
498        FlagSchema::new("group")
499            .with_description("Service group")
500            .with_default("reddb"),
501        FlagSchema::new("path")
502            .with_short('d')
503            .with_description("Persistent database file path")
504            .with_default(reddb_file::DEFAULT_SERVICE_DATABASE_PATH),
505        FlagSchema::new("bind").with_short('b').with_description(
506            "Bind address (host:port) for the routed front-door or legacy single-transport mode",
507        ),
508        FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
509        FlagSchema::boolean("http").with_description("Install an HTTP service"),
510        FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
511        FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
512    ]
513}
514
515fn query_flags() -> Vec<FlagSchema> {
516    vec![
517        FlagSchema::new("bind")
518            .with_short('b')
519            .with_description("Server address")
520            .with_default("0.0.0.0:6380"),
521        FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode"),
522        FlagSchema::new("param")
523            .with_short('p')
524            .with_description("Positional parameter for $1, $2, ... (repeatable)"),
525        FlagSchema::new("param-type").with_description("Type override for the preceding --param"),
526    ]
527}
528
529fn insert_flags() -> Vec<FlagSchema> {
530    vec![FlagSchema::new("bind")
531        .with_short('b')
532        .with_description("Server address")
533        .with_default("0.0.0.0:6380")]
534}
535
536fn get_flags() -> Vec<FlagSchema> {
537    vec![FlagSchema::new("bind")
538        .with_short('b')
539        .with_description("Server address")
540        .with_default("0.0.0.0:6380")]
541}
542
543fn delete_flags() -> Vec<FlagSchema> {
544    vec![FlagSchema::new("bind")
545        .with_short('b')
546        .with_description("Server address")
547        .with_default("0.0.0.0:6380")]
548}
549
550fn health_flags() -> Vec<FlagSchema> {
551    vec![
552        FlagSchema::new("bind")
553            .with_short('b')
554            .with_description("Server address; defaults by transport"),
555        FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
556        FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
557    ]
558}
559
560fn bootstrap_flags() -> Vec<FlagSchema> {
561    vec![
562        FlagSchema::new("path")
563            .with_short('d')
564            .with_description("Persistent database file path"),
565        FlagSchema::boolean("vault")
566            .with_description("Required: seal credentials in the encrypted vault"),
567        FlagSchema::new("username")
568            .with_short('u')
569            .with_description("Admin username (defaults to REDDB_USERNAME)"),
570        FlagSchema::new("password")
571            .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
572        FlagSchema::boolean("password-stdin")
573            .with_description("Read the admin password from stdin (one line)"),
574        FlagSchema::boolean("print-certificate")
575            .with_description("Print only the certificate to stdout"),
576    ]
577}
578
579fn doctor_flags() -> Vec<FlagSchema> {
580    vec![
581        FlagSchema::new("bind")
582            .with_description("HTTP address of the server to probe")
583            .with_default("127.0.0.1:5055"),
584        FlagSchema::new("token")
585            .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
586        FlagSchema::boolean("json")
587            .with_description("Emit a single JSON object instead of human text"),
588        FlagSchema::new("backup-age-warn-secs")
589            .with_description("Warn when last successful backup is older than N seconds")
590            .with_default("600"),
591        FlagSchema::new("backup-age-crit-secs")
592            .with_description("Critical when last successful backup is older than N seconds")
593            .with_default("3600"),
594        FlagSchema::new("wal-lag-warn")
595            .with_description("Warn when WAL archive lag exceeds N records")
596            .with_default("1000"),
597        FlagSchema::new("wal-lag-crit")
598            .with_description("Critical when WAL archive lag exceeds N records")
599            .with_default("10000"),
600    ]
601}
602
603fn dump_flags() -> Vec<FlagSchema> {
604    vec![
605        FlagSchema::new("path")
606            .with_description("Local database file to dump from")
607            .with_default("./data/reddb.rdb"),
608        FlagSchema::new("collection")
609            .with_short('c')
610            .with_description("Single collection to dump (omit for all)"),
611        FlagSchema::new("output")
612            .with_short('o')
613            .with_description("Destination file (defaults to stdout)"),
614    ]
615}
616
617fn restore_flags() -> Vec<FlagSchema> {
618    vec![
619        FlagSchema::new("path")
620            .with_description("Local database file to restore into")
621            .with_default("./data/reddb.rdb"),
622        FlagSchema::new("input")
623            .with_short('i')
624            .with_description("Dump file to read (required)"),
625        FlagSchema::new("collection")
626            .with_short('c')
627            .with_description("Override target collection name"),
628    ]
629}
630
631fn pitr_list_flags() -> Vec<FlagSchema> {
632    vec![
633        FlagSchema::new("snapshot-prefix")
634            .with_description("Directory (or remote prefix) holding .snapshot files"),
635        FlagSchema::new("wal-prefix")
636            .with_description("Directory (or remote prefix) holding archived WAL segments"),
637    ]
638}
639
640fn pitr_restore_flags() -> Vec<FlagSchema> {
641    vec![
642        FlagSchema::new("target-time")
643            .with_description("Recovery target — UNIX ms (0 = latest available)"),
644        FlagSchema::new("dest")
645            .with_description("Destination database file path for the restored DB"),
646        FlagSchema::new("snapshot-prefix")
647            .with_description("Directory (or remote prefix) holding .snapshot files"),
648        FlagSchema::new("wal-prefix")
649            .with_description("Directory (or remote prefix) holding archived WAL segments"),
650    ]
651}
652
653fn tick_flags() -> Vec<FlagSchema> {
654    vec![
655        FlagSchema::new("bind")
656            .with_short('b')
657            .with_description("Server HTTP bind address")
658            .with_default("127.0.0.1:5055"),
659        FlagSchema::new("operations")
660            .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
661        FlagSchema::boolean("dry-run")
662            .with_description("Validate operations without applying changes"),
663    ]
664}
665
666fn migrate_from_redis_flags() -> Vec<FlagSchema> {
667    vec![
668        FlagSchema::boolean("dry-run")
669            .with_description("Validate Redis and RedDB connectivity without cache writes"),
670        FlagSchema::new("redis-url")
671            .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
672        FlagSchema::new("path")
673            .with_short('d')
674            .with_description("Local RedDB .rdb file to open for connectivity validation"),
675        FlagSchema::new("phase")
676            .with_description("Migration phase: dry-run | dual-write")
677            .with_default("dry-run"),
678        FlagSchema::new("namespace")
679            .with_description("Blob Cache namespace recorded in dry-run output")
680            .with_default("redis-migration"),
681    ]
682}
683
684fn status_flags() -> Vec<FlagSchema> {
685    vec![FlagSchema::new("bind")
686        .with_short('b')
687        .with_description("Server address")
688        .with_default("0.0.0.0:6380")]
689}
690
691fn inspect_flags() -> Vec<FlagSchema> {
692    vec![
693        FlagSchema::new("path")
694            .with_short('d')
695            .with_description("Path to the on-disk database file"),
696        FlagSchema::new("at")
697            .with_description("Catalog at snapshot sequence (requires metadata journal)"),
698    ]
699}
700
701fn mcp_flags() -> Vec<FlagSchema> {
702    vec![FlagSchema::new("path")
703        .with_short('d')
704        .with_description("Data directory path (omit for in-memory)")
705        .with_default("")]
706}
707
708fn connect_flags() -> Vec<FlagSchema> {
709    vec![
710        FlagSchema::new("token")
711            .with_short('t')
712            .with_description("Auth token (session or API key)"),
713        FlagSchema::new("query")
714            .with_short('q')
715            .with_description("Execute a single query and exit"),
716        FlagSchema::new("user")
717            .with_short('u')
718            .with_description("Username for login"),
719        FlagSchema::new("password")
720            .with_short('p')
721            .with_description("Password for login"),
722    ]
723}
724
725fn auth_flags() -> Vec<FlagSchema> {
726    vec![
727        FlagSchema::new("bind")
728            .with_short('b')
729            .with_description("Server address")
730            .with_default("0.0.0.0:6380"),
731        FlagSchema::new("password")
732            .with_short('p')
733            .with_description("User password"),
734        FlagSchema::new("role")
735            .with_short('r')
736            .with_description("User role")
737            .with_choices(&["read", "write", "admin"]),
738        FlagSchema::new("name")
739            .with_short('n')
740            .with_description("API key name"),
741        FlagSchema::new("user")
742            .with_short('u')
743            .with_description("Target username"),
744    ]
745}
746
747// ============================================================================
748// Completion data helpers
749// ============================================================================
750
751/// Return domain data for completion scripts.
752pub fn completion_domains() -> Vec<(String, Vec<String>)> {
753    vec![
754        ("server".to_string(), vec![]),
755        ("service".to_string(), vec![]),
756        ("replica".to_string(), vec![]),
757        ("tick".to_string(), vec![]),
758        ("query".to_string(), vec!["q".to_string()]),
759        ("insert".to_string(), vec!["i".to_string()]),
760        ("get".to_string(), vec![]),
761        ("delete".to_string(), vec!["del".to_string()]),
762        ("health".to_string(), vec![]),
763        ("status".to_string(), vec![]),
764        ("inspect".to_string(), vec![]),
765        ("migrate-from-redis".to_string(), vec![]),
766        ("mcp".to_string(), vec![]),
767        ("auth".to_string(), vec![]),
768        ("connect".to_string(), vec![]),
769        ("version".to_string(), vec![]),
770    ]
771}
772
773/// Return global flag data for completion scripts.
774pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
775    vec![
776        ("help", Some('h')),
777        ("json", Some('j')),
778        ("output", Some('o')),
779        ("verbose", Some('v')),
780        ("no-color", None),
781        ("version", None),
782    ]
783}
784
785#[cfg(test)]
786mod tests {
787    use super::*;
788
789    #[test]
790    fn test_all_commands_defined() {
791        let cmds = all_commands();
792        let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
793        assert!(names.contains(&"server"));
794        assert!(names.contains(&"query"));
795        assert!(names.contains(&"insert"));
796        assert!(names.contains(&"get"));
797        assert!(names.contains(&"delete"));
798        assert!(names.contains(&"health"));
799        assert!(names.contains(&"tick"));
800        assert!(names.contains(&"migrate-from-redis"));
801        assert!(names.contains(&"status"));
802        assert!(names.contains(&"inspect"));
803        assert!(names.contains(&"connect"));
804        assert!(names.contains(&"version"));
805    }
806
807    #[test]
808    fn test_inspect_has_flags() {
809        let cmds = all_commands();
810        let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
811        let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
812        assert!(flag_names.contains(&"path"));
813        assert!(flag_names.contains(&"at"));
814    }
815
816    #[test]
817    fn test_server_has_flags() {
818        let cmds = all_commands();
819        let server = cmds.iter().find(|c| c.name == "server").unwrap();
820        let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
821        assert!(flag_names.contains(&"path"));
822        assert!(flag_names.contains(&"bind"));
823        // Slice 5 of issue #574 — HTTP handler-pool knobs.
824        assert!(flag_names.contains(&"http-max-handlers"));
825        assert!(flag_names.contains(&"http-handler-timeout-ms"));
826        assert!(flag_names.contains(&"http-retry-after-secs"));
827    }
828
829    #[test]
830    fn test_server_help_text_lists_http_limit_flags() {
831        let help = command_help_text("server").unwrap();
832        assert!(help.contains("--http-max-handlers"));
833        assert!(help.contains("--http-handler-timeout-ms"));
834        assert!(help.contains("--http-retry-after-secs"));
835        assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
836    }
837
838    #[test]
839    fn test_replica_has_flags() {
840        let cmds = all_commands();
841        let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
842        let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
843        assert!(flag_names.contains(&"primary-addr"));
844        assert!(flag_names.contains(&"path"));
845        assert!(flag_names.contains(&"bind"));
846    }
847
848    #[test]
849    fn test_main_help_text() {
850        let help = main_help_text();
851        assert!(help.contains("reddb"));
852        assert!(help.contains("Usage: red"));
853        assert!(help.contains("Commands:"));
854        assert!(help.contains("server"));
855        assert!(help.contains("query"));
856        assert!(help.contains("Global flags:"));
857        assert!(help.contains("--help"));
858        assert!(help.contains("Examples:"));
859    }
860
861    #[test]
862    fn test_command_help_text() {
863        let help = command_help_text("server").unwrap();
864        assert!(help.contains("red server"));
865        assert!(help.contains("--path"));
866        assert!(help.contains("--bind"));
867    }
868
869    #[test]
870    fn test_replica_command_help() {
871        let help = command_help_text("replica").unwrap();
872        assert!(help.contains("red replica"));
873        assert!(help.contains("--primary-addr"));
874    }
875
876    #[test]
877    fn test_migrate_from_redis_command_help() {
878        let help = command_help_text("migrate-from-redis").unwrap();
879        assert!(help.contains("red migrate-from-redis"));
880        assert!(help.contains("--dry-run"));
881        assert!(help.contains("--redis-url"));
882        assert!(help.contains("application-owned helper"));
883    }
884
885    #[test]
886    fn test_command_help_text_unknown() {
887        assert!(command_help_text("nonexistent").is_none());
888    }
889
890    #[test]
891    fn test_flag_builder() {
892        let flag = Flag::new("output", "Output format")
893            .with_short('o')
894            .with_default("text")
895            .with_arg("FORMAT");
896
897        assert_eq!(flag.long, "output");
898        assert_eq!(flag.short, Some('o'));
899        assert_eq!(flag.description, "Output format");
900        assert_eq!(flag.default, Some("text".to_string()));
901        assert_eq!(flag.arg, Some("FORMAT".to_string()));
902    }
903
904    #[test]
905    fn test_completion_domains() {
906        let domains = completion_domains();
907        let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
908        assert!(names.contains(&"server"));
909        assert!(names.contains(&"query"));
910        assert!(names.contains(&"health"));
911    }
912
913    #[test]
914    fn test_completion_global_flags() {
915        let flags = completion_global_flags();
916        assert!(flags.contains(&("help", Some('h'))));
917        assert!(flags.contains(&("json", Some('j'))));
918        assert!(flags.contains(&("verbose", Some('v'))));
919        assert!(flags.contains(&("no-color", None)));
920    }
921}