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 in addition to stderr, so a distroless init can read it back for the next boot's \
471 REDDB_CERTIFICATE_FILE unseal. Written only on the bootstrap-creating boot; a \
472 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: 64)",
523 ),
524 ]
525}
526
527fn replica_flags() -> Vec<FlagSchema> {
528 vec![
529 FlagSchema::new("primary-addr")
530 .with_short('p')
531 .with_description("Primary gRPC address (e.g. http://primary:55055)"),
532 FlagSchema::new("path")
533 .with_short('d')
534 .with_description("Local replica database file path")
535 .with_default("./data/reddb.rdb"),
536 FlagSchema::new("bind").with_short('b').with_description(
537 "Bind address (host:port) for the routed front-door or legacy single-transport mode",
538 ),
539 FlagSchema::boolean("grpc").with_description("Enable the gRPC API"),
540 FlagSchema::boolean("http").with_description("Serve the HTTP API"),
541 FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
542 FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
543 FlagSchema::new("wire-bind")
544 .with_description("Explicit wire bind address (host:port or unix:///path/to/socket)"),
545 storage_profile_flag(),
546 storage_packaging_flag(),
547 storage_preset_flag(),
548 FlagSchema::new("replica-count")
549 .with_description("Expected replica count for storage profile validation"),
550 FlagSchema::boolean("managed-backup")
551 .with_description("Declare managed backup for storage profile validation"),
552 FlagSchema::boolean("wal-retention")
553 .with_description("Declare WAL retention for storage profile validation"),
554 FlagSchema::boolean("auth").with_description("Enable authentication for this boot"),
555 FlagSchema::boolean("require-auth")
556 .with_description("Reject anonymous requests; implies --auth"),
557 FlagSchema::boolean("vault")
558 .with_description("Enable encrypted auth vault (reserved pages in main .rdb file)"),
559 FlagSchema::boolean("no-auth")
560 .with_description("Hard-disable auth: anonymous access, ignores vault"),
561 ]
562}
563
564fn ui_flags() -> Vec<FlagSchema> {
565 vec![
566 FlagSchema::boolean("server")
567 .with_description("Force the browser-served bridge path (skip the desktop deep link)"),
568 FlagSchema::boolean("desktop").with_description(
569 "Force the desktop app via the redui:// deep link (no browser fallback)",
570 ),
571 FlagSchema::new("ui-dir").with_description(
572 "Directory to serve the UI bundle from (defaults to the built-in fixture)",
573 ),
574 FlagSchema::new("port")
575 .with_description("Loopback port for the bridge (0 / omit picks an ephemeral port)"),
576 FlagSchema::new("tls-ca").with_description(
577 "PEM CA bundle to trust for a reds:// target (on top of system roots)",
578 ),
579 FlagSchema::new("token").with_short('t').with_description(
580 "Bearer token (session/API key). Held by red and injected into the \
581 RedWire handshake — the UI never sees it (env: RED_UI_TOKEN)",
582 ),
583 FlagSchema::boolean("no-browser").with_description(
584 "Do not open the default browser (also honoured via RED_UI_NO_BROWSER)",
585 ),
586 ]
587}
588
589fn vcs_flags() -> Vec<FlagSchema> {
590 vec![
591 FlagSchema::new("path")
592 .with_short('d')
593 .with_description("Persistent database file path (omit for in-memory)"),
594 FlagSchema::new("connection")
595 .with_short('c')
596 .with_description("Connection id for workset scoping")
597 .with_default("1"),
598 FlagSchema::new("branch").with_description("Branch name (for log/checkout/merge)"),
599 FlagSchema::new("from").with_description("Source ref or commit (branch create / merge)"),
600 FlagSchema::new("to").with_description("Upper bound for log range"),
601 FlagSchema::new("author")
602 .with_description("Commit author name")
603 .with_default("reddb"),
604 FlagSchema::new("email")
605 .with_description("Commit author email")
606 .with_default("reddb@localhost"),
607 FlagSchema::new("message")
608 .with_short('m')
609 .with_description("Commit message"),
610 FlagSchema::new("limit")
611 .with_description("Max log entries")
612 .with_default("20"),
613 FlagSchema::new("mode")
614 .with_description("Reset mode: soft | mixed | hard")
615 .with_default("mixed"),
616 FlagSchema::boolean("ff-only").with_description("Merge only if fast-forward"),
617 FlagSchema::boolean("no-ff").with_description("Always create a merge commit"),
618 ]
619}
620
621fn service_flags() -> Vec<FlagSchema> {
622 vec![
623 FlagSchema::new("binary")
624 .with_description("Path to the red binary")
625 .with_default("/usr/local/bin/red"),
626 FlagSchema::new("service-name")
627 .with_description("systemd unit name")
628 .with_default("reddb"),
629 FlagSchema::new("user")
630 .with_description("Service user")
631 .with_default("reddb"),
632 FlagSchema::new("group")
633 .with_description("Service group")
634 .with_default("reddb"),
635 FlagSchema::new("path")
636 .with_short('d')
637 .with_description("Persistent database file path")
638 .with_default(reddb_file::DEFAULT_SERVICE_DATABASE_PATH),
639 FlagSchema::new("bind").with_short('b').with_description(
640 "Bind address (host:port) for the routed front-door or legacy single-transport mode",
641 ),
642 FlagSchema::boolean("grpc").with_description("Enable the gRPC API in the service"),
643 FlagSchema::boolean("http").with_description("Install an HTTP service"),
644 FlagSchema::new("grpc-bind").with_description("Explicit gRPC bind address (host:port)"),
645 FlagSchema::new("http-bind").with_description("Explicit HTTP bind address (host:port)"),
646 ]
647}
648
649fn query_flags() -> Vec<FlagSchema> {
650 vec![
651 FlagSchema::new("bind")
652 .with_short('b')
653 .with_description("Server address")
654 .with_default("0.0.0.0:6380"),
655 FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode"),
656 FlagSchema::new("param")
657 .with_short('p')
658 .with_description("Positional parameter for $1, $2, ... (repeatable)"),
659 FlagSchema::new("param-type").with_description("Type override for the preceding --param"),
660 FlagSchema::new("format").with_description(
661 "Row output format for query results (table|json|ndjson|csv|tsv|toon)",
662 ),
663 FlagSchema::new("save")
664 .with_description("Persist an ephemeral data-file query session as a new .rdb file"),
665 FlagSchema::boolean("dry-run")
666 .with_description("Preview the statement via EXPLAIN without executing it"),
667 ]
668}
669
670fn insert_flags() -> Vec<FlagSchema> {
671 data_target_flags(Some('p'))
672}
673
674fn get_flags() -> Vec<FlagSchema> {
675 data_target_flags(Some('p'))
676}
677
678fn delete_flags() -> Vec<FlagSchema> {
679 data_target_flags(Some('p'))
680}
681
682fn health_flags() -> Vec<FlagSchema> {
683 vec![
684 FlagSchema::new("bind")
685 .with_short('b')
686 .with_description("Server address; defaults by transport"),
687 FlagSchema::boolean("grpc").with_description("Probe a gRPC listener (default transport)"),
688 FlagSchema::boolean("http").with_description("Probe an HTTP listener"),
689 ]
690}
691
692fn bootstrap_flags() -> Vec<FlagSchema> {
693 vec![
694 FlagSchema::new("path")
695 .with_short('d')
696 .with_description("Persistent database file path"),
697 FlagSchema::boolean("vault")
698 .with_description("Required: seal credentials in the encrypted vault"),
699 FlagSchema::new("username")
700 .with_short('u')
701 .with_description("Admin username (defaults to REDDB_USERNAME)"),
702 FlagSchema::new("password")
703 .with_description("Admin password (DEV ONLY; prefer --password-stdin)"),
704 FlagSchema::boolean("password-stdin")
705 .with_description("Read the admin password from stdin (one line)"),
706 FlagSchema::boolean("print-certificate")
707 .with_description("Print only the certificate to stdout"),
708 ]
709}
710
711fn doctor_flags() -> Vec<FlagSchema> {
712 vec![
713 FlagSchema::new("bind")
714 .with_description("HTTP address of the server to probe")
715 .with_default("127.0.0.1:5000"),
716 FlagSchema::new("token")
717 .with_description("Admin bearer token; defaults to RED_ADMIN_TOKEN env"),
718 FlagSchema::new("backup-age-warn-secs")
719 .with_description("Warn when last successful backup is older than N seconds")
720 .with_default("600"),
721 FlagSchema::new("backup-age-crit-secs")
722 .with_description("Critical when last successful backup is older than N seconds")
723 .with_default("3600"),
724 FlagSchema::new("wal-lag-warn")
725 .with_description("Warn when WAL archive lag exceeds N records")
726 .with_default("1000"),
727 FlagSchema::new("wal-lag-crit")
728 .with_description("Critical when WAL archive lag exceeds N records")
729 .with_default("10000"),
730 ]
731}
732
733fn dump_flags() -> Vec<FlagSchema> {
734 vec![
735 FlagSchema::new("path")
736 .with_description("Local database file to dump from")
737 .with_default("./data/reddb.rdb"),
738 storage_profile_flag(),
739 storage_packaging_flag(),
740 storage_preset_flag(),
741 FlagSchema::new("collection")
742 .with_short('c')
743 .with_description("Single collection to dump (omit for all)"),
744 FlagSchema::new("output")
745 .with_short('o')
746 .with_description("Destination file (defaults to stdout)"),
747 ]
748}
749
750fn restore_flags() -> Vec<FlagSchema> {
751 vec![
752 FlagSchema::new("path")
753 .with_description("Local database file to restore into")
754 .with_default("./data/reddb.rdb"),
755 storage_profile_flag(),
756 storage_packaging_flag(),
757 storage_preset_flag(),
758 FlagSchema::new("input")
759 .with_short('i')
760 .with_description("Dump file to read (required)"),
761 FlagSchema::new("collection")
762 .with_short('c')
763 .with_description("Override target collection name"),
764 ]
765}
766
767fn pitr_list_flags() -> Vec<FlagSchema> {
768 vec![
769 FlagSchema::new("snapshot-prefix")
770 .with_description("Directory (or remote prefix) holding .snapshot files"),
771 FlagSchema::new("wal-prefix")
772 .with_description("Directory (or remote prefix) holding archived WAL segments"),
773 ]
774}
775
776fn pitr_restore_flags() -> Vec<FlagSchema> {
777 vec![
778 FlagSchema::new("target-time")
779 .with_description("Recovery target — UNIX ms (0 = latest available)"),
780 FlagSchema::new("dest")
781 .with_description("Destination database file path for the restored DB"),
782 FlagSchema::new("snapshot-prefix")
783 .with_description("Directory (or remote prefix) holding .snapshot files"),
784 FlagSchema::new("wal-prefix")
785 .with_description("Directory (or remote prefix) holding archived WAL segments"),
786 ]
787}
788
789fn tick_flags() -> Vec<FlagSchema> {
790 vec![
791 FlagSchema::new("bind")
792 .with_short('b')
793 .with_description("Server HTTP bind address")
794 .with_default("127.0.0.1:5000"),
795 FlagSchema::new("operations")
796 .with_description("Comma-separated operations: maintenance,retention,checkpoint"),
797 FlagSchema::boolean("dry-run")
798 .with_description("Validate operations without applying changes"),
799 ]
800}
801
802fn migrate_from_redis_flags() -> Vec<FlagSchema> {
803 vec![
804 FlagSchema::boolean("dry-run")
805 .with_description("Validate Redis and RedDB connectivity without cache writes"),
806 FlagSchema::new("redis-url")
807 .with_description("Redis URL to validate, for example redis://127.0.0.1:6379/0"),
808 FlagSchema::new("path")
809 .with_short('d')
810 .with_description("Local RedDB .rdb file to open for connectivity validation"),
811 FlagSchema::new("phase")
812 .with_description("Migration phase: dry-run | dual-write")
813 .with_default("dry-run"),
814 FlagSchema::new("namespace")
815 .with_description("Blob Cache namespace recorded in dry-run output")
816 .with_default("redis-migration"),
817 ]
818}
819
820fn migrate_pager_zone_flags() -> Vec<FlagSchema> {
821 vec![FlagSchema::new("path")
822 .with_short('d')
823 .with_description("Closed legacy sidecar-backed .rdb file to convert")]
824}
825
826fn salvage_flags() -> Vec<FlagSchema> {
827 vec![
828 FlagSchema::new("source").with_description("Damaged source .rdb file to read"),
829 FlagSchema::new("destination").with_description("Fresh destination .rdb file to create"),
830 ]
831}
832
833fn status_flags() -> Vec<FlagSchema> {
834 data_target_flags(Some('p'))
835}
836
837fn inspect_flags() -> Vec<FlagSchema> {
838 vec![
839 FlagSchema::new("path")
840 .with_short('d')
841 .with_description("Path to the on-disk database file"),
842 FlagSchema::new("at")
843 .with_description("Catalog at snapshot sequence (requires metadata journal)"),
844 ]
845}
846
847fn mcp_flags() -> Vec<FlagSchema> {
848 vec![
849 FlagSchema::new("uri")
850 .with_description("Connection URI (overrides --url and REDDB_MCP_URI)"),
851 FlagSchema::new("path")
852 .with_short('d')
853 .with_description("Data directory path (omit for in-memory)")
854 .with_default(""),
855 FlagSchema::new("url")
856 .with_description("Remote or embedded MCP connection URI; overrides REDDB_MCP_URI"),
857 FlagSchema::new("token")
858 .with_description("Bearer token fallback when --url has no userinfo"),
859 FlagSchema::boolean("allow-write")
864 .with_description("Permit tools and statements that modify data or schema"),
865 FlagSchema::boolean("allow-admin")
866 .with_description("Permit vault and auth tools (implies --allow-write)"),
867 ]
868}
869
870fn connect_flags() -> Vec<FlagSchema> {
871 vec![
872 FlagSchema::new("token")
873 .with_short('t')
874 .with_description("Auth token (session or API key)"),
875 FlagSchema::new("query")
876 .with_short('q')
877 .with_description("Execute a single query and exit"),
878 FlagSchema::new("user")
879 .with_short('u')
880 .with_description("Username for login"),
881 FlagSchema::new("password")
882 .with_short('p')
883 .with_description("Password for login"),
884 ]
885}
886
887fn auth_flags() -> Vec<FlagSchema> {
888 vec![
889 FlagSchema::new("bind")
890 .with_short('b')
891 .with_description("Server address")
892 .with_default("0.0.0.0:6380"),
893 FlagSchema::new("password")
894 .with_short('p')
895 .with_description("User password"),
896 FlagSchema::new("role")
897 .with_short('r')
898 .with_description("User role")
899 .with_choices(&["read", "write", "admin"]),
900 FlagSchema::new("name")
901 .with_short('n')
902 .with_description("API key name"),
903 FlagSchema::new("user")
904 .with_short('u')
905 .with_description("Target username"),
906 ]
907}
908
909fn admin_flags() -> Vec<FlagSchema> {
910 vec![
911 FlagSchema::new("bind")
912 .with_short('b')
913 .with_description("Server HTTP address")
914 .with_default("127.0.0.1:5000"),
915 FlagSchema::new("token")
916 .with_short('t')
917 .with_description("Admin bearer token (env: RED_ADMIN_TOKEN)"),
918 FlagSchema::boolean("csv").with_description("Emit CSV for tabular admin catalog commands"),
919 FlagSchema::new("limit").with_description("Max rows for list/stats/query commands"),
920 FlagSchema::new("type").with_description("Filter collections by model"),
921 FlagSchema::boolean("include-internal").with_description("Include internal collections"),
922 FlagSchema::new("collection").with_description("Filter by collection"),
923 FlagSchema::boolean("yes")
924 .with_short('y')
925 .with_description("Skip destructive-command confirmation"),
926 FlagSchema::boolean("if-exists")
927 .with_description("Suppress errors for a missing collection"),
928 ]
929}
930
931fn rpc_flags() -> Vec<FlagSchema> {
932 vec![
933 FlagSchema::boolean("stdio")
934 .with_description("Speak JSON-RPC 2.0 line-delimited over stdin/stdout"),
935 FlagSchema::new("path")
936 .with_short('d')
937 .with_description("Persistent database file path (omit for in-memory)"),
938 FlagSchema::new("connect")
939 .with_short('c')
940 .with_description("Proxy to a remote gRPC server"),
941 FlagSchema::new("token")
942 .with_short('t')
943 .with_description("Auth token forwarded to the remote server"),
944 ]
945}
946
947fn data_target_flags(path_short: Option<char>) -> Vec<FlagSchema> {
948 let path = FlagSchema::new("path").with_description("Open a local .rdb file in embedded mode");
949 let path = match path_short {
950 Some(short) => path.with_short(short),
951 None => path,
952 };
953 vec![
954 FlagSchema::new("bind")
955 .with_short('b')
956 .with_description("Server address")
957 .with_default("0.0.0.0:6380"),
958 path,
959 ]
960}
961
962fn storage_profile_flag() -> FlagSchema {
963 FlagSchema::new("storage-profile")
964 .with_description("Storage deploy profile")
965 .with_choices(&["embedded", "serverless", "primary-replica", "cluster"])
966}
967
968fn storage_packaging_flag() -> FlagSchema {
969 FlagSchema::new("storage-packaging")
970 .with_description("Storage packaging contract")
971 .with_choices(&["single-file", "operational-directory"])
972}
973
974fn storage_preset_flag() -> FlagSchema {
975 FlagSchema::new("storage-preset")
976 .with_description("Storage/deploy preset")
977 .with_choices(&[
978 "embedded",
979 "serverless",
980 "primary-replica-dev",
981 "primary-replica-small",
982 "primary-replica-production-ha",
983 "primary-replica-backup",
984 "primary-replica-wal-retention",
985 "cluster",
986 ])
987}
988
989pub fn completion_domains() -> Vec<(String, Vec<String>)> {
995 vec![
996 ("server".to_string(), vec![]),
997 ("service".to_string(), vec![]),
998 ("replica".to_string(), vec![]),
999 ("tick".to_string(), vec![]),
1000 ("query".to_string(), vec!["q".to_string()]),
1001 ("insert".to_string(), vec!["i".to_string()]),
1002 ("get".to_string(), vec![]),
1003 ("delete".to_string(), vec!["del".to_string()]),
1004 ("health".to_string(), vec![]),
1005 ("status".to_string(), vec![]),
1006 ("inspect".to_string(), vec![]),
1007 ("migrate-from-redis".to_string(), vec![]),
1008 ("salvage".to_string(), vec![]),
1009 ("compact".to_string(), vec![]),
1010 ("mcp".to_string(), vec![]),
1011 ("auth".to_string(), vec![]),
1012 ("connect".to_string(), vec![]),
1013 ("version".to_string(), vec![]),
1014 ]
1015}
1016
1017pub fn completion_global_flags() -> Vec<(&'static str, Option<char>)> {
1019 vec![
1020 ("help", Some('h')),
1021 ("json", Some('j')),
1022 ("output", Some('o')),
1023 ("verbose", Some('v')),
1024 ("no-color", None),
1025 ("version", None),
1026 ]
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031 use super::*;
1032
1033 #[test]
1034 fn test_all_commands_defined() {
1035 let cmds = all_commands();
1036 let names: Vec<&str> = cmds.iter().map(|c| c.name).collect();
1037 assert!(names.contains(&"server"));
1038 assert!(names.contains(&"query"));
1039 assert!(names.contains(&"insert"));
1040 assert!(names.contains(&"get"));
1041 assert!(names.contains(&"delete"));
1042 assert!(names.contains(&"health"));
1043 assert!(names.contains(&"tick"));
1044 assert!(names.contains(&"migrate-from-redis"));
1045 assert!(names.contains(&"salvage"));
1046 assert!(names.contains(&"status"));
1047 assert!(names.contains(&"inspect"));
1048 assert!(names.contains(&"connect"));
1049 assert!(names.contains(&"version"));
1050 }
1051
1052 #[test]
1053 fn test_inspect_has_flags() {
1054 let cmds = all_commands();
1055 let inspect = cmds.iter().find(|c| c.name == "inspect").unwrap();
1056 let flag_names: Vec<&str> = inspect.flags.iter().map(|f| f.long.as_str()).collect();
1057 assert!(flag_names.contains(&"path"));
1058 assert!(flag_names.contains(&"at"));
1059 }
1060
1061 #[test]
1062 fn test_server_has_flags() {
1063 let cmds = all_commands();
1064 let server = cmds.iter().find(|c| c.name == "server").unwrap();
1065 let flag_names: Vec<&str> = server.flags.iter().map(|f| f.long.as_str()).collect();
1066 assert!(flag_names.contains(&"path"));
1067 assert!(flag_names.contains(&"bind"));
1068 assert!(flag_names.contains(&"http-max-handlers"));
1070 assert!(flag_names.contains(&"http-execution-workers"));
1071 assert!(flag_names.contains(&"http-handler-timeout-ms"));
1072 assert!(flag_names.contains(&"http-retry-after-secs"));
1073 }
1074
1075 #[test]
1076 fn test_server_help_text_lists_http_limit_flags() {
1077 let help = command_help_text("server").unwrap();
1078 assert!(help.contains("--http-max-handlers"));
1079 assert!(help.contains("--http-execution-workers"));
1080 assert!(help.contains("--http-handler-timeout-ms"));
1081 assert!(help.contains("--http-retry-after-secs"));
1082 assert!(help.contains("REDDB_HTTP_MAX_HANDLERS"));
1083 assert!(help.contains("REDDB_HTTP_EXECUTION_WORKERS"));
1084 }
1085
1086 #[test]
1087 fn test_replica_has_flags() {
1088 let cmds = all_commands();
1089 let replica = cmds.iter().find(|c| c.name == "replica").unwrap();
1090 let flag_names: Vec<&str> = replica.flags.iter().map(|f| f.long.as_str()).collect();
1091 assert!(flag_names.contains(&"primary-addr"));
1092 assert!(flag_names.contains(&"path"));
1093 assert!(flag_names.contains(&"bind"));
1094 }
1095
1096 #[test]
1097 fn test_main_help_text() {
1098 let help = main_help_text();
1099 assert!(help.contains("reddb"));
1100 assert!(help.contains("Usage: red"));
1101 assert!(help.contains("Commands:"));
1102 assert!(help.contains("server"));
1103 assert!(help.contains("query"));
1104 assert!(help.contains("Global flags:"));
1105 assert!(help.contains("--help"));
1106 assert!(help.contains("Examples:"));
1107 }
1108
1109 #[test]
1110 fn test_command_help_text() {
1111 let help = command_help_text("server").unwrap();
1112 assert!(help.contains("red server"));
1113 assert!(help.contains("--path"));
1114 assert!(help.contains("--bind"));
1115 }
1116
1117 #[test]
1118 fn test_replica_command_help() {
1119 let help = command_help_text("replica").unwrap();
1120 assert!(help.contains("red replica"));
1121 assert!(help.contains("--primary-addr"));
1122 }
1123
1124 #[test]
1125 fn test_migrate_from_redis_command_help() {
1126 let help = command_help_text("migrate-from-redis").unwrap();
1127 assert!(help.contains("red migrate-from-redis"));
1128 assert!(help.contains("--dry-run"));
1129 assert!(help.contains("--redis-url"));
1130 assert!(help.contains("application-owned helper"));
1131 }
1132
1133 #[test]
1134 fn test_migrate_pager_zone_command_help() {
1135 let help = command_help_text("migrate-pager-zone").unwrap();
1136 assert!(help.contains("red migrate-pager-zone"));
1137 assert!(help.contains("--path"));
1138 assert!(help.contains("legacy sidecar-backed"));
1139 }
1140
1141 #[test]
1142 fn test_command_help_text_unknown() {
1143 assert!(command_help_text("nonexistent").is_none());
1144 }
1145
1146 #[test]
1147 fn test_flag_builder() {
1148 let flag = Flag::new("output", "Output format")
1149 .with_short('o')
1150 .with_default("text")
1151 .with_arg("FORMAT");
1152
1153 assert_eq!(flag.long, "output");
1154 assert_eq!(flag.short, Some('o'));
1155 assert_eq!(flag.description, "Output format");
1156 assert_eq!(flag.default, Some("text".to_string()));
1157 assert_eq!(flag.arg, Some("FORMAT".to_string()));
1158 }
1159
1160 #[test]
1161 fn test_completion_domains() {
1162 let domains = completion_domains();
1163 let names: Vec<&str> = domains.iter().map(|(n, _)| n.as_str()).collect();
1164 assert!(names.contains(&"server"));
1165 assert!(names.contains(&"query"));
1166 assert!(names.contains(&"health"));
1167 }
1168
1169 #[test]
1170 fn test_completion_global_flags() {
1171 let flags = completion_global_flags();
1172 assert!(flags.contains(&("help", Some('h'))));
1173 assert!(flags.contains(&("json", Some('j'))));
1174 assert!(flags.contains(&("verbose", Some('v'))));
1175 assert!(flags.contains(&("no-color", None)));
1176 }
1177}