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