nodedb 0.2.0

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// SPDX-License-Identifier: BUSL-1.1

//! Subcommand dispatch table.

use std::path::PathBuf;

use super::args::parse_flags;
use super::{healthcheck, join_token, regen_certs, rotate_ca};

/// All operator subcommands. Constructed by [`parse_subcommand`] from
/// the raw `std::env::args()` tail so `main()` can decide before it
/// touches any config or tracing state.
#[derive(Debug, PartialEq)]
pub enum Subcommand {
    /// Reissue the per-node cert under the existing CA. Restart required.
    RegenCerts { data_dir: PathBuf, node_id: u64 },
    /// Stage a new CA: generate + register for cluster-wide trust.
    RotateCaStage { data_dir: PathBuf },
    /// Finalize a rotation: remove the named CA fingerprint from trust.
    RotateCaFinalize { remove_fingerprint: String },
    /// Issue a short-lived HMAC-signed token for a joining node.
    JoinTokenCreate {
        data_dir: PathBuf,
        for_node: u64,
        ttl: std::time::Duration,
    },
    /// Probe the local HTTP `/health` endpoint and exit 0/1.
    /// Used by container `HEALTHCHECK` directives so distroless /
    /// Chainguard runtime images don't need to ship `curl`.
    Healthcheck { port: u16 },
    /// Print the version string and exit 0.
    PrintVersion,
    /// Reserved subcommand that is not yet implemented.
    NotImplemented { name: String },
}

/// Stub subcommand descriptions for reserved names.
fn stub_description(name: &str) -> &'static str {
    match name {
        "migrate" => "schema/data migration",
        "backup" => "online backup",
        "restore" => "restore",
        "verify" => "verify (consistency check)",
        "repair" => "repair",
        "dump" => "dump (logical export)",
        "fsck" => "fsck",
        _ => "not yet implemented",
    }
}

/// Parse `args` (the tail of `std::env::args()` after the binary name)
/// into a subcommand. Returns `Ok(None)` when the first arg doesn't
/// look like a subcommand (i.e. it's a config-file path and the
/// caller should fall through to the server bootstrap path).
pub fn parse_subcommand(args: &[String]) -> Result<Option<Subcommand>, String> {
    let Some(first) = args.first() else {
        return Ok(None);
    };
    // Known subcommand names — anything else is assumed to be a config
    // file path so the `nodedb /etc/nodedb.toml` spelling keeps working.
    let name = first.as_str();
    if !matches!(
        name,
        "regen-certs"
            | "rotate-ca"
            | "join-token"
            | "healthcheck"
            | "help"
            | "--help"
            | "-h"
            | "--version"
            | "-V"
            | "version"
            | "migrate"
            | "backup"
            | "restore"
            | "verify"
            | "repair"
            | "dump"
            | "fsck"
    ) {
        return Ok(None);
    }

    if matches!(name, "help" | "--help" | "-h") {
        print_usage();
        std::process::exit(0);
    }

    if matches!(name, "--version" | "-V" | "version") {
        return Ok(Some(Subcommand::PrintVersion));
    }

    if matches!(
        name,
        "migrate" | "backup" | "restore" | "verify" | "repair" | "dump" | "fsck"
    ) {
        return Ok(Some(Subcommand::NotImplemented {
            name: name.to_string(),
        }));
    }

    let tail = &args[1..];
    match name {
        "regen-certs" => {
            let flags = parse_flags(tail)?;
            let data_dir = PathBuf::from(super::args::required(&flags, "data-dir")?);
            let node_id: u64 = super::args::required(&flags, "node-id")?
                .parse()
                .map_err(|_| "--node-id must be an integer".to_string())?;
            Ok(Some(Subcommand::RegenCerts { data_dir, node_id }))
        }
        "rotate-ca" => {
            // Sub-mode: `--stage` or `--finalize --remove <fp>`.
            let flags = parse_flags(tail)?;
            if flags.contains_key("stage") {
                let data_dir = PathBuf::from(super::args::required(&flags, "data-dir")?);
                Ok(Some(Subcommand::RotateCaStage { data_dir }))
            } else if flags.contains_key("finalize") {
                let remove = super::args::required(&flags, "remove")?.clone();
                Ok(Some(Subcommand::RotateCaFinalize {
                    remove_fingerprint: remove,
                }))
            } else {
                Err("rotate-ca requires --stage or --finalize --remove <fingerprint>".into())
            }
        }
        "healthcheck" => {
            let port = healthcheck::parse_port(tail)?;
            Ok(Some(Subcommand::Healthcheck { port }))
        }
        "join-token" => {
            let flags = parse_flags(tail)?;
            if !flags.contains_key("create") {
                return Err("join-token requires --create".into());
            }
            let data_dir = PathBuf::from(super::args::required(&flags, "data-dir")?);
            let for_node: u64 = super::args::required(&flags, "for-node")?
                .parse()
                .map_err(|_| "--for-node must be an integer".to_string())?;
            let ttl =
                super::args::parse_duration(flags.get("ttl").map(|s| s.as_str()).unwrap_or("10m"))?;
            Ok(Some(Subcommand::JoinTokenCreate {
                data_dir,
                for_node,
                ttl,
            }))
        }
        _ => unreachable!("name checked above"),
    }
}

