From 06acd510ce7afb6b20b56bf62a970f3458c13f53 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:12:26 -0500 Subject: [PATCH 01/78] feat(storage): add the clean-db scan and delete seam (#1184) --- Cargo.lock | 1 + crates/nostream-admin/tests/common/mod.rs | 29 + crates/nostream-mcp/tests/common/mod.rs | 26 + crates/nostream-relay/src/testing.rs | 90 ++- crates/nostream-relay/src/unavailable.rs | 35 +- crates/nostream-services/src/testing.rs | 90 ++- crates/nostream-services/src/unavailable.rs | 26 + crates/nostream-storage/Cargo.toml | 1 + crates/nostream-storage/src/lmdb/events.rs | 182 ++++- crates/nostream-storage/src/lmdb/mod.rs | 51 +- .../nostream-storage/src/postgres/events.rs | 166 ++++- .../src/postgres/repository.rs | 37 +- crates/nostream-storage/src/repositories.rs | 78 +++ crates/nostream-storage/tests/clean_up.rs | 639 ++++++++++++++++++ crates/nostream-storage/tests/storage.rs | 36 +- 15 files changed, 1455 insertions(+), 32 deletions(-) create mode 100644 crates/nostream-storage/tests/clean_up.rs diff --git a/Cargo.lock b/Cargo.lock index a084c7ccd..ec3c4274c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1539,6 +1539,7 @@ dependencies = [ "chrono", "clap", "futures-core", + "futures-util", "heed", "nostream-config", "nostream-core", 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-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 82fbd0fc2..ba6c0dda7 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -601,4 +601,30 @@ impl EventRepository for VanishingRepository { ) -> StorageFuture<'a, nostream_storage::repositories::EventPurgeCounts> { self.inner.delete_expired_and_retained(options) } + + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, nostream_storage::repositories::EventRecord>> { + self.inner.scan_live(after, limit) + } + + fn count_by_criteria<'a>( + &'a self, + criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + self.inner.count_by_criteria(criteria) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + self.inner.delete_by_criteria(criteria) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + self.inner.delete_all_events() + } } diff --git a/crates/nostream-relay/src/testing.rs b/crates/nostream-relay/src/testing.rs index 7fd5074e3..0d28cd3a7 100644 --- a/crates/nostream-relay/src/testing.rs +++ b/crates/nostream-relay/src/testing.rs @@ -27,10 +27,10 @@ use nostream_storage::MAX_PAGE_ROWS; use nostream_storage::StorageError; use nostream_storage::repositories::{ ActionableTarget, CreateInviteCodeOptions, DvmJob, DvmJobStatus, EmptyTagRule, - EventPurgeCounts, EventRecord, EventRepository, EventRetentionOptions, FieldUpdate, InviteCode, - InviteCodeRepository, NewReport, Nip05Verification, Nip05VerificationRepository, QueryStream, - ReconciliationItem, Report, ReportRepository, SearchRule, StorageFuture, StreamedEvent, User, - UserPatch, UserRepository, + EventCleanCriteria, EventPurgeCounts, EventRecord, EventRepository, EventRetentionOptions, + FieldUpdate, InviteCode, InviteCodeRepository, NewReport, Nip05Verification, + Nip05VerificationRepository, QueryStream, ReconciliationItem, Report, ReportRepository, + ScanCursor, SearchRule, StorageFuture, StreamedEvent, User, UserPatch, UserRepository, }; use tokio::sync::Notify; @@ -392,6 +392,19 @@ impl InMemoryEventRepository { } } +/// Whether one row is in a clean-up predicate's selection: `created_at < before` when set, and a +/// kind in `kinds` when set. A soft-deleted row is selected, because the capture's `DELETE` is +/// unfiltered on `deleted_at`. +fn selects(record: &EventRecord, criteria: &EventCleanCriteria) -> bool { + criteria + .before + .is_none_or(|before| record.event.created_at < before) + && criteria + .kinds + .as_ref() + .is_none_or(|kinds| kinds.contains(&record.event.kind)) +} + /// The filter a tag index built from non-empty values answers: the empty criteria removed from /// every generic tag family, or `None` when a family is left with no criterion — the one shape /// that selects nothing. @@ -821,6 +834,75 @@ impl EventRepository for InMemoryEventRepository { ) -> StorageFuture<'a, EventPurgeCounts> { Box::pin(async move { Ok(EventPurgeCounts::default()) }) } + + /// The double's live rows, oldest first: `deleted_at` hides a row and so does an + /// `expires_at` that has passed, which is the predicate both shipped backends answer with. + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + Box::pin(async move { + let now = chrono::Utc::now().timestamp(); + let mut live: Vec = self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| { + record.deleted_at.is_none() + && record.expires_at.is_none_or(|expires_at| expires_at > now) + && after.is_none_or(|cursor| { + (record.event.created_at, record.event.id) + > (cursor.created_at, cursor.event_id) + }) + }) + .cloned() + .collect(); + live.sort_by_key(|record| (record.event.created_at, record.event.id)); + live.truncate(usize::try_from(limit.min(MAX_PAGE_ROWS)).unwrap_or(0)); + + let items: Vec> = live.into_iter().map(Ok).collect(); + Ok(Box::pin(stream::iter(items)) as QueryStream<'a, EventRecord>) + }) + } + + fn count_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) -> StorageFuture<'a, u64> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| selects(record, criteria)) + .count() as u64) + }) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + let mut records = self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let before = records.len(); + records.retain(|record| !selects(record, criteria)); + Ok((before - records.len()) as u64) + }) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + Box::pin(async move { + self.records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clear(); + Ok(()) + }) + } } /// A user repository holding its rows in memory. diff --git a/crates/nostream-relay/src/unavailable.rs b/crates/nostream-relay/src/unavailable.rs index 0c434d471..a1c09a761 100644 --- a/crates/nostream-relay/src/unavailable.rs +++ b/crates/nostream-relay/src/unavailable.rs @@ -11,10 +11,11 @@ use nostream_core::{EventId, Filter, Kind, Pubkey}; use nostream_storage::StorageError; use nostream_storage::repositories::{ - ActionableTarget, CreateInviteCodeOptions, DvmJob, DvmJobUpdate, EventPurgeCounts, EventRecord, - EventRepository, EventRetentionOptions, InviteCode, InviteCodeRepository, Nip05Verification, - Nip05VerificationRepository, QueryStream, ReconciliationItem, Report, ReportRepository, - StorageFuture, StreamedEvent, User, UserPatch, UserRepository, + ActionableTarget, CreateInviteCodeOptions, DvmJob, DvmJobUpdate, EventCleanCriteria, + EventPurgeCounts, EventRecord, EventRepository, EventRetentionOptions, InviteCode, + InviteCodeRepository, Nip05Verification, Nip05VerificationRepository, QueryStream, + ReconciliationItem, Report, ReportRepository, ScanCursor, StorageFuture, StreamedEvent, User, + UserPatch, UserRepository, }; use crate::handlers::Stores; @@ -140,6 +141,32 @@ impl EventRepository for UnavailableEventRepository { ) -> StorageFuture<'a, EventPurgeCounts> { Box::pin(async { Err(unavailable()) }) } + + fn scan_live<'a>( + &'a self, + _after: Option, + _limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + Box::pin(async { Err(unavailable()) }) + } + + fn count_by_criteria<'a>( + &'a self, + _criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async { Err(unavailable()) }) + } + + fn delete_by_criteria<'a>( + &'a self, + _criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async { Err(unavailable()) }) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + Box::pin(async { Err(unavailable()) }) + } } /// The user store. diff --git a/crates/nostream-services/src/testing.rs b/crates/nostream-services/src/testing.rs index b6f5902ed..c59842ef9 100644 --- a/crates/nostream-services/src/testing.rs +++ b/crates/nostream-services/src/testing.rs @@ -21,13 +21,14 @@ use nostream_config::settings::Settings; use nostream_core::clock::Clock; use nostream_core::nip05::{FetchOutcome, Nip05Fetch}; use nostream_core::{Event, EventId, Filter, Kind, Pubkey, Secret}; +use nostream_storage::StorageError; use nostream_storage::repositories::{ DeliveryLogEntry, DeliveryLogFilters, DvmJob, DvmJobRepository, DvmJobStatus, DvmJobUpdate, - EventPurgeCounts, EventRecord, EventRepository, EventRetentionOptions, FieldUpdate, Invoice, - InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, Nip05Verification, + EventCleanCriteria, EventPurgeCounts, EventRecord, EventRepository, EventRetentionOptions, + FieldUpdate, Invoice, InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, Nip05Verification, Nip05VerificationRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, - OutboxMessage, OutboxPayload, QueryStream, ReconciliationItem, StorageFuture, StreamedEvent, - User, UserPatch, UserRepository, + OutboxMessage, OutboxPayload, QueryStream, ReconciliationItem, ScanCursor, StorageFuture, + StreamedEvent, User, UserPatch, UserRepository, }; use crate::error::ServicesError; @@ -432,6 +433,18 @@ impl InMemoryEventRepository { } } +/// Whether one row is in a clean-up predicate's selection: `created_at < before` when set, and a +/// kind in `kinds` when set. A soft-deleted row is selected, as the capture's `DELETE` is. +fn selects(record: &EventRecord, criteria: &EventCleanCriteria) -> bool { + criteria + .before + .is_none_or(|before| record.event.created_at < before) + && criteria + .kinds + .as_ref() + .is_none_or(|kinds| kinds.contains(&record.event.kind)) +} + fn matches_filter(record: &EventRecord, filter: &Filter) -> bool { if let Some(ids) = &filter.ids && !ids.iter().any(|id| *id == record.event.id.to_string()) @@ -632,6 +645,75 @@ impl EventRepository for InMemoryEventRepository { Ok(EventPurgeCounts::default()) }) } + + /// The double's live rows, oldest first: a soft-deleted or expired row is hidden, as both + /// shipped backends hide it. + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + Box::pin(async move { + let now = chrono::Utc::now().timestamp(); + let mut live: Vec = self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| { + record.deleted_at.is_none() + && record.expires_at.is_none_or(|expires_at| expires_at > now) + && after.is_none_or(|cursor| { + (record.event.created_at, record.event.id) + > (cursor.created_at, cursor.event_id) + }) + }) + .cloned() + .collect(); + live.sort_by_key(|record| (record.event.created_at, record.event.id)); + live.truncate(usize::try_from(limit.min(nostream_storage::MAX_PAGE_ROWS)).unwrap_or(0)); + + let items: Vec> = live.into_iter().map(Ok).collect(); + Ok(Box::pin(futures_util::stream::iter(items)) as QueryStream<'a, EventRecord>) + }) + } + + fn count_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) -> StorageFuture<'a, u64> { + Box::pin(async move { + Ok(self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .iter() + .filter(|record| selects(record, criteria)) + .count() as u64) + }) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + let mut records = self + .records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let before = records.len(); + records.retain(|record| !selects(record, criteria)); + Ok((before - records.len()) as u64) + }) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + Box::pin(async move { + self.records + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clear(); + Ok(()) + }) + } } /// An invoice repository holding its rows in memory. diff --git a/crates/nostream-services/src/unavailable.rs b/crates/nostream-services/src/unavailable.rs index 36b13c700..138cedf13 100644 --- a/crates/nostream-services/src/unavailable.rs +++ b/crates/nostream-services/src/unavailable.rs @@ -130,6 +130,32 @@ impl EventRepository for UnavailableEventRepository { ) -> StoreFuture<'a, nostream_storage::repositories::EventPurgeCounts> { Box::pin(async { Err(unavailable()) }) } + + fn scan_live<'a>( + &'a self, + _after: Option, + _limit: u64, + ) -> StoreFuture<'a, QueryStream<'a, nostream_storage::repositories::EventRecord>> { + Box::pin(async { Err(unavailable()) }) + } + + fn count_by_criteria<'a>( + &'a self, + _criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StoreFuture<'a, u64> { + Box::pin(async { Err(unavailable()) }) + } + + fn delete_by_criteria<'a>( + &'a self, + _criteria: &'a nostream_storage::repositories::EventCleanCriteria, + ) -> StoreFuture<'a, u64> { + Box::pin(async { Err(unavailable()) }) + } + + fn delete_all_events(&self) -> StoreFuture<'_, ()> { + Box::pin(async { Err(unavailable()) }) + } } /// The user store. diff --git a/crates/nostream-storage/Cargo.toml b/crates/nostream-storage/Cargo.toml index 7a1fdbaff..8099ae36f 100644 --- a/crates/nostream-storage/Cargo.toml +++ b/crates/nostream-storage/Cargo.toml @@ -20,6 +20,7 @@ lmdb = ["dep:heed", "dep:uuid", "dep:tracing"] [dependencies] chrono.workspace = true futures-core.workspace = true +futures-util.workspace = true heed = { workspace = true, optional = true } nostream-config.workspace = true nostream-core.workspace = true diff --git a/crates/nostream-storage/src/lmdb/events.rs b/crates/nostream-storage/src/lmdb/events.rs index df188365e..4e3e8c696 100644 --- a/crates/nostream-storage/src/lmdb/events.rs +++ b/crates/nostream-storage/src/lmdb/events.rs @@ -30,7 +30,8 @@ use crate::DEFAULT_PAGE_ROWS; use crate::error::StorageError; use crate::records::{distinct_replacements, replaces_fields}; use crate::repositories::{ - EventPurgeCounts, EventRecord, EventRetentionOptions, ReconciliationItem, StreamedEvent, + EventCleanCriteria, EventPurgeCounts, EventRecord, EventRetentionOptions, ReconciliationItem, + ScanCursor, StreamedEvent, }; /// The kind of the capture's `REQUEST_TO_VANISH`, which every retention whitelist keeps and @@ -695,6 +696,185 @@ fn kind_of(record: &EventRecord) -> Result { }) } +// --------------------------------------------------------------------------------------- +// Clean-up paths: the full scan and the delete-by-predicate `clean-db` runs on. +// --------------------------------------------------------------------------------------- + +/// Rows one `delete_by_criteria` batch holds before it deletes and resumes, so the run's memory +/// is a batch rather than a whole store's id list. +const CLEAN_BATCH_ROWS: usize = 1_000; + +/// The live rows after `after`, oldest first, at most `min(limit, MAX_PAGE_ROWS)` of them. +/// +/// Every key in `events_by_created_at` is `created_at ‖ event_id`, so the range's own order is +/// the contract's order and the cursor is a key. A key whose row is gone, soft-deleted or +/// expired is skipped **without** spending a page slot: the caller reads a short page as the +/// end of the store, and a vanished or hidden row between two live ones must not say that. +pub(crate) fn scan_live( + txn: &RoTxn<'_>, + databases: &Databases, + after: Option, + limit: u64, + now: i64, +) -> Result, StorageError> { + let limit = usize::try_from(limit.min(crate::MAX_PAGE_ROWS)).unwrap_or(0); + let mut records = Vec::new(); + let start = after.map(|cursor| encoding::created_at_key(cursor.created_at, &cursor.event_id)); + let bounds = encoding::resume_bounds(start.as_deref(), &[], &[]); + + for entry in databases.events_by_created_at.range(txn, &bounds)? { + if records.len() >= limit { + break; + } + let (key, _) = entry?; + let id = header_id(key, 8, "events_by_created_at")?; + let Some(value) = databases.events.get(txn, id.as_bytes())? else { + continue; + }; + let header = rows::event_header(value)?; + if header.deleted + || header + .expires_at + .is_some_and(|expires_at| expires_at <= now) + { + continue; + } + records.push(rows::decode_event(value)?); + } + + Ok(records) +} + +/// Whether one row's kind is in the criteria's kind list, which is a whitelist when set and an +/// empty selection when set to no kinds at all (`whereIn` over an empty list). +fn selected_kind(kind: i32, criteria: &EventCleanCriteria) -> bool { + match &criteria.kinds { + None => true, + Some(kinds) => kinds + .iter() + .any(|candidate| i32::try_from(candidate.0).unwrap_or(i32::MAX) == kind), + } +} + +/// The range one criteria walks: every key, or every key whose `created_at` is below `before`. +/// +/// The upper bound is exclusive at the eight-byte `created_at` prefix: a forty-byte key that +/// starts with the same prefix sorts after it, so every row at exactly `before` is left out. +fn criteria_upper(criteria: &EventCleanCriteria) -> Option<[u8; 8]> { + criteria.before.map(encoding::i64_key) +} + +/// `count_by_criteria`: the rows the delete would remove, soft-deleted rows included. +pub(crate) fn count_by_criteria( + txn: &RoTxn<'_>, + databases: &Databases, + criteria: &EventCleanCriteria, +) -> Result { + let upper = criteria_upper(criteria); + let bounds = ( + Bound::Unbounded, + upper + .as_ref() + .map_or(Bound::Unbounded, |key| Bound::Excluded(&key[..])), + ); + + let mut count = 0u64; + for entry in databases.events_by_created_at.range(txn, &bounds)? { + let (key, _) = entry?; + key_evaluated(); + let id = header_id(key, 8, "events_by_created_at")?; + let Some(value) = databases.events.get(txn, id.as_bytes())? else { + continue; + }; + let header = rows::event_header(value)?; + if selected_kind(header.kind, criteria) { + count += 1; + } + } + + Ok(count) +} + +/// `delete_by_criteria`: the hard delete of every row the predicate selects, one batch at a +/// time so the id list of a whole store is never resident. +/// +/// A batch's keys are collected and its range iterator dropped before anything is deleted: an +/// iterator over a database the same transaction is removing from is not a shape heed offers. +pub(crate) fn delete_by_criteria( + txn: &mut RwTxn<'_>, + databases: &Databases, + criteria: &EventCleanCriteria, +) -> Result { + let upper = criteria_upper(criteria); + let mut deleted = 0u64; + let mut after: Option> = None; + + loop { + let mut batch: Vec = Vec::new(); + let mut examined_to: Option> = None; + { + let bounds = ( + after.as_deref().map_or(Bound::Unbounded, Bound::Excluded), + upper + .as_ref() + .map_or(Bound::Unbounded, |key| Bound::Excluded(&key[..])), + ); + for entry in databases.events_by_created_at.range(txn, &bounds)? { + if batch.len() >= CLEAN_BATCH_ROWS { + break; + } + let (key, _) = entry?; + examined_to = Some(key.to_vec()); + key_evaluated(); + let id = header_id(key, 8, "events_by_created_at")?; + let Some(value) = databases.events.get(txn, id.as_bytes())? else { + continue; + }; + let header = rows::event_header(value)?; + if selected_kind(header.kind, criteria) { + batch.push(id); + } + } + } + + let Some(examined_to) = examined_to else { + return Ok(deleted); + }; + + for id in batch { + let Some(value) = databases.events.get(txn, id.as_bytes())? else { + continue; + }; + let record = rows::decode_event(value)?; + hard_delete(txn, databases, &record)?; + deleted += 1; + } + + after = Some(examined_to); + } +} + +/// `delete_all_events`: every event-backed database cleared in one write transaction, and the +/// metadata databases untouched. +pub(crate) fn delete_all_events( + txn: &mut RwTxn<'_>, + databases: &Databases, +) -> Result<(), StorageError> { + for database in [ + databases.events, + databases.events_by_created_at, + databases.events_by_author, + databases.events_deleted, + databases.events_expiring, + databases.replaceable, + databases.tags, + databases.events_by_term, + ] { + database.clear(txn)?; + } + Ok(()) +} + // --------------------------------------------------------------------------------------- // Read paths. // --------------------------------------------------------------------------------------- diff --git a/crates/nostream-storage/src/lmdb/mod.rs b/crates/nostream-storage/src/lmdb/mod.rs index f5abbca1a..ac7d8f00b 100644 --- a/crates/nostream-storage/src/lmdb/mod.rs +++ b/crates/nostream-storage/src/lmdb/mod.rs @@ -35,12 +35,12 @@ use crate::backend::LmdbEnv; use crate::error::StorageError; use crate::repositories::{ ActionableTarget, CreateInviteCodeOptions, DeliveryLogEntry, DeliveryLogFilters, DvmJob, - DvmJobRepository, DvmJobUpdate, EmptyTagRule, EventPurgeCounts, EventRecord, EventRepository, - EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, InvoiceRepository, - InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, Nip05VerificationRepository, - NotificationDeliveryLogRepository, NotificationOutboxRepository, OutboxMessage, OutboxPayload, - QueryStream, ReconciliationItem, Report, ReportRepository, SearchRule, StorageFuture, - StreamedEvent, User, UserPatch, UserRepository, + DvmJobRepository, DvmJobUpdate, EmptyTagRule, EventCleanCriteria, EventPurgeCounts, + EventRecord, EventRepository, EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, + InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, + Nip05VerificationRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, + OutboxMessage, OutboxPayload, QueryStream, ReconciliationItem, Report, ReportRepository, + ScanCursor, SearchRule, StorageFuture, StreamedEvent, User, UserPatch, UserRepository, }; /// The fixed map size every environment is opened with: `Env::resize` is `unsafe` and this @@ -656,6 +656,45 @@ impl EventRepository for LmdbBackend { .await }) } + + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + Box::pin(async move { + let now = Utc::now().timestamp(); + let records = self + .read(move |txn, databases| events::scan_live(txn, databases, after, limit, now)) + .await?; + let stream: QueryStream<'a, EventRecord> = + Box::pin(futures_util::stream::iter(records.into_iter().map(Ok))); + Ok(stream) + }) + } + + fn count_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) -> StorageFuture<'a, u64> { + Box::pin(async move { + let criteria = criteria.clone(); + self.read(move |txn, databases| events::count_by_criteria(txn, databases, &criteria)) + .await + }) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { + let criteria = criteria.clone(); + self.write(move |txn, databases| events::delete_by_criteria(txn, databases, &criteria)) + .await + }) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + Box::pin(async move { self.write(events::delete_all_events).await }) + } } impl InvoiceRepository for LmdbBackend { diff --git a/crates/nostream-storage/src/postgres/events.rs b/crates/nostream-storage/src/postgres/events.rs index 8d10370cd..112e0d169 100644 --- a/crates/nostream-storage/src/postgres/events.rs +++ b/crates/nostream-storage/src/postgres/events.rs @@ -15,8 +15,8 @@ use super::{Arg, Args, EventQuery, Gates, RETENTION_BATCH_SIZE}; use crate::error::StorageError; use crate::records::distinct_replacements; use crate::repositories::{ - EventPurgeCounts, EventRecord, EventRetentionOptions, QueryStream, ReconciliationItem, - StreamedEvent, + EventCleanCriteria, EventPurgeCounts, EventRecord, EventRetentionOptions, QueryStream, + ReconciliationItem, ScanCursor, StreamedEvent, }; /// The conflict target of every replaceable write, exactly as the capture spells it. @@ -182,6 +182,148 @@ pub(crate) fn find_by_filters<'a>( })) } +/// `scan_live`: the live rows after the cursor, oldest first, at most `min(limit, MAX_PAGE_ROWS)`. +/// +/// The liveness predicate and the keyset comparison run in the statement, before its `LIMIT`, so +/// a page cannot come up short while live rows remain: the server never spends a slot on a row +/// the caller would not be given. +pub(crate) fn scan_live<'a>( + reader: &'a sqlx::PgPool, + after: Option, + limit: u64, + now: i64, +) -> Result, StorageError> { + let mut args = Args::default(); + let now_slot = args.push(Arg::BigInt(now)); + let mut text = format!( + "SELECT {} FROM events WHERE events.deleted_at IS NULL \ + AND (events.expires_at IS NULL OR events.expires_at > {now_slot})", + sql::EVENT_COLUMNS + ); + + if let Some(cursor) = after { + let created_slot = args.push(Arg::BigInt(cursor.created_at)); + let id_slot = args.push(Arg::Bytes(cursor.event_id.as_bytes().to_vec())); + text.push_str(&format!( + " AND (events.event_created_at, events.event_id) > ({created_slot}, {id_slot})" + )); + } + + let limit = limit.min(crate::MAX_PAGE_ROWS); + let limit_slot = args.push(Arg::BigInt(i64::try_from(limit).unwrap_or(i64::MAX))); + text.push_str(&format!( + " ORDER BY events.event_created_at ASC, events.event_id ASC LIMIT {limit_slot}" + )); + + let query = EventQuery { sql: text, args }; + Ok(Box::pin(RecordStream { + inner: query.into_query().fetch(reader), + })) +} + +/// The two conditions of [`EventCleanCriteria`], as SQL, appended to `text` with their binds. +/// +/// A kind list that is set and empty is `= ANY('{}')`, which selects nothing — the same answer +/// knex's `whereIn` over an empty list gives, so a caller that filters every kind out counts and +/// deletes zero rather than everything. +fn push_criteria( + text: &mut String, + args: &mut Args, + criteria: &EventCleanCriteria, +) -> Result<(), StorageError> { + if let Some(before) = criteria.before { + let slot = args.push(Arg::BigInt(before)); + text.push_str(&format!(" AND events.event_created_at < {slot}")); + } + + if let Some(kinds) = &criteria.kinds { + let mut values = Vec::with_capacity(kinds.len()); + for kind in kinds { + let kind = i32::try_from(kind.0).map_err(|_| StorageError::ValueOutOfRange { + column: "event_kind", + value: kind.0.to_string(), + })?; + values.push(kind); + } + let slot = args.push(Arg::IntList(values)); + text.push_str(&format!(" AND events.event_kind = ANY({slot})")); + } + + Ok(()) +} + +/// `count_by_criteria`: the rows the delete would remove, soft-deleted rows included. +pub(crate) async fn count_by_criteria<'e, E>( + executor: E, + criteria: &EventCleanCriteria, +) -> Result +where + E: Executor<'e, Database = Postgres>, +{ + let mut args = Args::default(); + let mut text = String::from("SELECT count(*) AS count FROM events WHERE 1 = 1"); + push_criteria(&mut text, &mut args, criteria)?; + + let row = EventQuery { sql: text, args } + .into_query() + .fetch_one(executor) + .await?; + let count: i64 = row.try_get("count")?; + u64::try_from(count).map_err(|_| StorageError::ValueOutOfRange { + column: "count", + value: count.to_string(), + }) +} + +/// `delete_by_criteria`: the hard delete, then the `VACUUM ANALYZE events` the capture runs +/// after it (`src/clean-db.ts:211-216`). +/// +/// The vacuum is why this takes the pool rather than any executor: `VACUUM` cannot run inside a +/// transaction, so a caller that has one open must not reach this. The capture's clean-up is a +/// one-shot process and this is a one-shot statement. +pub(crate) async fn delete_by_criteria( + pool: &sqlx::PgPool, + criteria: &EventCleanCriteria, +) -> Result { + let mut args = Args::default(); + let mut text = String::from("DELETE FROM events WHERE 1 = 1"); + push_criteria(&mut text, &mut args, criteria)?; + + let deleted = EventQuery { sql: text, args } + .into_query() + .execute(pool) + .await? + .rows_affected(); + + EventQuery { + sql: "VACUUM ANALYZE events".to_owned(), + args: Args::default(), + } + .into_query() + .execute(pool) + .await?; + + Ok(deleted) +} + +/// `delete_all_events`: `TRUNCATE` of both event tables, and of nothing else. +/// +/// `event_tags` is truncated beside `events` because the trigger that fills it does not fire on +/// `TRUNCATE`, and `CASCADE` reaches no further: nothing in the schema references `events`. +pub(crate) async fn delete_all_events<'e, E>(executor: E) -> Result<(), StorageError> +where + E: Executor<'e, Database = Postgres>, +{ + EventQuery { + sql: "TRUNCATE TABLE events, event_tags RESTART IDENTITY CASCADE".to_owned(), + args: Args::default(), + } + .into_query() + .execute(executor) + .await?; + Ok(()) +} + /// `find_reconciliation_items`: the live `(created_at, event_id)` pairs, limit ignored. pub(crate) fn find_reconciliation_items<'a>( reader: &'a sqlx::PgPool, @@ -533,6 +675,26 @@ impl Stream for ReconciliationStream<'_> { } } +/// A stream of whole stored rows, mapping each driver row (`scan_live`'s item type: a slot this +/// query selected is a row by the time the server answered, so there is no marker to carry). +struct RecordStream<'a> { + inner: Pin> + Send + 'a>>, +} + +impl Stream for RecordStream<'_> { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + match this.inner.as_mut().poll_next(context) { + Poll::Ready(Some(Ok(row))) => Poll::Ready(Some(super::rows::event_record(&row))), + Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(StorageError::Database(error)))), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] diff --git a/crates/nostream-storage/src/postgres/repository.rs b/crates/nostream-storage/src/postgres/repository.rs index b474bf63b..6f4001833 100644 --- a/crates/nostream-storage/src/postgres/repository.rs +++ b/crates/nostream-storage/src/postgres/repository.rs @@ -9,12 +9,12 @@ use super::{ use crate::error::StorageError; use crate::repositories::{ ActionableTarget, CreateInviteCodeOptions, DeliveryLogEntry, DeliveryLogFilters, DvmJob, - DvmJobRepository, DvmJobUpdate, EmptyTagRule, EventPurgeCounts, EventRecord, EventRepository, - EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, InvoiceRepository, - InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, Nip05VerificationRepository, - NotificationDeliveryLogRepository, NotificationOutboxRepository, OutboxMessage, OutboxPayload, - QueryStream, ReconciliationItem, Report, ReportRepository, SearchRule, StorageFuture, - StreamedEvent, User, UserPatch, UserRepository, + DvmJobRepository, DvmJobUpdate, EmptyTagRule, EventCleanCriteria, EventPurgeCounts, + EventRecord, EventRepository, EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, + InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, + Nip05VerificationRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, + OutboxMessage, OutboxPayload, QueryStream, ReconciliationItem, Report, ReportRepository, + ScanCursor, SearchRule, StorageFuture, StreamedEvent, User, UserPatch, UserRepository, }; impl EventRepository for PostgresBackend { @@ -120,6 +120,31 @@ impl EventRepository for PostgresBackend { ) -> StorageFuture<'a, EventPurgeCounts> { Box::pin(async move { events::delete_expired_and_retained(&self.master, options).await }) } + + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + Box::pin(async move { + events::scan_live(&self.reader, after, limit, chrono::Utc::now().timestamp()) + }) + } + + fn count_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) -> StorageFuture<'a, u64> { + Box::pin(async move { events::count_by_criteria(&self.reader, criteria).await }) + } + + fn delete_by_criteria<'a>( + &'a self, + criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + Box::pin(async move { events::delete_by_criteria(&self.master, criteria).await }) + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + Box::pin(async move { events::delete_all_events(&self.master).await }) + } } impl InvoiceRepository for PostgresBackend { diff --git a/crates/nostream-storage/src/repositories.rs b/crates/nostream-storage/src/repositories.rs index aed9e78e2..54f1be807 100644 --- a/crates/nostream-storage/src/repositories.rs +++ b/crates/nostream-storage/src/repositories.rs @@ -60,6 +60,35 @@ pub struct EventRetentionOptions { pub pubkey_whitelist: Option>, } +/// A position in the live `(created_at, event_id)` order that +/// [`EventRepository::scan_live`] resumes strictly after. +/// +/// The pair is the whole key: `created_at` alone cannot order two events of one second, and an +/// id alone cannot be compared with a timestamp, so a caller that pages a full scan carries +/// both fields of the last row it read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ScanCursor { + pub created_at: i64, + pub event_id: EventId, +} + +/// The predicate a `clean-db` run selects rows with (`src/clean-db.ts:161-173`). +/// +/// A row is selected when `created_at < before` (when set) **and** its kind is in `kinds` (when +/// set). Neither field is a liveness filter: [`Default::default`] selects every stored row, +/// soft-deleted ones included, because the capture's `count(*)`/`DELETE` carry no `deleted_at` +/// condition and a clean-up run that quietly skipped soft-deleted rows would leave them behind +/// while reporting a clean store. +/// +/// The predicate is a **delete** list, not the retention API's keep list +/// ([`EventRetentionOptions`]): the two are opposite questions, and the count and the delete +/// share this one type so a `--dry-run` and the run that follows it select the same rows. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EventCleanCriteria { + pub before: Option, + pub kinds: Option>, +} + /// One stored event row: the seven wire fields plus the five columns that are storage /// state rather than wire data (`src/@types/event.ts` `DBEvent`, and the two insert-time /// Symbols in `src/constants/base.ts`). @@ -651,6 +680,55 @@ pub trait EventRepository: Send + Sync { &'a self, options: &'a EventRetentionOptions, ) -> StorageFuture<'a, EventPurgeCounts>; + + /// Streams every live row in ascending `(created_at, event_id)` order, resuming strictly + /// after `after`. + /// + /// This is the full-scan read a caller needs when a filter read is the wrong shape: + /// [`find_by_filters`](Self::find_by_filters) is bounded by each filter's `limit` and + /// clamped to the backend's page, so nothing built on it can enumerate a store. + /// + /// **The contract**, in four parts, each of which is a claim a backend can fail: + /// + /// - rows are **live** — not soft-deleted, and not expired — by the store's own live + /// predicate, so a scan yields nothing every other reader hides; + /// - rows ascend by `(created_at, event_id)`, the order a stable export writes; + /// - rows come **strictly after** `after`, so a caller that passes the last row it read + /// pages without repeating one, and `None` starts at the oldest row; + /// - a call yields **at most** `min(limit, page_bound())` rows, and fewer only when the + /// store holds no more live rows past the cursor. A backend that selected a key and + /// found it gone when it came to read it continues to the next live row instead of + /// spending the page slot: a short page is the caller's signal that the scan is done. + fn scan_live<'a>( + &'a self, + after: Option, + limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>>; + + /// Counts the rows [`delete_by_criteria`](Self::delete_by_criteria) would remove. + /// + /// The two read one [`EventCleanCriteria`], so a `--dry-run`'s number is the delete's, row + /// for row, including soft-deleted rows the predicate does not exclude. + fn count_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) -> StorageFuture<'a, u64>; + + /// Hard-deletes every row the criteria select, returning how many it removed. + /// + /// **Hard**, like [`delete_expired_and_retained`](Self::delete_expired_and_retained) and + /// unlike every other delete in the store: the capture's `clean-db` runs `DELETE FROM + /// events`, which is what makes a second `--dry-run` report 0 rather than repeating the + /// count. The row's index entries go with it, so no read path can still find it. + fn delete_by_criteria<'a>(&'a self, criteria: &'a EventCleanCriteria) + -> StorageFuture<'a, u64>; + + /// Empties the event store and nothing else. + /// + /// Every event-backed index is cleared with the rows — on Postgres `TRUNCATE TABLE events, + /// event_tags RESTART IDENTITY CASCADE`, on LMDB every event database in one write + /// transaction — while the metadata stores (users, invite codes, invoices, reports and the + /// rest) are left untouched. It returns no count because `TRUNCATE` reports none; a caller + /// that needs the number counts first with [`count_by_criteria`](Self::count_by_criteria) + /// over [`EventCleanCriteria::default`]. + fn delete_all_events(&self) -> StorageFuture<'_, ()>; } /// Invoice storage (`src/@types/repositories.ts` `IInvoiceRepository`). diff --git a/crates/nostream-storage/tests/clean_up.rs b/crates/nostream-storage/tests/clean_up.rs new file mode 100644 index 000000000..b14327546 --- /dev/null +++ b/crates/nostream-storage/tests/clean_up.rs @@ -0,0 +1,639 @@ +//! The clean-up seam: `scan_live`, `count_by_criteria`, `delete_by_criteria` and +//! `delete_all_events`, over the LMDB arm here and the Postgres arm behind `#[ignore]`. +//! +//! The predicates are the ones `nostream-cli clean-db` and `export` call, so each assertion is a +//! claim the CLI depends on: a page that is short only when the store is exhausted, a count and a +//! delete that select the same rows, and an emptying that leaves the metadata stores alone. +//! +//! The Postgres arm is `#[ignore]`d for the repository's own reason — a checkout without a +//! database still has to pass `cargo test --workspace` — and reads `PARITY_ADMIN_URL`, creating +//! its own scratch database the way `migration_pg.rs` does. + +#![cfg(feature = "lmdb")] +// This integration-test target may unwrap: a failed assertion here is a failed test, +// which is the point. The allowance names this file rather than exempting test targets +// workspace-wide, so a new test file still has to ask. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeMap; + +use chrono::Utc; +use futures_util::StreamExt; + +use nostream_core::{Event, EventId, Filter, Kind, Pubkey, Signature}; +use nostream_storage::repositories::{ + CreateInviteCodeOptions, EventCleanCriteria, EventRecord, EventRepository, FieldUpdate, + InviteCodeRepository, Invoice, InvoiceRepository, InvoiceStatus, InvoiceUnit, QueryStream, + ScanCursor, UserPatch, UserRepository, +}; +use nostream_storage::{DEFAULT_PAGE_ROWS, LmdbBackend, MAX_PAGE_ROWS}; + +/// A signed note by the key `secret`, at `created_at`, with the given kind and tags. +fn note(secret: u8, kind: u64, created_at: i64, content: &str, tags: Vec>) -> Event { + let mut event = Event { + id: EventId::from_byte_array([0; 32]), + pubkey: Pubkey::from_byte_array([0; 32]), + created_at, + kind: Kind(kind), + tags, + content: content.to_owned(), + sig: Signature::from_byte_array([0; 64]), + }; + nostream_core::crypto::sign_event(&[secret; 32], &mut event).expect("the event signs"); + event +} + +/// One kind-1 record at `created_at`, its content the only thing telling it from a neighbour. +fn plain(created_at: i64) -> EventRecord { + EventRecord::from_event(¬e( + 11, + 1, + created_at, + &format!("row {created_at}"), + Vec::new(), + )) +} + +/// Drains one `scan_live` page. +async fn page(stream: QueryStream<'_, EventRecord>) -> Vec { + let mut rows = Vec::new(); + let mut stream = stream; + while let Some(item) = stream.next().await { + rows.push(item.expect("a scan yields its rows")); + } + rows +} + +/// The cursor a page ends at, for the page that follows it. +fn cursor(record: &EventRecord) -> ScanCursor { + ScanCursor { + created_at: record.event.created_at, + event_id: record.event.id, + } +} + +async fn store() -> (tempfile::TempDir, LmdbBackend) { + let directory = tempfile::tempdir().expect("a temporary directory"); + let backend = LmdbBackend::open(directory.path()) + .await + .expect("the store opens"); + (directory, backend) +} + +/// AC50: the full scan pages by its own cursor, ascends by `(created_at, event_id)`, and is short +/// only when the store has nothing more to give. +#[tokio::test] +async fn scan_live_pages_the_store_and_shortens_only_at_its_end() { + let (_directory, backend) = store().await; + let rows: Vec = (0..MAX_PAGE_ROWS as i64 + 1) + .map(|step| plain(1_700_000_000 + step)) + .collect(); + backend + .create_many(&rows) + .await + .expect("the rows are written"); + + let first = page( + backend + .scan_live(None, MAX_PAGE_ROWS) + .await + .expect("a scan starts"), + ) + .await; + assert_eq!( + first.len() as u64, + MAX_PAGE_ROWS, + "a full page holds exactly the bound" + ); + assert!( + first + .windows(2) + .all(|pair| (pair[0].event.created_at, pair[0].event.id) + < (pair[1].event.created_at, pair[1].event.id)), + "the page ascends by (created_at, event_id)" + ); + + let rest = page( + backend + .scan_live( + Some(cursor(first.last().expect("a page has rows"))), + MAX_PAGE_ROWS, + ) + .await + .expect("the scan resumes"), + ) + .await; + assert_eq!(rest.len(), 1, "the second page is the one row past 5 000"); + + let thousand = page( + backend + .scan_live(None, DEFAULT_PAGE_ROWS * 2) + .await + .expect("a page of 1 000"), + ) + .await; + assert_eq!(thousand.len(), 1_000, "a limit below the bound is honoured"); +} + +/// AC50: a cursor's row that a delete removed, and a soft-deleted or expired row in the middle, +/// cost a page no slot — the page is still filled from what is live. +#[tokio::test] +async fn a_hidden_row_does_not_shorten_a_page() { + let (_directory, backend) = store().await; + let base = 1_700_000_000; + let rows: Vec = (0..5).map(|step| plain(base + step * 10)).collect(); + backend + .create_many(&rows[..3]) + .await + .expect("the rows are written"); + + // `base + 10` is soft-deleted (a live row's neighbour), and `base + 30` is expired (a hidden + // row between two live ones): neither may cost a page a slot. + backend + .delete_by_pubkey_and_ids(&rows[1].event.pubkey, &[rows[1].event.id]) + .await + .expect("the row is soft-deleted"); + let mut expired = + EventRecord::from_event(¬e(12, 1, base + 30, "an expired row", Vec::new())); + expired.expires_at = Some(Utc::now().timestamp() - 60); + EventRepository::create(&backend, &expired) + .await + .expect("the expired row"); + EventRepository::create(&backend, &rows[4]) + .await + .expect("the row past the expired one"); + + let first = page(backend.scan_live(None, 2).await.expect("a scan starts")).await; + assert_eq!( + first.len(), + 2, + "the page is filled from the live rows only: the soft-deleted row spent no slot" + ); + assert_eq!(first[0].event.created_at, base); + assert_eq!( + first[1].event.created_at, + base + 20, + "the soft-deleted row between them is skipped, not counted" + ); + + let second = page( + backend + .scan_live(Some(cursor(&first[1])), 1) + .await + .expect("the scan resumes"), + ) + .await; + assert_eq!( + second.len(), + 1, + "the expired row spends no slot, so the page is still filled" + ); + assert_eq!(second[0].event.created_at, base + 40); + + let third = page( + backend + .scan_live(Some(cursor(&second[0])), 5) + .await + .expect("the scan resumes"), + ) + .await; + assert!( + third.is_empty(), + "past the last live row the store is exhausted" + ); +} + +/// AC51: the count and the delete are one predicate, the comparison is strict, and soft-deleted +/// rows are in it. The test names one literal `cutoff` and uses it twice — as one row's +/// `created_at` and as the criteria's `before` — which is the only way `<` and `<=` are told +/// apart. +#[tokio::test] +async fn the_criteria_count_and_delete_the_same_rows() { + let (_directory, backend) = store().await; + let cutoff = 1_700_000_000i64; + const DAY: i64 = 86_400; + + let tagged = |kind: u64, created_at: i64, tag: &str, content: &str| { + EventRecord::from_event(¬e( + 21, + kind, + created_at, + content, + vec![vec!["t".to_owned(), tag.to_owned()]], + )) + }; + + let old_kind_one = tagged(1, cutoff - 10 * DAY, "gone", "old kind 1"); + let old_kind_seven = tagged(7, cutoff - 10 * DAY, "kept", "old kind 7"); + let new_kind_one = tagged(1, cutoff + 20 * DAY, "kept", "new kind 1"); + let old_deleted = tagged(1, cutoff - 10 * DAY, "gone", "old soft-deleted kind 1"); + let at_cutoff = tagged(7, cutoff, "kept", "exactly at the cutoff"); + + let rows = vec![ + old_kind_one.clone(), + old_kind_seven.clone(), + new_kind_one.clone(), + old_deleted.clone(), + at_cutoff.clone(), + ]; + backend + .create_many(&rows) + .await + .expect("the rows are written"); + backend + .delete_by_pubkey_and_ids(&old_deleted.event.pubkey, &[old_deleted.event.id]) + .await + .expect("one row is soft-deleted"); + + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria::default()) + .await + .expect("a count"), + 5, + "the default predicate counts every stored row, soft-deleted ones included" + ); + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria { + before: Some(cutoff), + kinds: None, + }) + .await + .expect("a count"), + 3, + "a row at exactly `before` is not selected: the predicate is `<`" + ); + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria { + before: Some(cutoff), + kinds: Some(vec![Kind(1)]), + }) + .await + .expect("a count"), + 2, + "the soft-deleted old kind-1 row is in the selection" + ); + + let deleted = backend + .delete_by_criteria(&EventCleanCriteria { + before: Some(cutoff), + kinds: Some(vec![Kind(1)]), + }) + .await + .expect("a delete"); + assert_eq!(deleted, 2, "the delete removes what the count counted"); + + let remaining = page( + backend + .scan_live(None, MAX_PAGE_ROWS) + .await + .expect("a scan"), + ) + .await; + assert_eq!(remaining.len(), 3, "three rows are left"); + assert!( + remaining + .iter() + .any(|record| record.event.id == at_cutoff.event.id), + "the row at exactly the cutoff survives" + ); + + // The tag index went with the deleted rows: the surviving rows' tags are still found, and the + // deleted rows' are not. + let gone = Filter { + tags: BTreeMap::from([("#t".to_owned(), vec!["gone".to_owned()])]), + ..Filter::default() + }; + let kept = Filter { + tags: BTreeMap::from([("#t".to_owned(), vec!["kept".to_owned()])]), + ..Filter::default() + }; + assert_eq!( + backend + .count_by_filters(std::slice::from_ref(&gone)) + .await + .expect("a count"), + 0, + "a deleted row's tag entry is gone" + ); + assert_eq!( + backend + .count_by_filters(std::slice::from_ref(&kept)) + .await + .expect("a count"), + 3, + "the surviving rows keep their tag entries" + ); +} + +/// AC52: `delete_all_events` empties the event store and nothing else. +#[tokio::test] +async fn delete_all_events_leaves_the_metadata_stores_alone() { + let (_directory, backend) = store().await; + let now = Utc::now(); + + let events: Vec = (0..3).map(|step| plain(1_700_000_000 + step)).collect(); + backend + .create_many(&events) + .await + .expect("the events are written"); + + let invite = InviteCodeRepository::create( + &backend, + "0123456789abcdef0123456789abcdef", + &CreateInviteCodeOptions { + expires_at: None, + remaining_uses: FieldUpdate::Set(1), + created_by: None, + }, + ) + .await + .expect("the invite code is minted"); + let invoice = Invoice { + id: "40000000-0000-4000-8000-000000000001".to_owned(), + pubkey: Pubkey::from_byte_array([5; 32]), + bolt11: "lnbc1cleanup".to_owned(), + amount_requested: 1_000, + amount_paid: None, + unit: InvoiceUnit::Msats, + status: InvoiceStatus::Pending, + description: "a row the clean-up must not touch".to_owned(), + confirmed_at: None, + expires_at: None, + updated_at: now, + created_at: now, + verify_url: None, + }; + InvoiceRepository::upsert(&backend, &invoice) + .await + .expect("the invoice is written"); + UserRepository::upsert( + &backend, + &UserPatch { + pubkey: Pubkey::from_byte_array([6; 32]), + is_admitted: FieldUpdate::Set(true), + is_vanished: FieldUpdate::Absent, + tos_accepted_at: FieldUpdate::Absent, + }, + ) + .await + .expect("the user is written"); + + backend + .delete_all_events() + .await + .expect("the event store empties"); + + assert_eq!( + backend + .count_by_filters(&[Filter::default()]) + .await + .expect("a count"), + 0, + "no live event is left" + ); + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria::default()) + .await + .expect("a count"), + 0, + "no event row is left, soft-deleted or not" + ); + assert!( + page( + backend + .scan_live(None, MAX_PAGE_ROWS) + .await + .expect("a scan") + ) + .await + .is_empty(), + "the created-at index yields nothing" + ); + assert!( + backend + .find_by_code(&invite.code) + .await + .expect("the invite reads") + .is_some(), + "the invite code survives" + ); + assert!( + backend + .find_by_id(&invoice.id) + .await + .expect("the invoice reads") + .is_some(), + "the invoice survives" + ); + assert!( + backend + .find_by_pubkey(&Pubkey::from_byte_array([6; 32])) + .await + .expect("the user reads") + .is_some(), + "the user survives" + ); +} + +#[cfg(feature = "postgres")] +mod postgres_arm { + use super::*; + + use sqlx::postgres::PgPool; + use sqlx::{Executor, Row}; + + use nostream_storage::postgres::PostgresBackend; + + const DATABASE: &str = "nostream_clean_up_rust"; + + fn admin_url() -> String { + std::env::var("PARITY_ADMIN_URL").expect( + "PARITY_ADMIN_URL must name an administrative database, e.g. \ + postgres://postgres:postgres@host:5432/postgres", + ) + } + + fn with_database(url: &str, database: &str) -> String { + let (prefix, query) = match url.split_once('?') { + Some((prefix, query)) => (prefix, Some(query)), + None => (url, None), + }; + let base = match prefix.rfind('/') { + Some(index) if index > "postgres://".len() => &prefix[..index], + _ => prefix, + }; + match query { + Some(query) => format!("{base}/{database}?{query}"), + None => format!("{base}/{database}"), + } + } + + /// A fresh scratch database with the schema applied, as `migration_pg.rs` makes one. + async fn scratch() -> PostgresBackend { + let admin = PgPool::connect(&admin_url()) + .await + .expect("the administrative database is reachable"); + admin + .execute(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS {DATABASE} WITH (FORCE)" + ))) + .await + .expect("the scratch database drops"); + admin + .execute(sqlx::AssertSqlSafe(format!("CREATE DATABASE {DATABASE}"))) + .await + .expect("the scratch database is created"); + drop(admin); + + let source = PostgresBackend::connect(&with_database(&admin_url(), DATABASE)) + .await + .expect("the scratch database is reachable"); + source.migrate().await.expect("the schema migrates"); + source + } + + /// AC53: the same three assertions against `PostgresBackend`. + #[tokio::test] + #[ignore = "needs PARITY_ADMIN_URL; the Rust Checks job sets it"] + async fn the_postgres_arm_answers_the_three_assertions() { + let backend = scratch().await; + let cutoff = 1_700_000_000i64; + const DAY: i64 = 86_400; + + let rows: Vec = (0..MAX_PAGE_ROWS as i64 + 1) + .map(|step| plain(1_700_000_000 + step)) + .collect(); + backend + .create_many(&rows) + .await + .expect("the rows are written"); + + let first = page( + backend + .scan_live(None, MAX_PAGE_ROWS) + .await + .expect("a scan starts"), + ) + .await; + assert_eq!(first.len() as u64, MAX_PAGE_ROWS, "a full page"); + assert!( + first + .windows(2) + .all(|pair| (pair[0].event.created_at, pair[0].event.id) + < (pair[1].event.created_at, pair[1].event.id)), + "the page ascends by (created_at, event_id)" + ); + let rest = page( + backend + .scan_live( + Some(cursor(first.last().expect("a page has rows"))), + MAX_PAGE_ROWS, + ) + .await + .expect("the scan resumes"), + ) + .await; + assert_eq!( + rest.len(), + 1, + "the second page is the one row past the bound" + ); + + // The predicate, over its own rows and its own scratch store state. + backend + .delete_all_events() + .await + .expect("the event store empties"); + let at_cutoff = + EventRecord::from_event(¬e(22, 7, cutoff, "exactly at the cutoff", Vec::new())); + let old_one = EventRecord::from_event(¬e( + 23, + 1, + cutoff - 10 * DAY, + "old kind 1", + vec![vec!["t".to_owned(), "gone".to_owned()]], + )); + let old_deleted = EventRecord::from_event(¬e( + 24, + 1, + cutoff - 10 * DAY, + "old soft-deleted kind 1", + Vec::new(), + )); + backend + .create_many(&[ + at_cutoff.clone(), + old_one.clone(), + old_deleted.clone(), + EventRecord::from_event(¬e(25, 1, cutoff + 20 * DAY, "new kind 1", Vec::new())), + EventRecord::from_event(¬e(26, 7, cutoff - 10 * DAY, "old kind 7", Vec::new())), + ]) + .await + .expect("the rows are written"); + backend + .delete_by_pubkey_and_ids(&old_deleted.event.pubkey, &[old_deleted.event.id]) + .await + .expect("one row is soft-deleted"); + + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria::default()) + .await + .expect("a count"), + 5, + "every row counts, soft-deleted ones included" + ); + assert_eq!( + backend + .count_by_criteria(&EventCleanCriteria { + before: Some(cutoff), + kinds: None, + }) + .await + .expect("a count"), + 3, + "a row at exactly `before` is not selected" + ); + assert_eq!( + backend + .delete_by_criteria(&EventCleanCriteria { + before: Some(cutoff), + kinds: Some(vec![Kind(1)]), + }) + .await + .expect("a delete"), + 2, + "the delete removes what the count counted" + ); + assert!( + page( + backend + .scan_live(None, MAX_PAGE_ROWS) + .await + .expect("a scan") + ) + .await + .iter() + .any(|record| record.event.id == at_cutoff.event.id), + "the row at exactly the cutoff survives" + ); + + // `delete_all_events` leaves no `event_tags` row behind: the trigger does not fire on + // `TRUNCATE`, so the truncate names the table. + backend + .delete_all_events() + .await + .expect("the event store empties"); + let tags: i64 = sqlx::query("SELECT count(*) AS count FROM event_tags") + .fetch_one(backend.master()) + .await + .expect("event_tags counts") + .try_get("count") + .expect("a count"); + assert_eq!(tags, 0, "event_tags is emptied with the events"); + } +} diff --git a/crates/nostream-storage/tests/storage.rs b/crates/nostream-storage/tests/storage.rs index 6cec0547e..22712ffcb 100644 --- a/crates/nostream-storage/tests/storage.rs +++ b/crates/nostream-storage/tests/storage.rs @@ -47,13 +47,13 @@ async fn the_repository_traits_are_dyn_compatible() { use nostream_storage::StorageError; use nostream_storage::repositories::{ ActionableTarget, CreateInviteCodeOptions, DeliveryLogEntry, DeliveryLogFilters, DvmJob, - DvmJobRepository, DvmJobUpdate, EventPurgeCounts, EventRecord, EventRepository, - EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, InvoiceRepository, - InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, + DvmJobRepository, DvmJobUpdate, EventCleanCriteria, EventPurgeCounts, EventRecord, + EventRepository, EventRetentionOptions, InviteCode, InviteCodeRepository, Invoice, + InvoiceRepository, InvoiceStatus, NewDeliveryLogEntry, NewReport, Nip05Verification, Nip05VerificationRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, OutboxMessage, OutboxPayload, QueryStream, - ReconciliationItem, Report, ReportRepository, StorageFuture, StreamedEvent, User, - UserPatch, UserRepository, + ReconciliationItem, Report, ReportRepository, ScanCursor, StorageFuture, StreamedEvent, + User, UserPatch, UserRepository, }; struct Noop; @@ -135,6 +135,32 @@ async fn the_repository_traits_are_dyn_compatible() { ) -> StorageFuture<'a, EventPurgeCounts> { unsupported("noop::events::delete_expired_and_retained") } + + fn scan_live<'a>( + &'a self, + _after: Option, + _limit: u64, + ) -> StorageFuture<'a, QueryStream<'a, EventRecord>> { + unsupported("noop::events::scan_live") + } + + fn count_by_criteria<'a>( + &'a self, + _criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + unsupported("noop::events::count_by_criteria") + } + + fn delete_by_criteria<'a>( + &'a self, + _criteria: &'a EventCleanCriteria, + ) -> StorageFuture<'a, u64> { + unsupported("noop::events::delete_by_criteria") + } + + fn delete_all_events(&self) -> StorageFuture<'_, ()> { + unsupported("noop::events::delete_all_events") + } } impl InvoiceRepository for Noop { From 374f6029e6b900696a2cd654c61639d2d8921571 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:14:00 -0500 Subject: [PATCH 02/78] feat(core): decode npub bech32 forms for the operator CLI --- Cargo.lock | 7 +++ Cargo.toml | 3 ++ crates/nostream-core/Cargo.toml | 1 + crates/nostream-core/src/lib.rs | 1 + crates/nostream-core/src/nip19.rs | 88 +++++++++++++++++++++++++++++++ 5 files changed, 100 insertions(+) create mode 100644 crates/nostream-core/src/nip19.rs diff --git a/Cargo.lock b/Cargo.lock index ec3c4274c..d5e083dc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -195,6 +195,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" @@ -1449,6 +1455,7 @@ version = "0.1.0" dependencies = [ "aes", "base64 0.22.1", + "bech32", "cbc", "chacha20", "getrandom 0.3.4", 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/crates/nostream-core/Cargo.toml b/crates/nostream-core/Cargo.toml index 971e9e895..198c713ba 100644 --- a/crates/nostream-core/Cargo.toml +++ b/crates/nostream-core/Cargo.toml @@ -10,6 +10,7 @@ description = "Nostr domain types, wire messages and NIP surfaces for the nostre [dependencies] aes.workspace = true base64.workspace = true +bech32.workspace = true cbc.workspace = true chacha20.workspace = true getrandom.workspace = true diff --git a/crates/nostream-core/src/lib.rs b/crates/nostream-core/src/lib.rs index 286ce7036..2a286e551 100644 --- a/crates/nostream-core/src/lib.rs +++ b/crates/nostream-core/src/lib.rs @@ -68,6 +68,7 @@ pub mod negentropy; pub mod nip03; pub mod nip04; pub mod nip05; +pub mod nip19; pub mod nip25; pub mod nip42; pub mod nip43; diff --git a/crates/nostream-core/src/nip19.rs b/crates/nostream-core/src/nip19.rs new file mode 100644 index 000000000..393dc5ba4 --- /dev/null +++ b/crates/nostream-core/src/nip19.rs @@ -0,0 +1,88 @@ +//! NIP-19: the bech32 forms a human types where a hex value belongs. +//! +//! Mirrors `fromBech32` (`src/utils/transform.ts`) and the one caller the CLI has for it: +//! `parseRelayPubkey` (`src/utils/nip43-invites.ts:29-47`) accepts an `npub1…` where a settings +//! file holds `info.self`, so an operator may write either form. Only the public key is decoded +//! here; `nsec`/`note`/`nprofile` are the relay's to add when a caller needs them, and adding one +//! without a caller would be a decoder nobody has exercised. + +use crate::error::CoreError; + +/// The 32 bytes a NIP-19 `npub` encodes. +/// +/// A `bech32` failure, a foreign human-readable part and a payload of the wrong length are one +/// answer on purpose: the caller has one message for all three (`info.self npub did not decode to +/// a 32-byte pubkey`), and a caller that needs to tell them apart does not exist. +pub fn decode_npub(value: &str) -> Result<[u8; 32], CoreError> { + let (hrp, data) = bech32::decode(value).map_err(|error| { + CoreError::InvalidMessage(format!("nip19: `{value}` is not bech32: {error}")) + })?; + + if !hrp.as_str().eq_ignore_ascii_case("npub") { + return Err(CoreError::InvalidMessage(format!( + "nip19: `{value}` is `{}`, not an npub", + hrp.as_str() + ))); + } + + data.try_into().map_err(|data: Vec| { + CoreError::InvalidMessage(format!( + "nip19: `{value}` decoded to {} bytes, not 32", + data.len() + )) + }) +} + +/// Decodes one `npub1…` to its lowercase hex form, the spelling the capture stores. +pub fn decode_npub_hex(value: &str) -> Result { + Ok(hex::encode(decode_npub(value)?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The fixture pair the CLI's criterion names (`test/unit/utils/nip43-invites.spec.ts:29,75-89`). + const NPUB: &str = "npub1yt5qf5nw694k3k6jt8ncgj0fdk4463jv3arshk37kxnsgeljc7fsmhwffw"; + const HEX: &str = "22e804d26ed16b68db5259e78449e96dab5d464c8f470bda3eb1a70467f2c793"; + + #[test] + fn an_npub_decodes_to_its_hex_form() { + assert_eq!(decode_npub_hex(NPUB).expect("the fixture decodes"), HEX); + } + + #[test] + fn the_hex_form_round_trips_through_bech32() { + let bytes = decode_npub(NPUB).expect("the fixture decodes"); + let encoded = + bech32::encode::(bech32::Hrp::parse("npub").expect("a hrp"), &bytes) + .expect("the bytes encode"); + assert_eq!(encoded, NPUB); + } + + #[test] + fn a_malformed_npub_is_refused() { + assert!(decode_npub("npub1invalid").is_err()); + assert!(decode_npub("not-bech32").is_err()); + } + + #[test] + fn a_payload_of_the_wrong_length_is_refused() { + let short = bech32::encode::( + bech32::Hrp::parse("npub").expect("a hrp"), + &[1u8; 16], + ) + .expect("the bytes encode"); + assert!(decode_npub(&short).is_err()); + } + + #[test] + fn another_prefix_is_refused() { + let note = bech32::encode::( + bech32::Hrp::parse("note").expect("a hrp"), + &[2u8; 32], + ) + .expect("the bytes encode"); + assert!(decode_npub(¬e).is_err()); + } +} From 2ba1206b96c6730b44dea325cd9a17c079ce0bd2 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:14:00 -0500 Subject: [PATCH 03/78] feat(services): add the spawn seam the operator CLI drives --- crates/nostream-services/src/lib.rs | 1 + crates/nostream-services/src/process.rs | 388 ++++++++++++++++++++++++ 2 files changed, 389 insertions(+) create mode 100644 crates/nostream-services/src/process.rs diff --git a/crates/nostream-services/src/lib.rs b/crates/nostream-services/src/lib.rs index c67de5acf..a17c8cf96 100644 --- a/crates/nostream-services/src/lib.rs +++ b/crates/nostream-services/src/lib.rs @@ -34,6 +34,7 @@ pub mod http; pub mod invoice; pub mod monitor; pub mod payments; +pub mod process; pub mod scheduler; pub mod services; pub mod testing; diff --git a/crates/nostream-services/src/process.rs b/crates/nostream-services/src/process.rs new file mode 100644 index 000000000..28ec55360 --- /dev/null +++ b/crates/nostream-services/src/process.rs @@ -0,0 +1,388 @@ +//! The spawn seam: the one place in the workspace that opens a child process for the operator +//! command line. +//! +//! It owns `src/cli/utils/process.ts`'s two entry points, `runCommand` and +//! `runCommandWithOutput`, and nothing else: `nostream-services` is the only crate allowed +//! tokio's `process` feature (`CLAUDE.md:116`), so a front end that shells out reaches the +//! spawner through this module rather than taking the feature itself. Both entry points are +//! `async` and are driven by a runtime the **caller** owns — the CLI builds a current-thread +//! runtime per command — so this module never starts, stops or blocks a runtime. +//! +//! `run` inherits the parent's stdio, which is what a compose `up` needs: an operator watching +//! the terminal sees the build. `capture` takes both pipes and a budget, which is what a probe +//! needs: `docker inspect` answered inside a second, or the answer is that docker is slow. + +use std::process::Stdio; +use std::time::Duration; + +use tokio::process::Command; + +/// Why a child could not be started, or could not be read. +/// +/// The three classes are Node's `ENOENT` / `EACCES` / everything else, which the capture's +/// `runCommandWithOutput` matches by `err.code` (`src/cli/utils/process.ts:87-98`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpawnFailure { + /// The program is not on `PATH` (or `argv[0]` is not a path to a file). + NotFound { program: String }, + /// The program exists and this user may not execute it. + PermissionDenied { program: String }, + /// Anything else the operating system answered. + Spawn { program: String, message: String }, +} + +impl std::fmt::Display for SpawnFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotFound { program } => write!(formatter, "{program} is not installed"), + Self::PermissionDenied { program } => { + write!(formatter, "{program} is not executable by this user") + } + Self::Spawn { program, message } => { + write!(formatter, "{program} could not be run: {message}") + } + } + } +} + +/// What one captured run answered (`src/cli/utils/process.ts:10-17` `CommandResult`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CapturedResult { + /// The child ran to completion. A status with no exit code is reported as `1`, which is + /// what the capture's `code ?? 1` does. + Exited { + code: i32, + stdout: String, + stderr: String, + }, + /// The child was killed by a signal, so it has no exit code of its own. + Signalled { + signal: String, + stdout: String, + stderr: String, + }, + /// The child outlived the budget the caller gave it and was killed. + /// + /// shortcut: a timed-out capture yields no output, because the pipes are drained by the same + /// future the budget cancels; upgrade when a caller has to parse what a slow child printed + /// before it was killed, which needs the readers to outlive the wait. + TimedOut, + /// The child never started. + Failed { + failure: SpawnFailure, + stdout: String, + stderr: String, + }, +} + +impl CapturedResult { + /// The exit code, when the child answered with one. + pub fn code(&self) -> Option { + match self { + Self::Exited { code, .. } => Some(*code), + Self::Signalled { .. } | Self::TimedOut | Self::Failed { .. } => None, + } + } + + /// What the child printed on stdout, or nothing when it never ran. + pub fn stdout(&self) -> &str { + match self { + Self::Exited { stdout, .. } + | Self::Signalled { stdout, .. } + | Self::Failed { stdout, .. } => stdout, + Self::TimedOut => "", + } + } + + /// What the child printed on stderr, or nothing when it never ran. + pub fn stderr(&self) -> &str { + match self { + Self::Exited { stderr, .. } + | Self::Signalled { stderr, .. } + | Self::Failed { stderr, .. } => stderr, + Self::TimedOut => "", + } + } +} + +/// One command line: the program first, then its arguments. +fn split(argv: &[String]) -> (&str, &[String]) { + match argv.split_first() { + Some((program, arguments)) => (program.as_str(), arguments), + None => ("", &[]), + } +} + +/// Builds the child with the caller's environment additions layered over the parent's, and the +/// classification every entry point shares. +fn command(argv: &[String], env: &[(&str, String)]) -> Command { + let (program, arguments) = split(argv); + let mut command = Command::new(program); + command.args(arguments); + for (name, value) in env { + command.env(name, value); + } + command +} + +fn classify(program: &str, error: std::io::Error) -> SpawnFailure { + match error.kind() { + std::io::ErrorKind::NotFound => SpawnFailure::NotFound { + program: program.to_owned(), + }, + std::io::ErrorKind::PermissionDenied => SpawnFailure::PermissionDenied { + program: program.to_owned(), + }, + _ => SpawnFailure::Spawn { + program: program.to_owned(), + message: error.to_string(), + }, + } +} + +/// `runCommand`: runs `argv` with the parent's stdio and answers its exit code. +/// +/// An empty `argv` is [`SpawnFailure::NotFound`] with an empty program name: there is nothing to +/// start, and a caller that assembled the command from empty parts should read that as the +/// missing program it is. +pub async fn run(argv: &[String], env: &[(&str, String)]) -> Result { + let (program, _) = split(argv); + if program.is_empty() { + return Err(SpawnFailure::NotFound { + program: String::new(), + }); + } + + let mut child = command(argv, env) + .stdin(Stdio::inherit()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|error| classify(program, error))?; + + let status = child.wait().await.map_err(|error| SpawnFailure::Spawn { + program: program.to_owned(), + message: error.to_string(), + })?; + + // The capture's `resolve(code ?? 1)`: a signal leaves no code, and a caller comparing to zero + // must read that as failure rather than as success. + Ok(status.code().unwrap_or(1)) +} + +/// `runCommandWithOutput`: runs `argv` with both pipes and answers what it printed and how it +/// ended, or why it did not. +/// +/// `timeout` of `None` waits forever, which is the capture's default. +pub async fn capture(argv: &[String], timeout: Option) -> CapturedResult { + let (program, _) = split(argv); + if program.is_empty() { + return CapturedResult::Failed { + failure: SpawnFailure::NotFound { + program: String::new(), + }, + stdout: String::new(), + stderr: String::new(), + }; + } + + let mut child = match command(argv, &[]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + { + Ok(child) => child, + Err(error) => { + return CapturedResult::Failed { + failure: classify(program, error), + stdout: String::new(), + stderr: String::new(), + }; + } + }; + + let waited = match timeout { + Some(budget) => match tokio::time::timeout(budget, child.wait_with_output()).await { + Ok(waited) => waited, + // Dropping the wait drops the child, and `kill_on_drop` kills it. + Err(_) => return CapturedResult::TimedOut, + }, + None => child.wait_with_output().await, + }; + + let output = match waited { + Ok(output) => output, + Err(error) => { + return CapturedResult::Failed { + failure: SpawnFailure::Spawn { + program: program.to_owned(), + message: error.to_string(), + }, + stdout: String::new(), + stderr: String::new(), + }; + } + }; + + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + + match output.status.code() { + Some(code) => CapturedResult::Exited { + code, + stdout, + stderr, + }, + None => CapturedResult::Signalled { + signal: signal_name(&output.status), + stdout, + stderr, + }, + } +} + +/// The signal's name, as the capture's `child.on('close', code, signal)` reports it. +#[cfg(unix)] +fn signal_name(status: &std::process::ExitStatus) -> String { + use std::os::unix::process::ExitStatusExt; + + status.signal().map_or_else( + || "unknown".to_owned(), + |signal| match signal { + 1 => "SIGHUP".to_owned(), + 2 => "SIGINT".to_owned(), + 3 => "SIGQUIT".to_owned(), + 6 => "SIGABRT".to_owned(), + 9 => "SIGKILL".to_owned(), + 15 => "SIGTERM".to_owned(), + other => format!("signal {other}"), + }, + ) +} + +#[cfg(not(unix))] +fn signal_name(_status: &std::process::ExitStatus) -> String { + "unknown".to_owned() +} + +#[cfg(all(test, unix))] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use std::os::unix::fs::PermissionsExt; + + use super::*; + + /// Writes an executable shell script into `directory` under `name`. + fn shim(directory: &std::path::Path, name: &str, body: &str) -> String { + let path = directory.join(name); + std::fs::write(&path, format!("#!/bin/bash\n{body}\n")).expect("the shim is written"); + let mut permissions = std::fs::metadata(&path) + .expect("the shim exists") + .permissions(); + permissions.set_mode(0o755); + std::fs::set_permissions(&path, permissions).expect("the shim is executable"); + path.display().to_string() + } + + fn argv(program: &str, arguments: &[&str]) -> Vec { + std::iter::once(program.to_owned()) + .chain(arguments.iter().map(|argument| (*argument).to_owned())) + .collect() + } + + #[tokio::test] + async fn a_missing_binary_is_not_found() { + let failure = run(&argv("nostream-cli-no-such-binary", &[]), &[]) + .await + .expect_err("the binary is not there"); + assert_eq!( + failure, + SpawnFailure::NotFound { + program: "nostream-cli-no-such-binary".to_owned() + } + ); + + let captured = capture(&argv("nostream-cli-no-such-binary", &[]), None).await; + assert!(matches!( + captured, + CapturedResult::Failed { + failure: SpawnFailure::NotFound { .. }, + .. + } + )); + } + + #[tokio::test] + async fn a_script_without_the_execute_bit_is_refused() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let path = directory.path().join("not-executable"); + std::fs::write(&path, "#!/bin/bash\nexit 0\n").expect("the file is written"); + let failure = run(&argv(&path.display().to_string(), &[]), &[]) + .await + .expect_err("the file is not executable"); + assert_eq!( + failure, + SpawnFailure::PermissionDenied { + program: path.display().to_string() + } + ); + } + + #[tokio::test] + async fn a_slow_child_times_out() { + let directory = tempfile::tempdir().expect("a temporary directory"); + let slow = shim(directory.path(), "slow", "sleep 30"); + let started = std::time::Instant::now(); + let captured = capture(&argv(&slow, &[]), Some(Duration::from_millis(150))).await; + assert_eq!(captured, CapturedResult::TimedOut); + assert!( + started.elapsed() < Duration::from_secs(5), + "the budget is what ended the wait" + ); + } + + #[tokio::test] + async fn run_answers_the_child_exit_code_and_capture_answers_its_output() { + let directory = tempfile::tempdir().expect("a temporary directory"); + // The environment the caller adds reaches the child: the shim answers 0 only when it + // finds the variable it was handed. + let env_check = shim( + directory.path(), + "env-check", + "env | grep -q '^NOSTREAM_PROBE=yes$'", + ); + let code = run( + &argv(&env_check, &[]), + &[("NOSTREAM_PROBE", "yes".to_owned())], + ) + .await + .expect("the child runs"); + assert_eq!(code, 0, "the added environment reaches the child"); + + let echo = shim(directory.path(), "echoer", "printf '%s\\n' \"$@\""); + let captured = capture(&argv(&echo, &["two"]), None).await; + let CapturedResult::Exited { code, stdout, .. } = captured else { + panic!("the child exits"); + }; + assert_eq!(code, 0); + assert!(stdout.contains("two"), "the argument is echoed"); + } + + #[tokio::test] + async fn an_empty_argv_is_not_a_program() { + assert!(matches!( + run(&[], &[]).await, + Err(SpawnFailure::NotFound { .. }) + )); + assert!(matches!( + capture(&[], None).await, + CapturedResult::Failed { + failure: SpawnFailure::NotFound { .. }, + .. + } + )); + } +} From 2c70de7acf87fc860b2eba685f96eab9e9867b1e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:20:57 -0500 Subject: [PATCH 04/78] feat(cli): add the compose, env, store and compression seams the port drives --- Cargo.lock | 71 +++++ crates/nostream-cli/Cargo.toml | 5 +- crates/nostream-cli/src/app.rs | 185 +++++++++++ crates/nostream-cli/src/bootstrap.rs | 120 +++++++ crates/nostream-cli/src/commands/start.rs | 159 +++++++++- crates/nostream-cli/src/commands/stop.rs | 127 +++++++- crates/nostream-cli/src/compose.rs | 269 ++++++++++++++++ crates/nostream-cli/src/compression.rs | 243 ++++++++++++++ crates/nostream-cli/src/config.rs | 352 +++++++++++++++++--- crates/nostream-cli/src/env_file.rs | 370 ++++++++++++++++++++++ crates/nostream-cli/src/error.rs | 63 +++- crates/nostream-cli/src/lib.rs | 6 + crates/nostream-cli/src/main.rs | 119 +++++-- crates/nostream-cli/src/store.rs | 220 +++++++++++++ crates/nostream-services/src/process.rs | 2 +- 15 files changed, 2230 insertions(+), 81 deletions(-) create mode 100644 crates/nostream-cli/src/app.rs create mode 100644 crates/nostream-cli/src/bootstrap.rs create mode 100644 crates/nostream-cli/src/compose.rs create mode 100644 crates/nostream-cli/src/compression.rs create mode 100644 crates/nostream-cli/src/env_file.rs create mode 100644 crates/nostream-cli/src/store.rs diff --git a/Cargo.lock b/Cargo.lock index d5e083dc1..0b271362d 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" @@ -437,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" @@ -632,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" @@ -1332,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" @@ -1369,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" @@ -1420,10 +1467,12 @@ dependencies = [ "anyhow", "chrono", "clap", + "flate2", "heed", "hex", "nostream-config", "nostream-core", + "nostream-relay", "nostream-services", "nostream-storage", "serde", @@ -1433,6 +1482,7 @@ dependencies = [ "tempfile", "thiserror", "tokio", + "xz2", ] [[package]] @@ -2468,6 +2518,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" @@ -3503,6 +3559,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" @@ -3606,6 +3671,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/crates/nostream-cli/Cargo.toml b/crates/nostream-cli/Cargo.toml index fca0a721b..120f828c8 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,9 @@ serde_yaml.workspace = true sha2.workspace = true thiserror.workspace = true tokio.workspace = true +xz2.workspace = true [dev-dependencies] -chrono.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..bffc1b476 --- /dev/null +++ b/crates/nostream-cli/src/app.rs @@ -0,0 +1,185 @@ +//! The shared command context, the hand-written top-level page, the pre-parse, the dispatch and +//! the renderer: the four things `src/cli/index.ts` does around the command modules. +//! +//! 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, in one place, so the parser never sees a case that has its own answer (R1, C1). + +use std::future::Future; +use std::path::PathBuf; +use std::process::ExitCode; + +use crate::config::CommandOutput; +use crate::env_file::Environment; +use crate::error::CliError; + +/// 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 the tests name. + 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) + } +} + +/// The version page (V44): `nostream/`, the crate's own version, which is 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 (`Values` 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() +} + +/// 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. +pub fn render(result: Result) -> ExitCode { + match result { + Ok(output) => { + for line in &output.lines { + println!("{line}"); + } + output.exit_code() + } + Err(error) => { + let code = match error { + CliError::Usage(message) => { + eprintln!("Error: {message}"); + 2 + } + CliError::Command(message) => { + eprintln!("Error: {message}"); + 1 + } + CliError::Config(line) => { + eprintln!("{line}"); + 1 + } + CliError::Reported { lines, exit_code } => { + for line in lines { + eprintln!("{line}"); + } + exit_code + } + CliError::Json { message, code } => { + let envelope = ErrorEnvelope { + error: ErrorBody { + message: &message, + code, + }, + }; + match serde_json::to_string(&envelope) { + Ok(rendered) => eprintln!("{rendered}"), + Err(_) => { + eprintln!("{{\"error\":{{\"message\":\"error\",\"code\":{code}}}}}") + } + } + code + } + CliError::NotImplemented { module } => { + eprintln!("not implemented in Phase 1 (job 005): {module}"); + 1 + } + CliError::Import(message) => { + eprintln!("Import failed: {message}"); + 1 + } + CliError::Migrate(message) => { + eprintln!("Migration failed: {message}"); + 1 + } + }; + ExitCode::from(code) + } + } +} diff --git a/crates/nostream-cli/src/bootstrap.rs b/crates/nostream-cli/src/bootstrap.rs new file mode 100644 index 000000000..cb32d8759 --- /dev/null +++ b/crates/nostream-cli/src/bootstrap.rs @@ -0,0 +1,120 @@ +//! 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::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 it is absent. +pub fn ensure_config_bootstrap(cwd: &Path) -> Result<(), CliError> { + let paths = resolve_paths(cwd, None); + + 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() { + 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/start.rs b/crates/nostream-cli/src/commands/start.rs index b625cd1cd..3180dd881 100644 --- a/crates/nostream-cli/src/commands/start.rs +++ b/crates/nostream-cli/src/commands/start.rs @@ -1,10 +1,157 @@ -//! `start.ts`. +//! `start.ts`: start the Docker Compose stack. +//! +//! The order is the capture's (`runStart`, `src/cli/commands/start.ts:71-141`): the root check, +//! the port check, the config bootstrap, the overlay for each flag, the nginx bootstrap, the +//! port-override file, then `docker compose … up --build --remove-orphans [-d] …`. The override +//! file is removed in every outcome, including a failure. +use crate::app::Context; +use crate::bootstrap::{ + ensure_config_bootstrap, ensure_i2p_data_dir, ensure_not_root, ensure_tor_data_dir, +}; +use crate::compose::{create_port_override, nginx_configuration, run_compose}; +use crate::config::CommandOutput; use crate::error::CliError; -/// Phase 1 stub — job 005; will starts the relay stack; see `src/cli/commands/start.ts`. -pub fn run() -> Result<(), CliError> { - Err(CliError::NotImplemented { - module: "cli::commands::start", - }) +/// The port the capture refuses outside `1..=65535`, with its one message. +pub const PORT_MESSAGE: &str = "Port must be a safe integer between 1 and 65535"; + +/// The `DEBUG` default `--debug` sets when the operator has not chosen one. +const DEFAULT_DEBUG: &str = "primary:*,worker:*,knex:*"; + +/// The parsed `start` flags. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StartOptions { + pub tor: bool, + pub i2p: bool, + pub nginx: bool, + pub debug: bool, + pub detach: bool, + /// The raw `--port` value, validated here rather than by the argument parser: the capture + /// accepts `--port abc` and refuses it with its own message at exit 1. + pub port: Option, +} + +/// Runs `start` on a runtime the command owns. +pub fn run( + context: &Context, + options: &StartOptions, + passthrough: &[String], +) -> Result { + context.block_on(start(context, options, passthrough)) +} + +/// `runStart`. +pub(crate) async fn start( + context: &Context, + options: &StartOptions, + passthrough: &[String], +) -> Result { + ensure_not_root().await?; + + let port = match &options.port { + Some(raw) => Some(parse_port(raw)?), + None => None, + }; + + ensure_config_bootstrap(&context.cwd)?; + + let mut files: Vec = vec!["docker-compose.yml".to_owned()]; + + if options.tor { + ensure_tor_data_dir(&context.cwd)?; + files.push("docker-compose.tor.yml".to_owned()); + } + + if options.i2p { + ensure_i2p_data_dir(&context.cwd)?; + files.push("docker-compose.i2p.yml".to_owned()); + } + + if options.nginx { + let domain = nginx_configuration(&context.env)?; + crate::compose::ensure_nginx_bootstrap(&context.cwd, &domain).await?; + files.push("docker-compose.nginx.yml".to_owned()); + } + + let override_file = match port { + Some(port) => { + let file = create_port_override(port)?; + files.push(file.display().to_string()); + Some(file) + } + None => None, + }; + + let mut environment: Vec<(&str, String)> = Vec::new(); + if options.debug { + environment.push(( + "DEBUG", + context + .env + .get("DEBUG") + .unwrap_or_else(|| DEFAULT_DEBUG.to_owned()), + )); + } + + let mut up: Vec = vec![ + "up".to_owned(), + "--build".to_owned(), + "--remove-orphans".to_owned(), + ]; + if options.detach { + up.push("-d".to_owned()); + } + up.extend( + passthrough + .iter() + .filter(|argument| argument.as_str() != "--") + .cloned(), + ); + + let named: Vec<&str> = files.iter().map(String::as_str).collect(); + let outcome = run_compose(&context.cwd, &named, &up, &environment).await; + + if let Some(file) = override_file + && file.exists() + { + let _ = std::fs::remove_file(&file); + } + + let code = outcome?; + Ok(CommandOutput::with_code( + Vec::new(), + u8::try_from(code).unwrap_or(1), + )) +} + +/// The capture's port check: a safe integer in `1..=65535`, one message for every refusal. +pub fn parse_port(raw: &str) -> Result { + let trimmed = raw.trim(); + let digits = trimmed.strip_prefix('+').unwrap_or(trimmed); + + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(CliError::command(PORT_MESSAGE)); + } + + match trimmed.parse::() { + Ok(port) if port >= 1 => Ok(port), + _ => Err(CliError::command(PORT_MESSAGE)), + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + #[test] + fn the_port_range_and_its_one_message() { + assert_eq!(parse_port("9999").unwrap(), 9999); + for bad in ["0", "70000", "abc", "", "-1", "12.5"] { + let error = parse_port(bad).unwrap_err(); + assert_eq!(error.to_string(), PORT_MESSAGE, "`{bad}` is refused"); + } + } } diff --git a/crates/nostream-cli/src/commands/stop.rs b/crates/nostream-cli/src/commands/stop.rs index 5124a2781..3674145ba 100644 --- a/crates/nostream-cli/src/commands/stop.rs +++ b/crates/nostream-cli/src/commands/stop.rs @@ -1,10 +1,125 @@ -//! `stop.ts`. +//! `stop.ts`: stop the Docker Compose stack, selecting the overlays the flags name. +//! +//! The capture's default is the interesting half (`src/cli/commands/stop.ts:9`): **no** overlay +//! flag means *all four*, because a stack started with `--tor` must still stop when the operator +//! types plain `stop`. +use crate::app::Context; +use crate::compose::run_compose; +use crate::config::CommandOutput; use crate::error::CliError; -/// Phase 1 stub — job 005; will stops the relay stack; see `src/cli/commands/stop.ts`. -pub fn run() -> Result<(), CliError> { - Err(CliError::NotImplemented { - module: "cli::commands::stop", - }) +/// The parsed `stop` flags. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StopOptions { + pub tor: bool, + pub i2p: bool, + pub nginx: bool, + pub local: bool, + pub all: bool, +} + +impl StopOptions { + /// Every overlay, which `update` and `clean` ask for. + pub fn every_overlay() -> Self { + Self { + all: true, + ..Self::default() + } + } +} + +/// The overlay files `stop` names, base file first. +pub fn compose_files(options: &StopOptions) -> Vec { + let include_all = + options.all || (!options.tor && !options.i2p && !options.nginx && !options.local); + + let mut files = vec!["docker-compose.yml".to_owned()]; + + if include_all || options.tor { + files.push("docker-compose.tor.yml".to_owned()); + } + if include_all || options.i2p { + files.push("docker-compose.i2p.yml".to_owned()); + } + if include_all || options.nginx { + files.push("docker-compose.nginx.yml".to_owned()); + } + if include_all || options.local { + files.push("docker-compose.local.yml".to_owned()); + } + + files +} + +/// Runs `stop` on a runtime the command owns. +pub fn run( + context: &Context, + options: &StopOptions, + passthrough: &[String], +) -> Result { + context.block_on(stop(context, options, passthrough)) +} + +/// `runStop`: `docker compose -f … down …`, answering the child's exit code. +pub(crate) async fn stop( + context: &Context, + options: &StopOptions, + passthrough: &[String], +) -> Result { + let files = compose_files(options); + let mut args = vec!["down".to_owned()]; + args.extend(passthrough.iter().cloned()); + + let named: Vec<&str> = files.iter().map(String::as_str).collect(); + let code = run_compose(&context.cwd, &named, &args, &[]).await?; + Ok(CommandOutput::with_code( + Vec::new(), + u8::try_from(code).unwrap_or(1), + )) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + /// Every overlay file `stop` can name, in the order it names them. + fn all() -> Vec { + [ + "docker-compose.yml", + "docker-compose.tor.yml", + "docker-compose.i2p.yml", + "docker-compose.nginx.yml", + "docker-compose.local.yml", + ] + .map(str::to_owned) + .to_vec() + } + + #[test] + fn no_flag_means_every_overlay() { + assert_eq!(compose_files(&StopOptions::default()), all()); + } + + #[test] + fn one_flag_selects_only_its_overlay() { + let tor = StopOptions { + tor: true, + ..StopOptions::default() + }; + assert_eq!( + compose_files(&tor), + vec![ + "docker-compose.yml".to_owned(), + "docker-compose.tor.yml".to_owned() + ] + ); + } + + #[test] + fn all_is_every_overlay_too() { + assert_eq!(compose_files(&StopOptions::every_overlay()), all()); + } } diff --git a/crates/nostream-cli/src/compose.rs b/crates/nostream-cli/src/compose.rs new file mode 100644 index 000000000..396fa7e59 --- /dev/null +++ b/crates/nostream-cli/src/compose.rs @@ -0,0 +1,269 @@ +//! The Docker Compose argv, the port-override file and the nginx bootstrap: the half of `start` +//! and `stop` that builds a command line rather than running one. +//! +//! Mirrors `src/cli/utils/docker.ts` and `ensureNginxBootstrap` +//! (`src/cli/commands/start.ts:15-69`). A compose file is named only when it exists in the +//! working directory, which is what lets a checkout without the overlays still start. + +use std::path::{Path, PathBuf}; + +use nostream_services::process::{CapturedResult, SpawnFailure}; + +use crate::bootstrap::project_path; +use crate::error::CliError; + +/// One compose invocation's files, in the order the flags named them. +pub fn compose_args(cwd: &Path, files: &[&str], args: &[String]) -> Vec { + let mut out = vec!["compose".to_owned()]; + + for file in files { + let path = project_path(cwd, &[file]); + if path.exists() { + out.push("-f".to_owned()); + out.push(path.display().to_string()); + } + } + + out.extend(args.iter().cloned()); + out +} + +/// `runDockerCompose`: `docker compose -f … args`, with the child's stdio inherited. +pub async fn run_compose( + cwd: &Path, + files: &[&str], + args: &[String], + env: &[(&str, String)], +) -> Result { + let mut argv = vec!["docker".to_owned()]; + argv.extend(compose_args(cwd, files, args)); + + nostream_services::process::run(&argv, env) + .await + .map_err(|failure| CliError::command(failure.to_string())) +} + +/// `createPortOverrideComposeFile`: a temporary compose file that rebinds the relay's port. +/// +/// The name carries the process id and the millisecond clock, exactly as the capture's does, so +/// two starts in one second cannot share a file. +pub fn create_port_override(port: u16) -> Result { + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_millis()) + .unwrap_or(0); + let file = std::env::temp_dir().join(format!( + "nostream-port-override-{}-{millis}.yml", + std::process::id() + )); + + let content = [ + "services:".to_owned(), + " nostream:".to_owned(), + " environment:".to_owned(), + format!(" RELAY_PORT: {port}"), + " ports:".to_owned(), + format!(" - 127.0.0.1:{port}:{port}"), + ] + .join("\n"); + + std::fs::write(&file, content).map_err(|error| { + CliError::command(format!("unable to write {}: {error}", file.display())) + })?; + + Ok(file) +} + +/// `ensureNginxBootstrap`: render the nginx site from its template and, when the certificates are +/// missing, mint a self-signed pair with `openssl`. +pub async fn ensure_nginx_bootstrap(cwd: &Path, relay_domain: &str) -> Result<(), CliError> { + let conf_dir = project_path(cwd, &["nginx", "conf.d"]); + let template = conf_dir.join("nostream.conf.template"); + let rendered = conf_dir.join("nostream.conf"); + + let content = std::fs::read_to_string(&template).map_err(|error| { + CliError::command(format!("unable to read {}: {error}", template.display())) + })?; + std::fs::write(&rendered, content.replace("${RELAY_DOMAIN}", relay_domain)).map_err( + |error| CliError::command(format!("unable to write {}: {error}", rendered.display())), + )?; + + let ssl_dir = project_path(cwd, &["nginx", "ssl", "live", relay_domain]); + let fullchain = ssl_dir.join("fullchain.pem"); + let privkey = ssl_dir.join("privkey.pem"); + + if fullchain.exists() && privkey.exists() { + return Ok(()); + } + + std::fs::create_dir_all(&ssl_dir).map_err(|error| { + CliError::command(format!("unable to create {}: {error}", ssl_dir.display())) + })?; + + let argv: Vec = [ + "openssl".to_owned(), + "req".to_owned(), + "-x509".to_owned(), + "-nodes".to_owned(), + "-newkey".to_owned(), + "rsa:2048".to_owned(), + "-days".to_owned(), + "1".to_owned(), + "-keyout".to_owned(), + privkey.display().to_string(), + "-out".to_owned(), + fullchain.display().to_string(), + "-subj".to_owned(), + format!("/CN={relay_domain}"), + ] + .to_vec(); + + let code = nostream_services::process::run(&argv, &[]) + .await + .map_err(|failure: SpawnFailure| CliError::command(failure.to_string()))?; + + if code != 0 { + return Err(CliError::command( + "Failed to generate self-signed SSL certificate. Ensure openssl is installed and retry.", + )); + } + + Ok(()) +} + +/// The `RELAY_DOMAIN`/`CERTBOT_EMAIL` checks `--nginx` runs before it renders anything. +pub fn nginx_configuration(env: &crate::env_file::Environment) -> Result { + let Some(domain) = env.get("RELAY_DOMAIN").map(|value| value.trim().to_owned()) else { + return Err(CliError::command( + "RELAY_DOMAIN environment variable is required when using --nginx (example: \ + RELAY_DOMAIN=relay.example.com).", + )); + }; + + if domain.is_empty() { + return Err(CliError::command( + "RELAY_DOMAIN environment variable is required when using --nginx (example: \ + RELAY_DOMAIN=relay.example.com).", + )); + } + + if !is_fqdn(&domain) { + return Err(CliError::command( + "RELAY_DOMAIN must be a valid fully-qualified domain name when using --nginx.", + )); + } + + match env + .get("CERTBOT_EMAIL") + .map(|value| value.trim().to_owned()) + { + Some(email) if !email.is_empty() => Ok(domain), + _ => Err(CliError::command( + "CERTBOT_EMAIL environment variable is required when using --nginx (example: \ + CERTBOT_EMAIL=you@example.com).", + )), + } +} + +/// The capture's `FQDN_REGEX` (`src/cli/commands/start.ts:12-13`): dot-separated labels, each +/// starting and ending alphanumeric, at most 63 characters. +pub fn is_fqdn(value: &str) -> bool { + let labels: Vec<&str> = value.split('.').collect(); + if labels.len() < 2 { + return false; + } + + labels.iter().all(|label| { + !label.is_empty() + && label.len() <= 63 + && label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + && label + .as_bytes() + .first() + .is_some_and(u8::is_ascii_alphanumeric) + && label + .as_bytes() + .last() + .is_some_and(u8::is_ascii_alphanumeric) + }) +} + +/// The capture's `runCommandWithOutput` answer for a docker probe, as the two `info` paths read +/// it: stdout when the child exited 0, and nothing otherwise. +pub fn captured_stdout(result: &CapturedResult) -> Option { + match result { + CapturedResult::Exited { + code: 0, stdout, .. + } => Some(stdout.trim().to_owned()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + #[test] + fn an_fqdn_needs_two_labels() { + assert!(is_fqdn("relay.example.com")); + assert!(is_fqdn("r-1.example")); + assert!(!is_fqdn("localhost")); + assert!(!is_fqdn("-bad.example")); + assert!(!is_fqdn("bad-.example")); + assert!(!is_fqdn("example..com")); + assert!(!is_fqdn("")); + } + + #[test] + fn only_existing_compose_files_are_named() { + let directory = tempfile::tempdir().expect("a temporary directory"); + std::fs::write( + directory.path().join("docker-compose.yml"), + "services: {}\n", + ) + .expect("the base file"); + + let args = compose_args( + directory.path(), + &["docker-compose.yml", "docker-compose.tor.yml"], + &["down".to_owned()], + ); + + assert_eq!(args[0], "compose"); + assert!(args.contains(&"-f".to_owned())); + assert!( + args.iter() + .any(|argument| argument.ends_with("docker-compose.yml")) + ); + assert!( + !args + .iter() + .any(|argument| argument.ends_with("docker-compose.tor.yml")), + "a missing overlay is not named" + ); + assert_eq!(args.last().map(String::as_str), Some("down")); + } + + #[test] + fn the_port_override_carries_the_captures_body() { + let file = create_port_override(9999).expect("the override writes"); + let content = std::fs::read_to_string(&file).expect("the override reads"); + assert_eq!( + content, + "services:\n nostream:\n environment:\n RELAY_PORT: 9999\n ports:\n - \ + 127.0.0.1:9999:9999" + ); + assert!( + file.file_name() + .and_then(|name| name.to_str()) + .is_some_and( + |name| name.starts_with("nostream-port-override-") && name.ends_with(".yml") + ) + ); + std::fs::remove_file(&file).expect("the override is removed"); + } +} diff --git a/crates/nostream-cli/src/compression.rs b/crates/nostream-cli/src/compression.rs new file mode 100644 index 000000000..dd1063181 --- /dev/null +++ b/crates/nostream-cli/src/compression.rs @@ -0,0 +1,243 @@ +//! The two compressed export shapes: gzip and xz, their format names and their environment knobs. +//! +//! Mirrors `src/utils/compression.ts`. The xz preset and thread cap are the capture's — 6 and 4, +//! one core left to the relay — and both environment overrides keep its messages +//! (`Invalid NOSTREAM_XZ_PRESET: 10. Expected an integer between 0 and 9.`). + +use std::io::Write; +use std::path::Path; + +use crate::env_file::Environment; +use crate::error::CliError; + +/// The compression a compressed export writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Compression { + Gzip, + Xz, +} + +/// `DEFAULT_XZ_PRESET` and `DEFAULT_MAX_XZ_THREADS` (`src/utils/compression.ts:15-16`). +const DEFAULT_XZ_PRESET: u32 = 6; +const DEFAULT_MAX_XZ_THREADS: usize = 4; +const MIN_XZ_PRESET: u32 = 0; +const MAX_XZ_PRESET: u32 = 9; + +impl Compression { + /// The label the summary lines print. + pub fn label(self) -> &'static str { + match self { + Self::Gzip => "gzip", + Self::Xz => "xz", + } + } + + /// `parseCompressionFormat`: `gzip`/`gz` and `xz`, case- and space-insensitive. + pub fn parse(token: &str) -> Option { + match token.trim().to_ascii_lowercase().as_str() { + "gzip" | "gz" => Some(Self::Gzip), + "xz" => Some(Self::Xz), + _ => None, + } + } + + /// `getCompressionFormatFromExtension`: `.gz` and `.xz`. + pub fn from_extension(path: &Path) -> Option { + match path + .extension() + .and_then(|extension| extension.to_str()) + .map(str::to_ascii_lowercase) + .as_deref() + { + Some("gz") => Some(Self::Gzip), + Some("xz") => Some(Self::Xz), + _ => None, + } + } +} + +/// The xz encoder's knobs, resolved from the environment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct XzOptions { + pub preset: u32, + /// The threads this run may use. `xz2` 0.1 exposes no multithreaded encoder, so the number is + /// resolved and validated here and does not reach the encoder: + /// + /// shortcut: the xz stream is written single-threaded; upgrade when `xz2` exposes + /// `lzma_stream_encoder_mt`, which is the only way this number can take effect. + pub threads: usize, +} + +/// `getXzCompressionOptions`: the preset, then the thread cap. +pub fn xz_options(env: &Environment) -> Result { + let preset = match parse_integer("NOSTREAM_XZ_PRESET", env)? { + Some(preset) => u32::try_from(preset).unwrap_or(0), + None => DEFAULT_XZ_PRESET, + }; + + if !(MIN_XZ_PRESET..=MAX_XZ_PRESET).contains(&preset) { + return Err(CliError::command(format!( + "Invalid NOSTREAM_XZ_PRESET: {preset}. Expected an integer between {MIN_XZ_PRESET} \ + and {MAX_XZ_PRESET}." + ))); + } + + let cap = match parse_integer("NOSTREAM_XZ_THREADS", env)? { + Some(threads) => { + if threads <= 0 { + return Err(CliError::command( + "Invalid NOSTREAM_XZ_THREADS: expected a positive integer.", + )); + } + usize::try_from(threads).unwrap_or(DEFAULT_MAX_XZ_THREADS) + } + None => DEFAULT_MAX_XZ_THREADS, + }; + + let available = std::thread::available_parallelism() + .map(|count| count.get().saturating_sub(1).max(1)) + .unwrap_or(1); + + Ok(XzOptions { + preset, + threads: available.min(cap).max(1), + }) +} + +/// `parseIntegerEnv`: an unset or blank value is absent; anything else must be an integer. +fn parse_integer(key: &str, env: &Environment) -> Result, CliError> { + let Some(raw) = env.get(key) else { + return Ok(None); + }; + let trimmed = raw.trim(); + + if trimmed.is_empty() { + return Ok(None); + } + + let digits = trimmed.strip_prefix('-').unwrap_or(trimmed); + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(CliError::command(format!( + "Invalid {key}: {raw}. Expected an integer." + ))); + } + + trimmed + .parse::() + .map(Some) + .map_err(|_| CliError::command(format!("Invalid {key}: {raw}. Expected an integer."))) +} + +/// A writer that compresses `inner` in `format`. +/// +/// The xz encoder's preset comes from the environment, so this can fail; gzip's cannot. +pub fn encoder<'a, W: Write + 'a>( + format: Compression, + inner: W, + env: &Environment, +) -> Result, CliError> { + match format { + Compression::Gzip => Ok(Box::new(flate2::write::GzEncoder::new( + inner, + flate2::Compression::default(), + ))), + Compression::Xz => { + let options = xz_options(env)?; + Ok(Box::new(xz2::write::XzEncoder::new(inner, options.preset))) + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + use std::collections::BTreeMap; + + fn environment(pairs: &[(&str, &str)]) -> Environment { + let table: BTreeMap = pairs + .iter() + .map(|(key, value)| ((*key).to_owned(), (*value).to_owned())) + .collect(); + Environment::from_values(table) + } + + #[test] + fn the_two_formats_parse_by_their_names() { + assert_eq!(Compression::parse("gzip"), Some(Compression::Gzip)); + assert_eq!(Compression::parse("GZ"), Some(Compression::Gzip)); + assert_eq!(Compression::parse("xz"), Some(Compression::Xz)); + assert_eq!(Compression::parse("bzip2"), None); + } + + #[test] + fn the_extension_names_the_format() { + assert_eq!( + Compression::from_extension(Path::new("out.jsonl.gz")), + Some(Compression::Gzip) + ); + assert_eq!( + Compression::from_extension(Path::new("out.xz")), + Some(Compression::Xz) + ); + assert_eq!(Compression::from_extension(Path::new("out.jsonl")), None); + } + + #[test] + fn the_preset_defaults_to_six_and_is_capped() { + assert_eq!(xz_options(&environment(&[])).unwrap().preset, 6); + assert_eq!( + xz_options(&environment(&[("NOSTREAM_XZ_PRESET", "9")])) + .unwrap() + .preset, + 9 + ); + + let error = xz_options(&environment(&[("NOSTREAM_XZ_PRESET", "10")])).unwrap_err(); + assert_eq!( + error.to_string(), + "Invalid NOSTREAM_XZ_PRESET: 10. Expected an integer between 0 and 9." + ); + + let error = xz_options(&environment(&[("NOSTREAM_XZ_THREADS", "0")])).unwrap_err(); + assert_eq!( + error.to_string(), + "Invalid NOSTREAM_XZ_THREADS: expected a positive integer." + ); + + let error = xz_options(&environment(&[("NOSTREAM_XZ_PRESET", "high")])).unwrap_err(); + assert_eq!( + error.to_string(), + "Invalid NOSTREAM_XZ_PRESET: high. Expected an integer." + ); + } + + #[test] + fn the_threads_never_exceed_the_cap_or_the_cores() { + let options = xz_options(&environment(&[("NOSTREAM_XZ_THREADS", "2")])).unwrap(); + assert!(options.threads >= 1 && options.threads <= 2); + } + + #[test] + fn gzip_output_starts_with_its_magic() { + let mut buffer = Vec::new(); + { + let mut encoder = encoder(Compression::Gzip, &mut buffer, &environment(&[])).unwrap(); + encoder.write_all(b"hello world\n").unwrap(); + encoder.flush().unwrap(); + } + assert_eq!(&buffer[..2], &[0x1f, 0x8b]); + } + + #[test] + fn xz_output_starts_with_its_magic() { + let mut buffer = Vec::new(); + { + let mut encoder = encoder(Compression::Xz, &mut buffer, &environment(&[])).unwrap(); + encoder.write_all(b"hello world\n").unwrap(); + encoder.flush().unwrap(); + } + assert_eq!(&buffer[..6], &[0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00]); + } +} diff --git a/crates/nostream-cli/src/config.rs b/crates/nostream-cli/src/config.rs index 07ca3b207..e15405192 100644 --- a/crates/nostream-cli/src/config.rs +++ b/crates/nostream-cli/src/config.rs @@ -2,17 +2,24 @@ //! //! Defaults resolve from the process working directory (`resources/default-settings.yaml`), //! exactly as `src/utils/settings-paths.ts` does; `--config-dir` overrides `NOSTR_CONFIG_DIR`. +//! +//! Mirrors `src/cli/commands/config.ts`: `list` dumps the merged settings, `get` reads one +//! dot-path, `set` validates the path against the defaults, parses the value, validates the +//! merged result and saves with a backup. Validation findings are reported with the capture's +//! bytes and its class (`Config update rejected by validation:` bare on stderr, exit 1). use std::path::Path; use std::process::ExitCode; -use nostream_config::path::get_by_path; +use chrono::Utc; +use nostream_config::path::{get_by_path, parse_typed_json, parse_value, set_by_path}; +use nostream_config::store::save_with_backup; use nostream_config::{ - SettingsPaths, fit, load, load_defaults, load_document, load_user_settings, merge, - validate_document, + Issue, SettingsPaths, fit, load_defaults, load_user_settings, merge, validate_document, }; use serde_yaml::Value; +use crate::env_file; use crate::error::CliError; /// Resolves the paths, honouring `--config-dir` over the environment. @@ -34,10 +41,63 @@ impl CommandOutput { pub fn exit_code(&self) -> ExitCode { ExitCode::from(self.exit_code) } + + /// Lines on stdout, exit 0. + pub fn print(lines: Vec) -> Self { + Self { + lines, + exit_code: 0, + } + } + + /// Lines on stdout, the given code: the capture's `logInfo` then `return N`. + pub fn with_code(lines: Vec, exit_code: u8) -> Self { + Self { lines, exit_code } + } +} + +/// The defaults document and the merged effective document, without validation. +/// +/// The capture's `loadMergedSettings` merges and does **not** validate: a document the validator +/// dislikes still loads, which is what lets `info`, `invite` and `export` read a store the +/// operator has not finished configuring. `config validate` is the command that says so. +pub fn merged_documents(paths: &SettingsPaths) -> Result<(Value, Value), CliError> { + let defaults = load_defaults(&paths.default_settings_file) + .map_err(|error| CliError::Config(error.to_string()))?; + let user = load_user_settings(&paths.config_base_dir) + .map_err(|error| CliError::Config(error.to_string()))?; + let merged = match &user { + Some(user) => merge(&defaults, user), + None => defaults.clone(), + }; + Ok((defaults, merged)) +} + +/// The merged document as typed settings, which is what a command that opens a store needs. +pub fn effective_settings(paths: &SettingsPaths) -> Result { + let (defaults, merged) = merged_documents(paths)?; + fit(&merged, &defaults).map_err(|issue| CliError::Config(issue.to_string())) +} + +/// Every issue `config validate` and `config set` report: the document walk, then the typed +/// schema, so a document the walk approves but the daemon cannot load is refused with the field +/// named. +pub fn validate_documents(merged: &Value, defaults: &Value) -> Vec { + let mut issues = validate_document(merged, defaults); + if issues.is_empty() + && let Err(issue) = fit(merged, defaults) + { + issues.push(issue); + } + issues } /// `config validate`: print one `path: message` line per issue and exit 2, or confirm a clean /// document and exit 0. +/// +/// **Exit 2 is deliberately not the capture's 1** (`docs/rewrite/decisions/0015-cli-surface.md` +/// D9): the command's exit 2 and `settings valid: N issues` are shipped, tested and agreed with +/// the daemon's `DaemonError::InvalidSettings` → 2 mapping. pub fn validate( paths: &SettingsPaths, config_file: Option<&Path>, @@ -45,9 +105,10 @@ pub fn validate( let defaults = load_defaults(&paths.default_settings_file) .map_err(|error| CliError::Config(error.to_string()))?; let user = match config_file { - Some(file) => { - Some(load_document(file).map_err(|error| CliError::Config(error.to_string()))?) - } + Some(file) => Some( + nostream_config::load_document(file) + .map_err(|error| CliError::Config(error.to_string()))?, + ), None => load_user_settings(&paths.config_base_dir) .map_err(|error| CliError::Config(error.to_string()))?, }; @@ -56,16 +117,7 @@ pub fn validate( None => defaults.clone(), }; - let mut issues = validate_document(&merged, &defaults); - if issues.is_empty() { - // The document walk grades JavaScript types; the typed schema is stricter. A document - // the walk approves but the daemon cannot load (a fractional integer, for one) is - // refused here, with the field named, so `config validate` never blesses a config the - // daemon will discard. - if let Err(issue) = fit(&merged, &defaults) { - issues.push(issue); - } - } + let issues = validate_documents(&merged, &defaults); if issues.is_empty() { return Ok(CommandOutput { @@ -83,42 +135,268 @@ pub fn validate( }) } +/// `config list`: the merged settings as YAML, or as JSON with `--json`. +pub fn list(paths: &SettingsPaths, json: bool) -> Result { + let (_, merged) = merged_documents(paths)?; + + if json { + return Ok(CommandOutput::print(vec![to_json(&merged)?])); + } + + let rendered = + serde_yaml::to_string(&merged).map_err(|error| CliError::Config(error.to_string()))?; + Ok(CommandOutput::print(vec![rendered.trim_end().to_owned()])) +} + /// `config get`: print the value at a dot-path from the effective settings. +/// +/// A missing path is the capture's `Path not found: `, reported bare (`logError`) or as the +/// JSON envelope when the caller asked for `--json`. pub fn get(paths: &SettingsPaths, path: &str, json: bool) -> Result { - let defaults = load_defaults(&paths.default_settings_file) - .map_err(|error| CliError::Config(error.to_string()))?; - let user = load_user_settings(&paths.config_base_dir) - .map_err(|error| CliError::Config(error.to_string()))?; - let merged = match user { - Some(user) => merge(&defaults, &user), - None => defaults.clone(), - }; + let (_, merged) = merged_documents(paths)?; let Some(value) = get_by_path(&merged, path).map_err(|error| CliError::Config(error.to_string()))? else { - return Err(CliError::Config(format!("settings path not found: {path}"))); + return Err(if json { + CliError::json(format!("Path not found: {path}"), 1) + } else { + CliError::reported_line(format!("Path not found: {path}")) + }); }; let rendered = if json { - serde_json::to_string(&value).map_err(|error| CliError::Config(error.to_string()))? + to_json(value)? } else { + serialize(value)? + }; + + Ok(CommandOutput::print(vec![rendered])) +} + +/// The value type `config set --type` names. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ValueType { + /// `parseValue`: booleans, null, integers, bigints and JSON literals, else the raw string. + Inferred, + /// `JSON.parse`. + Json, +} + +impl ValueType { + pub fn parse(value: &str) -> Option { match value { - Value::String(text) => text.clone(), - Value::Null => "null".to_owned(), - other => { - serde_json::to_string(other).map_err(|error| CliError::Config(error.to_string()))? - } + "inferred" => Some(Self::Inferred), + "json" => Some(Self::Json), + _ => None, + } + } +} + +/// `config set `: validate the path against the defaults, parse the value, +/// validate the merged result unless told not to, save with a backup, print `Updated `. +pub fn set( + paths: &SettingsPaths, + path: &str, + raw_value: &str, + value_type: ValueType, + validate_before_write: bool, +) -> Result { + let defaults = load_defaults(&paths.default_settings_file) + .map_err(|error| CliError::Config(error.to_string()))?; + + let path_issues = nostream_config::path::validate_path_against_defaults(&defaults, path) + .map_err(|error| CliError::Config(error.to_string()))?; + if let Some(issue) = path_issues.first() { + return Err(CliError::reported_line(issue.message.clone())); + } + + let value = match value_type { + ValueType::Inferred => parse_value(raw_value).to_value(), + ValueType::Json => parse_typed_json(raw_value).map_err(CliError::reported_line)?, + }; + + let user = load_user_settings(&paths.config_base_dir) + .map_err(|error| CliError::Config(error.to_string()))? + .unwrap_or(Value::Mapping(Default::default())); + let next = + set_by_path(&user, path, value).map_err(|error| CliError::Config(error.to_string()))?; + + if validate_before_write { + let (_, merged) = merged_documents(paths)?; + let introduced = get_by_path(&next, path) + .map_err(|error| CliError::Config(error.to_string()))? + .cloned() + .unwrap_or(Value::Null); + let merged_next = set_by_path(&merged, path, introduced) + .map_err(|error| CliError::Config(error.to_string()))?; + let issues = validate_documents(&merged_next, &defaults); + + if !issues.is_empty() { + let mut lines = vec!["Config update rejected by validation:".to_owned()]; + lines.extend( + issues + .iter() + .map(|issue| format!("- {}: {}", issue.path, issue.message)), + ); + return Err(CliError::Reported { + lines, + exit_code: 1, + }); } + } + + save(paths, &next)?; + + Ok(CommandOutput::print(vec![format!("Updated {path}")])) +} + +/// Writes the settings document with a timestamped backup of the previous file. +pub fn save(paths: &SettingsPaths, document: &Value) -> Result<(), CliError> { + save_with_backup(paths, document, Utc::now()) + .map_err(|error| CliError::Config(error.to_string())) +} + +/// `config env list`: the `.env` table, sorted by key, secrets masked unless `--show-secrets`. +pub fn env_list(cwd: &Path, show_secrets: bool) -> Result { + let environment = env_file::Environment::load(cwd); + let values = environment.file_values(); + + if values.is_empty() { + return Ok(CommandOutput::print(vec![ + "No .env entries found".to_owned(), + ])); + } + + let lines = values + .iter() + .map(|(key, value)| { + let display = if show_secrets || !env_file::is_secret_key(key) { + value.clone() + } else { + env_file::mask_secret_value(value) + }; + format!("{key}={display}") + }) + .collect(); + + Ok(CommandOutput::print(lines)) +} + +/// `config env get `: one masked value, or the capture's two refusals. +pub fn env_get(cwd: &Path, key: &str, show_secrets: bool) -> Result { + let key = key.trim(); + + if !env_file::is_supported_key(key) { + return Err(CliError::reported_line(format!( + "Unsupported env key: {key}" + ))); + } + + let environment = env_file::Environment::load(cwd); + let Some(value) = environment.file(key) else { + return Err(CliError::reported_line(format!("Env key not set: {key}"))); }; - Ok(CommandOutput { - lines: vec![rendered], - exit_code: 0, + let display = if show_secrets || !env_file::is_secret_key(key) { + value.to_owned() + } else { + env_file::mask_secret_value(value) + }; + + Ok(CommandOutput::print(vec![display])) +} + +/// `config env set `: validate the pair, then replace or append the line. +pub fn env_set(cwd: &Path, key: &str, value: &str) -> Result { + let key = key.trim(); + + if !env_file::is_supported_key(key) { + return Err(CliError::reported_line(format!( + "Unsupported env key: {key}" + ))); + } + + if let Some(issue) = env_file::validate_pair(key, value) { + return Err(CliError::reported_line(issue)); + } + + let path = cwd.join(".env"); + let content = std::fs::read_to_string(&path).unwrap_or_default(); + let next = env_file::upsert_value(&content, key, value); + std::fs::write(&path, next).map_err(|error| { + CliError::Config(format!("unable to write {}: {error}", path.display())) + })?; + + Ok(CommandOutput::print(vec![format!("Updated {key}")])) +} + +/// `config env validate`: the label-form finding lines, or the confirmation. +pub fn env_validate(cwd: &Path) -> Result { + let environment = env_file::Environment::load(cwd); + let issues = env_file::validate_values(environment.file_values()); + + if issues.is_empty() { + return Ok(CommandOutput::print(vec![ + "Environment settings are valid".to_owned(), + ])); + } + + let mut lines = vec!["Environment validation failed:".to_owned()]; + lines.extend( + issues.iter().map(|(key, message)| { + format!("- {} ({key}): {message}", env_file::category_label(key)) + }), + ); + + Err(CliError::Reported { + lines, + exit_code: 1, }) } -/// Loads the effective settings the way the daemon does (defaults on any failure). -pub fn effective(paths: &SettingsPaths) -> Result { - load(paths).map_err(|error| CliError::Config(error.to_string())) +/// `JSON.stringify(value, null, 2)`, with a bigint rendered as its digits. +pub fn to_json(value: &Value) -> Result { + let json = serde_json::to_value(value).map_err(|error| CliError::Config(error.to_string()))?; + serde_json::to_string_pretty(&json).map_err(|error| CliError::Config(error.to_string())) +} + +/// The capture's `serialize`: a string verbatim, `null` as `null`, everything else as YAML with +/// the trailing newline trimmed. +pub fn serialize(value: &Value) -> Result { + match value { + Value::String(text) => Ok(text.clone()), + Value::Null => Ok("null".to_owned()), + other => { + let rendered = serde_yaml::to_string(other) + .map_err(|error| CliError::Config(error.to_string()))?; + Ok(rendered.trim_end().to_owned()) + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + #[test] + fn a_string_serialises_verbatim_and_null_as_null() { + assert_eq!(serialize(&Value::String("abc".to_owned())).unwrap(), "abc"); + assert_eq!(serialize(&Value::Null).unwrap(), "null"); + } + + #[test] + fn a_number_serialises_as_yaml() { + let value: Value = serde_yaml::from_str("2048").unwrap(); + assert_eq!(serialize(&value).unwrap(), "2048"); + } + + #[test] + fn the_value_types_parse_by_their_names() { + assert_eq!(ValueType::parse("inferred"), Some(ValueType::Inferred)); + assert_eq!(ValueType::parse("json"), Some(ValueType::Json)); + assert_eq!(ValueType::parse("yaml"), None); + } } diff --git a/crates/nostream-cli/src/env_file.rs b/crates/nostream-cli/src/env_file.rs new file mode 100644 index 000000000..fd3304039 --- /dev/null +++ b/crates/nostream-cli/src/env_file.rs @@ -0,0 +1,370 @@ +//! The `.env` file, and the environment as the CLI reads it. +//! +//! Mirrors `src/cli/utils/env-config.ts` (the key tables, the validators, the secret mask and +//! the upsert) and the one behaviour the capture gets from its entry points rather than its +//! code: every `pnpm run cli` runs under `node --env-file-if-exists=.env` +//! (`package.json:58`), so a value in `.env` is in the environment unless the process already +//! set it. That order — process first, file second — is what [`Environment::get`] answers. +//! +//! The file is read, never written through the environment: this crate cannot call +//! `std::env::set_var` (it is `unsafe` in edition 2024 and the workspace denies unsafe code), so +//! the `.env` layer is a lookup every caller goes through instead of a mutation. + +use std::collections::BTreeMap; +use std::path::Path; + +/// The environment one command sees: the process's variables, then the `.env` file's. +#[derive(Debug, Clone, Default)] +pub struct Environment { + file: BTreeMap, +} + +impl Environment { + /// Reads `/.env` when it exists; a missing file is an empty layer. + pub fn load(cwd: &Path) -> Self { + let path = cwd.join(".env"); + match std::fs::read_to_string(&path) { + Ok(content) => Self { + file: parse_values(&content), + }, + Err(_) => Self::default(), + } + } + + /// An environment with no file layer, which is what unit tests build. + pub fn empty() -> Self { + Self::default() + } + + /// An environment whose file layer is the given table. + pub fn from_values(file: BTreeMap) -> Self { + Self { file } + } + + /// One value: the process's, else the file's. + pub fn get(&self, key: &str) -> Option { + std::env::var(key) + .ok() + .filter(|value| !value.is_empty()) + .or_else(|| self.file.get(key).cloned()) + } + + /// One value from the file layer alone, ignoring the process environment. + pub fn file(&self, key: &str) -> Option<&str> { + self.file.get(key).map(String::as_str) + } + + /// The file layer, for `config env list` and `validate`. + pub fn file_values(&self) -> &BTreeMap { + &self.file + } +} + +/// The key tables (`src/cli/utils/env-config.ts:18-73`). +const SUPPORTED_KEYS: &[&str] = &[ + "SECRET", + "RELAY_PORT", + "RELAY_PRIVATE_KEY", + "MONITOR_PRIVATE_KEY", + "WORKER_COUNT", + "DB_URI", + "DB_HOST", + "DB_PORT", + "DB_USER", + "DB_PASSWORD", + "DB_NAME", + "DB_MIN_POOL_SIZE", + "DB_MAX_POOL_SIZE", + "DB_ACQUIRE_CONNECTION_TIMEOUT", + "READ_REPLICA_ENABLED", + "READ_REPLICAS", + "TOR_HOST", + "TOR_CONTROL_PORT", + "TOR_PASSWORD", + "HIDDEN_SERVICE_PORT", + "REDIS_URI", + "REDIS_HOST", + "REDIS_PORT", + "REDIS_USER", + "REDIS_PASSWORD", + "NOSTR_CONFIG_DIR", + "DEBUG", + "ZEBEDEE_API_KEY", + "NODELESS_API_KEY", + "NODELESS_WEBHOOK_SECRET", + "OPENNODE_API_KEY", + "LNBITS_API_KEY", + "LOG_LEVEL", +]; + +const INTEGER_KEYS: &[&str] = &[ + "RELAY_PORT", + "WORKER_COUNT", + "DB_PORT", + "DB_MIN_POOL_SIZE", + "DB_MAX_POOL_SIZE", + "DB_ACQUIRE_CONNECTION_TIMEOUT", + "READ_REPLICAS", + "TOR_CONTROL_PORT", + "HIDDEN_SERVICE_PORT", + "REDIS_PORT", +]; + +const BOOLEAN_KEYS: &[&str] = &["READ_REPLICA_ENABLED"]; + +/// `RR\d+_DB_(…)` — the read-replica family, which the key table accepts by shape. +fn is_replica_key(key: &str) -> bool { + const SUFFIXES: &[&str] = &[ + "HOST", + "PORT", + "USER", + "PASSWORD", + "NAME", + "MIN_POOL_SIZE", + "MAX_POOL_SIZE", + "ACQUIRE_CONNECTION_TIMEOUT", + ]; + let Some(rest) = key.strip_prefix("RR") else { + return false; + }; + let Some((index, suffix)) = rest.split_once("_DB_") else { + return false; + }; + !index.is_empty() + && index.bytes().all(|byte| byte.is_ascii_digit()) + && SUFFIXES.contains(&suffix) +} + +fn is_replica_integer_key(key: &str) -> bool { + const SUFFIXES: &[&str] = &[ + "PORT", + "MIN_POOL_SIZE", + "MAX_POOL_SIZE", + "ACQUIRE_CONNECTION_TIMEOUT", + ]; + let Some(rest) = key.strip_prefix("RR") else { + return false; + }; + let Some((index, suffix)) = rest.split_once("_DB_") else { + return false; + }; + !index.is_empty() + && index.bytes().all(|byte| byte.is_ascii_digit()) + && SUFFIXES.contains(&suffix) +} + +/// Whether `config env` may read or write this key. +pub fn is_supported_key(key: &str) -> bool { + SUPPORTED_KEYS.contains(&key) || is_replica_key(key) +} + +/// Whether the key's value is a secret the list and get commands mask. +pub fn is_secret_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + ["SECRET", "PASSWORD", "API_KEY", "PRIVATE_KEY"] + .iter() + .any(|needle| upper.contains(needle)) +} + +/// The masked form `config env` prints: two characters either side, `***` between; a short value +/// is all stars, and an empty one is `***` (`maskSecretValue`, `src/cli/utils/env-config.ts:206-216`). +pub fn mask_secret_value(value: &str) -> String { + if value.is_empty() { + return "***".to_owned(); + } + + let characters: Vec = value.chars().collect(); + if characters.len() <= 4 { + return "*".repeat(characters.len()); + } + + let head: String = characters[..2].iter().collect(); + let tail: String = characters[characters.len() - 2..].iter().collect(); + format!("{head}***{tail}") +} + +/// `toCategoryLabel` (`src/utils/settings-config.ts:189-195`): the first letter of each +/// `_`/`-`/`.`-separated part raised, then joined with spaces. +pub fn category_label(key: &str) -> String { + key.split(['_', '-', '.']) + .filter(|part| !part.is_empty()) + .map(|part| { + let mut characters = part.chars(); + match characters.next() { + Some(first) => first.to_uppercase().collect::() + characters.as_str(), + None => String::new(), + } + }) + .collect::>() + .join(" ") +} + +/// The value checks one key answers, or `None` when the pair is valid +/// (`validateEnvPair`, `src/cli/utils/env-config.ts:138-152`). +pub fn validate_pair(key: &str, value: &str) -> Option { + if !is_supported_key(key) { + return Some(format!("{key} is not a supported environment setting")); + } + + if INTEGER_KEYS.contains(&key) || is_replica_integer_key(key) { + let trimmed = value.trim(); + let digits = trimmed.strip_prefix('-').unwrap_or(trimmed); + if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) { + return Some(format!("{key} must be an integer")); + } + if trimmed.parse::().is_err() { + return Some(format!("{key} must be a safe integer")); + } + return None; + } + + if BOOLEAN_KEYS.contains(&key) { + let normalized = value.trim().to_ascii_lowercase(); + if normalized != "true" && normalized != "false" { + return Some(format!("{key} must be true or false")); + } + } + + None +} + +/// Every invalid pair in a `.env` table, in key order. +pub fn validate_values(values: &BTreeMap) -> Vec<(String, String)> { + values + .iter() + .filter_map(|(key, value)| validate_pair(key, value).map(|message| (key.clone(), message))) + .collect() +} + +/// The `KEY=VALUE` pairs a `.env` document holds, in file order collapsed to key order. +/// +/// A comment line and a line that is not `KEY=…` are skipped, exactly as the capture's +/// `ENV_LINE_REGEX` parse does; the value keeps everything after the first `=`. +pub fn parse_values(content: &str) -> BTreeMap { + let mut values = BTreeMap::new(); + + for line in content.split('\n') { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let key = key.trim(); + if key.is_empty() + || !key + .chars() + .next() + .is_some_and(|first| first.is_ascii_alphabetic() || first == '_') + { + continue; + } + if !key + .chars() + .all(|character| character.is_ascii_alphanumeric() || character == '_') + { + continue; + } + values.insert(key.to_owned(), value.trim().to_owned()); + } + + values +} + +/// `upsertEnvValue`: replaces the key's first line, or appends `KEY=VALUE` after a blank line, +/// and leaves the document newline-terminated (`src/cli/utils/env-config.ts:165-182`). +pub fn upsert_value(content: &str, key: &str, value: &str) -> String { + let mut lines: Vec = content.split('\n').map(str::to_owned).collect(); + let replacement = format!("{key}={value}"); + + let existing = lines.iter().position(|line| { + let trimmed = line.trim(); + !trimmed.starts_with('#') + && trimmed + .split_once('=') + .is_some_and(|(candidate, _)| candidate.trim() == key) + }); + + match existing { + Some(index) => lines[index] = replacement, + None => { + if lines.last().is_some_and(|line| !line.trim().is_empty()) { + lines.push(String::new()); + } + lines.push(replacement); + } + } + + let mut joined = lines.join("\n"); + if !joined.ends_with('\n') { + joined.push('\n'); + } + joined +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + #[test] + fn a_secret_is_masked_two_characters_either_side() { + assert_eq!(mask_secret_value("abcdef"), "ab***ef"); + assert_eq!(mask_secret_value("abcd"), "****"); + assert_eq!(mask_secret_value(""), "***"); + } + + #[test] + fn the_value_checks_are_the_captures() { + assert_eq!( + validate_pair("FOO", "bar").as_deref(), + Some("FOO is not a supported environment setting") + ); + assert_eq!( + validate_pair("RELAY_PORT", "x").as_deref(), + Some("RELAY_PORT must be an integer") + ); + assert_eq!( + validate_pair("READ_REPLICA_ENABLED", "yes").as_deref(), + Some("READ_REPLICA_ENABLED must be true or false") + ); + assert_eq!(validate_pair("RELAY_PORT", "8008"), None); + assert_eq!(validate_pair("RR1_DB_HOST", "replica"), None); + assert_eq!( + validate_pair("RR1_DB_PORT", "not-a-port").as_deref(), + Some("RR1_DB_PORT must be an integer") + ); + assert!(is_supported_key("RR12_DB_MAX_POOL_SIZE")); + assert!(!is_supported_key("RR_DB_HOST")); + } + + #[test] + fn the_category_label_raises_only_the_first_letter() { + assert_eq!(category_label("FOO"), "FOO"); + // `toCategoryLabel` uppercases each part's first letter and keeps the rest + // (`src/utils/settings-config.ts:190-196`): a part is never lowercased. + assert_eq!(category_label("RR1_DB_HOST"), "RR1 DB HOST"); + } + + #[test] + fn an_upsert_replaces_the_key_or_appends_it() { + assert_eq!( + upsert_value("SECRET=abcdef\nFOO=bar\n", "FOO", "baz"), + "SECRET=abcdef\nFOO=baz\n" + ); + assert_eq!( + upsert_value("SECRET=abcdef\n", "RELAY_PORT", "8008"), + "SECRET=abcdef\n\nRELAY_PORT=8008\n" + ); + } + + #[test] + fn the_parse_skips_comments_and_keeps_the_value_whole() { + let values = parse_values("# a comment\nSECRET=abc=def\n\nnot a pair\nFOO=bar\n"); + assert_eq!(values.get("SECRET").map(String::as_str), Some("abc=def")); + assert_eq!(values.get("FOO").map(String::as_str), Some("bar")); + assert_eq!(values.len(), 2); + } +} diff --git a/crates/nostream-cli/src/error.rs b/crates/nostream-cli/src/error.rs index 96a5826a3..cfe6b82ac 100644 --- a/crates/nostream-cli/src/error.rs +++ b/crates/nostream-cli/src/error.rs @@ -1,4 +1,12 @@ //! The CLI error type. `anyhow` lives in the binary; the library keeps its own type. +//! +//! Three failure **shapes** and their exit codes are the capture's, not this crate's choice +//! (`docs/rewrite/decisions/0015-cli-surface.md` D2): a failure thrown out of a command is +//! prefixed `Error: ` and exits 2 (`Usage`) or 1 (`Command`); a failure the command reports +//! itself is printed bare and exits with the code it chose (`Config`, and `Reported` for more +//! than one line); and a `--json` failure is the capture's `{"error":{…}}` envelope (`Json`). +//! Each command picks its shape from the capture's own class — `src/cli/index.ts:38-42`, +//! `:116-135` and `src/utils/output.ts:27-29` — never by convenience. use thiserror::Error; @@ -9,10 +17,30 @@ pub enum CliError { #[error("not implemented in Phase 1 (job 005): {module}")] NotImplemented { module: &'static str }, - /// A config file or path could not be read. + /// A failure the command reports itself, one line, written to stderr **without** a prefix + /// (`logError`, `src/cli/utils/output.ts:27-29`). Exit code 1. #[error("{0}")] Config(String), + /// A failure the command reports itself, several lines, written verbatim to stderr. Exit + /// code 1, or the code the report carries. + #[error("{}", lines.join(" | "))] + Reported { lines: Vec, exit_code: u8 }, + + /// A thrown usage failure (`CliUsageError`): `Error: ` on stderr, exit code 2. + #[error("{0}")] + Usage(String), + + /// A thrown plain failure (`throw new Error(…)`): `Error: ` on stderr, exit 1. + #[error("{0}")] + Command(String), + + /// A failure in a command that was asked for `--json`: the capture's envelope, + /// `{"error":{"message":…,"code":N}}`, on stderr with exit code `N` + /// (`src/cli/index.ts:129-131`). + #[error("{message}")] + Json { message: String, code: u8 }, + /// The import could not run: a bad argument, a missing file or a storage failure. #[error("{0}")] Import(String), @@ -22,3 +50,36 @@ pub enum CliError { #[error("{0}")] Migrate(String), } + +impl CliError { + /// A reported failure of one line, exit 1: the capture's `logError` sites. + pub fn reported_line(line: impl Into) -> Self { + Self::Config(line.into()) + } + + /// A reported failure of several lines, exit 1. + pub fn reported(lines: Vec) -> Self { + Self::Reported { + lines, + exit_code: 1, + } + } + + /// A thrown plain failure: `Error: ` on stderr, exit 1. + pub fn command(message: impl Into) -> Self { + Self::Command(message.into()) + } + + /// A thrown usage failure: `Error: ` on stderr, exit 2. + pub fn usage(message: impl Into) -> Self { + Self::Usage(message.into()) + } + + /// The `--json` form of a failure, which the capture renders as the envelope. + pub fn json(message: impl Into, code: u8) -> Self { + Self::Json { + message: message.into(), + code, + } + } +} diff --git a/crates/nostream-cli/src/lib.rs b/crates/nostream-cli/src/lib.rs index 752235168..24083a6a6 100644 --- a/crates/nostream-cli/src/lib.rs +++ b/crates/nostream-cli/src/lib.rs @@ -11,11 +11,17 @@ //! Phase 1 implements `config validate` and `config get` end to end; the remaining commands, //! the TUI and the docker/process supervisors are labelled stubs (Phase 2). +pub mod app; +pub mod bootstrap; pub mod commands; +pub mod compose; +pub mod compression; pub mod config; pub mod docker; +pub mod env_file; pub mod error; pub mod process; +pub mod store; pub mod tui; pub use error::CliError; diff --git a/crates/nostream-cli/src/main.rs b/crates/nostream-cli/src/main.rs index 3489932b0..8625ffc4c 100644 --- a/crates/nostream-cli/src/main.rs +++ b/crates/nostream-cli/src/main.rs @@ -7,8 +7,9 @@ use std::path::PathBuf; use std::process::ExitCode; use clap::{Parser, Subcommand}; +use nostream_cli::app::{self, Context}; +use nostream_cli::commands; use nostream_cli::config::CommandOutput; -use nostream_cli::{CliError, commands}; // `import` parses its own arguments, so clap's `help` subcommand would render a second, // contradictory page for it; `--help` is the single help surface. @@ -59,9 +60,58 @@ enum Command { /// Run the first-time setup flow. Setup, /// Start the relay stack. - Start, + 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 { + /// 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, /// Run the interactive settings editor. @@ -165,34 +215,45 @@ fn main() -> ExitCode { }, Command::Seed => commands::seed::run().map(|_| CommandOutput::default()), Command::Setup => commands::setup::run().map(|_| CommandOutput::default()), - Command::Start => commands::start::run().map(|_| CommandOutput::default()), - Command::Stop => commands::stop::run().map(|_| CommandOutput::default()), + Command::Start { + tor, + i2p, + nginx, + debug, + detach, + port, + args, + } => { + let options = commands::start::StartOptions { + tor, + i2p, + nginx, + debug, + detach, + port, + }; + Context::at(cwd).and_then(|context| commands::start::run(&context, &options, &args)) + } + Command::Stop { + tor, + i2p, + nginx, + local, + all, + args, + } => { + let options = commands::stop::StopOptions { + tor, + i2p, + nginx, + local, + all, + }; + Context::at(cwd).and_then(|context| commands::stop::run(&context, &options, &args)) + } Command::Update => commands::update::run().map(|_| CommandOutput::default()), Command::Tui => nostream_cli::tui::run().map(|_| CommandOutput::default()), }; - match result { - Ok(output) => { - for line in &output.lines { - println!("{line}"); - } - output.exit_code() - } - Err(CliError::NotImplemented { module }) => { - eprintln!("not implemented in Phase 1 (job 005): {module}"); - ExitCode::from(1) - } - Err(CliError::Config(message)) => { - eprintln!("{message}"); - ExitCode::from(1) - } - Err(CliError::Import(message)) => { - eprintln!("Import failed: {message}"); - ExitCode::from(1) - } - Err(CliError::Migrate(message)) => { - eprintln!("Migration failed: {message}"); - ExitCode::from(1) - } - } + app::render(result) } diff --git a/crates/nostream-cli/src/store.rs b/crates/nostream-cli/src/store.rs new file mode 100644 index 000000000..3b736e144 --- /dev/null +++ b/crates/nostream-cli/src/store.rs @@ -0,0 +1,220 @@ +//! The store the CLI opens, from the settings' `eventStore.backend` and the command's +//! `--data-dir`. +//! +//! `nostream-cli` is a front end over the store, not a worker: it reads the settings the daemon +//! would read, opens the backend they name and closes it when the command is done. The LMDB +//! store is `/lmdb` — the same layout `migrate pg-to-lmdb --target` writes +//! (`crates/nostream-storage/src/backend.rs:47-52`) — and Postgres is the `DB_*` family, with +//! `DB_URI` winning when both are set (`src/database/client.ts`). + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use nostream_config::Settings; +use nostream_core::EventStoreBackend; +use nostream_storage::repositories::{ + EventRepository, InviteCodeRepository, InvoiceRepository, UserRepository, +}; +use nostream_storage::{LmdbBackend, StorageError, backend}; + +use crate::env_file::Environment; +use crate::error::CliError; + +/// An opened store, one of the two shipped backends. +#[derive(Debug)] +pub enum Opened { + Lmdb(Box), + Postgres(Box), +} + +impl Opened { + /// The event store, whatever backend answered. + pub fn events(&self) -> &dyn EventRepository { + match self { + Self::Lmdb(backend) => backend.as_ref(), + Self::Postgres(backend) => backend.as_ref(), + } + } + + /// The invite-code store. + pub fn invites(&self) -> &dyn InviteCodeRepository { + match self { + Self::Lmdb(backend) => backend.as_ref(), + Self::Postgres(backend) => backend.as_ref(), + } + } + + /// The invoice store. + pub fn invoices(&self) -> &dyn InvoiceRepository { + match self { + Self::Lmdb(backend) => backend.as_ref(), + Self::Postgres(backend) => backend.as_ref(), + } + } + + /// The user store. + pub fn users(&self) -> &dyn UserRepository { + match self { + Self::Lmdb(backend) => backend.as_ref(), + Self::Postgres(backend) => backend.as_ref(), + } + } +} + +/// The backend the settings name, defaulting to Postgres (`configured_backend`). +pub fn selected_backend(settings: &Settings) -> EventStoreBackend { + nostream_storage::event_store::configured_backend(settings) +} + +/// The Postgres connection string the environment describes, or `None` when neither `DB_URI` nor +/// `DB_HOST` is set. +/// +/// `DB_URI` wins. Otherwise the parts are assembled into a URL, with the user and the password +/// percent-encoded: a password holding `@` or `/` is common, and a URL that mis-parses it fails +/// as a wrong host rather than as a wrong password. +pub fn postgres_url(env: &Environment) -> Option { + if let Some(uri) = env.get("DB_URI") { + return Some(uri); + } + + let host = env.get("DB_HOST")?; + let port = env.get("DB_PORT").unwrap_or_else(|| "5432".to_owned()); + let user = env.get("DB_USER").unwrap_or_else(|| "postgres".to_owned()); + let database = env.get("DB_NAME").unwrap_or_else(|| "postgres".to_owned()); + + let credentials = match env.get("DB_PASSWORD") { + Some(password) => format!("{}:{}@", encode_userinfo(&user), encode_userinfo(&password)), + None => format!("{}@", encode_userinfo(&user)), + }; + + Some(format!( + "postgres://{credentials}{host}:{port}/{}", + encode_userinfo(&database) + )) +} + +/// Percent-encodes the characters that would end a userinfo or a path segment. +fn encode_userinfo(value: &str) -> String { + let mut encoded = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b':' => { + encoded.push(char::from(byte)); + } + other => encoded.push_str(&format!("%{other:02X}")), + } + } + encoded +} + +/// The path the LMDB store lives at, `/lmdb`. +pub fn lmdb_store_dir(data_dir: &Path) -> PathBuf { + backend::store_dir(data_dir) +} + +/// Opens the store the settings name. +/// +/// With the lmdb backend and no `--data-dir` the command fails rather than inventing a root: +/// `the lmdb backend needs --data-dir ` (the thrown class, exit 1). +pub async fn open( + settings: &Settings, + data_dir: Option<&Path>, + env: &Environment, +) -> Result { + match selected_backend(settings) { + EventStoreBackend::Lmdb => { + let Some(root) = data_dir else { + return Err(CliError::command( + "the lmdb backend needs --data-dir ", + )); + }; + let store = LmdbBackend::open(root) + .await + .map_err(|error| storage_error(&error))?; + Ok(Opened::Lmdb(Box::new(store))) + } + EventStoreBackend::Postgres => { + let Some(url) = postgres_url(env) else { + return Err(CliError::command( + "PostgreSQL is not configured (set DB_URI or DB_HOST)", + )); + }; + let store = nostream_storage::PostgresBackend::connect(&url) + .await + .map_err(|error| storage_error(&error))?; + Ok(Opened::Postgres(Box::new(store))) + } + } +} + +/// Opens the store, but gives up after `budget` — the shape `info` needs, where an unreachable +/// host is reported as a missing number rather than as a failure. +pub async fn open_within( + settings: &Settings, + data_dir: Option<&Path>, + env: &Environment, + budget: Duration, +) -> Option { + tokio::time::timeout(budget, open(settings, data_dir, env)) + .await + .ok()? + .ok() +} + +/// Renders a storage failure the way a command reports it. +pub fn storage_error(error: &StorageError) -> CliError { + CliError::command(error.to_string()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + fn environment(pairs: &[(&str, &str)]) -> Environment { + let content: String = pairs + .iter() + .map(|(key, value)| format!("{key}={value}\n")) + .collect(); + let file = crate::env_file::parse_values(&content); + // `Environment::load` reads the process environment first; a test that wants the file + // layer alone builds the struct it would hold. + crate::env_file::Environment::from_values(file) + } + + #[test] + fn db_uri_wins_over_the_parts() { + let env = environment(&[("DB_URI", "postgres://a@b/c"), ("DB_HOST", "ignored")]); + assert_eq!(postgres_url(&env).as_deref(), Some("postgres://a@b/c")); + } + + #[test] + fn the_parts_build_a_url_with_the_defaults() { + let env = environment(&[("DB_HOST", "db.internal")]); + assert_eq!( + postgres_url(&env).as_deref(), + Some("postgres://postgres@db.internal:5432/postgres") + ); + } + + #[test] + fn a_password_is_percent_encoded() { + let env = environment(&[ + ("DB_HOST", "db.internal"), + ("DB_PORT", "6543"), + ("DB_USER", "nostr"), + ("DB_PASSWORD", "p@ss/word"), + ("DB_NAME", "relay"), + ]); + assert_eq!( + postgres_url(&env).as_deref(), + Some("postgres://nostr:p%40ss%2Fword@db.internal:6543/relay") + ); + } + + #[test] + fn no_db_configuration_is_no_url() { + assert_eq!(postgres_url(&environment(&[])), None); + } +} diff --git a/crates/nostream-services/src/process.rs b/crates/nostream-services/src/process.rs index 28ec55360..5ac024f5b 100644 --- a/crates/nostream-services/src/process.rs +++ b/crates/nostream-services/src/process.rs @@ -186,7 +186,7 @@ pub async fn capture(argv: &[String], timeout: Option) -> CapturedResu }; } - let mut child = match command(argv, &[]) + let child = match command(argv, &[]) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) From aa0e14dc949cbb51f2c95d5fbf1fd083c506d22e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:22:34 -0500 Subject: [PATCH 05/78] feat(cli): answer help, version and unknown words the capture's way --- crates/nostream-cli/src/app.rs | 450 ++++++++++++++++++++- crates/nostream-cli/src/commands/config.rs | 103 ++++- crates/nostream-cli/src/commands/dev.rs | 10 - crates/nostream-cli/src/commands/import.rs | 28 ++ crates/nostream-cli/src/commands/mod.rs | 1 - crates/nostream-cli/src/docker.rs | 10 - crates/nostream-cli/src/lib.rs | 2 - crates/nostream-cli/src/main.rs | 255 +----------- crates/nostream-cli/src/process.rs | 10 - crates/nostream-cli/tests/import_cli.rs | 7 +- 10 files changed, 569 insertions(+), 307 deletions(-) delete mode 100644 crates/nostream-cli/src/commands/dev.rs delete mode 100644 crates/nostream-cli/src/docker.rs delete mode 100644 crates/nostream-cli/src/process.rs diff --git a/crates/nostream-cli/src/app.rs b/crates/nostream-cli/src/app.rs index bffc1b476..ac82459f3 100644 --- a/crates/nostream-cli/src/app.rs +++ b/crates/nostream-cli/src/app.rs @@ -1,25 +1,33 @@ -//! The shared command context, the hand-written top-level page, the pre-parse, the dispatch and -//! the renderer: the four things `src/cli/index.ts` does around the command modules. +//! 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, in one place, so the parser never sees a case that has its own answer (R1, C1). +//! 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::future::Future; 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. + /// 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, @@ -33,7 +41,7 @@ impl Context { Self::at(cwd) } - /// A context for `cwd`, which the tests name. + /// 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() @@ -49,17 +57,17 @@ impl Context { } } -/// The version page (V44): `nostream/`, the crate's own version, which is the -/// same string `info` prints as `Nostream v` and the admin diagnostics serve. +/// 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 (`Values` 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). +/// 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(), @@ -101,6 +109,409 @@ pub fn page_lines() -> Vec { .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, + /// 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] = &[ + "config", "export", "import", "info", "invite", "migrate", "seed", "setup", "start", "stop", + "tui", "update", +]; + +/// `src/cli/index.ts:470-531`: the three answers that are not a command's, before `parse`. +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) => Invocation::Command, + word => Invocation::Unknown(word.to_owned()), + } +} + +/// 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_lines(&page_lines()); + ExitCode::SUCCESS + } + Invocation::Version => { + println!("{}", version_line()); + ExitCode::SUCCESS + } + 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). + eprintln!("Unknown command: {word}"); + print_lines(&page_lines()); + ExitCode::from(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)) + } + } +} + +/// One command, dispatched. The only place that knows a subcommand exists. +fn dispatch(command: Command, context: &Context) -> Result { + match command { + Command::Config { command } => match command { + ConfigCommand::Validate { config_dir, config } => { + commands::config::validate(&context.cwd, config_dir.as_deref(), config.as_deref()) + } + ConfigCommand::Get { + path, + config_dir, + json, + } => commands::config::get(&context.cwd, config_dir.as_deref(), &path, json), + ConfigCommand::List { config_dir, json } => { + commands::config::list(&context.cwd, config_dir.as_deref(), json) + } + ConfigCommand::Set { + path, + value, + config_dir, + value_type, + no_validate, + restart, + } => commands::config::set( + context, + config_dir.as_deref(), + commands::config::SetRequest { + path: &path, + value: &value, + value_type: value_type.as_deref(), + validate: !no_validate, + restart, + }, + ), + ConfigCommand::Env { command } => match command { + ConfigEnvCommand::List { show_secrets } => { + commands::config::env_list(&context.cwd, show_secrets) + } + ConfigEnvCommand::Get { key, show_secrets } => { + commands::config::env_get(&context.cwd, &key, show_secrets) + } + ConfigEnvCommand::Set { key, value } => { + commands::config::env_set(&context.cwd, &key, &value) + } + ConfigEnvCommand::Validate => commands::config::env_validate(&context.cwd), + }, + }, + Command::Export => commands::export::run().map(|_| CommandOutput::default()), + Command::Import { args } => { + let mut stdout = std::io::stdout().lock(); + commands::import::run(&args, &context.cwd, &mut stdout) + } + Command::Info => commands::info::run().map(|_| CommandOutput::default()), + Command::Invite => commands::invite::run().map(|_| CommandOutput::default()), + 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 => commands::seed::run().map(|_| CommandOutput::default()), + Command::Setup => commands::setup::run().map(|_| CommandOutput::default()), + 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 => commands::update::run().map(|_| CommandOutput::default()), + 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 { + /// Inspect and validate the effective settings. + Config { + #[command(subcommand)] + command: ConfigCommand, + }, + /// Export events to a file. + Export, + /// 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, + /// Mint and manage invite codes. + Invite, + /// Copy the Postgres store into an LMDB store. + Migrate { + #[command(subcommand)] + command: MigrateCommand, + }, + /// Seed the database. + Seed, + /// Run the first-time setup flow. + Setup, + /// 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, + /// Run the interactive settings editor. + Tui, +} + +#[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, + /// Write the value without validating the merged settings. + #[arg(long)] + 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 @@ -126,9 +537,7 @@ struct ErrorBody<'a> { pub fn render(result: Result) -> ExitCode { match result { Ok(output) => { - for line in &output.lines { - println!("{line}"); - } + print_lines(&output.lines); output.exit_code() } Err(error) => { @@ -161,7 +570,7 @@ pub fn render(result: Result) -> ExitCode { match serde_json::to_string(&envelope) { Ok(rendered) => eprintln!("{rendered}"), Err(_) => { - eprintln!("{{\"error\":{{\"message\":\"error\",\"code\":{code}}}}}") + eprintln!("{{\"error\":{{\"message\":\"error\",\"code\":{code}}}}}"); } } code @@ -183,3 +592,10 @@ pub fn render(result: Result) -> ExitCode { } } } + +/// Prints lines on stdout, one per line. +fn print_lines(lines: &[String]) { + for line in lines { + println!("{line}"); + } +} diff --git a/crates/nostream-cli/src/commands/config.rs b/crates/nostream-cli/src/commands/config.rs index 45d7b0e87..ef1087161 100644 --- a/crates/nostream-cli/src/commands/config.rs +++ b/crates/nostream-cli/src/commands/config.rs @@ -1,9 +1,13 @@ -//! The `config` subcommand: validate and get, on top of `crate::config`. +//! The `config` subcommand: validate, list, get, set and `env`, on top of `crate::config`. -use crate::config::{CommandOutput, resolve_paths}; -use crate::error::CliError; use std::path::Path; +use crate::app::Context; +use crate::commands::start::StartOptions; +use crate::commands::stop::StopOptions; +use crate::config::{CommandOutput, ValueType, resolve_paths}; +use crate::error::CliError; + /// Runs `config validate`. pub fn validate( cwd: &Path, @@ -13,6 +17,11 @@ pub fn validate( crate::config::validate(&resolve_paths(cwd, config_dir), config_file) } +/// Runs `config list`. +pub fn list(cwd: &Path, config_dir: Option<&Path>, json: bool) -> Result { + crate::config::list(&resolve_paths(cwd, config_dir), json) +} + /// Runs `config get `. pub fn get( cwd: &Path, @@ -22,3 +31,91 @@ pub fn get( ) -> Result { crate::config::get(&resolve_paths(cwd, config_dir), path, json) } + +/// One `config set` request, as the parser read it. +pub struct SetRequest<'a> { + pub path: &'a str, + pub value: &'a str, + /// `--type`, which the capture treats as `inferred` for anything but `json`. + pub value_type: Option<&'a str>, + /// Validation runs unless `--no-validate`. + pub validate: bool, + /// `--restart`: stop and start the stack after the write. + pub restart: bool, +} + +/// Runs `config set `, and the restart `--restart` asks for. +/// +/// shortcut: a failed `--restart` reports its own step's failure but not the `Updated ` +/// line the capture prints before restarting, because a command returns either its lines or its +/// failure and not both; upgrade when a criterion pins the pair. +pub fn set( + context: &Context, + config_dir: Option<&Path>, + request: SetRequest<'_>, +) -> Result { + let value_type = request + .value_type + .and_then(ValueType::parse) + .unwrap_or(ValueType::Inferred); + + let output = crate::config::set( + &resolve_paths(&context.cwd, config_dir), + request.path, + request.value, + value_type, + request.validate, + )?; + + if !request.restart { + return Ok(output); + } + + let restarted = context.block_on(restart(context))?; + let mut lines = output.lines; + lines.extend(restarted.lines); + Ok(CommandOutput::with_code(lines, restarted.exit_code)) +} + +/// `restartRelay`: stop every overlay, then start, answering the step that failed. +async fn restart(context: &Context) -> Result { + let stopped = crate::commands::stop::stop(context, &StopOptions::every_overlay(), &[]).await?; + + if stopped.exit_code != 0 { + return Err(CliError::Reported { + lines: vec!["Restart failed while stopping relay".to_owned()], + exit_code: stopped.exit_code, + }); + } + + let started = crate::commands::start::start(context, &StartOptions::default(), &[]).await?; + + if started.exit_code != 0 { + return Err(CliError::Reported { + lines: vec!["Restart failed while starting relay".to_owned()], + exit_code: started.exit_code, + }); + } + + Ok(CommandOutput::print(vec!["Relay restarted".to_owned()])) +} + +/// Runs `config env list`. +pub fn env_list(cwd: &Path, show_secrets: bool) -> Result { + crate::config::env_list(cwd, show_secrets) +} + +/// Runs `config env get `. +pub fn env_get(cwd: &Path, key: &str, show_secrets: bool) -> Result { + crate::config::env_get(cwd, key, show_secrets) +} + +/// Runs `config env set `. +pub fn env_set(cwd: &Path, key: &str, value: &str) -> Result { + crate::config::env_set(cwd, key, value) +} + +/// Runs `config env validate`. +pub fn env_validate(cwd: &Path) -> Result { + crate::config::env_validate(cwd) +} diff --git a/crates/nostream-cli/src/commands/dev.rs b/crates/nostream-cli/src/commands/dev.rs deleted file mode 100644 index 2b78ebda9..000000000 --- a/crates/nostream-cli/src/commands/dev.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! `dev.ts`. - -use crate::error::CliError; - -/// Phase 1 stub — job 005; will drives the local development loop; see `src/cli/commands/dev.ts`. -pub fn run() -> Result<(), CliError> { - Err(CliError::NotImplemented { - module: "cli::commands::dev", - }) -} diff --git a/crates/nostream-cli/src/commands/import.rs b/crates/nostream-cli/src/commands/import.rs index e0c6f28f0..2740eedd6 100644 --- a/crates/nostream-cli/src/commands/import.rs +++ b/crates/nostream-cli/src/commands/import.rs @@ -52,6 +52,9 @@ pub enum ParsedArgs { struct ImportHelp { /// The .jsonl or .json file to import. file: Option, + /// Path to .jsonl/.json file. + #[arg(long = "file", value_name = "file")] + file_option: Option, /// Events per insert batch. #[arg(long, value_name = "N")] batch_size: Option, @@ -81,6 +84,31 @@ pub fn parse_args(args: &[String]) -> Result { while index < args.len() { let arg = &args[index]; + if arg == "--file" { + let Some(value) = args.get(index + 1) else { + return Err(CliError::Import("Missing value for --file".to_owned())); + }; + if file.is_some() { + return Err(CliError::Import(format!( + "Unexpected extra argument: {value}" + ))); + } + file = Some(PathBuf::from(value)); + index += 2; + continue; + } + + if let Some(value) = arg.strip_prefix("--file=") { + if file.is_some() { + return Err(CliError::Import(format!( + "Unexpected extra argument: {value}" + ))); + } + file = Some(PathBuf::from(value)); + index += 1; + continue; + } + if arg == "--batch-size" { let Some(value) = args.get(index + 1) else { return Err(CliError::Import( diff --git a/crates/nostream-cli/src/commands/mod.rs b/crates/nostream-cli/src/commands/mod.rs index b463b2623..c3c38025d 100644 --- a/crates/nostream-cli/src/commands/mod.rs +++ b/crates/nostream-cli/src/commands/mod.rs @@ -2,7 +2,6 @@ //! process supervisor. pub mod config; -pub mod dev; pub mod export; pub mod import; pub mod info; diff --git a/crates/nostream-cli/src/docker.rs b/crates/nostream-cli/src/docker.rs deleted file mode 100644 index 473b0fb94..000000000 --- a/crates/nostream-cli/src/docker.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! The docker supervisor. Mirrors `src/cli/utils/docker.ts`. - -use crate::error::CliError; - -/// Phase 1 stub — job 005; will run compose commands against the deployment; see `src/cli/utils/docker.ts`. -pub fn compose(_args: &[String]) -> Result { - Err(CliError::NotImplemented { - module: "cli::docker::compose", - }) -} diff --git a/crates/nostream-cli/src/lib.rs b/crates/nostream-cli/src/lib.rs index 24083a6a6..3c94d9750 100644 --- a/crates/nostream-cli/src/lib.rs +++ b/crates/nostream-cli/src/lib.rs @@ -17,10 +17,8 @@ pub mod commands; pub mod compose; pub mod compression; pub mod config; -pub mod docker; pub mod env_file; pub mod error; -pub mod process; pub mod store; pub mod tui; diff --git a/crates/nostream-cli/src/main.rs b/crates/nostream-cli/src/main.rs index 8625ffc4c..f56133f46 100644 --- a/crates/nostream-cli/src/main.rs +++ b/crates/nostream-cli/src/main.rs @@ -1,259 +1,10 @@ //! `nostream-cli` — the operator command line. //! -//! `anyhow` is allowed here (binaries only, spec D10); every subcommand handler lives in the -//! library so the error model stays typed. +//! The surface lives in the library (`nostream_cli::app`); this file only hands the process's +//! arguments to it, so the binary has no logic of its own to keep in step with a test. -use std::path::PathBuf; use std::process::ExitCode; -use clap::{Parser, Subcommand}; -use nostream_cli::app::{self, Context}; -use nostream_cli::commands; -use nostream_cli::config::CommandOutput; - -// `import` parses its own arguments, so clap's `help` subcommand would render a second, -// contradictory page for it; `--help` is the single help surface. -#[derive(Debug, Parser)] -#[command( - name = "nostream-cli", - about = "Operate a nostream relay", - disable_help_subcommand = true -)] -struct Cli { - #[command(subcommand)] - command: Command, -} - -#[derive(Debug, Subcommand)] -enum Command { - /// Inspect and validate the effective settings. - Config { - #[command(subcommand)] - command: ConfigCommand, - }, - /// Drive the local development loop. - Dev, - /// Export events to a file. - Export, - /// 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, - /// Mint and manage invite codes. - Invite, - /// Copy the Postgres store into an LMDB store. - Migrate { - #[command(subcommand)] - command: MigrateCommand, - }, - /// Seed the database. - Seed, - /// Run the first-time setup flow. - Setup, - /// 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, - /// Run the interactive settings editor. - Tui, -} - -#[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 value at a dot-path. - 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, - }, -} - -#[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, - }, -} - fn main() -> ExitCode { - let cli = Cli::parse(); - let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); - let result = match cli.command { - Command::Config { command } => match command { - ConfigCommand::Validate { config_dir, config } => { - commands::config::validate(&cwd, config_dir.as_deref(), config.as_deref()) - } - ConfigCommand::Get { - path, - config_dir, - json, - } => commands::config::get(&cwd, config_dir.as_deref(), &path, json), - }, - Command::Dev => commands::dev::run().map(|_| CommandOutput::default()), - Command::Export => commands::export::run().map(|_| CommandOutput::default()), - Command::Import { args } => { - let mut stdout = std::io::stdout().lock(); - commands::import::run(&args, &cwd, &mut stdout) - } - Command::Info => commands::info::run().map(|_| CommandOutput::default()), - Command::Invite => commands::invite::run().map(|_| CommandOutput::default()), - 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 => commands::seed::run().map(|_| CommandOutput::default()), - Command::Setup => commands::setup::run().map(|_| CommandOutput::default()), - Command::Start { - tor, - i2p, - nginx, - debug, - detach, - port, - args, - } => { - let options = commands::start::StartOptions { - tor, - i2p, - nginx, - debug, - detach, - port, - }; - Context::at(cwd).and_then(|context| commands::start::run(&context, &options, &args)) - } - Command::Stop { - tor, - i2p, - nginx, - local, - all, - args, - } => { - let options = commands::stop::StopOptions { - tor, - i2p, - nginx, - local, - all, - }; - Context::at(cwd).and_then(|context| commands::stop::run(&context, &options, &args)) - } - Command::Update => commands::update::run().map(|_| CommandOutput::default()), - Command::Tui => nostream_cli::tui::run().map(|_| CommandOutput::default()), - }; - - app::render(result) + nostream_cli::app::run(std::env::args().skip(1).collect()) } diff --git a/crates/nostream-cli/src/process.rs b/crates/nostream-cli/src/process.rs deleted file mode 100644 index 3cd0677d1..000000000 --- a/crates/nostream-cli/src/process.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! The process supervisor. Mirrors `src/cli/utils/process.ts`. - -use crate::error::CliError; - -/// Phase 1 stub — job 005; will spawn and supervise child processes; see `src/cli/utils/process.ts`. -pub fn spawn(_command: &str) -> Result { - Err(CliError::NotImplemented { - module: "cli::process::spawn", - }) -} diff --git a/crates/nostream-cli/tests/import_cli.rs b/crates/nostream-cli/tests/import_cli.rs index cd57e0ebe..236bd5dcf 100644 --- a/crates/nostream-cli/tests/import_cli.rs +++ b/crates/nostream-cli/tests/import_cli.rs @@ -197,11 +197,14 @@ fn the_help_route_does_not_print_a_second_import_page() { .output() .expect("the binary runs"); + // The port answers every word that is no command with the capture's marker, so `help` is + // refused before any parser runs and no second import page can be rendered. assert_eq!(output.status.code(), Some(2), "{}", stderr(&output)); + assert_eq!(stderr(&output), "Unknown command: help\n"); assert!( - stderr(&output).contains("unrecognized subcommand"), + !String::from_utf8_lossy(&output.stdout).contains("The .jsonl or .json file to import"), "{}", - stderr(&output) + String::from_utf8_lossy(&output.stdout) ); } From 4561b23cf57d630616d6a330c66c75dae418f163 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 12:27:34 -0500 Subject: [PATCH 06/78] feat(cli): report, export and clean the store's events --- crates/nostream-cli/src/app.rs | 81 +- crates/nostream-cli/src/commands/clean_db.rs | 426 +++++++++ crates/nostream-cli/src/commands/export.rs | 914 ++++++++++++++++++- crates/nostream-cli/src/commands/info.rs | 461 +++++++++- crates/nostream-cli/src/commands/mod.rs | 1 + crates/nostream-storage/src/repositories.rs | 19 + 6 files changed, 1885 insertions(+), 17 deletions(-) create mode 100644 crates/nostream-cli/src/commands/clean_db.rs diff --git a/crates/nostream-cli/src/app.rs b/crates/nostream-cli/src/app.rs index ac82459f3..f9676497d 100644 --- a/crates/nostream-cli/src/app.rs +++ b/crates/nostream-cli/src/app.rs @@ -125,8 +125,8 @@ pub enum Invocation { /// 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] = &[ - "config", "export", "import", "info", "invite", "migrate", "seed", "setup", "start", "stop", - "tui", "update", + "clean-db", "config", "export", "import", "info", "invite", "migrate", "seed", "setup", + "start", "stop", "tui", "update", ]; /// `src/cli/index.ts:470-531`: the three answers that are not a command's, before `parse`. @@ -175,6 +175,7 @@ pub fn run(argv: Vec) -> ExitCode { /// One command, dispatched. The only place that knows a subcommand exists. fn dispatch(command: Command, context: &Context) -> Result { match command { + 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()) @@ -218,12 +219,40 @@ fn dispatch(command: Command, context: &Context) -> Result commands::config::env_validate(&context.cwd), }, }, - Command::Export => commands::export::run().map(|_| CommandOutput::default()), + 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, &mut stdout) } - Command::Info => commands::info::run().map(|_| CommandOutput::default()), + 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 => commands::invite::run().map(|_| CommandOutput::default()), Command::Migrate { command } => match command { MigrateCommand::PgToLmdb { @@ -300,13 +329,40 @@ struct Cli { #[derive(Debug, Subcommand)] enum Command { + /// 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, + 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 { @@ -319,7 +375,20 @@ enum Command { args: Vec, }, /// Print the relay's NIP-11 info. - 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, /// Copy the Postgres store into an LMDB store. 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..b14bc75d1 --- /dev/null +++ b/crates/nostream-cli/src/commands/clean_db.rs @@ -0,0 +1,426 @@ +//! `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). +//! +//! Every failure here is reported **bare**, with exit 1: the capture's own entry point catches +//! them all and prints them with `console.error` (`src/clean-db.ts:270-277`), so none of them +//! carries the `Error: ` prefix (V63 class B). 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_config::SettingsPaths; +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