beamdb 0.17.0

BEAM — distributed graph database syncing over WebSocket, WebRTC, and multicast. Successor to rod.
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! CLI argument parsing for the BEAM binary.
//!
//! Uses clap 4 derive API to define [`Cli`], [`Command`], [`StartArgs`], and
//! [`MigrateArgs`]. This module is a transport adapter — it parses
//! command-line arguments and environment variables into typed structs,
//! leaving domain logic to [`Config`](beam::Config) and the binary's
//! `main()`.
//!
//! # Subcommands
//!
//! - `start` — Run a BEAM node server with configurable storage and network
//! - `migrate` — Migrate data between redb and persy storage backends
//!
//! # Environment Variables
//!
//! All `start` options support env var fallback (uppercase, with underscores).
//! CLI flags take precedence over env vars.

use clap::{Args, Parser, Subcommand};

/// BEAM — a Rust implementation of the Gun.js P2P synchronized graph database.
#[derive(Debug, Parser)]
#[command(name = "BEAM", version, about = "BEAM node runner")]
pub struct Cli {
    /// Sets a custom config file.
    #[arg(short = 'c', long = "config", value_name = "FILE")]
    pub config: Option<String>,

    #[command(subcommand)]
    pub command: Command,
}

/// Available BEAM subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Run the BEAM server.
    Start(StartArgs),

    /// Migrate storage between redb and persy backends.
    Migrate(MigrateArgs),
}

/// Arguments for the `start` subcommand.
#[derive(Debug, Args)]
pub struct StartArgs {
    /// Run websocket server?
    #[arg(
        long = "ws-server",
        env = "WS_SERVER",
        value_name = "BOOL",
        default_value = "true"
    )]
    pub ws_server: String,

    /// Websocket server port.
    #[arg(
        short = 'p',
        long = "port",
        env = "PORT",
        value_name = "NUMBER",
        default_value = "4944"
    )]
    pub port: u16,

    /// TLS certificate path.
    #[arg(long = "cert-path", env = "CERT_PATH", value_name = "FILE")]
    pub cert_path: Option<String>,

    /// TLS key path.
    #[arg(long = "key-path", env = "KEY_PATH", value_name = "FILE")]
    pub key_path: Option<String>,

    /// Comma-separated outgoing websocket peers (wss://...).
    #[arg(long = "peers", env = "PEERS", value_name = "URLS")]
    pub peers: Option<String>,

    /// Enable multicast sync?
    #[arg(
        long = "multicast",
        env = "MULTICAST",
        value_name = "BOOL",
        default_value = "false"
    )]
    pub multicast: String,

    /// In-memory storage.
    #[arg(
        long = "memory-storage",
        env = "MEMORY_STORAGE",
        value_name = "BOOL",
        default_value = "false"
    )]
    pub memory_storage: String,

    /// redb storage (disk+mem).
    #[arg(
        long = "redb-storage",
        env = "REDB_STORAGE",
        value_name = "BOOL",
        default_value = "true"
    )]
    pub redb_storage: String,

    /// Path to the redb database file.
    #[arg(
        long = "redb-path",
        env = "REDB_PATH",
        value_name = "PATH",
        default_value = "beam.redb"
    )]
    pub redb_path: String,

    /// Allow writes that are not content hash addressed or user-signed.
    #[arg(
        long = "allow-public-space",
        env = "ALLOW_PUBLIC_SPACE",
        value_name = "BOOL",
        default_value = "true"
    )]
    pub allow_public_space: String,

    /// Graceful shutdown timeout in seconds.
    ///
    /// When the node receives SIGINT or SIGTERM, it begins a graceful
    /// shutdown: flush storage, close connections, drain in-flight
    /// messages. If the graceful shutdown does not complete within this
    /// duration, the node force-stops and exits.
    #[arg(
        long = "shutdown-timeout",
        env = "SHUTDOWN_TIMEOUT",
        value_name = "SECONDS",
        default_value = "30"
    )]
    pub shutdown_timeout: u64,
}

/// Arguments for the `migrate` subcommand.
#[derive(Debug, Args)]
pub struct MigrateArgs {
    /// Source backend: 'redb', 'persy', or 'fjall'.
    #[arg(long = "from", value_name = "BACKEND")]
    pub from: String,