/// Execute a parsed subcommand. Returns process exit code.
pub fn run_subcommand(cmd: Subcommand) -> i32 {
    match cmd {
        Subcommand::RegenCerts { data_dir, node_id } => {
            match regen_certs::run(&data_dir, node_id) {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("error: {e}");
                    1
                }
            }
        }
        Subcommand::RotateCaStage { data_dir } => match rotate_ca::stage(&data_dir) {
            Ok(()) => 0,
            Err(e) => {
                eprintln!("error: {e}");
                1
            }
        },
        Subcommand::RotateCaFinalize { remove_fingerprint } => {
            match rotate_ca::finalize(&remove_fingerprint) {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("error: {e}");
                    1
                }
            }
        }
        Subcommand::JoinTokenCreate {
            data_dir,
            for_node,
            ttl,
        } => match join_token::create(&data_dir, for_node, ttl) {
            Ok(()) => 0,
            Err(e) => {
                eprintln!("error: {e}");
                1
            }
        },
        Subcommand::Healthcheck { port } => healthcheck::run(port),
        Subcommand::PrintVersion => {
            print!("{}", format_version_block());
            0
        }
        Subcommand::NotImplemented { name } => {
            let desc = stub_description(&name);
            eprintln!("error: {desc} not yet implemented");
            1
        }
    }
}

/// Returns the enriched version block printed by `--version` / `-V` / `version`.
///
/// Extracted as a pure function so unit tests can assert on the output without
/// capturing stdout.
pub(crate) fn format_version_block() -> String {
    use crate::version::{
        BUILD_DATE, BUILD_PROFILE, GIT_COMMIT, RUST_VERSION, VERSION, WIRE_FORMAT_VERSION,
    };
    format!(
        "nodedb {VERSION}\ngit commit:    {GIT_COMMIT}\nbuild date:    {BUILD_DATE}\nbuild profile: {BUILD_PROFILE}\nrust version:  {RUST_VERSION}\nwire format:   {WIRE_FORMAT_VERSION}\n"
    )
}

