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: "migrate-pager-zone",
127 summary: "Convert a closed legacy sidecar-backed store to the zoned .rdb format",
128 usage: "red migrate-pager-zone --path ./data/reddb.rdb [--json]",
129 flags: migrate_pager_zone_flags(),
130 },
131 CommandDef {
132 name: "salvage",
133 summary: "Extract verified data from a damaged embedded store into a fresh .rdb",
134 usage: "red salvage --source damaged.rdb --destination recovered.rdb [--json]",
135 flags: salvage_flags(),
136 },
137 CommandDef {
138 name: "replica",
139 summary: "Start as a read replica connected to a primary",
140 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]",
141 flags: replica_flags(),
142 },
143 CommandDef {
144 name: "status",
145 summary: "Show replication status",
146 usage: "red status [--bind 0.0.0.0:6380]",
147 flags: status_flags(),
148 },
149 CommandDef {
150 name: "inspect",
151 summary: "Inspect on-disk database state (catalog snapshot)",
152 usage: "red inspect catalog --path <FILE> [--at <SEQ>] [--json]",
153 flags: inspect_flags(),
154 },
155 CommandDef {
156 name: "mcp",
157 summary: "Start MCP server for AI agent integration",
158 usage: "red mcp [--path /data | --url <URI>] [--token <token>]",
159 flags: mcp_flags(),
160 },
161 CommandDef {
162 name: "auth",
163 summary: "Manage authentication (users, tokens, roles)",
164 usage: "red auth <subcommand>",
165 flags: auth_flags(),
166 },
167 CommandDef {
168 name: "connect",
169 summary: "Connect to a remote RedDB server (interactive REPL)",
170 usage: "red connect [--token <token>] [--query <sql>] <addr>",
171 flags: connect_flags(),
172 },
173 CommandDef {
174 name: "dump",
175 summary: "Export one or all collections as JSONL for backup/migration",
176 usage: "red dump [--path file] [--collection NAME] [-o FILE]",
177 flags: dump_flags(),
178 },
179 CommandDef {
180 name: "restore",
181 summary: "Import a previously dumped JSONL file into the database",
182 usage: "red restore [--path file] -i FILE [--collection NAME]",
183 flags: restore_flags(),
184 },
185 CommandDef {
186 name: "pitr-list",
187 summary: "List available point-in-time restore points from a snapshot archive",
188 usage: "red pitr-list --snapshot-prefix DIR --wal-prefix DIR",
189 flags: pitr_list_flags(),
190 },
191 CommandDef {
192 name: "pitr-restore",
193 summary: "Restore a database to a specific point in time from snapshots + WAL archive",
194 usage: "red pitr-restore --target-time UNIX_MS --dest PATH --snapshot-prefix DIR --wal-prefix DIR",
195 flags: pitr_restore_flags(),
196 },
197 CommandDef {
198 name: "doctor",
199 summary: "Health-check a running server against operator thresholds (PLAN.md Phase 5.5)",
200 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]",
201 flags: doctor_flags(),
202 },
203 CommandDef {
204 name: "bootstrap",
205 summary: "One-shot first-admin bootstrap for headless containers / K8s Jobs",
206 usage: "red bootstrap --path PATH --vault [--username USER] [--password-stdin] [--print-certificate] [--json]",
207 flags: bootstrap_flags(),
208 },
209 CommandDef {
210 name: "version",
211 summary: "Show RedDB version information",
212 usage: "red version",
213 flags: vec![],
214 },
215 CommandDef {
216 name: "vcs",
217 summary: "Version-control operations (Git for Data)",
218 usage: "red vcs <commit|branch|branches|tag|tags|checkout|merge|log|status|lca|resolve> [args] [flags]",
219 flags: vcs_flags(),
220 },
221 CommandDef {
222 name: "ui",
223 summary: "Open a graphical UI against a local .rdb or a remote red:///reds:// instance over a RedWire-over-WS bridge",
224 usage: "red ui file://./data.rdb | red ui red://host:port [--token TOKEN] [--ui-dir DIR] [--port N] [--tls-ca PEM] [--no-browser]",
225 flags: ui_flags(),
226 },
227 ]
228}
229
230pub fn flags_for_command(command: Option<&str>) -> Vec<FlagSchema> {
235 let mut flags = super::types::global_flags();
236 if matches!(command, Some("dump")) {
237 flags.retain(|flag| flag.long != "output" && flag.short != Some('o'));
238 }
239
240 if command == Some("admin") {
241 flags.extend(admin_flags());
242 return flags;
243 }
244 if command == Some("rpc") {
245 flags.extend(rpc_flags());
246 return flags;
247 }
248 if let Some(definition) = all_commands()
249 .into_iter()
250 .find(|definition| Some(definition.name) == command)
251 {
252 flags.extend(definition.flags);
253 }
254 flags
255}
256
257pub fn main_help_text() -> String {
259 let mut out = String::with_capacity(1024);
260
261 out.push_str("reddb -- unified multi-model database engine\n");
262 out.push('\n');
263 out.push_str("Usage: red <command> [args] [flags]\n");
264 out.push('\n');
265
266 out.push_str("Commands:\n");
267 for cmd in all_commands() {
268 out.push_str(&format!(" {:<14} {}\n", cmd.name, cmd.summary));
269 }
270 out.push_str(&format!(" {:<14} {}\n", "help", "Show help for a command"));
271 out.push('\n');
272
273 out.push_str("Global flags:\n");
274 out.push_str(&format!(" {:<24} {}\n", "-h, --help", "Show help"));
275 out.push_str(&format!(" {:<24} {}\n", "-j, --json", "Force JSON output"));
276 out.push_str(&format!(
277 " {:<24} {}\n",
278 "-o, --output FORMAT", "Output format [text|json|yaml]"
279 ));
280 out.push_str(&format!(" {:<24} {}\n", "-v, --verbose", "Verbose output"));
281 out.push_str(&format!(
282 " {:<24} {}\n",
283 " --no-color", "Disable colors"
284 ));
285 out.push_str(&format!(" {:<24} {}\n", " --version", "Show version"));
286 out.push('\n');
287
288 out.push_str("Examples:\n");
289 out.push_str(" red server --path ./data/reddb.rdb\n");
290 out.push_str(" red server --grpc-bind 127.0.0.1:55055 --http-bind 127.0.0.1:5000 --path ./data/reddb.rdb\n");
291 out.push_str(" red server --wire-bind 127.0.0.1:5050 --path ./data/reddb.rdb\n");
292 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");
293 out.push_str(" red replica --primary-addr http://primary:55055 --path ./data/replica.rdb\n");
294 out.push_str(" red query \"SELECT * FROM users\"\n");
295 out.push_str(" red insert users '{\"name\": \"Alice\"}'\n");
296 out.push_str(" red get users abc123\n");
297 out.push_str(" red health\n");
298 out.push_str(
299 " red tick --bind 127.0.0.1:5000 --operations maintenance,retention,checkpoint\n",
300 );
301 out.push_str(" red auth create-user alice --password secret --role admin\n");
302 out.push_str(" red auth create-api-key alice --name \"ci-token\" --role write\n");
303 out.push_str(" red auth list-users\n");
304 out.push_str(" red auth login alice --password secret\n");
305 out.push_str(" red connect 127.0.0.1:5050\n");
306 out.push_str(" red connect --query \"SELECT * FROM users\" 127.0.0.1:5050\n");
307 out.push('\n');
308
309 out.push_str("Run 'red <command> --help' for more information on a command.\n");
310 out
311}
312
313pub fn command_help_text(name: &str) -> Option<String> {
315 let cmds = all_commands();
316 let cmd = cmds.iter().find(|c| c.name == name)?;
317
318 let mut out = String::with_capacity(512);
319
320 out.push_str(&format!("red {} -- {}\n", cmd.name, cmd.summary));
321 out.push('\n');
322 out.push_str(&format!("Usage: {}\n", cmd.usage));
323 out.push('\n');
324
325 if !cmd.flags.is_empty() {
326 out.push_str("Flags:\n");
327 for flag in &cmd.flags {
328 let short_part = match flag.short {
329 Some(ch) => format!("-{}, ", ch),
330 None => " ".to_string(),
331 };
332 let value_part = if flag.expects_value {
333 format!(" <{}>", flag.long.to_uppercase())
334 } else {
335 String::new()
336 };
337 let label = format!("{}--{}{}", short_part, flag.long, value_part);
338 let padding = if label.len() < 24 {
339 24 - label.len()
340 } else {
341 2
342 };
343 let default_text = match &flag.default {
344 Some(d) => format!(" (default: {})", d),
345 None => String::new(),
346 };
347 out.push_str(&format!(
348 " {}{}{}{}\n",
349 label,
350 " ".repeat(padding),
351 flag.description,
352 default_text,
353 ));
354 }
355 out.push('\n');
356 }
357
358 Some(out)
359}
360
361fn server_flags() -> Vec<FlagSchema> {
366 vec![
367 FlagSchema::new("path")
368 .with_short('d')
369 .with_description("Persistent database file path (omit for in-memory)")
370 .with_default("./data/reddb.rdb"),
371 FlagSchema::new("bind").with_short('b').with_description(
372 "Bind address (host:port) for the routed front-door or legacy single-transport mode",
373 ),
374 FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
375 FlagSchema::boolean("http").with_description("Serve the HTTP API"),
376 FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
377 FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
378 FlagSchema::new("http-tls-bind")
379 .with_description("HTTPS bind address (host:port). Runs alongside --http-bind"),
380 FlagSchema::new("http-tls-cert").with_description("Path to HTTPS server certificate PEM"),
381 FlagSchema::new("http-tls-key").with_description("Path to HTTPS server private key PEM"),
382 FlagSchema::new("http-tls-client-ca")
383 .with_description("Path to PEM CA bundle for client cert verification (mTLS)"),
384 FlagSchema::new("wire-bind")
385 .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
386 FlagSchema::new("wire-tls-bind")
387 .with_description("Explicit wire TLS bind address (host:port)"),
388 FlagSchema::new("wire-tls-cert")
389 .with_description("Path to TLS certificate PEM for wire TLS"),
390 FlagSchema::new("wire-tls-key")
391 .with_description("Path to TLS private key PEM for wire TLS"),
392 FlagSchema::new("pg-bind").with_description(
393 "PostgreSQL wire protocol bind address (enables psql / JDBC / DBeaver clients)",
394 ),
395 FlagSchema::new("role")
396 .with_short('r')
397 .with_description("Replication role")
398 .with_choices(&["standalone", "primary", "replica"])
399 .with_default("standalone"),
400 storage_profile_flag(),
401 storage_packaging_flag(),
402 storage_preset_flag(),
403 FlagSchema::new("replica-count")
404 .with_description("Expected replica count for storage profile validation"),
405 FlagSchema::boolean("managed-backup")
406 .with_description("Declare managed backup for storage profile validation"),
407 FlagSchema::boolean("wal-retention")
408 .with_description("Declare WAL retention for storage profile validation"),
409 FlagSchema::new("primary-addr").with_description("Primary gRPC address for replica mode"),
410 FlagSchema::boolean("read-only").with_description("Open the database in read-only mode"),
411 FlagSchema::boolean("no-create-if-missing")
412 .with_description("Fail instead of creating the database file"),
413 FlagSchema::boolean("auth").with_description("Enable authentication for this boot"),
414 FlagSchema::boolean("require-auth")
415 .with_description("Reject anonymous requests; implies --auth"),
416 FlagSchema::boolean("vault")
417 .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)"),
418 FlagSchema::boolean("no-auth").with_description(
419 "Hard-disable auth: anonymous access, ignores REDDB_USERNAME/PASSWORD/vault, \
420 prints a startup warning. Local-dev shortcut — NEVER use in production.",
421 ),
422 FlagSchema::boolean("dev")
423 .with_description("Alias for --no-auth (local development convenience)."),
424 FlagSchema::new("bootstrap-preset")
425 .with_description(
426 "First-boot preset. With --vault on a fresh --path, red server \
427 self-bootstraps the paged vault in place (no separate `red bootstrap`) \
428 then applies the preset and serves; a re-boot against the existing \
429 vault just serves (idempotent — no re-bootstrap, no new certificate).",
430 )
431 .with_choices(&["simple", "production", "regulated", "cloud"]),
432 FlagSchema::new("bootstrap-manifest").with_description(
433 "Path to manifest-driven first boot JSON. Applied once on a fresh database \
434 before serving; later boots observe bootstrap state and skip re-applying \
435 the manifest (idempotent).",
436 ),
437 FlagSchema::new("bootstrap-admin")
438 .with_description("First admin username for production/cloud bootstrap"),
439 FlagSchema::new("bootstrap-admin-password").with_description(
440 "First admin password (DEV ONLY; prefer --bootstrap-admin-password-file)",
441 ),
442 FlagSchema::new("bootstrap-admin-password-file")
443 .with_description("File containing first admin password"),
444 FlagSchema::new("cloud-head-admin")
445 .with_description("Cloud preset head/platform admin username"),
446 FlagSchema::new("cloud-head-admin-password").with_description(
447 "Cloud preset head/platform admin password (DEV ONLY; prefer file flag)",
448 ),
449 FlagSchema::new("cloud-head-admin-password-file")
450 .with_description("File containing cloud head admin password"),
451 FlagSchema::new("customer-admin").with_description("Cloud preset customer admin username"),
452 FlagSchema::new("customer-admin-password")
453 .with_description("Cloud preset customer admin password (DEV ONLY; prefer file flag)"),
454 FlagSchema::new("customer-admin-password-file")
455 .with_description("File containing cloud customer admin password"),
456 FlagSchema::new("bootstrap-cert-out").with_description(
457 "Write the first-boot unseal certificate to this file (e.g. /run/reddb/cert.pem) \
458 in addition to stderr, so a distroless init can read it back for the next boot's \
459 REDDB_CERTIFICATE_FILE unseal. Written only on the bootstrap-creating boot; a \
460 re-boot against the existing vault does not rewrite it.",
461 ),
462 FlagSchema::boolean("ui")
463 .with_description("Serve the pinned red-ui bundle as static assets"),
464 FlagSchema::new("ui-dir").with_description("Directory containing the red-ui bundle"),
465 FlagSchema::new("workers")
466 .with_short('w')
467 .with_description("Worker thread count (default: auto-detect from CPUs)"),
468 FlagSchema::new("log-dir").with_description(
469 "Directory for rotating log files (defaults to the parent of --path / ./logs)",
470 ),
471 FlagSchema::new("log-level")
472 .with_description(
473 "Log level filter — trace / debug / info / warn / error, or a RUST_LOG expression",
474 )
475 .with_default("info"),
476 FlagSchema::new("log-format")
477 .with_description("Log output format")
478 .with_choices(&["pretty", "json"])
479 .with_default("pretty"),
480 FlagSchema::new("log-keep-days")
481 .with_description("Number of rotated log files to keep")
482 .with_default("14"),
483 FlagSchema::boolean("no-log-file")
484 .with_description("Disable rotating file logs (stderr only)"),
485 FlagSchema::new("http-max-handlers").with_description(
486 "Max concurrent HTTP handler threads (env: REDDB_HTTP_MAX_HANDLERS; \
487 red_config: red.http.max_handlers; default: (2 x num_cpus).clamp(8, 256))",
488 ),
489 FlagSchema::new("http-handler-timeout-ms")
490 .with_description(
491 "Per-handler total-time budget in ms (env: REDDB_HTTP_HANDLER_TIMEOUT_MS; \
492 red_config: red.http.handler_timeout_ms)",
493 )
494 .with_default("30000"),
495 FlagSchema::new("http-retry-after-secs")
496 .with_description(
497 "Retry-After seconds on limiter 503 (env: REDDB_HTTP_RETRY_AFTER_SECS; \
498 red_config: red.http.retry_after_secs; clamped to [1, 30])",
499 )
500 .with_default("5"),
501 FlagSchema::new("http-max-inflight-per-principal").with_description(
502 "Max concurrent in-flight HTTP requests per principal; over-cap requests \
503 get a structured 429 (env: REDDB_HTTP_MAX_INFLIGHT_PER_PRINCIPAL; \
504 red_config: red.http.max_inflight_per_principal; 0 disables; default: 64)",
505 ),
506 ]
507}
508
509fn replica_flags() -> Vec<FlagSchema> {
510 vec![
511 FlagSchema::new("primary-addr")
512 .with_short('p')
513 .with_description("Primary gRPC address (e.g. http://primary:55055)"),
514 FlagSchema::new("path")
515 .with_short('d')
516 .with_description("Local replica database file path")
517 .with_default("./data/reddb.rdb"),
518 FlagSchema::new("bind").with_short('b').with_description(
519 "Bind address (host:port) for the routed front-door or legacy single-transport mode",
520 ),
521 FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
522 FlagSchema::boolean("http").with_description("Serve the HTTP API"),
523 FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
524 FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
525 FlagSchema::new("wire-bind")
526 .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
527 storage_profile_flag(),
528 storage_packaging_flag(),
529 storage_preset_flag(),
530 FlagSchema::new("replica-count")
531 .with_description("Expected replica count for storage profile validation"),
532 FlagSchema::boolean("managed-backup")
533 .with_description("Declare managed backup for storage profile validation"),
534 FlagSchema::boolean("wal-retention")
535 .with_description("Declare WAL retention for storage profile validation"),
536 FlagSchema::boolean("auth").with_description("Enable authentication for this boot"),
537 FlagSchema::boolean("require-auth")
538 .with_description("Reject anonymous requests; implies --auth"),
539 FlagSchema::boolean("vault")
540 .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)"),
541 FlagSchema::boolean("no-auth")
542 .with_description("Hard-disable auth: anonymous access, ignores vault"),
543 ]
544}
545
546fn ui_flags() -> Vec<FlagSchema> {
547 vec![
548 FlagSchema::boolean("server")
549 .with_description("Force the browser-served bridge path (skip the desktop deep link)"),
550 FlagSchema::boolean("desktop").with_description(
551 "Force the desktop app via the redui:// deep link (no browser fallback)",
552 ),
553 FlagSchema::new("ui-dir").with_description(
554 "Directory to serve the UI bundle from (defaults to the built-in fixture)",
555 ),
556 FlagSchema::new("port")
557 .with_description("Loopback port for the bridge (0 / omit picks an ephemeral port)"),
558 FlagSchema::new("tls-ca").with_description(
559 "PEM CA bundle to trust for a reds:// target (on top of system roots)",
560 ),
561 FlagSchema::new("token").with_short('t').with_description(
562 "Bearer token (session/API key). Held by red and injected into the \
563 RedWire handshake — the UI never sees it (env: RED_UI_TOKEN)",
564 ),
565 FlagSchema::boolean("no-browser").with_description(
566 "Do not open the default browser (also honoured via RED_UI_NO_BROWSER)",
567 ),
568 ]
569}
570
571fn vcs_flags() -> Vec<FlagSchema> {
572 vec![
573 FlagSchema::new("path")
574 .with_short('d')
575 .with_description("Persistent database file path (omit for in-memory)"),
576 FlagSchema::new("connection")
577 .with_short('c')
578 .with_description("Connection id for workset scoping")
579 .with_default("1"),
580 FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
581 FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
582 FlagSchema::new("to").with_description("Upper bound for log range"),
583 FlagSchema::new("author")
584 .with_description("Commit author name")
585 .with_default("reddb"),
586 FlagSchema::new("email")
587 .with_description("Commit author email")
588 .with_default("reddb@localhost"),
589 FlagSchema::new("message")
590 .with_short('m')
591 .with_description("Commit message"),
592 FlagSchema::new("limit")
593 .with_description("Max log entries")
594 .with_default("20"),
595 FlagSchema::new("mode")
596 .with_description("Reset mode: soft | mixed | hard")
597 .with_default("mixed"),
598 FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
599 FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
600 ]
601}
602
603fn service_flags() -> Vec<FlagSchema> {
604 vec![
605 FlagSchema::new("binary")
606 .with_description("Path to the red binary")
607 .with_default("/usr/local/bin/red"),
608 FlagSchema::new("service-name")
609 .with_description("systemd unit name")
610 .with_default("reddb"),
611 FlagSchema::new("user")
612 .with_description("Service user")
613 .with_default("reddb"),
614 FlagSchema::new("group")
615 .with_description("Service group")
616 .with_default("reddb"),
617 FlagSchema::new("path")
618 .with_short('d')
619 .with_description("Persistent database file path")
620 .with_default(reddb_file::DEFAULT_SERVICE_DATABASE_PATH),
621 FlagSchema::new("bind").with_short('b').with_description(
622 "Bind address (host:port) for the routed front-door or legacy single-transport mode",
623 ),
624 FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
625 FlagSchema::boolean("http").with_description("Install an HTTP service"),
626 FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
627 FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
628 ]
629}
630
631fn query_flags() -> Vec<FlagSchema> {
632 vec![
633 FlagSchema::new("bind")
634 .with_short('b')
635 .with_description("Server address")
636 .with_default("0.0.0.0:6380"),
637 FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode"),
638 FlagSchema::new("param")
639 .with_short('p')
640 .with_description("Positional parameter for $1, $2, ... (repeatable)"),
641 FlagSchema::new("param-type").with_description("Type override for the preceding --param"),
642 FlagSchema::new("format").with_description(
643 "Row output format for query results (table|json|ndjson|csv|tsv|toon)",
644 ),
645 FlagSchema::new("save")
646 .with_description("Persist an ephemeral data-file query session as a new .rdb file"),
647 FlagSchema::boolean("dry-run")
648 .with_description("Preview the statement via EXPLAIN without executing it"),
649 ]
650}
651
652fn insert_flags() -> Vec<FlagSchema> {
653 data_target_flags(Some('p'))
654}
655
656fn get_flags() -> Vec<FlagSchema> {
657 data_target_flags(Some('p'))
658}
659
660fn delete_flags() -> Vec<FlagSchema> {
661 data_target_flags(Some('p'))
662}
663
664fn health_flags() -> Vec<FlagSchema> {
665 vec![
666 FlagSchema::new("bind")
667 .with_short('b')
668 .with_description("Server address; defaults by transport"),
669 FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
670 FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
671 ]
672}
673
674fn bootstrap_flags() -> Vec<FlagSchema> {
675 vec![
676 FlagSchema::new("path")
677 .with_short('d')
678 .with_description("Persistent database file path"),
679 FlagSchema::boolean("vault")
680 .with_description("Required: seal credentials in the encrypted vault"),
681 FlagSchema::new("username")
682 .with_short('u')
683 .with_description("Admin username (defaults to REDDB_USERNAME)"),
684 FlagSchema::new("password")
685 .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
686 FlagSchema::boolean("password-stdin")
687 .with_description("Read the admin password from stdin (one line)"),
688 FlagSchema::boolean("print-certificate")
689 .with_description("Print only the certificate to stdout"),
690 ]
691}
692
693fn doctor_flags() -> Vec<FlagSchema> {
694 vec![
695 FlagSchema::new("bind")
696 .with_description("HTTP address of the server to probe")
697 .with_default("127.0.0.1:5000"),
698 FlagSchema::new("token")
699 .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
700 FlagSchema::new("backup-age-warn-secs")
701 .with_description("Warn when last successful backup is older than N seconds")
702 .with_default("600"),
703 FlagSchema::new("backup-age-crit-secs")
704 .with_description("Critical when last successful backup is older than N seconds")
705 .with_default("3600"),
706 FlagSchema::new("wal-lag-warn")
707 .with_description("Warn when WAL archive lag exceeds N records")
708 .with_default("1000"),
709 FlagSchema::new("wal-lag-crit")
710 .with_description("Critical when WAL archive lag exceeds N records")
711 .with_default("10000"),
712 ]
713}
714
715fn dump_flags() -> Vec<FlagSchema> {
716 vec![
717 FlagSchema::new("path")
718 .with_description("Local database file to dump from")
719 .with_default("./data/reddb.rdb"),
720 storage_profile_flag(),
721 storage_packaging_flag(),
722 storage_preset_flag(),
723 FlagSchema::new("collection")
724 .with_short('c')
725 .with_description("Single collection to dump (omit for all)"),
726 FlagSchema::new("output")
727 .with_short('o')
728 .with_description("Destination file (defaults to stdout)"),
729 ]
730}
731
732fn restore_flags() -> Vec<FlagSchema> {
733 vec![
734 FlagSchema::new("path")
735 .with_description("Local database file to restore into")
736 .with_default("./data/reddb.rdb"),
737 storage_profile_flag(),
738 storage_packaging_flag(),
739 storage_preset_flag(),
740 FlagSchema::new("input")
741 .with_short('i')
742 .with_description("Dump file to read (required)"),
743 FlagSchema::new("collection")
744 .with_short('c')
745 .with_description("Override target collection name"),
746 ]
747}
748
749fn pitr_list_flags() -> Vec<FlagSchema> {
750 vec![
751 FlagSchema::new("snapshot-prefix")
752 .with_description("Directory (or remote prefix) holding .snapshot files"),
753 FlagSchema::new("wal-prefix")
754 .with_description("Directory (or remote prefix) holding archived WAL segments"),
755 ]
756}
757
758fn pitr_restore_flags() -> Vec<FlagSchema> {
759 vec![
760 FlagSchema::new("target-time")
761 .with_description("Recovery target — UNIX ms (0 = latest available)"),
762 FlagSchema::new("dest")
763 .with_description("Destination database file path for the restored DB"),
764 FlagSchema::new("snapshot-prefix")
765 .with_description("Directory (or remote prefix) holding .snapshot files"),
766 FlagSchema::new("wal-prefix")
767 .with_description("Directory (or remote prefix) holding archived WAL segments"),
768 ]
769}
770
771fn tick_flags() -> Vec<FlagSchema> {
772 vec![
773 FlagSchema::new("bind")
774 .with_short('b')
775 .with_description("Server HTTP bind address")
776 .with_default("127.0.0.1:5000"),
777 FlagSchema::new("operations")
778 .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
779 FlagSchema::boolean("dry-run")
780 .with_description("Validate operations without applying changes"),
781 ]
782}
783
784fn migrate_from_redis_flags() -> Vec<FlagSchema> {
785 vec![
786 FlagSchema::boolean("dry-run")
787 .with_description("Validate Redis and RedDB connectivity without cache writes"),
788 FlagSchema::new("redis-url")
789 .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
790 FlagSchema::new("path")
791 .with_short('d')
792 .with_description("Local RedDB .rdb file to open for connectivity validation"),
793 FlagSchema::new("phase")
794 .with_description("Migration phase: dry-run | dual-write")
795 .with_default("dry-run"),
796 FlagSchema::new("namespace")
797 .with_description("Blob Cache namespace recorded in dry-run output")
798 .with_default("redis-migration"),
799 ]
800}
801
802fn migrate_pager_zone_flags() -> Vec<FlagSchema> {
803 vec![FlagSchema::new("path")
804 .with_short('d')
805 .with_description("Closed legacy sidecar-backed .rdb file to convert")]
806}
807
808fn salvage_flags() -> Vec<FlagSchema> {
809 vec![
810 FlagSchema::new("source").with_description("Damaged source .rdb file to read"),
811 FlagSchema::new("destination").with_description("Fresh destination .rdb file to create"),
812 ]
813}
814
815fn status_flags() -> Vec<FlagSchema> {
816 data_target_flags(Some('p'))
817}
818
819fn inspect_flags() -> Vec<FlagSchema> {
820 vec![
821 FlagSchema::new("path")
822 .with_short('d')
823 .with_description("Path to the on-disk database file"),
824 FlagSchema::new("at")
825 .with_description("Catalog at snapshot sequence (requires metadata journal)"),
826 ]
827}
828
829fn mcp_flags() -> Vec<FlagSchema> {
830 vec![
831 FlagSchema::new("uri")
832 .with_description("Connection URI (overrides --url and REDDB_MCP_URI)"),
833 FlagSchema::new("path")
834 .with_short('d')
835 .with_description("Data directory path (omit for in-memory)")
836 .with_default(""),
837 FlagSchema::new("url")
838 .with_description("Remote or embedded MCP connection URI; overrides REDDB_MCP_URI"),
839 FlagSchema::new("token")
840 .with_description("Bearer token fallback when --url has no userinfo"),
841 FlagSchema::boolean("allow-write")
846 .with_description("Permit tools and statements that modify data or schema"),
847 FlagSchema::boolean("allow-admin")
848 .with_description("Permit vault and auth tools (implies --allow-write)"),
849 ]
850}
851
852fn connect_flags() -> Vec<FlagSchema> {
853 vec![
854 FlagSchema::new("token")
855 .with_short('t')
856 .with_description("Auth token (session or API key)"),
857 FlagSchema::new("query")
858 .with_short('q')
859 .with_description("Execute a single query and exit"),
860 FlagSchema::new("user")
861 .with_short('u')
862 .with_description("Username for login"),
863 FlagSchema::new("password")
864 .with_short('p')
865 .with_description("Password for login"),
866 ]
867}
868
869fn auth_flags() -> Vec<FlagSchema> {
870 vec![
871 FlagSchema::new("bind")
872 .with_short('b')
873 .with_description("Server address")
874 .with_default("0.0.0.0:6380"),
875 FlagSchema::new("password")
876 .with_short('p')
877 .with_description("User password"),
878 FlagSchema::new("role")
879 .with_short('r')
880 .with_description("User role")
881 .with_choices(&["read", "write", "admin"]),
882 FlagSchema::new("name")
883 .with_short('n')
884 .with_description("API key name"),
885 FlagSchema::new("user")
886 .with_short('u')
887 .with_description("Target username"),
888 ]
889}
890
891fn admin_flags() -> Vec<FlagSchema> {
892 vec![
893 FlagSchema::new("bind")
894 .with_short('b')
895 .with_description("Server HTTP address")
896 .with_default("127.0.0.1:5000"),
897 FlagSchema::new("token")
898 .with_short('t')
899 .with_description("Admin bearer token (env: RED_ADMIN_TOKEN)"),
900 FlagSchema::boolean("csv").with_description("Emit CSV for tabular admin catalog commands"),
901 FlagSchema::new("limit").with_description("Max rows for list/stats/query commands"),
902 FlagSchema::new("type").with_description("Filter collections by model"),
903 FlagSchema::boolean("include-internal").with_description("Include internal collections"),
904 FlagSchema::new("collection").with_description("Filter by collection"),
905 FlagSchema::boolean("yes")
906 .with_short('y')
907 .with_description("Skip destructive-command confirmation"),
908 FlagSchema::boolean("if-exists")
909 .with_description("Suppress errors for a missing collection"),
910 ]
911}
912
913fn rpc_flags() -> Vec<FlagSchema> {
914 vec![
915 FlagSchema::boolean("stdio")
916 .with_description("Speak JSON-RPC 2.0 line-delimited over stdin/stdout"),
917 FlagSchema::new("path")
918 .with_short('d')
919 .with_description("Persistent database file path (omit for in-memory)"),
920 FlagSchema::new("connect")
921 .with_short('c')
922 .with_description("Proxy to a remote gRPC server"),
923 FlagSchema::new("token")
924 .with_short('t')
925 .with_description("Auth token forwarded to the remote server"),
926 ]
927}
928
929fn data_target_flags(path_short: Option<char>) -> Vec<FlagSchema> {
930 let path = FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode");
931 let path = match path_short {
932 Some(short) => path.with_short(short),
933 None => path,
934 };
935 vec![
936 FlagSchema::new("bind")
937 .with_short('b')
938 .with_description("Server address")
939 .with_default("0.0.0.0:6380"),
940 path,
941 ]
942}
943
944fn storage_profile_flag() -> FlagSchema {
945 FlagSchema::new("storage-profile")
946 .with_description("Storage deploy profile")
947 .with_choices(&["embedded", "serverless", "primary-replica", "cluster"])
948}
949
950fn storage_packaging_flag() -> FlagSchema {
951 FlagSchema::new("storage-packaging")
952 .with_description("Storage packaging contract")
953 .with_choices(&["single-file", "operational-directory"])
954}
955
956fn storage_preset_flag() -> FlagSchema {
957 FlagSchema::new("storage-preset")
958 .with_description("Storage/deploy preset")
959 .with_choices(&[
960 "embedded",
961 "serverless",
962 "primary-replica-dev",
963 "primary-replica-small",
964 "primary-replica-production-ha",
965 "primary-replica-backup",
966 "primary-replica-wal-retention",
967 "cluster",
968 ])
969}
970
971pub fn completion_domains() -> Vec<(String, Vec<String>)> {
977 vec![
978 ("server".to_string(), vec![]),
979 ("service".to_string(), vec![]),
980 ("replica".to_string(), vec![]),
981 ("tick".to_string(), vec![]),
982 ("query".to_string(), vec!["q".to_string()]),
983 ("insert".to_string(), vec!["i".to_string()]),
984 ("get".to_string(), vec![]),
985 ("delete".to_string(), vec!["del".to_string()]),
986 ("health".to_string(), vec![]),
987 ("status".to_string(), vec![]),
988 ("inspect".to_string(), vec![]),
989 ("migrate-from-redis".to_string(), vec![]),
990 ("salvage".to_string(), vec![]),
991 ("mcp".to_string(), vec![]),
992 ("auth".to_string(), vec![]),
993 ("connect".to_string(), vec![]),
994 ("version".to_string(), vec![]),
995 ]
996}
997
998pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
1000 vec![
1001 ("help", Some('h')),
1002 ("json", Some('j')),
1003 ("output", Some('o')),
1004 ("verbose", Some('v')),
1005 ("no-color", None),
1006 ("version", None),
1007 ]
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012 use super::*;
1013
1014 #[test]
1015 fn test_all_commands_defined() {
1016 let cmds = all_commands();
1017 let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
1018 assert!(names.contains(&"server"));
1019 assert!(names.contains(&"query"));
1020 assert!(names.contains(&"insert"));
1021 assert!(names.contains(&"get"));
1022 assert!(names.contains(&"delete"));
1023 assert!(names.contains(&"health"));
1024 assert!(names.contains(&"tick"));
1025 assert!(names.contains(&"migrate-from-redis"));
1026 assert!(names.contains(&"salvage"));
1027 assert!(names.contains(&"status"));
1028 assert!(names.contains(&"inspect"));
1029 assert!(names.contains(&"connect"));
1030 assert!(names.contains(&"version"));
1031 }
1032
1033 #[test]
1034 fn test_inspect_has_flags() {
1035 let cmds = all_commands();
1036 let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
1037 let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
1038 assert!(flag_names.contains(&"path"));
1039 assert!(flag_names.contains(&"at"));
1040 }
1041
1042 #[test]
1043 fn test_server_has_flags() {
1044 let cmds = all_commands();
1045 let server = cmds.iter().find(|c| c.name == "server").unwrap();
1046 let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
1047 assert!(flag_names.contains(&"path"));
1048 assert!(flag_names.contains(&"bind"));
1049 assert!(flag_names.contains(&"http-max-handlers"));
1051 assert!(flag_names.contains(&"http-handler-timeout-ms"));
1052 assert!(flag_names.contains(&"http-retry-after-secs"));
1053 }
1054
1055 #[test]
1056 fn test_server_help_text_lists_http_limit_flags() {
1057 let help = command_help_text("server").unwrap();
1058 assert!(help.contains("--http-max-handlers"));
1059 assert!(help.contains("--http-handler-timeout-ms"));
1060 assert!(help.contains("--http-retry-after-secs"));
1061 assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
1062 }
1063
1064 #[test]
1065 fn test_replica_has_flags() {
1066 let cmds = all_commands();
1067 let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
1068 let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
1069 assert!(flag_names.contains(&"primary-addr"));
1070 assert!(flag_names.contains(&"path"));
1071 assert!(flag_names.contains(&"bind"));
1072 }
1073
1074 #[test]
1075 fn test_main_help_text() {
1076 let help = main_help_text();
1077 assert!(help.contains("reddb"));
1078 assert!(help.contains("Usage: red"));
1079 assert!(help.contains("Commands:"));
1080 assert!(help.contains("server"));
1081 assert!(help.contains("query"));
1082 assert!(help.contains("Global flags:"));
1083 assert!(help.contains("--help"));
1084 assert!(help.contains("Examples:"));
1085 }
1086
1087 #[test]
1088 fn test_command_help_text() {
1089 let help = command_help_text("server").unwrap();
1090 assert!(help.contains("red server"));
1091 assert!(help.contains("--path"));
1092 assert!(help.contains("--bind"));
1093 }
1094
1095 #[test]
1096 fn test_replica_command_help() {
1097 let help = command_help_text("replica").unwrap();
1098 assert!(help.contains("red replica"));
1099 assert!(help.contains("--primary-addr"));
1100 }
1101
1102 #[test]
1103 fn test_migrate_from_redis_command_help() {
1104 let help = command_help_text("migrate-from-redis").unwrap();
1105 assert!(help.contains("red migrate-from-redis"));
1106 assert!(help.contains("--dry-run"));
1107 assert!(help.contains("--redis-url"));
1108 assert!(help.contains("application-owned helper"));
1109 }
1110
1111 #[test]
1112 fn test_migrate_pager_zone_command_help() {
1113 let help = command_help_text("migrate-pager-zone").unwrap();
1114 assert!(help.contains("red migrate-pager-zone"));
1115 assert!(help.contains("--path"));
1116 assert!(help.contains("legacy sidecar-backed"));
1117 }
1118
1119 #[test]
1120 fn test_command_help_text_unknown() {
1121 assert!(command_help_text("nonexistent").is_none());
1122 }
1123
1124 #[test]
1125 fn test_flag_builder() {
1126 let flag = Flag::new("output", "Output format")
1127 .with_short('o')
1128 .with_default("text")
1129 .with_arg("FORMAT");
1130
1131 assert_eq!(flag.long, "output");
1132 assert_eq!(flag.short, Some('o'));
1133 assert_eq!(flag.description, "Output format");
1134 assert_eq!(flag.default, Some("text".to_string()));
1135 assert_eq!(flag.arg, Some("FORMAT".to_string()));
1136 }
1137
1138 #[test]
1139 fn test_completion_domains() {
1140 let domains = completion_domains();
1141 let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
1142 assert!(names.contains(&"server"));
1143 assert!(names.contains(&"query"));
1144 assert!(names.contains(&"health"));
1145 }
1146
1147 #[test]
1148 fn test_completion_global_flags() {
1149 let flags = completion_global_flags();
1150 assert!(flags.contains(&("help", Some('h'))));
1151 assert!(flags.contains(&("json", Some('j'))));
1152 assert!(flags.contains(&("verbose", Some('v'))));
1153 assert!(flags.contains(&("no-color", None)));
1154 }
1155}