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