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