fn print_usage() {
    println!(
        "nodedb — NodeDB server + operator tooling

USAGE:
    nodedb [CONFIG_FILE]                     Run the server (default mode)
    nodedb --version                         Print version and exit
    nodedb regen-certs --data-dir D --node-id N
                                             Reissue this node's cert under the existing CA
    nodedb rotate-ca --stage --data-dir D    Generate a new CA, write to ca.d/, emit staged bundle
    nodedb rotate-ca --finalize --remove FP  Ask the running node to remove CA with fingerprint FP
    nodedb join-token --create --data-dir D --for-node N [--ttl 10m]
                                             Emit a one-time HMAC token for a joining node
    nodedb healthcheck [--port N]            Probe local HTTP /health (exit 0=healthy, 1=unhealthy)
    nodedb help                              Print this message

RESERVED (not yet implemented):
    nodedb migrate                           Schema/data migration
    nodedb backup                            Online backup
    nodedb restore                           Restore from backup
    nodedb verify                            Consistency check
    nodedb repair                            Repair corrupted data
    nodedb dump                              Logical export
    nodedb fsck                              Filesystem consistency check"
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args(s: &[&str]) -> Vec<String> {
        s.iter().map(|&x| x.to_string()).collect()
    }

    // --version and version → PrintVersion
    #[test]
    fn version_flag_parses() {
        assert_eq!(
            parse_subcommand(&args(&["--version"])).unwrap(),
            Some(Subcommand::PrintVersion)
        );
    }

    #[test]
    fn version_subcommand_parses() {
        assert_eq!(
            parse_subcommand(&args(&["version"])).unwrap(),
            Some(Subcommand::PrintVersion)
        );
    }

    // 7 reserved stub subcommands → NotImplemented
    #[test]
    fn stub_migrate() {
        assert_eq!(
            parse_subcommand(&args(&["migrate"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "migrate".to_string()
            })
        );
    }

    #[test]
    fn stub_backup() {
        assert_eq!(
            parse_subcommand(&args(&["backup"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "backup".to_string()
            })
        );
    }

    #[test]
    fn stub_restore() {
        assert_eq!(
            parse_subcommand(&args(&["restore"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "restore".to_string()
            })
        );
    }

    #[test]
    fn stub_verify() {
        assert_eq!(
            parse_subcommand(&args(&["verify"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "verify".to_string()
            })
        );
    }

    #[test]
    fn stub_repair() {
        assert_eq!(
            parse_subcommand(&args(&["repair"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "repair".to_string()
            })
        );
    }

    #[test]
    fn stub_dump() {
        assert_eq!(
            parse_subcommand(&args(&["dump"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "dump".to_string()
            })
        );
    }

    #[test]
    fn stub_fsck() {
        assert_eq!(
            parse_subcommand(&args(&["fsck"])).unwrap(),
            Some(Subcommand::NotImplemented {
                name: "fsck".to_string()
            })
        );
    }

    // Existing subcommands still parse correctly
    #[test]
    fn regen_certs_parses() {
        let result = parse_subcommand(&args(&[
            "regen-certs",
            "--data-dir",
            "/data",
            "--node-id",
            "42",
        ]));
        assert!(matches!(
            result,
            Ok(Some(Subcommand::RegenCerts { node_id: 42, .. }))
        ));
    }

    #[test]
    fn rotate_ca_stage_parses() {
        let result = parse_subcommand(&args(&["rotate-ca", "--stage", "--data-dir", "/data"]));
        assert!(matches!(result, Ok(Some(Subcommand::RotateCaStage { .. }))));
    }

    #[test]
    fn rotate_ca_finalize_parses() {
        let result = parse_subcommand(&args(&["rotate-ca", "--finalize", "--remove", "abcdef"]));
        assert!(matches!(
            result,
            Ok(Some(Subcommand::RotateCaFinalize { .. }))
        ));
    }

    #[test]
    fn join_token_parses() {
        let result = parse_subcommand(&args(&[
            "join-token",
            "--create",
            "--data-dir",
            "/data",
            "--for-node",
            "7",
        ]));
        assert!(matches!(
            result,
            Ok(Some(Subcommand::JoinTokenCreate { for_node: 7, .. }))
        ));
    }

    // Config file path passes through as Ok(None)
    #[test]
    fn config_path_passthrough() {
        assert_eq!(parse_subcommand(&args(&["./config.toml"])).unwrap(), None);
    }

    #[test]
    fn absolute_config_path_passthrough() {
        assert_eq!(
            parse_subcommand(&args(&["/etc/nodedb/nodedb.toml"])).unwrap(),
            None
        );
    }

    #[test]
    fn dash_capital_v_alias_for_version() {
        assert_eq!(
            parse_subcommand(&args(&["-V"])).unwrap(),
            Some(Subcommand::PrintVersion)
        );
    }

    #[test]
    fn print_version_output_contains_enriched_fields() {
        let block = format_version_block();
        assert!(block.contains("git commit:"), "missing git commit label");
        assert!(block.contains("build date:"), "missing build date label");
        assert!(
            block.contains("build profile:"),
            "missing build profile label"
        );
        assert!(
            block.contains("rust version:"),
            "missing rust version label"
        );
        assert!(block.contains("wire format:"), "missing wire format label");
    }

    // No args → Ok(None)
    #[test]
    fn empty_args_passthrough() {
        assert_eq!(parse_subcommand(&[]).unwrap(), None);
    }

    // run_subcommand for PrintVersion returns 0
    #[test]
    fn run_print_version_exit_code() {
        // We can't capture stdout easily here without additional infrastructure,
        // but we can at least verify the exit code is 0 by testing the dispatcher
        // classification. The actual println! is a side effect.
        assert!(matches!(
            parse_subcommand(&args(&["--version"])).unwrap(),
            Some(Subcommand::PrintVersion)
        ));
    }

    // run_subcommand for NotImplemented returns 1
    #[test]
    fn not_implemented_exit_code() {
        let cmd = Subcommand::NotImplemented {
            name: "migrate".to_string(),
        };
        assert_eq!(run_subcommand(cmd), 1);
    }
}