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 FlagSchema::boolean("dry-run")
573 .with_description("Preview the statement via EXPLAIN without executing it"),
574 ]
575}
576
577fn insert_flags() -> Vec<FlagSchema> {
578 vec![FlagSchema::new("bind")
579 .with_short('b')
580 .with_description("Server address")
581 .with_default("0.0.0.0:6380")]
582}
583
584fn get_flags() -> Vec<FlagSchema> {
585 vec![FlagSchema::new("bind")
586 .with_short('b')
587 .with_description("Server address")
588 .with_default("0.0.0.0:6380")]
589}
590
591fn delete_flags() -> Vec<FlagSchema> {
592 vec![FlagSchema::new("bind")
593 .with_short('b')
594 .with_description("Server address")
595 .with_default("0.0.0.0:6380")]
596}
597
598fn health_flags() -> Vec<FlagSchema> {
599 vec![
600 FlagSchema::new("bind")
601 .with_short('b')
602 .with_description("Server address; defaults by transport"),
603 FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
604 FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
605 ]
606}
607
608fn bootstrap_flags() -> Vec<FlagSchema> {
609 vec![
610 FlagSchema::new("path")
611 .with_short('d')
612 .with_description("Persistent database file path"),
613 FlagSchema::boolean("vault")
614 .with_description("Required: seal credentials in the encrypted vault"),
615 FlagSchema::new("username")
616 .with_short('u')
617 .with_description("Admin username (defaults to REDDB_USERNAME)"),
618 FlagSchema::new("password")
619 .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
620 FlagSchema::boolean("password-stdin")
621 .with_description("Read the admin password from stdin (one line)"),
622 FlagSchema::boolean("print-certificate")
623 .with_description("Print only the certificate to stdout"),
624 ]
625}
626
627fn doctor_flags() -> Vec<FlagSchema> {
628 vec![
629 FlagSchema::new("bind")
630 .with_description("HTTP address of the server to probe")
631 .with_default("127.0.0.1:5000"),
632 FlagSchema::new("token")
633 .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
634 FlagSchema::boolean("json")
635 .with_description("Emit a single JSON object instead of human text"),
636 FlagSchema::new("backup-age-warn-secs")
637 .with_description("Warn when last successful backup is older than N seconds")
638 .with_default("600"),
639 FlagSchema::new("backup-age-crit-secs")
640 .with_description("Critical when last successful backup is older than N seconds")
641 .with_default("3600"),
642 FlagSchema::new("wal-lag-warn")
643 .with_description("Warn when WAL archive lag exceeds N records")
644 .with_default("1000"),
645 FlagSchema::new("wal-lag-crit")
646 .with_description("Critical when WAL archive lag exceeds N records")
647 .with_default("10000"),
648 ]
649}
650
651fn dump_flags() -> Vec<FlagSchema> {
652 vec![
653 FlagSchema::new("path")
654 .with_description("Local database file to dump from")
655 .with_default("./data/reddb.rdb"),
656 FlagSchema::new("collection")
657 .with_short('c')
658 .with_description("Single collection to dump (omit for all)"),
659 FlagSchema::new("output")
660 .with_short('o')
661 .with_description("Destination file (defaults to stdout)"),
662 ]
663}
664
665fn restore_flags() -> Vec<FlagSchema> {
666 vec![
667 FlagSchema::new("path")
668 .with_description("Local database file to restore into")
669 .with_default("./data/reddb.rdb"),
670 FlagSchema::new("input")
671 .with_short('i')
672 .with_description("Dump file to read (required)"),
673 FlagSchema::new("collection")
674 .with_short('c')
675 .with_description("Override target collection name"),
676 ]
677}
678
679fn pitr_list_flags() -> Vec<FlagSchema> {
680 vec![
681 FlagSchema::new("snapshot-prefix")
682 .with_description("Directory (or remote prefix) holding .snapshot files"),
683 FlagSchema::new("wal-prefix")
684 .with_description("Directory (or remote prefix) holding archived WAL segments"),
685 ]
686}
687
688fn pitr_restore_flags() -> Vec<FlagSchema> {
689 vec![
690 FlagSchema::new("target-time")
691 .with_description("Recovery target — UNIX ms (0 = latest available)"),
692 FlagSchema::new("dest")
693 .with_description("Destination database file path for the restored DB"),
694 FlagSchema::new("snapshot-prefix")
695 .with_description("Directory (or remote prefix) holding .snapshot files"),
696 FlagSchema::new("wal-prefix")
697 .with_description("Directory (or remote prefix) holding archived WAL segments"),
698 ]
699}
700
701fn tick_flags() -> Vec<FlagSchema> {
702 vec![
703 FlagSchema::new("bind")
704 .with_short('b')
705 .with_description("Server HTTP bind address")
706 .with_default("127.0.0.1:5000"),
707 FlagSchema::new("operations")
708 .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
709 FlagSchema::boolean("dry-run")
710 .with_description("Validate operations without applying changes"),
711 ]
712}
713
714fn migrate_from_redis_flags() -> Vec<FlagSchema> {
715 vec![
716 FlagSchema::boolean("dry-run")
717 .with_description("Validate Redis and RedDB connectivity without cache writes"),
718 FlagSchema::new("redis-url")
719 .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
720 FlagSchema::new("path")
721 .with_short('d')
722 .with_description("Local RedDB .rdb file to open for connectivity validation"),
723 FlagSchema::new("phase")
724 .with_description("Migration phase: dry-run | dual-write")
725 .with_default("dry-run"),
726 FlagSchema::new("namespace")
727 .with_description("Blob Cache namespace recorded in dry-run output")
728 .with_default("redis-migration"),
729 ]
730}
731
732fn status_flags() -> Vec<FlagSchema> {
733 vec![FlagSchema::new("bind")
734 .with_short('b')
735 .with_description("Server address")
736 .with_default("0.0.0.0:6380")]
737}
738
739fn inspect_flags() -> Vec<FlagSchema> {
740 vec![
741 FlagSchema::new("path")
742 .with_short('d')
743 .with_description("Path to the on-disk database file"),
744 FlagSchema::new("at")
745 .with_description("Catalog at snapshot sequence (requires metadata journal)"),
746 ]
747}
748
749fn mcp_flags() -> Vec<FlagSchema> {
750 vec![
751 FlagSchema::new("path")
752 .with_short('d')
753 .with_description("Data directory path (omit for in-memory)")
754 .with_default(""),
755 FlagSchema::new("url")
756 .with_description("Remote or embedded MCP connection URI; overrides REDDB_MCP_URI"),
757 FlagSchema::new("token")
758 .with_description("Bearer token fallback when --url has no userinfo"),
759 ]
760}
761
762fn connect_flags() -> Vec<FlagSchema> {
763 vec![
764 FlagSchema::new("token")
765 .with_short('t')
766 .with_description("Auth token (session or API key)"),
767 FlagSchema::new("query")
768 .with_short('q')
769 .with_description("Execute a single query and exit"),
770 FlagSchema::new("user")
771 .with_short('u')
772 .with_description("Username for login"),
773 FlagSchema::new("password")
774 .with_short('p')
775 .with_description("Password for login"),
776 ]
777}
778
779fn auth_flags() -> Vec<FlagSchema> {
780 vec![
781 FlagSchema::new("bind")
782 .with_short('b')
783 .with_description("Server address")
784 .with_default("0.0.0.0:6380"),
785 FlagSchema::new("password")
786 .with_short('p')
787 .with_description("User password"),
788 FlagSchema::new("role")
789 .with_short('r')
790 .with_description("User role")
791 .with_choices(&["read", "write", "admin"]),
792 FlagSchema::new("name")
793 .with_short('n')
794 .with_description("API key name"),
795 FlagSchema::new("user")
796 .with_short('u')
797 .with_description("Target username"),
798 ]
799}
800
801pub fn completion_domains() -> Vec<(String, Vec<String>)> {
807 vec![
808 ("server".to_string(), vec![]),
809 ("service".to_string(), vec![]),
810 ("replica".to_string(), vec![]),
811 ("tick".to_string(), vec![]),
812 ("query".to_string(), vec!["q".to_string()]),
813 ("insert".to_string(), vec!["i".to_string()]),
814 ("get".to_string(), vec![]),
815 ("delete".to_string(), vec!["del".to_string()]),
816 ("health".to_string(), vec![]),
817 ("status".to_string(), vec![]),
818 ("inspect".to_string(), vec![]),
819 ("migrate-from-redis".to_string(), vec![]),
820 ("mcp".to_string(), vec![]),
821 ("auth".to_string(), vec![]),
822 ("connect".to_string(), vec![]),
823 ("version".to_string(), vec![]),
824 ]
825}
826
827pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
829 vec![
830 ("help", Some('h')),
831 ("json", Some('j')),
832 ("output", Some('o')),
833 ("verbose", Some('v')),
834 ("no-color", None),
835 ("version", None),
836 ]
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 #[test]
844 fn test_all_commands_defined() {
845 let cmds = all_commands();
846 let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
847 assert!(names.contains(&"server"));
848 assert!(names.contains(&"query"));
849 assert!(names.contains(&"insert"));
850 assert!(names.contains(&"get"));
851 assert!(names.contains(&"delete"));
852 assert!(names.contains(&"health"));
853 assert!(names.contains(&"tick"));
854 assert!(names.contains(&"migrate-from-redis"));
855 assert!(names.contains(&"status"));
856 assert!(names.contains(&"inspect"));
857 assert!(names.contains(&"connect"));
858 assert!(names.contains(&"version"));
859 }
860
861 #[test]
862 fn test_inspect_has_flags() {
863 let cmds = all_commands();
864 let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
865 let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
866 assert!(flag_names.contains(&"path"));
867 assert!(flag_names.contains(&"at"));
868 }
869
870 #[test]
871 fn test_server_has_flags() {
872 let cmds = all_commands();
873 let server = cmds.iter().find(|c| c.name == "server").unwrap();
874 let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
875 assert!(flag_names.contains(&"path"));
876 assert!(flag_names.contains(&"bind"));
877 assert!(flag_names.contains(&"http-max-handlers"));
879 assert!(flag_names.contains(&"http-handler-timeout-ms"));
880 assert!(flag_names.contains(&"http-retry-after-secs"));
881 }
882
883 #[test]
884 fn test_server_help_text_lists_http_limit_flags() {
885 let help = command_help_text("server").unwrap();
886 assert!(help.contains("--http-max-handlers"));
887 assert!(help.contains("--http-handler-timeout-ms"));
888 assert!(help.contains("--http-retry-after-secs"));
889 assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
890 }
891
892 #[test]
893 fn test_replica_has_flags() {
894 let cmds = all_commands();
895 let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
896 let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
897 assert!(flag_names.contains(&"primary-addr"));
898 assert!(flag_names.contains(&"path"));
899 assert!(flag_names.contains(&"bind"));
900 }
901
902 #[test]
903 fn test_main_help_text() {
904 let help = main_help_text();
905 assert!(help.contains("reddb"));
906 assert!(help.contains("Usage: red"));
907 assert!(help.contains("Commands:"));
908 assert!(help.contains("server"));
909 assert!(help.contains("query"));
910 assert!(help.contains("Global flags:"));
911 assert!(help.contains("--help"));
912 assert!(help.contains("Examples:"));
913 }
914
915 #[test]
916 fn test_command_help_text() {
917 let help = command_help_text("server").unwrap();
918 assert!(help.contains("red server"));
919 assert!(help.contains("--path"));
920 assert!(help.contains("--bind"));
921 }
922
923 #[test]
924 fn test_replica_command_help() {
925 let help = command_help_text("replica").unwrap();
926 assert!(help.contains("red replica"));
927 assert!(help.contains("--primary-addr"));
928 }
929
930 #[test]
931 fn test_migrate_from_redis_command_help() {
932 let help = command_help_text("migrate-from-redis").unwrap();
933 assert!(help.contains("red migrate-from-redis"));
934 assert!(help.contains("--dry-run"));
935 assert!(help.contains("--redis-url"));
936 assert!(help.contains("application-owned helper"));
937 }
938
939 #[test]
940 fn test_command_help_text_unknown() {
941 assert!(command_help_text("nonexistent").is_none());
942 }
943
944 #[test]
945 fn test_flag_builder() {
946 let flag = Flag::new("output", "Output format")
947 .with_short('o')
948 .with_default("text")
949 .with_arg("FORMAT");
950
951 assert_eq!(flag.long, "output");
952 assert_eq!(flag.short, Some('o'));
953 assert_eq!(flag.description, "Output format");
954 assert_eq!(flag.default, Some("text".to_string()));
955 assert_eq!(flag.arg, Some("FORMAT".to_string()));
956 }
957
958 #[test]
959 fn test_completion_domains() {
960 let domains = completion_domains();
961 let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
962 assert!(names.contains(&"server"));
963 assert!(names.contains(&"query"));
964 assert!(names.contains(&"health"));
965 }
966
967 #[test]
968 fn test_completion_global_flags() {
969 let flags = completion_global_flags();
970 assert!(flags.contains(&("help", Some('h'))));
971 assert!(flags.contains(&("json", Some('j'))));
972 assert!(flags.contains(&("verbose", Some('v'))));
973 assert!(flags.contains(&("no-color", None)));
974 }
975}