diff --git a/.changeset/cli-surface.md b/.changeset/cli-surface.md new file mode 100644 index 000000000..d3f3e250d --- /dev/null +++ b/.changeset/cli-surface.md @@ -0,0 +1,11 @@ +--- +--- + +feat(cli): port the `pnpm run cli` surface into `nostream-cli` + +The operator line now answers the capture's page, version and unknown-command contract, and +implements the eight missing commands: `start`, `stop`, `update`, `clean`, `info`, `seed`, +`invite`, `setup`, plus `export` and `clean-db` and the `config list`/`set`/`env` family. +`nostream dev` is removed. Three dependencies are added (bech32, flate2, xz2) and four +`EventRepository` methods (`scan_live`, `count_by_criteria`, `delete_by_criteria`, +`delete_all_events`); child processes go through `nostream_services::process`. diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3f6950aa8..5ebec3363 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -278,7 +278,7 @@ jobs: - name: Storage parity against Postgres env: PARITY_ADMIN_URL: postgres://postgres:postgres@localhost:5432/postgres - run: cargo test -p nostream-storage --test migrations --test parity --test migration_pg -- --ignored --test-threads=1 + run: cargo test -p nostream-storage --test migrations --test parity --test migration_pg --test clean_up -- --ignored --test-threads=1 # The benchmark rig's Postgres column: the same workload and the same `--verify` the LMDB # arm runs, against the scratch database it drops and recreates. The dev profile is # deliberate — this proves the path and the counts, and its timings are cited nowhere. @@ -313,6 +313,8 @@ jobs: run: cargo build -p nostream-cli --no-default-features - name: CLI refuses the migration on Windows run: cargo test -p nostream-cli --no-default-features --test migrate_cli_unsupported + - name: CLI surface on Windows + run: cargo test -p nostream-cli --no-default-features --test cli_surface_windows changeset-check: name: Changeset Required diff --git a/CLAUDE.md b/CLAUDE.md index b3ccf25e1..c541f66ef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,7 +103,7 @@ resolver 3: | `nostream-relay` | connections, wire protocol, handlers, rate limiters, live dispatch, NIP-77 engine (the acceptor lives in `nostreamd`) | | `nostream-services` | payment processors and the invoice lifecycle, operator notifications, the web-of-trust graph, Tor, the scheduler and its workers, event import, NIP-66 monitors (#865) | | `nostream-admin` | admin API and auth | -| `nostream-cli` | operator command line (`nostream-cli config validate`, `nostream-cli import`, `nostream-cli migrate pg-to-lmdb`) | +| `nostream-cli` | operator command line: `start`, `stop`, `update`, `clean`, `info`, `seed`, `invite`, `setup`, `export`, `clean-db`, `import`, `config`, `migrate pg-to-lmdb`, `tui` (stub) | | `nostreamd` | the daemon binary: runtime, telemetry, signals, the services composition root and the worker supervisor | - Every crate manifest repeats `version.workspace = true`, `edition.workspace = true`, @@ -115,9 +115,11 @@ resolver 3: bump; do not add one. - `nostream-services` is the only crate that opens sockets and child processes: `reqwest` (`default-features = false` with `rustls-tls`, so no new TLS stack) behind the - `HttpClient` seam, and tokio's `process`/`fs` for the DVM worker pipes and the onion key - file. Nothing else may take those features. The branch's other third-party additions are - `aes` and `cbc`, in `nostream-core`, for the NIP-04 body NIP-47 encrypts (ADR 0010, A23). + `HttpClient` seam, and tokio's `process`/`fs` for the DVM worker pipes, the onion key file + and the operator CLI's spawn seam (ADR 0015, D11). Nothing else may take those features. + The branch's other third-party additions are `aes` and `cbc`, in `nostream-core`, for the + NIP-04 body NIP-47 encrypts (ADR 0010, A23); `bech32` in `nostream-core` for NIP-19 `npub` + decoding; and `flate2` and `xz2` in `nostream-cli` for `export`'s two codecs (ADR 0015, D6). - Each crate's `lib.rs` doc comment names the TypeScript paths it owns at the capture commit, and separately names what it deliberately does **not** own. Preserve both: a reader must be able to tell an omission from a gap. diff --git a/CLI.md b/CLI.md index 80d80bc21..f59068820 100644 --- a/CLI.md +++ b/CLI.md @@ -1,14 +1,16 @@ # Nostream CLI -Nostream ships a unified command-line interface: +Nostream ships a unified command-line interface, `nostream-cli`, whose program name on every +page and message is `nostream`: ```bash nostream --help -pnpm run cli -- --help +nostream --version ``` -When run with no arguments in an interactive terminal, `nostream` launches an interactive TUI. -In non-interactive environments, it prints help and exits successfully. +With no arguments it prints the help page on stdout and exits successfully, in a terminal and +out of one alike; the page, `--help` and an unknown command are answered before the argument +parser runs. ## Exit Codes @@ -16,6 +18,21 @@ In non-interactive environments, it prints help and exits successfully. - `1`: runtime/validation error - `2`: usage error (invalid command/options) +An unknown command prints `Unknown command: ` on stderr and the help page on stdout, at +exit `2`. + +A failure carries the `Error: ` prefix only when the command threw it — the parser's own usage +errors and the commands' thrown validations. A message a command reports itself is printed bare, +with the code it chose: + +```bash +nostream invite create --uses 0 # Error: --uses must be a positive integer, exit 2 +nostream seed --count 0 # Error: --count must be a positive integer, exit 1 +nostream config get payments.x # Path not found: payments.x, exit 1 +``` + +`--json` failures are the envelope `{"error":{"message":…,"code":N}}` on stderr. + ## Core Commands ```bash @@ -28,9 +45,59 @@ nostream setup [--yes] [--start] nostream seed [--count 100] nostream invite create [--uses N] [--expires-in ] [--json] nostream import [file.jsonl|file.json] [--file file.jsonl|file.json] [--batch-size 1000] -nostream export [output] [--output output] [--format jsonl|json] +nostream export [output] [--output output] [--format jsonl|json|gzip|gz|xz] [-z] +nostream clean-db [--all|--older-than=|--kinds=<1,7,4>] [--dry-run] [--force] ``` +`--version` and `-v` print `nostream/`. + +`info`, `seed`, `invite create`, `export` and `clean-db` read the store the settings name, and +take `--data-dir ` for the LMDB root: the environment lives at `/lmdb`, the layout +`nostream-cli migrate pg-to-lmdb --target ` writes. With the lmdb backend selected and no +`--data-dir`, the command fails with `Error: the lmdb backend needs --data-dir `. + +`start` and `setup` create `/settings.yaml` from the defaults only when the config +directory has neither `settings.yaml` nor the deprecated `settings.json`. If it holds only +`settings.json`, both leave it in place and write no `settings.yaml`, and the relay keeps reading +its values; move the overrides into YAML yourself when you want them in the new file. + +## Cleaning events + +`clean-db` deletes events by age, by kind, or every event. Nothing else is touched: invite +codes, invoices and users survive. + +``` +nostream clean-db [options] + + --all Delete all events. + --older-than= Delete events older than the given number of days. + --kinds=<1,7,4> Delete events for specific kinds. + --dry-run Show how many rows would be deleted without deleting them. + --force Skip interactive confirmation prompt. + --help Show this help message. +``` + +`--all` cannot be combined with `--older-than` or `--kinds`, and at least one of the three is +required. Without `--force` a terminal is asked to type `DELETE`; a piped stdin refuses with +`Interactive confirmation is unavailable. Re-run with --force.` and exit 1. `NODE_ENV=production` +prints a warning on stderr and changes nothing else. + +What a run costs: the LMDB delete commits one batch of 10 000 rows at a time so a relay sharing +the store keeps its writer between batches. On a 160 001-row store that is 17 commits and about +1.6× the wall clock of one statement — 28 s in the shipped shape against 17.94 s for the same +store deleted in one transaction, both measured in one sweep (the first cut's own run, before +that sweep, timed the one-transaction shape at 19.46 s; ADR 0015's D13 labels every figure). It +also writes more bytes than the rows it removes, and the two measured ends of that trade bracket +the shipped shape: the 1 000-row batch shape wrote **5.31 GB** where one transaction wrote +**1.41 MB**, and it grows the store file less (**69.8 MB** against **242.9 MB**). The shipped +10 000-row shape's write volume sits between the two and was not measured; its commit count, +which is what charges it, is 17. `--dry-run` counts the same rows with one read walk (202 ms on +that store), so run it first on a big store. + +A run that stops after some batches committed says so: the failure's line opens with the rows +already deleted (`4000 events were deleted before the failure: …`, exit 1). The store is then +part-deleted by design, and a re-run removes only what is left. + ## NIP-43 invite codes Join (kind 28934) is already implemented. Operators mint a claim string and share it out of band; the client then publishes a join request with a `claim` tag. @@ -102,24 +169,20 @@ nostream config set limits.event.content[0].maxLength 2048 nostream config set nip05.domainWhitelist '["example.com","relay.io"]' --type json ``` -## Development Commands +## Development -```bash -nostream dev db:clean [--all|--older-than=30|--kinds=1,7,4] [--dry-run] [--force] -nostream dev db:reset [--yes] -nostream dev seed:relay -nostream dev docker:clean [--yes] -nostream dev test:unit -nostream dev test:cli -nostream dev test:integration -``` +The TypeScript development loop (`db:reset`, `seed:relay`, `docker:clean`, the `test:*` +wrappers) is not part of this binary: the wrapper died with the TypeScript line (#869). Its one +real operator operation, `db:clean`, is the top-level `clean-db` above. The Rust suite is the +one `cargo test --workspace --all-features` runs. ## TUI Navigation -Run: +The interactive settings editor is not ported yet: `nostream tui` is a labelled stub, and the +no-argument path prints the help page rather than launching it. What the capture's TUI offered: ```bash -nostream +nostream tui ``` Main menu includes: diff --git a/Cargo.lock b/Cargo.lock index a084c7ccd..7bb6a24d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aes" version = "0.8.4" @@ -195,6 +201,12 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bech32" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" + [[package]] name = "bincode" version = "1.3.3" @@ -431,6 +443,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-queue" version = "0.3.14" @@ -626,6 +647,17 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "flume" version = "0.12.0" @@ -1326,6 +1358,17 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "lzma-sys" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + [[package]] name = "matchers" version = "0.2.0" @@ -1363,6 +1406,16 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -1414,10 +1467,13 @@ dependencies = [ "anyhow", "chrono", "clap", + "flate2", + "futures-util", "heed", "hex", "nostream-config", "nostream-core", + "nostream-relay", "nostream-services", "nostream-storage", "serde", @@ -1427,6 +1483,7 @@ dependencies = [ "tempfile", "thiserror", "tokio", + "xz2", ] [[package]] @@ -1449,6 +1506,7 @@ version = "0.1.0" dependencies = [ "aes", "base64 0.22.1", + "bech32", "cbc", "chacha20", "getrandom 0.3.4", @@ -1539,6 +1597,7 @@ dependencies = [ "chrono", "clap", "futures-core", + "futures-util", "heed", "nostream-config", "nostream-core", @@ -2460,6 +2519,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "siphasher" version = "1.0.4" @@ -3495,6 +3560,15 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xz2" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2" +dependencies = [ + "lzma-sys", +] + [[package]] name = "yoke" version = "0.8.3" @@ -3598,6 +3672,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 807a8f890..b2f3ad297 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,10 +14,12 @@ aes = "0.8" anyhow = "1" axum = "0.8" base64 = "0.22.1" +bech32 = "0.11" cbc = { version = "0.1", features = ["alloc", "block-padding"] } chacha20 = "0.10.2" chrono = { version = "0.4", default-features = false, features = ["std", "clock", "serde"] } clap = { version = "4", features = ["derive"] } +flate2 = "1" futures-core = "0.3" futures-util = "0.3" getrandom = "0.3" @@ -58,6 +60,7 @@ tracing-opentelemetry = "0.34" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } url = "2" uuid = { version = "1", features = ["v4"] } +xz2 = "0.1" [workspace.lints.rust] # `deny` rather than `forbid`: heed's LMDB `EnvOpenOptions::open` is an `unsafe fn` diff --git a/README.md b/README.md index 921c3d8c6..273f3a555 100644 --- a/README.md +++ b/README.md @@ -573,37 +573,39 @@ pnpm db:verify-index-impact It seeds ~200k synthetic events, drops the hot-path indexes, runs EXPLAIN (ANALYZE, BUFFERS) for each hot query, recreates the indexes, and prints a BEFORE/AFTER table. See the *Database indexes and benchmarking* section of [CONFIGURATION.md](CONFIGURATION.md). ## Relay Maintenance -Use `nostream dev db:clean` to wipe or prune `events` table data. This also removes -corresponding data from the derived `event_tags` table when present. +Use `nostream clean-db` to wipe or prune stored events. This also removes the +corresponding tags. It runs against whichever store the settings select — LMDB under +`--data-dir`, or the Postgres database the `DB_*` variables name — and `nostream clean-db --help` +lists the same options the capture's `dev db:clean` took. Dry run (no deletion): ``` -nostream dev db:clean --all --dry-run +nostream clean-db --all --dry-run ``` Full wipe: ``` -nostream dev db:clean --all --force +nostream clean-db --all --force ``` Delete events older than N days: ``` -nostream dev db:clean --older-than=30 --force +nostream clean-db --older-than=30 --force ``` Delete only selected kinds: ``` -nostream dev db:clean --kinds=1,7,4 --force +nostream clean-db --kinds=1,7,4 --force ``` Delete only selected kinds older than N days: ``` -nostream dev db:clean --older-than=30 --kinds=1,7,4 --force +nostream clean-db --older-than=30 --kinds=1,7,4 --force ``` By default, the command asks for explicit confirmation (`Type 'DELETE' to confirm`). diff --git a/crates/nostream-admin/tests/common/mod.rs b/crates/nostream-admin/tests/common/mod.rs index 405fd6e7b..3a54771d5 100644 --- a/crates/nostream-admin/tests/common/mod.rs +++ b/crates/nostream-admin/tests/common/mod.rs @@ -573,6 +573,35 @@ impl EventRepository for SlowEventRepository { Box::pin(async { Err(not_implemented()) }) } + fn scan_live<'a>( + &'a self, + _after: Option, + _limit: u64, + ) -> nostream_storage::repositories::StorageFuture< + 'a, + QueryStream<'a, nostream_storage::repositories::EventRecord>, + > { + Box::pin(async { Err(not_implemented()) }) + } + + fn count_by_criteria<'a>( + &'a self, + _criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> nostream_storage::repositories::StorageFuture<'a, u64> { + Box::pin(async { Err(not_implemented()) }) + } + + fn delete_by_criteria<'a>( + &'a self, + _criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> nostream_storage::repositories::StorageFuture<'a, u64> { + Box::pin(async { Err(not_implemented()) }) + } + + fn delete_all_events(&self) -> nostream_storage::repositories::StorageFuture<'_, ()> { + Box::pin(async { Err(not_implemented()) }) + } + fn page_bound(&self) -> u64 { nostream_storage::MAX_PAGE_ROWS } diff --git a/crates/nostream-cli/Cargo.toml b/crates/nostream-cli/Cargo.toml index fca0a721b..2d976f615 100644 --- a/crates/nostream-cli/Cargo.toml +++ b/crates/nostream-cli/Cargo.toml @@ -14,9 +14,12 @@ path = "src/main.rs" [dependencies] clap.workspace = true anyhow = { workspace = true } +chrono.workspace = true +flate2.workspace = true hex.workspace = true nostream-config.workspace = true nostream-core.workspace = true +nostream-relay.workspace = true nostream-services.workspace = true nostream-storage.workspace = true serde.workspace = true @@ -25,9 +28,10 @@ serde_yaml.workspace = true sha2.workspace = true thiserror.workspace = true tokio.workspace = true +xz2.workspace = true [dev-dependencies] -chrono.workspace = true +futures-util.workspace = true heed.workspace = true tempfile.workspace = true diff --git a/crates/nostream-cli/src/app.rs b/crates/nostream-cli/src/app.rs new file mode 100644 index 000000000..7cc93b509 --- /dev/null +++ b/crates/nostream-cli/src/app.rs @@ -0,0 +1,871 @@ +//! The surface: the pre-parse, the hand-written top-level page, the dispatch and the renderer. +//! +//! The capture's entry point answers `--help`/`-h` and an empty command line with the page on +//! stdout at exit 0, `-v`/`--version` with the version page, and an unknown first word with +//! `Unknown command: ` on stderr plus the page on stdout at exit 2, and only then hands the +//! arguments to its parser (`src/cli/index.ts:470-531`). A port built on clap repeats that order +//! here, so the parser never sees a case that has its own answer (R1, C1). +//! +//! Everything a command needs from the process it runs in is one [`Context`]: the working +//! directory its files resolve against, the environment with the `.env` layer behind it, and the +//! runtime its futures run on. + +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::{Parser, Subcommand}; + +use crate::commands; +use crate::config::CommandOutput; +use crate::env_file::Environment; +use crate::error::CliError; + +/// The program name every page and every error message carries (R4). +const PROGRAM: &str = "nostream"; + +/// What a command needs from the process it runs in. +pub struct Context { + /// The working directory the command resolves its files against — `resources/`, `seeds/`, + /// the compose overlays and `.env` are all read relative to it, exactly as the capture's + /// `getProjectPath` reads them. + pub cwd: PathBuf, + /// The process environment with the `.env` layer behind it (`src/cli/utils/env-config.ts`). + pub env: Environment, + runtime: tokio::runtime::Runtime, +} + +impl Context { + /// A context for the process's own working directory. + pub fn new() -> Result { + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + Self::at(cwd) + } + + /// A context for `cwd`, which a test names. + pub fn at(cwd: PathBuf) -> Result { + let env = Environment::load(&cwd); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| CliError::command(format!("unable to start a runtime: {error}")))?; + Ok(Self { cwd, env, runtime }) + } + + /// Drives one command's future to completion on the context's runtime. + pub fn block_on(&self, future: F) -> F::Output { + self.runtime.block_on(future) + } + + /// Enters the runtime, so a command can spawn a task that runs alongside its futures. + pub fn enter(&self) -> tokio::runtime::EnterGuard<'_> { + self.runtime.enter() + } +} + +/// The version page (V44): `nostream/`, the crate's own version — the same +/// string `info` prints as `Nostream v` and the admin diagnostics serve. +pub fn version_line() -> String { + format!("nostream/{}", env!("CARGO_PKG_VERSION")) +} + +/// The top-level page, on stdout, at exit 0. +/// +/// It is the capture's `cac` page (V2) with two edits, both from the removal of `dev` (R17): the +/// ` dev [...args]` row and the footer's ` $ nostream dev --help` line are gone. The version +/// line is the crate's own (R2). +pub fn page_lines() -> Vec { + [ + version_line(), + String::new(), + "Usage:".to_owned(), + " $ nostream [options]".to_owned(), + String::new(), + "Commands:".to_owned(), + " start [...args] Start Nostream (Docker Compose)".to_owned(), + " stop [...args] Stop Nostream".to_owned(), + " info Show relay/runtime info".to_owned(), + " update [...args] Pull latest git changes and restart relay".to_owned(), + " clean Clean Docker resources (legacy script replacement)" + .to_owned(), + " import [file] [...args] Import events from .jsonl or .json".to_owned(), + " export [output] [...args] Export events to file".to_owned(), + " seed Seed relay with test data".to_owned(), + " invite [...args] Mint NIP-43 invite codes".to_owned(), + " setup Initial interactive setup".to_owned(), + " config [...args] Manage settings".to_owned(), + String::new(), + "For more info, run any command with the `--help` flag:".to_owned(), + " $ nostream start --help".to_owned(), + " $ nostream stop --help".to_owned(), + " $ nostream info --help".to_owned(), + " $ nostream update --help".to_owned(), + " $ nostream clean --help".to_owned(), + " $ nostream import --help".to_owned(), + " $ nostream export --help".to_owned(), + " $ nostream seed --help".to_owned(), + " $ nostream invite --help".to_owned(), + " $ nostream setup --help".to_owned(), + " $ nostream config --help".to_owned(), + String::new(), + "Options:".to_owned(), + " -h, --help Display this message".to_owned(), + " -v, --version Display version number".to_owned(), + ] + .to_vec() +} + +/// What the pre-parse decided before the argument parser sees anything. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Invocation { + /// `-h`, `--help`, or no arguments at all: the page, on stdout, at exit 0. + Help, + /// `-v` or `--version`: the version page, on stdout, at exit 0. + Version, + /// A top-level command the parser reads. + Command, + /// `start` with a `--port` that received no value: the port's own message, at exit 1. + Port, + /// A word that is no command: `Unknown command: `, at exit 2. + Unknown(String), +} + +/// The top-level words, in the page's order. A word not here is the capture's unknown command +/// (`src/cli/index.ts:514-518`), which is answered before the parser runs. +pub const COMMANDS: &[&str] = &[ + "clean", "clean-db", "config", "export", "import", "info", "invite", "migrate", "seed", + "setup", "start", "stop", "tui", "update", +]; + +/// `src/cli/index.ts:470-531`: the four answers that are not a command's, before `parse` — the +/// page, the version, the unknown word, and `start`'s valueless `--port` (D1). +pub fn pre_parse(argv: &[String]) -> Invocation { + let Some(first) = argv.first() else { + return Invocation::Help; + }; + + match first.as_str() { + "-h" | "--help" => Invocation::Help, + "-v" | "--version" => Invocation::Version, + word if COMMANDS.contains(&word) => { + // V5's second boundary: the capture reads its own `argv` for the flag + // (`src/cli/commands/start.ts:74-78`) and throws the port's message, so a flag whose + // value never arrived is answered here rather than as the parser's missing-value + // error at exit 2. + if word == "start" && port_without_a_value(argv) { + Invocation::Port + } else { + Invocation::Command + } + } + word => Invocation::Unknown(word.to_owned()), + } +} + +/// Whether a `start` invocation names `--port` with no value after it. A following word that +/// starts with `-` is another flag rather than a value, which is also how the parser reads it. +fn port_without_a_value(argv: &[String]) -> bool { + argv.iter().enumerate().any(|(index, word)| { + word == "--port" + && match argv.get(index + 1) { + Some(next) => next.starts_with('-'), + None => true, + } + }) +} + +/// The process entry point, from the arguments after the binary's own name. +pub fn run(argv: Vec) -> ExitCode { + match pre_parse(&argv) { + Invocation::Help => print_page(&page_lines(), 0), + // The version line is data like the page, so a write that fails answers the same way: + // one line on stderr and exit 1, never `println!`'s panic at 101 (V1). + Invocation::Version => print_page(&[version_line()], 0), + Invocation::Port => render(Err(CliError::command(commands::start::PORT_MESSAGE))), + Invocation::Unknown(word) => { + // The marker is the error and the page is the help: the capture writes the first + // with `logError` (stderr) and the second with `outputHelp` (stdout) (V46). + let _ = print_error_lines(&[format!("Unknown command: {word}")]); + print_page(&page_lines(), 2) + } + Invocation::Command => { + let cli = Cli::parse_from(std::iter::once(PROGRAM.to_owned()).chain(argv)); + let context = match Context::new() { + Ok(context) => context, + Err(error) => return render(Err(error)), + }; + render(dispatch(cli.command, &context)) + } + } +} + +/// Prints `lines` on stdout and answers `code`, with `render`'s rule for a write that failed: a +/// closed reader ends the output at that code rather than at exit 101, and any other error is one +/// line on stderr. +/// +/// The code a caller passes is the answer it already has. A page that could not be written is a +/// failure when the page *was* the answer (`--help`, `--version`: 0 becomes 1), and stays the +/// answer when the page was a failure's decoration (`Unknown command:` keeps 2) — a write the +/// stream refused does not re-code what the command decided. +fn print_page(lines: &[String], code: u8) -> ExitCode { + match print_lines(lines) { + Ok(()) => ExitCode::from(code), + Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => ExitCode::from(code), + Err(error) => { + let _ = print_error_lines(&[format!("Error: unable to write output: {error}")]); + ExitCode::from(if code == 0 { 1 } else { code }) + } + } +} + +/// One command, dispatched. The only place that knows a subcommand exists. +fn dispatch(command: Command, context: &Context) -> Result { + match command { + Command::Clean => commands::clean::run(context), + Command::CleanDb { args } => commands::clean_db::run(context, &args), + Command::Config { command } => match command { + ConfigCommand::Validate { config_dir, config } => commands::config::validate( + &context.cwd, + config_dir.as_deref(), + config.as_deref(), + &context.env, + ), + ConfigCommand::Get { + path, + config_dir, + json, + } => commands::config::get( + &context.cwd, + config_dir.as_deref(), + &path, + json, + &context.env, + ), + ConfigCommand::List { config_dir, json } => { + commands::config::list(&context.cwd, config_dir.as_deref(), json, &context.env) + } + ConfigCommand::Set { + path, + value, + config_dir, + value_type, + validate, + no_validate, + restart, + } => commands::config::set( + context, + config_dir.as_deref(), + commands::config::SetRequest { + path: &path, + value: &value, + value_type: value_type.as_deref(), + // The capture's one boolean: `resolved.validate !== false`. clap's + // `overrides_with` leaves at most one of the pair set, so the last flag wins. + validate: validate || !no_validate, + restart, + }, + ), + ConfigCommand::Env { command } => match command { + ConfigEnvCommand::List { show_secrets } => { + commands::config::env_list(&context.env, show_secrets) + } + ConfigEnvCommand::Get { key, show_secrets } => { + commands::config::env_get(&context.env, &key, show_secrets) + } + ConfigEnvCommand::Set { key, value } => { + commands::config::env_set(&context.cwd, &key, &value) + } + ConfigEnvCommand::Validate => commands::config::env_validate(&context.env), + }, + }, + Command::Export { + output, + output_option, + compress, + format, + data_dir, + } => { + let options = commands::export::ExportOptions { + output: output_option.or(output), + compress, + format, + data_dir, + }; + let mut stdout = std::io::stdout().lock(); + commands::export::run(context, &options, &mut stdout) + } + Command::Import { args } => { + let mut stdout = std::io::stdout().lock(); + commands::import::run(&args, &context.cwd, &context.env, &mut stdout) + } + Command::Info { + tor_hostname, + i2p_hostname, + json, + data_dir, + } => { + let options = commands::info::InfoOptions { + tor_hostname, + i2p_hostname, + json, + data_dir, + }; + commands::info::run(context, &options) + } + Command::Invite { command } => match command { + Some(InviteCommand::Create { + uses, + expires_in, + json, + data_dir, + }) => commands::invite::run( + context, + &commands::invite::InviteOptions { + uses, + expires_in, + json, + data_dir, + }, + ), + None => Err(CliError::usage(commands::invite::INVITE_USAGE)), + }, + Command::Migrate { command } => match command { + MigrateCommand::PgToLmdb { + target, + batch_size, + verify, + } => { + let options = commands::migrate::MigrateOptions { + target, + batch_size, + verify, + }; + let mut stdout = std::io::stdout().lock(); + commands::migrate::run(options, &mut stdout) + } + }, + Command::Seed { count, data_dir } => { + commands::seed::run(context, &commands::seed::SeedOptions { count, data_dir }) + } + Command::Setup { yes, start } => { + commands::setup::run(context, &commands::setup::SetupOptions { yes, start }) + } + Command::Start { + tor, + i2p, + nginx, + debug, + detach, + port, + args, + } => { + let options = commands::start::StartOptions { + tor, + i2p, + nginx, + debug, + detach, + port, + }; + commands::start::run(context, &options, &args) + } + Command::Stop { + tor, + i2p, + nginx, + local, + all, + args, + } => { + let options = commands::stop::StopOptions { + tor, + i2p, + nginx, + local, + all, + }; + commands::stop::run(context, &options, &args) + } + Command::Update { args } => commands::update::run(context, &args), + Command::Tui => crate::tui::run().map(|_| CommandOutput::default()), + } +} + +/// The command line, as the parser reads it. +// `import` and `clean-db` parse their own arguments, so clap's `help` subcommand would render a +// second, contradictory page for them; `--help` is the single help surface. +#[derive(Debug, Parser)] +#[command( + name = "nostream", + about = "Operate a nostream relay", + disable_help_subcommand = true, + disable_version_flag = true +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Clean Docker resources (legacy script replacement). + Clean, + /// Delete events by age or kind, or every event. + #[command(disable_help_flag = true)] + CleanDb { + /// The command's own arguments, parsed by the command (see its help). + #[arg( + value_name = "ARGS", + trailing_var_arg = true, + allow_hyphen_values = true + )] + args: Vec, + }, + /// Inspect and validate the effective settings. + Config { + #[command(subcommand)] + command: ConfigCommand, + }, + /// Export events to a file. + Export { + /// Output path (alias to the positional argument) + #[arg(value_name = "output")] + output: Option, + /// Output path (alias to the positional argument) + #[arg(long = "output", value_name = "output")] + output_option: Option, + /// Enable compression (legacy compatibility) + #[arg(short = 'z', long)] + compress: bool, + /// Export format (jsonl|json|gzip|gz|xz) + #[arg(long, value_name = "format")] + format: Option, + /// The store root (the LMDB environment lives under `/lmdb`). + #[arg(long, value_name = "DIR")] + data_dir: Option, + }, + /// Import events from a .jsonl or .json file. + #[command(disable_help_flag = true)] + Import { + /// The command's own arguments, parsed by the command (see its help). + #[arg( + value_name = "ARGS", + trailing_var_arg = true, + allow_hyphen_values = true + )] + args: Vec, + }, + /// Print the relay's NIP-11 info. + Info { + /// Print the Tor hostname. + #[arg(long)] + tor_hostname: bool, + /// Print the I2P hostnames. + #[arg(long)] + i2p_hostname: bool, + /// Print the payload as JSON. + #[arg(long)] + json: bool, + /// The store root (the LMDB environment lives under `/lmdb`). + #[arg(long, value_name = "DIR")] + data_dir: Option, + }, + /// Mint and manage invite codes. + Invite { + #[command(subcommand)] + command: Option, + }, + /// Copy the Postgres store into an LMDB store. + Migrate { + #[command(subcommand)] + command: MigrateCommand, + }, + /// Seed the database. + Seed { + /// Number of events to seed + #[arg(long, value_name = "count")] + count: Option, + /// The store root (the LMDB environment lives under `/lmdb`). + #[arg(long, value_name = "DIR")] + data_dir: Option, + }, + /// Run the first-time setup flow. + Setup { + /// Non-interactive defaults + #[arg(short = 'y', long)] + yes: bool, + /// Start relay after setup + #[arg(long)] + start: bool, + }, + /// Start the relay stack. + Start { + /// Enable Tor hidden service + #[arg(long)] + tor: bool, + /// Enable I2P hidden service + #[arg(long)] + i2p: bool, + /// Enable nginx reverse proxy + #[arg(long)] + nginx: bool, + /// Enable debug logging + #[arg(long)] + debug: bool, + /// Run in detached mode + #[arg(short = 'd', long)] + detach: bool, + /// Host port for the relay + #[arg(long, value_name = "port")] + port: Option, + /// Additional arguments passed to docker compose + #[arg( + value_name = "ARGS", + trailing_var_arg = true, + allow_hyphen_values = true + )] + args: Vec, + }, + /// Stop the relay stack. + Stop { + /// Stop the Tor overlay + #[arg(long)] + tor: bool, + /// Stop the I2P overlay + #[arg(long)] + i2p: bool, + /// Stop the nginx overlay + #[arg(long)] + nginx: bool, + /// Stop the local overlay + #[arg(long)] + local: bool, + /// Stop every overlay + #[arg(long)] + all: bool, + /// Additional arguments passed to docker compose + #[arg( + value_name = "ARGS", + trailing_var_arg = true, + allow_hyphen_values = true + )] + args: Vec, + }, + /// Update the deployment. + Update { + /// Additional arguments passed to docker compose when the stack restarts + #[arg( + value_name = "ARGS", + trailing_var_arg = true, + allow_hyphen_values = true + )] + args: Vec, + }, + /// Run the interactive settings editor. + Tui, +} + +#[derive(Debug, Subcommand)] +enum InviteCommand { + /// Mint an invite code. + Create { + /// Times the code can be claimed (default: nip43.defaultMaxUses) + #[arg(long, value_name = "uses")] + uses: Option, + /// Code lifetime in seconds (default: nip43.inviteCodeExpirySeconds) + #[arg(long = "expires-in", value_name = "seconds")] + expires_in: Option, + /// Print machine-readable JSON + #[arg(long)] + json: bool, + /// The store root (the LMDB environment lives under `/lmdb`). + #[arg(long, value_name = "DIR")] + data_dir: Option, + }, +} + +#[derive(Debug, Subcommand)] +enum ConfigCommand { + /// Validate the effective settings and print one `path: message` line per issue. + Validate { + /// The configuration directory (overrides NOSTR_CONFIG_DIR). + #[arg(long)] + config_dir: Option, + /// Validate this file instead of the configured settings. + #[arg(long)] + config: Option, + }, + /// Print the effective settings as YAML. + List { + /// The configuration directory (overrides NOSTR_CONFIG_DIR). + #[arg(long)] + config_dir: Option, + /// Print the document as JSON. + #[arg(long)] + json: bool, + }, + /// Print the effective value at a dot-path. + #[command(override_usage = "nostream config get ")] + Get { + /// The dot-path to read (for example `info.relay_url`). + path: String, + /// The configuration directory (overrides NOSTR_CONFIG_DIR). + #[arg(long)] + config_dir: Option, + /// Print the value as JSON. + #[arg(long)] + json: bool, + }, + /// Set a value at a dot-path and save the settings. + Set { + /// The dot-path to write (for example `info.relay_url`). + path: String, + /// The value, parsed as the type says. + value: String, + /// The configuration directory (overrides NOSTR_CONFIG_DIR). + #[arg(long)] + config_dir: Option, + /// How to parse the value: `inferred` or `json`. + #[arg(long = "type", value_name = "type")] + value_type: Option, + /// Validate the merged settings before writing (the default). + // The capture declares both spellings and reads them as one boolean + // (`src/cli/index.ts:339-340,412`): `--validate` is the default named, not a second mode, + // and the last flag wins through `overrides_with`. Kept out of the doc comment because + // clap renders it under `--help`, and a per-command page carries the capture's spellings + // and one-line descriptions, not the sources behind them (ADR 0015 D1). + #[arg(long, overrides_with = "no_validate")] + validate: bool, + /// Write the value without validating the merged settings. + #[arg(long, overrides_with = "validate")] + no_validate: bool, + /// Restart the relay stack after the write. + #[arg(long)] + restart: bool, + }, + /// Read and write `.env`. + #[command( + override_usage = "nostream config env [args] [--show-secrets]" + )] + Env { + #[command(subcommand)] + command: ConfigEnvCommand, + }, +} + +#[derive(Debug, Subcommand)] +enum ConfigEnvCommand { + /// List the `.env` entries, secrets masked. + List { + /// Print secret values unmasked. + #[arg(long)] + show_secrets: bool, + }, + /// Print one `.env` value. + Get { + /// The key to read. + key: String, + /// Print a secret value unmasked. + #[arg(long)] + show_secrets: bool, + }, + /// Set one `.env` value. + Set { + /// The key to write. + key: String, + /// The value to write. + value: String, + }, + /// Validate the `.env` entries. + Validate, +} + +#[derive(Debug, Subcommand)] +enum MigrateCommand { + /// Copy every table from Postgres into an LMDB store, with the relay stopped. + /// + /// The source is Postgres from `DB_URI`, else the `DB_*` parts. The target is a store root: + /// the environment is `/lmdb` and the manifest `/migration-manifest.json`. + /// + /// The first connection to the source is bounded at ten seconds whatever + /// `DB_ACQUIRE_CONNECTION_TIMEOUT` says: a mistyped host is reported at once with the + /// driver's reason, not after the pool's minute. + /// + /// A re-run resumes where the manifest says the last one stopped. Deleting + /// `/migration-manifest.json` does not restart a half-filled store: a store that holds + /// rows and no manifest is refused, so starting over takes a fresh `--target`, or the + /// manifest and the store removed together. Nothing may write to either store while a run + /// is in progress, so the relay must be stopped on both before the first batch is read. + PgToLmdb { + /// The store root (the environment lives under `/lmdb`). + #[arg(long, value_name = "DIR")] + target: PathBuf, + /// Rows per batch, and the page size verify reads with. + #[arg( + long, + value_name = "N", + default_value_t = 1_000, + value_parser = clap::builder::RangedU64ValueParser::::new().range(1..) + )] + batch_size: usize, + /// Verify the store against its manifest and copy nothing. + #[arg(long)] + verify: bool, + }, +} + +/// The `--json` failure envelope: `{"error":{"message":…,"code":N}}` (`src/cli/index.ts:129-131`). +/// +/// It is a struct rather than a `serde_json::Value` because a map's key order is not the +/// contract's: the capture writes `message` first, and only a struct's declaration order is +/// guaranteed to keep it there. +#[derive(serde::Serialize)] +struct ErrorEnvelope<'a> { + error: ErrorBody<'a>, +} + +#[derive(serde::Serialize)] +struct ErrorBody<'a> { + message: &'a str, + code: u8, +} + +/// Writes one command's `Result` — the single place that picks a stream and an exit code. +/// +/// The three failure shapes are the capture's (R3, V63): a failure thrown out of a command is +/// prefixed `Error: ` and exits 2 (`Usage`) or 1 (`Command`); a failure the command reports +/// itself is written bare, line by line, with the code it chose (`Config`, `Reported`); and a +/// `--json` failure is the envelope. `Import` and `Migrate` keep the prefixes they shipped. +/// +/// The fourth is composed here rather than classed: `ReportedAfter` writes the lines the command +/// already earned to stdout, then hands the inner failure to `failure_lines`, which is the only +/// place a class becomes a stream and a code (ADR 0015 D3). +pub fn render(result: Result) -> ExitCode { + match result { + Ok(output) => match print_lines(&output.lines) { + Ok(()) => output.exit_code(), + // A closed reader — `nostream config list | head -1` — ends the output and leaves the + // command's own code alone: `println!` panics on a broken pipe, and exit 101 is + // outside the surface's 0/1/2 vocabulary (V1). + Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => output.exit_code(), + Err(error) => { + let _ = print_error_lines(&[format!("Error: unable to write output: {error}")]); + ExitCode::from(1) + } + }, + Err(error) => { + let (code, lines) = match failure_lines(error) { + Failure::ReportedFirst { + output, + lines, + code, + } => { + // The data was earned before the failure happened, so it keeps the stream a + // successful run writes it to; only the failure goes to stderr. + let _ = print_lines(&output); + (code, lines) + } + Failure::Lines { lines, code } => (code, lines), + }; + // A write failure on the stream a failure goes to is not a panic and does not + // re-code the answer: there is nowhere left to report it, so the command's code + // stands. `eprintln!` here panicked at 101 on a full disk, which is the defect. + let _ = print_error_lines(&lines); + ExitCode::from(code) + } + } +} + +/// One failure, as the lines it renders to and the code it answers. +enum Failure { + /// The capture's three shapes and the two the binary shipped (`Import`, `Migrate`) — every + /// line goes to stderr. + Lines { lines: Vec, code: u8 }, + /// [`CliError::ReportedAfter`]: data the command earned on stdout first, then the failure. + ReportedFirst { + output: Vec, + lines: Vec, + code: u8, + }, +} + +/// Renders one failure: the single place a class becomes a stream's bytes and a code. +fn failure_lines(error: CliError) -> Failure { + let (lines, code) = match error { + CliError::Usage(message) => (vec![format!("Error: {message}")], 2), + CliError::Command(message) => (vec![format!("Error: {message}")], 1), + CliError::Config(line) => (vec![line], 1), + CliError::Reported { lines, exit_code } => (lines, exit_code), + CliError::ReportedAfter { output, failure } => { + return match failure_lines(*failure) { + Failure::Lines { lines, code } => Failure::ReportedFirst { + output, + lines, + code, + }, + // A wrapper inside a wrapper: the earned lines keep the order the commands + // wrote them in, outer first. + Failure::ReportedFirst { + output: inner_output, + lines, + code, + } => { + let mut all = output; + all.extend(inner_output); + Failure::ReportedFirst { + output: all, + lines, + code, + } + } + }; + } + CliError::Json { message, code } => { + let envelope = ErrorEnvelope { + error: ErrorBody { + message: &message, + code, + }, + }; + let rendered = serde_json::to_string(&envelope).unwrap_or_else(|_| { + format!("{{\"error\":{{\"message\":\"error\",\"code\":{code}}}}}") + }); + (vec![rendered], code) + } + CliError::NotImplemented { module } => ( + vec![format!("not implemented in Phase 1 (job 005): {module}")], + 1, + ), + CliError::Import(message) => (vec![format!("Import failed: {message}")], 1), + CliError::Migrate(message) => (vec![format!("Migration failed: {message}")], 1), + }; + + Failure::Lines { lines, code } +} + +/// Prints lines on stdout, one per line. +fn print_lines(lines: &[String]) -> std::io::Result<()> { + let mut stdout = std::io::stdout().lock(); + + for line in lines { + writeln!(stdout, "{line}")?; + } + + Ok(()) +} + +/// Prints lines on stderr, one per line, answering the write's result for the same reason +/// [`print_lines`] does: a full disk is the write's failure, not a panic. +/// +/// `pub(crate)` because a command's own advisory line writes through it too: `clean-db`'s +/// `NODE_ENV=production` warning is written before its delete, so an `eprintln!` there turned a +/// full disk into exit 101 on the run that had not started yet. +pub(crate) fn print_error_lines(lines: &[String]) -> std::io::Result<()> { + let mut stderr = std::io::stderr().lock(); + + for line in lines { + writeln!(stderr, "{line}")?; + } + + Ok(()) +} diff --git a/crates/nostream-cli/src/bootstrap.rs b/crates/nostream-cli/src/bootstrap.rs new file mode 100644 index 000000000..28c5c9d32 --- /dev/null +++ b/crates/nostream-cli/src/bootstrap.rs @@ -0,0 +1,128 @@ +//! The bootstrap steps `start` and `setup` run before anything else: the config directory and +//! its settings file, the Tor and I2P data directories, and the two paths those data live at. +//! +//! Mirrors `src/cli/utils/bootstrap.ts` and the capture's `getProjectPath`, which resolves +//! against the **working directory** — so `nginx/`, `.nostr/` and `.env.example` are the ones +//! under the directory the operator ran the binary from, not under the binary. + +use std::path::{Path, PathBuf}; + +use crate::config::resolve_paths; +use crate::env_file::Environment; +use crate::error::CliError; + +/// The working directory's path to `parts` (`getProjectPath`). +pub fn project_path(cwd: &Path, parts: &[&str]) -> PathBuf { + let mut path = cwd.to_path_buf(); + for part in parts { + path.push(part); + } + path +} + +/// `ensureNotRoot`: refuses to run as uid 0, because a compose stack started as root owns files +/// the operator cannot then change afterwards. +/// +/// The uid is read the way every other probe reads its subject — a child through +/// `nostream_services::process`, because this crate opens no processes of its own +/// (`CLAUDE.md:116`). A host without `id` cannot answer, and the check then declines to refuse: +/// the capture's own guard is `typeof process.geteuid === 'function'`, which is exactly a check +/// that stays silent where the platform cannot speak. +pub async fn ensure_not_root() -> Result<(), CliError> { + let argv = ["id".to_owned(), "-u".to_owned()]; + match nostream_services::process::capture(&argv, None).await { + nostream_services::process::CapturedResult::Exited { + code: 0, stdout, .. + } if stdout.trim() == "0" => Err(CliError::command("Nostream should not be run as root.")), + _ => Ok(()), + } +} + +/// `ensureConfigBootstrap`: the config directory, and `settings.yaml` copied from the defaults +/// when neither it nor the deprecated `settings.json` is there. +/// +/// The legacy check is not the capture's: `src/cli/utils/bootstrap.ts` tests only +/// `settings.yaml`, so `start` copies the defaults over a deployment that still keeps its +/// overrides in `settings.json` — and because the loader prefers `settings.yaml` +/// (`nostream_config::load_user_settings`), every override in the legacy file is silently +/// replaced by a default on the next start. Testing both files keeps that deployment effective +/// and leaves the migration of `settings.json` to `settings.yaml` to the operator. +pub fn ensure_config_bootstrap(cwd: &Path, env: &Environment) -> Result<(), CliError> { + let paths = resolve_paths(cwd, None, env); + + std::fs::create_dir_all(&paths.config_base_dir).map_err(|error| { + CliError::command(format!( + "unable to create {}: {error}", + paths.config_base_dir.display() + )) + })?; + + if !paths.settings_file.exists() && !paths.legacy_settings_file.exists() { + if !paths.default_settings_file.exists() { + return Err(CliError::command(format!( + "the default settings file is missing: {}", + paths.default_settings_file.display() + ))); + } + std::fs::copy(&paths.default_settings_file, &paths.settings_file).map_err(|error| { + CliError::command(format!( + "unable to write {}: {error}", + paths.settings_file.display() + )) + })?; + } + + Ok(()) +} + +/// The Tor data directory a `--tor` run needs. +pub fn ensure_tor_data_dir(cwd: &Path) -> Result<(), CliError> { + let path = project_path(cwd, &[".nostr", "tor", "data"]); + std::fs::create_dir_all(&path) + .map_err(|error| CliError::command(format!("unable to create {}: {error}", path.display()))) +} + +/// The I2P data directory an `--i2p` run needs. +pub fn ensure_i2p_data_dir(cwd: &Path) -> Result<(), CliError> { + let path = project_path(cwd, &[".nostr", "i2p", "data"]); + std::fs::create_dir_all(&path) + .map_err(|error| CliError::command(format!("unable to create {}: {error}", path.display()))) +} + +/// The file the Tor hidden service publishes its `.onion` name in (`getTorHostnamePath`). +pub fn tor_hostname_path(cwd: &Path) -> PathBuf { + project_path(cwd, &[".nostr", "tor", "data", "nostream", "hostname"]) +} + +/// The i2pd destination keys file (`info.ts:180`). +pub fn i2p_keys_path(cwd: &Path) -> PathBuf { + project_path(cwd, &[".nostr", "i2p", "data", "nostream.dat"]) +} + +/// The directory the settings live in, as the process environment names it +/// (`NOSTR_CONFIG_DIR`, else `/.nostr`). +pub fn config_dir(cwd: &Path, env: &crate::env_file::Environment) -> PathBuf { + match env.get("NOSTR_CONFIG_DIR") { + Some(dir) => PathBuf::from(dir), + None => cwd.join(".nostr"), + } +} + +/// `getOnionKeyPath`: `/v3_onion_private_key`, else `/.nostr/…`. +pub fn onion_key_path(cwd: &Path, env: &crate::env_file::Environment) -> PathBuf { + match env.get("NOSTR_CONFIG_DIR") { + Some(dir) => PathBuf::from(dir).join("v3_onion_private_key"), + None => home_dir() + .unwrap_or_else(|| cwd.to_path_buf()) + .join(".nostr") + .join("v3_onion_private_key"), + } +} + +/// `os.homedir()`: `$HOME` on Unix, `$USERPROFILE` on Windows. +pub fn home_dir() -> Option { + std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) +} diff --git a/crates/nostream-cli/src/commands/clean.rs b/crates/nostream-cli/src/commands/clean.rs new file mode 100644 index 000000000..015821f5e --- /dev/null +++ b/crates/nostream-cli/src/commands/clean.rs @@ -0,0 +1,47 @@ +//! `dev.ts`'s `docker:clean`, as the top-level `clean` the capture already had +//! (`src/cli/index.ts:184-188`): stop every overlay, then prune the two docker families. +//! +//! The confirmation the capture's `dev docker:clean` asks is already answered here +//! (`runDevDockerClean({ yes: true })`, V14), which is why this command has no `--yes`. +//! Each step answers the child's code, and a step that fails ends the run with it. + +use crate::app::Context; +use crate::commands::stop::StopOptions; +use crate::config::CommandOutput; +use crate::error::CliError; + +/// Runs `clean` on a runtime the command owns. +pub fn run(context: &Context) -> Result { + context.block_on(clean(context)) +} + +/// `runDevDockerClean` with the confirmation already answered. +pub(crate) async fn clean(context: &Context) -> Result { + let stopped = crate::commands::stop::stop(context, &StopOptions::every_overlay(), &[]).await?; + + if stopped.exit_code != 0 { + return Ok(CommandOutput::with_code(Vec::new(), stopped.exit_code)); + } + + let pruned = docker(&["system", "prune", "-a", "-f"]).await?; + + if pruned != 0 { + return Ok(CommandOutput::with_code(Vec::new(), pruned)); + } + + let pruned = docker(&["volume", "prune", "-f"]).await?; + + Ok(CommandOutput::with_code(Vec::new(), pruned)) +} + +/// One `docker ` run, inheriting the terminal, answering the child's code. +async fn docker(arguments: &[&str]) -> Result { + let mut argv = vec!["docker".to_owned()]; + argv.extend(arguments.iter().map(|argument| (*argument).to_owned())); + + let code = nostream_services::process::run(&argv, &[]) + .await + .map_err(|failure| CliError::command(failure.to_string()))?; + + Ok(u8::try_from(code).unwrap_or(1)) +} diff --git a/crates/nostream-cli/src/commands/clean_db.rs b/crates/nostream-cli/src/commands/clean_db.rs new file mode 100644 index 000000000..71f47351e --- /dev/null +++ b/crates/nostream-cli/src/commands/clean_db.rs @@ -0,0 +1,502 @@ +//! `clean-db.ts`: the delete-list clean-up, as its own top-level command. +//! +//! The capture's parser is hand-written and its messages are the contract +//! (`src/clean-db.ts:97-159`), so this module parses the same way, prints the capture's +//! `HELP_TEXT` for `--help`, and selects rows with [`EventCleanCriteria`] — the same predicate +//! for the count and the delete (C2, V49). +//! +//! The capture's own entry point catches the parser's and the database's failures and prints +//! them with `console.error` (`src/clean-db.ts:270-277`), so those are reported **bare**, with +//! exit 1 (V63 class B). The store the command opens is the port's own seam, and its refusal is +//! C3's class A — `Error: `, exit 1 — the same shape `export`, `seed` and `invite` +//! give it. The `NODE_ENV=production` warning is written straight to stderr before the run, as +//! the capture's `console.warn` is, and leaves the exit code alone. + +use std::io::IsTerminal; +use std::path::PathBuf; + +use chrono::Utc; +use nostream_core::Kind; +use nostream_storage::repositories::EventCleanCriteria; + +use crate::app::Context; +use crate::config::CommandOutput; +use crate::error::CliError; +use crate::store; + +/// The capture's `HELP_TEXT` (`src/clean-db.ts:15-31`), with `nostream dev db:clean` replaced by +/// `nostream clean-db` on the five lines that name it (V53). +pub fn help_lines() -> Vec { + [ + "Usage: nostream clean-db [options]", + "", + "Options:", + " --all Delete all events.", + " --older-than= Delete events older than the given number of days.", + " --kinds=<1,7,4> Delete events for specific kinds.", + " --dry-run Show how many rows would be deleted without deleting them.", + " --force Skip interactive confirmation prompt.", + " --help Show this help message.", + "", + "Examples:", + " nostream clean-db --all --dry-run", + " nostream clean-db --all --force", + " nostream clean-db --older-than=30 --force", + " nostream clean-db --older-than=30 --kinds=1,7,4 --dry-run", + ] + .map(str::to_owned) + .to_vec() +} + +/// The parsed `clean-db` arguments (`CleanDbOptions`, `src/clean-db.ts:9-16`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CleanDbOptions { + pub all: bool, + pub dry_run: bool, + pub force: bool, + pub help: bool, + pub kinds: Vec, + pub older_than_days: Option, + /// The store root, which the capture's `--older-than`/`--kinds` paths did not need because + /// they always spoke to Postgres (R21). + pub data_dir: Option, +} + +/// `parseCleanDbOptions`, case for case. +/// +/// `--data-dir` is the one option the capture does not have: the port reads the settings' own +/// store, and the LMDB root has to be named (R21). +pub fn parse_args(args: &[String]) -> Result { + let mut options = CleanDbOptions::default(); + let mut index = 0; + + while index < args.len() { + let argument = &args[index]; + + match argument.as_str() { + "--all" => { + options.all = true; + index += 1; + } + "--dry-run" => { + options.dry_run = true; + index += 1; + } + "--force" => { + options.force = true; + index += 1; + } + "--help" | "-h" => { + options.help = true; + index += 1; + } + other if matches_option(other, "--older-than") => { + let (value, next) = option_value(other, args, index)?; + options.older_than_days = Some(parse_older_than_days(&value)?); + index = next + 1; + } + other if matches_option(other, "--kinds") => { + let (value, next) = option_value(other, args, index)?; + options.kinds = parse_kinds(&value)?; + index = next + 1; + } + other if matches_option(other, "--data-dir") => { + let (value, next) = option_value(other, args, index)?; + options.data_dir = Some(PathBuf::from(value)); + index = next + 1; + } + other => { + return Err(CliError::reported_line(format!("Unknown option: {other}"))); + } + } + } + + if options.help { + return Ok(options); + } + + if !options.all && options.older_than_days.is_none() && options.kinds.is_empty() { + return Err(CliError::reported_line( + "Select a target with --all, --older-than, or --kinds", + )); + } + + if options.all && (options.older_than_days.is_some() || !options.kinds.is_empty()) { + return Err(CliError::reported_line( + "--all cannot be combined with --older-than or --kinds", + )); + } + + Ok(options) +} + +/// `arg === option || arg.startsWith(\`${option}=\`)` (`src/clean-db.ts:93-95`): an option that +/// merely shares a prefix is not this option. +fn matches_option(argument: &str, option: &str) -> bool { + argument == option + || argument + .strip_prefix(option) + .is_some_and(|rest| rest.starts_with('=')) +} + +/// `getOptionValue`: an inline `=value` or the next argument, and `Missing value for