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