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