    /// Target backend: 'redb', 'persy', or 'fjall'.
    #[arg(long = "to", value_name = "BACKEND")]
    pub to: String,

    /// Path to source database file.
    #[arg(long = "source", value_name = "PATH")]
    pub source: String,

    /// Path to target database file (will be created).
    #[arg(long = "target", value_name = "PATH")]
    pub target: String,

    /// Records per batch (default: 1000).
    #[arg(long = "batch-size", value_name = "N", default_value = "1000")]
    pub batch_size: usize,

    /// Overwrite target if it already exists.
    #[arg(long = "force")]
    pub force: bool,

    /// Preview the migration without writing.
    #[arg(long = "dry-run")]
    pub dry_run: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::sync::Mutex;

    /// Serializes tests that mutate process-wide env vars.
    /// Without this, `env_var_peers` leaks `PEERS` into `start_with_defaults`
    /// when tests run in parallel.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn start_with_defaults() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: serialized by ENV_LOCK — no other test touches env vars.
        unsafe {
            std::env::remove_var("PEERS");
            std::env::remove_var("PORT");
        }
        let cli = Cli::parse_from(["beam", "start"]);
        match cli.command {
            Command::Start(args) => {
                assert_eq!(args.port, 4944);
                assert_eq!(args.ws_server, "true");
                assert_eq!(args.multicast, "false");
                assert_eq!(args.redb_storage, "true");
                assert_eq!(args.redb_path, "beam.redb");
                assert_eq!(args.memory_storage, "false");
                assert_eq!(args.allow_public_space, "true");
                assert!(args.cert_path.is_none());
                assert!(args.key_path.is_none());
                assert!(args.peers.is_none());
            }
            Command::Migrate(_) => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_custom_port() {
        let cli = Cli::parse_from(["beam", "start", "--port", "8080"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.port, 8080),
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_short_port_flag() {
        let cli = Cli::parse_from(["beam", "start", "-p", "3000"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.port, 3000),
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_peers() {
        let cli = Cli::parse_from([
            "beam",
            "start",
            "--peers",
            "wss://peer1.example.com,wss://peer2.example.com",
        ]);
        match cli.command {
            Command::Start(args) => {
                let peers = args.peers.unwrap();
                assert!(peers.contains("peer1.example.com"));
                assert!(peers.contains("peer2.example.com"));
            }
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_tls() {
        let cli = Cli::parse_from([
            "beam",
            "start",
            "--cert-path",
            "/path/cert.pem",
            "--key-path",
            "/path/key.pem",
        ]);
        match cli.command {
            Command::Start(args) => {
                assert_eq!(args.cert_path.unwrap(), "/path/cert.pem");
                assert_eq!(args.key_path.unwrap(), "/path/key.pem");
            }
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_disable_redb() {
        let cli = Cli::parse_from([
            "beam",
            "start",
            "--redb-storage",
            "false",
            "--memory-storage",
            "true",
        ]);
        match cli.command {
            Command::Start(args) => {
                assert_eq!(args.redb_storage, "false");
                assert_eq!(args.memory_storage, "true");
            }
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_disable_public_space() {
        let cli = Cli::parse_from(["beam", "start", "--allow-public-space", "false"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.allow_public_space, "false"),
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_custom_redb_path() {
        let cli = Cli::parse_from(["beam", "start", "--redb-path", "/tmp/custom.beam"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.redb_path, "/tmp/custom.beam"),
            _ => panic!("expected Start"),
        }
    }

    #[test]
    fn start_with_config_flag() {
        let cli = Cli::parse_from(["beam", "-c", "config.toml", "start"]);
        assert_eq!(cli.config, Some("config.toml".to_string()));
    }

    #[test]
    fn start_with_config_long_flag() {
        let cli = Cli::parse_from(["beam", "--config", "config.toml", "start"]);
        assert_eq!(cli.config, Some("config.toml".to_string()));
    }

    #[test]
    fn migrate_basic() {
        let cli = Cli::parse_from([
            "beam",
            "migrate",
            "--from",
            "redb",
            "--to",
            "persy",
            "--source",
            "/tmp/source.redb",
            "--target",
            "/tmp/target.persy",
        ]);
        match cli.command {
            Command::Migrate(args) => {
                assert_eq!(args.from, "redb");
                assert_eq!(args.to, "persy");
                assert_eq!(args.source, "/tmp/source.redb");
                assert_eq!(args.target, "/tmp/target.persy");
                assert_eq!(args.batch_size, 1000);
                assert!(!args.force);
                assert!(!args.dry_run);
            }
            _ => panic!("expected Migrate"),
        }
    }

    #[test]
    fn migrate_with_batch_size() {
        let cli = Cli::parse_from([
            "beam",
            "migrate",
            "--from",
            "persy",
            "--to",
            "redb",
            "--source",
            "/tmp/s.persy",
            "--target",
            "/tmp/t.redb",
            "--batch-size",
            "500",
        ]);
        match cli.command {
            Command::Migrate(args) => assert_eq!(args.batch_size, 500),
            _ => panic!("expected Migrate"),
        }
    }

    #[test]
    fn migrate_with_flags() {
        let cli = Cli::parse_from([
            "beam",
            "migrate",
            "--from",
            "redb",
            "--to",
            "persy",
            "--source",
            "/tmp/s.redb",
            "--target",
            "/tmp/t.persy",
            "--force",
            "--dry-run",
        ]);
        match cli.command {
            Command::Migrate(args) => {
                assert!(args.force);
                assert!(args.dry_run);
            }
            _ => panic!("expected Migrate"),
        }
    }

    #[test]
    fn env_var_port() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: serialized by ENV_LOCK — no other test touches env vars
        // while this test holds the lock.
        unsafe {
            std::env::set_var("PORT", "9999");
        }
        let cli = Cli::parse_from(["beam", "start"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.port, 9999),
            _ => panic!("expected Start"),
        }
        unsafe {
            std::env::remove_var("PORT");
        }
    }

    #[test]
    fn env_var_peers() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: serialized by ENV_LOCK.
        unsafe {
            std::env::set_var("PEERS", "wss://env-peer.example.com");
        }
        let cli = Cli::parse_from(["beam", "start"]);
        match cli.command {
            Command::Start(args) => {
                assert_eq!(args.peers.unwrap(), "wss://env-peer.example.com");
            }
            _ => panic!("expected Start"),
        }
        unsafe {
            std::env::remove_var("PEERS");
        }
    }

    #[test]
    fn cli_flag_overrides_env_var() {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: serialized by ENV_LOCK.
        unsafe {
            std::env::set_var("PORT", "9999");
        }
        let cli = Cli::parse_from(["beam", "start", "--port", "7777"]);
        match cli.command {
            Command::Start(args) => assert_eq!(args.port, 7777),
            _ => panic!("expected Start"),
        }
        unsafe {
            std::env::remove_var("PORT");
        }
    }

    #[test]
    fn migrate_missing_from() {
        // clap exits the process on missing required args; use try_parse
        let result = Cli::try_parse_from([
            "beam", "migrate", "--to", "persy", "--source", "s", "--target", "t",
        ]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("required"),
            "error should mention required: {err}"
        );
    }

    #[test]
    fn migrate_missing_to() {
        let result = Cli::try_parse_from([
            "beam", "migrate", "--from", "redb", "--source", "s", "--target", "t",
        ]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("required"),
            "error should mention required: {err}"
        );
    }

    #[test]
    fn migrate_missing_source() {
        let result = Cli::try_parse_from([
            "beam", "migrate", "--from", "redb", "--to", "persy", "--target", "t",
        ]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("required"),
            "error should mention required: {err}"
        );
    }

    #[test]
    fn migrate_missing_target() {
        let result = Cli::try_parse_from([
            "beam", "migrate", "--from", "redb", "--to", "persy", "--source", "s",
        ]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("required"),
            "error should mention required: {err}"
        );
    }

    #[test]
    fn no_subcommand_fails() {
        // Without a subcommand, clap should error.
        let result = Cli::try_parse_from(["beam"]);
        assert!(result.is_err(), "parsing without subcommand should fail");
    }
}