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