diff --git a/.changeset/daemon-opens-its-store.md b/.changeset/daemon-opens-its-store.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/daemon-opens-its-store.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index aafbba537..c211fc9f6 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -279,6 +279,12 @@ jobs: env: PARITY_ADMIN_URL: postgres://postgres:postgres@localhost:5432/postgres run: cargo test -p nostream-storage --test migrations --test parity --test migration_pg --test clean_up -- --ignored --test-threads=1 + # The daemon's own composition over Postgres (#1206): an event one nostreamd process + # accepts is read back by a second, against a scratch database the target migrates. + - name: Daemon store against Postgres + env: + PARITY_ADMIN_URL: postgres://postgres:postgres@localhost:5432/postgres + run: cargo test -p nostreamd --all-features --test store_wiring -- --ignored --test-threads=1 # The benchmark rig's Postgres column: the same workload and the same `--verify` the LMDB # arm runs, against the scratch database it drops and recreates. The dev profile is # deliberate — this proves the path and the counts, and its timings are cited nowhere. diff --git a/CLAUDE.md b/CLAUDE.md index c541f66ef..2341eff77 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ cargo test --workspace --all-features cargo build --workspace --all-features --release ``` -CI additionally runs five database- and example-backed checks. Three are the storage tests +CI additionally runs six database- and example-backed checks. Three are the storage tests ("Storage parity against Postgres"), against a `postgres:16-alpine` service; they are `#[ignore]`d so a checkout without a database still passes `cargo test --workspace`: @@ -45,12 +45,20 @@ cargo test -p nostream-storage --test migrations --test parity --test migration_ -- --ignored --test-threads=1 ``` +The fourth is the daemon's own composition against Postgres ("Daemon store against Postgres"): +`nostreamd`'s `store_wiring` target starts the binary twice over a scratch database it migrates +and requires the second process to read back the event the first accepted: + +``` +cargo test -p nostreamd --all-features --test store_wiring -- --ignored --test-threads=1 +``` + `PARITY_ADMIN_URL` names the administrative database (CI sets `postgres://postgres:postgres@localhost:5432/postgres`); the targets create, migrate and drop their own scratch databases — `migration_pg` seeds one and copies it into a temporary LMDB -store. The fourth is the benchmark rig's Postgres arm ("Benchmark harness against Postgres"): +store. The fifth is the benchmark rig's Postgres arm ("Benchmark harness against Postgres"): it runs `crates/nostream-storage/examples/bench.rs` against a scratch database and proves the path -and `--verify`, and its numbers are cited nowhere. The fifth, below, is the rig's own unit tests. +and `--verify`, and its numbers are cited nowhere. The sixth, below, is the rig's own unit tests. The rig's own unit tests need their own command, because `cargo test --workspace` only *builds* an example target. CI runs it as "Benchmark harness unit tests", and so must you when you touch the diff --git a/Cargo.lock b/Cargo.lock index 0f94be220..0125d5570 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1641,6 +1641,7 @@ dependencies = [ "opentelemetry-otlp", "rmcp", "serde_json", + "sqlx", "tempfile", "thiserror", "tokio", diff --git a/crates/nostream-cli/src/store.rs b/crates/nostream-cli/src/store.rs index f8e846e54..a81d7d74a 100644 --- a/crates/nostream-cli/src/store.rs +++ b/crates/nostream-cli/src/store.rs @@ -15,49 +15,37 @@ use nostream_core::EventStoreBackend; use nostream_storage::repositories::{ EventRepository, InviteCodeRepository, InvoiceRepository, UserRepository, }; -use nostream_storage::{LmdbBackend, StorageError, backend}; +use nostream_storage::{LmdbBackend, Repositories, 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), -} +/// An opened store: the repositories of whichever shipped backend the settings name. +/// +/// The nine handles are `nostream_storage::Repositories`, the same the daemon builds its +/// bundles from; the CLI reads four of them, borrowed for the command's lifetime. +#[derive(Debug, Clone)] +pub struct Opened(Repositories); 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(), - } + self.0.events.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(), - } + self.0.invites.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(), - } + self.0.invoices.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(), - } + self.0.users.as_ref() } } @@ -105,7 +93,7 @@ pub async fn open( let store = LmdbBackend::open(root) .await .map_err(|error| storage_error(&error))?; - Ok(Opened::Lmdb(Box::new(store))) + Ok(Opened(Repositories::over(store))) } EventStoreBackend::Postgres => { if !postgres_configured(env) { @@ -116,7 +104,7 @@ pub async fn open( let store = nostream_storage::PostgresBackend::from_lookup(&|key: &str| env.get(key)) .await .map_err(|error| storage_error(&error))?; - Ok(Opened::Postgres(Box::new(store))) + Ok(Opened(Repositories::over(store))) } } } diff --git a/crates/nostream-relay/src/handlers/mod.rs b/crates/nostream-relay/src/handlers/mod.rs index e2e3a78ac..de7293bfd 100644 --- a/crates/nostream-relay/src/handlers/mod.rs +++ b/crates/nostream-relay/src/handlers/mod.rs @@ -67,6 +67,20 @@ pub struct Stores { pub reports: Arc, } +impl From<&nostream_storage::Repositories> for Stores { + /// The six of an opened backend's nine repositories the handlers call. + fn from(repositories: &nostream_storage::Repositories) -> Self { + Self { + events: Arc::clone(&repositories.events), + users: Arc::clone(&repositories.users), + nip05: Arc::clone(&repositories.nip05), + invites: Arc::clone(&repositories.invites), + dvm_jobs: Arc::clone(&repositories.dvm_jobs), + reports: Arc::clone(&repositories.reports), + } + } +} + /// The context one socket shares across handlers (`src/@types/message-handlers.ts`). /// /// `settings` is the loaded document, read through on every check (R27); `pow` is this diff --git a/crates/nostream-relay/src/unavailable.rs b/crates/nostream-relay/src/unavailable.rs index 746b323c1..fbe9019a7 100644 --- a/crates/nostream-relay/src/unavailable.rs +++ b/crates/nostream-relay/src/unavailable.rs @@ -1,12 +1,11 @@ -//! Repository seams for a daemon whose storage backend is not wired yet. +//! Repository seams that report every storage call as `NotImplemented`. //! -//! The relay is generic over `nostream-storage`'s repository traits, and the daemon has no -//! live backend to hand it: the LMDB environment is a labelled stub -//! (`crates/nostream-storage/src/lib.rs:17-19`) and the Postgres backend needs a database the -//! daemon is not yet configured with. Wiring these seams keeps the wire served — handshake, -//! NIP-42 challenge, REQ/COUNT validation — while every storage call reports -//! `StorageError::NotImplemented`, which is the workspace's convention for an unwired -//! backend (`CLAUDE.md:148-151`). +//! The daemon no longer serves over these: since #1206 it opens the backend the settings name +//! and builds `Stores` from it (`nostreamd::stores`). They remain the doubles for a caller with +//! no backend at all — a test that needs the wire without a store, or a composition that must +//! say "not wired" rather than invent rows — and every call answers +//! `StorageError::NotImplemented`, the workspace's convention for an unwired backend +//! (`CLAUDE.md:148-151`). use nostream_core::{EventId, Filter, Kind, Pubkey}; use nostream_storage::StorageError; diff --git a/crates/nostream-services/src/services/payments_service.rs b/crates/nostream-services/src/services/payments_service.rs index a07eb8fd1..68a8ea1f9 100644 --- a/crates/nostream-services/src/services/payments_service.rs +++ b/crates/nostream-services/src/services/payments_service.rs @@ -154,6 +154,14 @@ impl PaymentsService { } /// `confirmInvoice`: the three guards, the confirmation, admission and the outbox row. + /// + /// The capture runs the three writes in one `SERIALIZABLE` transaction. Here they are three + /// repository calls on either backend: the traits carry no transaction (only + /// `PostgresTransaction` does, and LMDB has no counterpart), so a process that stops between + /// them leaves the invoice confirmed without the admission or the notification. Each write + /// is safe to repeat — confirming a confirmed invoice and admitting an admitted user change + /// nothing — so a retry finishes the work, at the cost of a second outbox row. A + /// cross-repository transaction on the seam is what would close this (#1206). pub async fn confirm_invoice(&self, invoice: &Invoice) -> Result<(), ServicesError> { let Some(confirmed_at) = invoice.confirmed_at else { return Err(ServicesError::Payment( diff --git a/crates/nostream-services/src/unavailable.rs b/crates/nostream-services/src/unavailable.rs index a3b1caac7..78e7380d7 100644 --- a/crates/nostream-services/src/unavailable.rs +++ b/crates/nostream-services/src/unavailable.rs @@ -1,5 +1,7 @@ -//! The services' store bundle, and the doubles a daemon whose storage backend is not wired -//! yet hands it. +//! The services' store bundle, and the doubles for a caller with no storage backend. +//! +//! The daemon builds the bundle from the backend it opened (`ServiceStores::from`, #1206); the +//! doubles below answer `NotImplemented` for tests and compositions that have no store. //! //! The relay has its own `Stores` (`nostream_relay::handlers::Stores`) for the six //! repositories its handlers call; this bundle carries the eight the door and the services @@ -35,6 +37,22 @@ pub struct ServiceStores { pub reports: Arc, } +impl From<&nostream_storage::Repositories> for ServiceStores { + /// The eight of an opened backend's nine repositories the services and the doors reach. + fn from(repositories: &nostream_storage::Repositories) -> Self { + Self { + events: Arc::clone(&repositories.events), + users: Arc::clone(&repositories.users), + invoices: Arc::clone(&repositories.invoices), + nip05: Arc::clone(&repositories.nip05), + dvm_jobs: Arc::clone(&repositories.dvm_jobs), + notification_outbox: Arc::clone(&repositories.notification_outbox), + notification_delivery_log: Arc::clone(&repositories.notification_delivery_log), + reports: Arc::clone(&repositories.reports), + } + } +} + fn unavailable() -> StorageError { StorageError::NotImplemented { module: "storage::backend::wiring", diff --git a/crates/nostream-storage/src/error.rs b/crates/nostream-storage/src/error.rs index b91c17beb..6e1241522 100644 --- a/crates/nostream-storage/src/error.rs +++ b/crates/nostream-storage/src/error.rs @@ -95,6 +95,16 @@ pub enum StorageError { #[error("lmdb values must be valid utf-8")] NotUtf8, + /// The file that serialises the search-index rebuild between processes could not be + /// opened or locked (ADR 0012 D9, amended by #1206). + #[cfg(feature = "lmdb")] + #[error("failed to lock {path} for the search index check: {source}")] + RebuildLock { + path: std::path::PathBuf, + #[source] + source: std::io::Error, + }, + /// The environment's data directory could not be created. #[error("failed to create {path}: {source}")] CreateDirectory { diff --git a/crates/nostream-storage/src/lib.rs b/crates/nostream-storage/src/lib.rs index 21e926829..2a58e834d 100644 --- a/crates/nostream-storage/src/lib.rs +++ b/crates/nostream-storage/src/lib.rs @@ -38,6 +38,7 @@ mod keys; #[cfg(feature = "lmdb")] pub mod lmdb; pub mod migration; +pub mod opened; #[cfg(feature = "postgres")] pub mod postgres; pub mod records; @@ -49,6 +50,7 @@ pub use backend::data_dir; pub use error::StorageError; #[cfg(feature = "lmdb")] pub use lmdb::{LmdbBackend, MapUsage}; +pub use opened::Repositories; #[cfg(feature = "postgres")] pub use postgres::{PostgresBackend, PostgresTransaction}; diff --git a/crates/nostream-storage/src/lmdb/mod.rs b/crates/nostream-storage/src/lmdb/mod.rs index 164550e76..2b6f373bc 100644 --- a/crates/nostream-storage/src/lmdb/mod.rs +++ b/crates/nostream-storage/src/lmdb/mod.rs @@ -273,6 +273,26 @@ fn rebuild_lock(path: &Path) -> Arc> { Arc::clone(locks.entry(path.to_path_buf()).or_default()) } +/// The file beside `data.mdb` whose exclusive lock serialises the search-index check and rebuild +/// between processes. +pub const REBUILD_LOCK_FILE: &str = "search-index.lock"; + +/// Takes the exclusive, process-wide advisory lock on `/search-index.lock`, waiting for a +/// holder in another process. The lock goes with the returned file, and with the process. +fn lock_rebuild_file(path: &Path) -> Result { + let lock_path = path.join(REBUILD_LOCK_FILE); + let locked = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&lock_path) + .and_then(|file| file.lock().map(|()| file)); + locked.map_err(|source| StorageError::RebuildLock { + path: lock_path, + source, + }) +} + /// An embedded LMDB event store with its metadata tail, built from the root a caller supplies. #[derive(Debug, Clone)] pub struct LmdbBackend { @@ -307,6 +327,11 @@ impl LmdbBackend { let rebuilding = rebuilding .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The same section, across processes: the relay and a `--mcp-stdio` sidecar open one + // store (#1206), and LMDB serialises their write transactions but not this + // read-modify-write. The operating system drops the lock with its holder, so a + // process killed mid-rebuild leaves nothing to recover (ADR 0012 D9). + let across_processes = lock_rebuild_file(handle.path())?; let mut transaction = handle.write_txn()?; let databases = Databases::create(&handle, &mut transaction)?; let marker = databases @@ -319,6 +344,7 @@ impl LmdbBackend { if marker.as_deref() != Some(&[search::SEARCH_INDEX_VERSION][..]) { search::rebuild(&handle, &databases)?; } + drop(across_processes); drop(rebuilding); let used_bytes = handle.non_free_pages_size()?; Ok::<_, StorageError>((environment, databases, used_bytes)) @@ -1325,6 +1351,43 @@ mod tests { use super::*; + /// #1206 puts a second process on one store (the relay and its `--mcp-stdio` sidecar), so the + /// marker check and rebuild are serialised by a file lock as well as the in-process mutex. A + /// second descriptor on the lock file contends exactly as another process does — `flock` is + /// per open file description — so this one stands in for that process. + #[tokio::test] + async fn an_open_waits_while_another_holder_has_the_rebuild_lock() { + let directory = tempfile::tempdir().expect("tempdir"); + drop( + LmdbBackend::open(directory.path()) + .await + .expect("the store opens"), + ); + let lock_path = crate::backend::store_dir(directory.path()).join(REBUILD_LOCK_FILE); + assert!(lock_path.is_file(), "the first open leaves the lock file"); + + let held = std::fs::OpenOptions::new() + .write(true) + .open(&lock_path) + .expect("the lock file opens"); + held.lock().expect("the stand-in process takes the lock"); + + let root = directory.path().to_path_buf(); + let opening = tokio::spawn(async move { LmdbBackend::open(root).await }); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + assert!( + !opening.is_finished(), + "the open waits for the other holder instead of reading the marker beside it" + ); + + drop(held); + tokio::time::timeout(std::time::Duration::from_secs(5), opening) + .await + .expect("the open finishes once the lock is released") + .expect("the task ran") + .expect("the store opens"); + } + #[tokio::test] async fn the_backend_opens_and_creates_every_database() { let directory = tempfile::tempdir().expect("tempdir"); diff --git a/crates/nostream-storage/src/opened.rs b/crates/nostream-storage/src/opened.rs new file mode 100644 index 000000000..e9b5ed52b --- /dev/null +++ b/crates/nostream-storage/src/opened.rs @@ -0,0 +1,67 @@ +//! One opened backend and the nine repositories it answers for. +//! +//! Every shipped backend implements all nine traits (ADR 0011), so the caller that opened one +//! hands this out instead of matching on the backend at each accessor. The daemon builds its +//! relay and services bundles from it, and the CLI reads the four it needs through it; neither +//! names a backend again after the open. +//! +//! The tenth capture repository, `user_subscriptions`, has no trait yet (see the crate doc), so +//! it is not here. + +use std::sync::Arc; + +use crate::repositories::{ + DvmJobRepository, EventRepository, InviteCodeRepository, InvoiceRepository, + Nip05VerificationRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, + ReportRepository, UserRepository, +}; + +/// The nine repositories of one opened backend, each a handle on the same store. +#[derive(Clone)] +pub struct Repositories { + pub events: Arc, + pub users: Arc, + pub invoices: Arc, + pub nip05: Arc, + pub invites: Arc, + pub dvm_jobs: Arc, + pub reports: Arc, + pub notification_outbox: Arc, + pub notification_delivery_log: Arc, +} + +impl Repositories { + /// The nine handles on one backend. + pub fn over(backend: B) -> Self + where + B: EventRepository + + UserRepository + + InvoiceRepository + + Nip05VerificationRepository + + InviteCodeRepository + + DvmJobRepository + + ReportRepository + + NotificationOutboxRepository + + NotificationDeliveryLogRepository + + 'static, + { + let backend = Arc::new(backend); + Self { + events: backend.clone(), + users: backend.clone(), + invoices: backend.clone(), + nip05: backend.clone(), + invites: backend.clone(), + dvm_jobs: backend.clone(), + reports: backend.clone(), + notification_outbox: backend.clone(), + notification_delivery_log: backend, + } + } +} + +impl std::fmt::Debug for Repositories { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("Repositories { .. }") + } +} diff --git a/crates/nostreamd/Cargo.toml b/crates/nostreamd/Cargo.toml index 055861912..387a39069 100644 --- a/crates/nostreamd/Cargo.toml +++ b/crates/nostreamd/Cargo.toml @@ -42,6 +42,7 @@ otlp = ["dep:opentelemetry", "dep:opentelemetry-otlp", "dep:tracing-opentelemetr [dev-dependencies] futures-util.workspace = true +sqlx.workspace = true nostream-relay.workspace = true tempfile.workspace = true tokio-tungstenite.workspace = true diff --git a/crates/nostreamd/src/error.rs b/crates/nostreamd/src/error.rs index 719e81ed8..41f19c42e 100644 --- a/crates/nostreamd/src/error.rs +++ b/crates/nostreamd/src/error.rs @@ -13,6 +13,12 @@ pub enum DaemonError { #[error("daemon setup failed: {0}")] Setup(String), + /// The event store the settings name could not be opened: the LMDB backend has no + /// `--data-dir`, or the backend itself refused (an unreachable Postgres, an unopenable + /// LMDB root). The daemon refuses to start rather than serve a wire that stores nothing. + #[error("event store: {0}")] + Store(String), + /// Settings failed validation; the daemon refuses to start. #[error("settings invalid: {count} issues")] InvalidSettings { count: usize }, diff --git a/crates/nostreamd/src/lib.rs b/crates/nostreamd/src/lib.rs index 35caa6220..a2622ad74 100644 --- a/crates/nostreamd/src/lib.rs +++ b/crates/nostreamd/src/lib.rs @@ -49,6 +49,7 @@ pub mod admin_http; pub mod error; pub mod mcp_stdio; pub mod settings_gate; +pub mod stores; pub mod telemetry; pub mod workers; diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 985bd23e0..23f9293ed 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -26,6 +26,12 @@ struct Cli { #[arg(long, global = true)] config_dir: Option, + /// The store root: the LMDB backend keeps its store at `/lmdb`, the layout + /// `nostream-cli --data-dir` and `migrate pg-to-lmdb --target` use. Required when + /// `eventStore.backend` is `lmdb`; the Postgres backend reads `DB_*` and ignores it. + #[arg(long, global = true, value_name = "DIR")] + data_dir: Option, + /// Validate the effective settings and exit. #[arg(long)] check: bool, @@ -138,8 +144,8 @@ fn run(cli: Cli) -> Result { let config_dir = paths.config_base_dir; - // R17: the MCP mode serves stdin/stdout and returns; it binds no socket and opens no - // store of its own, so `--listen-port` is not read on this path. + // R17: the MCP mode serves stdin/stdout and returns; it binds no socket, so + // `--listen-port` is not read on this path. It opens the same store the relay door does. let port = cli .listen_port .or_else(|| { @@ -180,7 +186,14 @@ fn run(cli: Cli) -> Result { )?; let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); return runtime.block_on(async move { - nostreamd::mcp_stdio::serve(cwd, config_dir, credential).await?; + nostreamd::mcp_stdio::serve( + cwd, + config_dir, + credential, + Arc::new(settings), + cli.data_dir, + ) + .await?; Ok(ExitCode::SUCCESS) }); } @@ -192,7 +205,7 @@ fn run(cli: Cli) -> Result { return Err(DaemonError::MissingSecret); } - runtime.block_on(async move { serve(listen, settings, config_dir, port).await }) + runtime.block_on(async move { serve(listen, settings, config_dir, cli.data_dir, port).await }) } fn payments_enabled(settings: &nostream_config::Settings) -> bool { @@ -213,6 +226,7 @@ async fn serve( listen: SocketAddr, settings: nostream_config::Settings, config_dir: PathBuf, + data_dir: Option, port: u16, ) -> Result { let acceptor = nostreamd::Acceptor::bind(listen).await?; @@ -230,9 +244,13 @@ async fn serve( // The one environment read: the drain deadline is the operator's. relay_config.drain_timeout = nostream_relay::transport::drain_timeout(); - // The storage backend is not wired yet (the LMDB environment is a stub), so the relay - // runs over seams that report `NotImplemented`; the wire itself is served in full. - let service_stores = Arc::new(nostream_services::unavailable::stores()); + // #1206: one opened backend; the relay and the services take their bundles from it. + let repositories = nostreamd::stores::open(backend, &settings, data_dir.as_deref(), &|key| { + std::env::var(key).ok() + }) + .await?; + tracing::info!(backend = ?backend, "event store opened"); + let service_stores = Arc::new(nostream_services::ServiceStores::from(&repositories)); let wot: Arc = Arc::new(WotGraphService::new( Arc::clone(&settings), Arc::clone(&service_stores.events), @@ -244,7 +262,7 @@ async fn serve( let relay = Relay::new( (*settings).clone(), - Arc::new(nostream_relay::unavailable::stores()), + Arc::new(nostream_relay::handlers::Stores::from(&repositories)), wot, Arc::new(SystemClock), relay_keys.clone(), diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs index 44682f881..e1e042328 100644 --- a/crates/nostreamd/src/mcp_stdio.rs +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -7,14 +7,13 @@ //! writer per configuration (D18). //! //! The mode binds **no socket** — `nostreamd` stays the crate that binds, and this mode is not -//! one of its listeners (D13) — and opens **no store of its own**: the admin state comes from -//! [`crate::admin_http::compose`] over an `unavailable::stores()` bundle composed here, as the -//! relay path composes its own in `crates/nostreamd/src/main.rs`'s `serve`. The two are -//! independent `Arc`s in two processes, not one shared value (D7, D18), and while the store is -//! unwired neither opens an LMDB directory at all — so ADR 0012 D9's second-writer hazard cannot -//! arise. When the store is wired, `main.rs`'s bundle and this one have to be wired together in -//! the same change, or this mode keeps answering the store-backed tools with the store's own -//! `NotImplemented` message (R19). +//! one of its listeners (D13). It opens **the same store the relay door opens**, through +//! [`crate::stores::open`] with the same settings and `--data-dir` (#1206), so the store-backed +//! tools read and write real rows. The two doors hold independent handles in two processes, not +//! one shared value (D7, D18). On LMDB that makes this mode the second process ADR 0012 D9 named: +//! the search-index check is serialised between them by the store's file lock, and the record's +//! remaining rule — a rebuild must not overlap another process's writes — holds for two processes +//! of one version, because the first to open makes the marker current. //! //! The credential is this mode's own and comes from its two flags, never the environment: the //! variable that used to carry a console session token is retired, and a mode started with it @@ -74,8 +73,17 @@ pub async fn serve( cwd: PathBuf, config_dir: PathBuf, credential: Credential, + settings: Arc, + data_dir: Option, ) -> Result<(), DaemonError> { - let stores = Arc::new(nostream_services::unavailable::stores()); + // The same store the relay door opens (#1206): the tools read and write real rows. + let backend = nostream_storage::event_store::resolved_backend(&settings, false) + .map_err(|error| DaemonError::Setup(format!("event store backend: {error}")))?; + let repositories = crate::stores::open(backend, &settings, data_dir.as_deref(), &|key| { + std::env::var(key).ok() + }) + .await?; + let stores = Arc::new(nostream_services::ServiceStores::from(&repositories)); let client = Arc::new( nostream_services::ReqwestClient::new() .map_err(|error| DaemonError::Setup(error.to_string()))?, diff --git a/crates/nostreamd/src/stores.rs b/crates/nostreamd/src/stores.rs new file mode 100644 index 000000000..adb254036 --- /dev/null +++ b/crates/nostreamd/src/stores.rs @@ -0,0 +1,64 @@ +//! The event store the daemon serves from, opened once and shared by both doors. +//! +//! `serve` (the relay door) and `mcp_stdio::serve` (the MCP door) call [`open`] with the same +//! inputs, so the two compose the same nine repositories: the relay's six through +//! `nostream_relay::handlers::Stores::from`, the services' eight through +//! `nostream_services::ServiceStores::from`. Neither builds an `unavailable` bundle. +//! +//! The backend is the one the settings name (`eventStore.backend`, Postgres when absent): +//! +//! - **LMDB** lives at `<--data-dir>/lmdb`, the layout `nostream-cli` and +//! `migrate pg-to-lmdb --target` use (ADR 0015 D8). There is no default root and no +//! environment variable for one, so the daemon refuses to start without the flag, with the +//! CLI's message. +//! - **Postgres** is the `DB_*` family read from the process environment, `DB_URI` winning +//! (`PostgresBackend::from_lookup`). It dials at open, so an unreachable server fails the +//! start instead of the first REQ. The daemon does not apply migrations: the schema is the +//! operator's step, as it is for the capture (`npm run db:migrate`). +//! +//! Both backends get the loaded settings, which carry the NIP-50 and NIP-56 gates their +//! queries read. + +use std::path::Path; +use std::sync::Arc; + +use nostream_config::Settings; +use nostream_core::EventStoreBackend; +use nostream_storage::{LmdbBackend, PostgresBackend, Repositories}; + +use crate::DaemonError; + +/// Opens the store `backend` names. +/// +/// `lookup` reads the environment (`std::env::var` in the binary); a test passes its own. +pub async fn open( + backend: EventStoreBackend, + settings: &Arc, + data_dir: Option<&Path>, + lookup: &F, +) -> Result +where + F: Fn(&str) -> Option + Sync, +{ + match backend { + EventStoreBackend::Lmdb => { + let Some(root) = data_dir else { + return Err(DaemonError::Store( + "the lmdb backend needs --data-dir ".to_owned(), + )); + }; + let store = LmdbBackend::open(root) + .await + .map_err(|error| DaemonError::Store(error.to_string()))? + .with_settings(Arc::clone(settings)); + Ok(Repositories::over(store)) + } + EventStoreBackend::Postgres => { + let store = PostgresBackend::from_lookup(lookup) + .await + .map_err(|error| DaemonError::Store(error.to_string()))? + .with_settings(Arc::clone(settings)); + Ok(Repositories::over(store)) + } + } +} diff --git a/crates/nostreamd/tests/admin_http.rs b/crates/nostreamd/tests/admin_http.rs index b46ef810a..be074b73d 100644 --- a/crates/nostreamd/tests/admin_http.rs +++ b/crates/nostreamd/tests/admin_http.rs @@ -47,7 +47,7 @@ fn start_daemon() -> (Daemon, tempfile::TempDir) { drop(listener); let settings = format!( - "info:\n name: Example\n relay_url: ws://127.0.0.1:{port}\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" + "info:\n name: Example\n relay_url: ws://127.0.0.1:{port}\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\neventStore:\n backend: lmdb\n" ); let mut file = std::fs::File::create(config_dir.join("settings.yaml")).expect("settings"); file.write_all(settings.as_bytes()).expect("write settings"); @@ -60,6 +60,9 @@ fn start_daemon() -> (Daemon, tempfile::TempDir) { .arg(port.to_string()) .arg("--log-level") .arg("info") + // The daemon opens a real store (#1206): a scratch LMDB root beside the settings. + .arg("--data-dir") + .arg(temp.path().join("data")) .current_dir(&workspace) .env("SECRET", "a-test-secret") // One runtime worker, so a verification that ran on the runtime would stall the diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 0fd1416a0..3bab8980f 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -1,5 +1,5 @@ //! AC5, AC29, AC30, AC33, AC36, AC37 — the stdio mode in the real binary: the flag, the JSON-RPC -//! stream, the banner's stream, the absent socket, the exit code, the unwired store's answer, the +//! stream, the banner's stream, the absent socket, the exit code, the store the mode opens, the //! ways the mode refuses to start with a credential it cannot accept, and the payments refusal //! that belongs to the relay path rather than to this door. //! @@ -10,10 +10,10 @@ //! | `settings_get_answers_redacted_over_stdio` | a real call answers the redacted document | //! | `the_mode_binds_no_socket` | the dialogue completes while the port the flag names is held by the test | //! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | -//! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | -//! | `the_write_tools_report_the_unwired_store` | both write tools reach the unwired store and answer its message, rather than a protocol error | -//! | `the_store_family_tools_report_the_unwired_store` | the five store-family tools reach the unwired store and answer its message | -//! | `the_maintenance_tools_report_the_unwired_store` | `maintenance_run` reaches the unwired store and answers its message while `maintenance_last_run` answers `{"run": null}` | +//! | `the_store_backed_tools_read_the_opened_store` | `list_events` reads the LMDB store the mode opened: an empty page, not an error | +//! | `the_write_tools_reach_the_opened_store` | both write tools reach the opened store; a delete of an unknown id is the store's `not_found` | +//! | `the_store_family_tools_write_through_to_the_opened_store` | the store-family tools reach the opened store, and a user admitted by one process is admitted when a second reads it | +//! | `the_maintenance_tools_run_against_the_opened_store` | `maintenance_run` completes over the opened store and `maintenance_last_run` answers its record | //! | `the_help_text_names_the_credential` | `--help` names the two flags, the document's shape and scopes, the file rule and the retired variable | //! | `a_console_session_token_in_the_environment_refuses_to_start` | the retired variable is named rather than ignored, even when it carries a token the console would accept | //! | `a_group_readable_token_file_refuses_to_start` | mode 0644 fails the start, and the message names both modes | @@ -77,6 +77,8 @@ fn write_private(path: &Path, contents: &str) { struct Prepared { _temp: tempfile::TempDir, config_dir: PathBuf, + /// The LMDB root the mode opens (#1206): the door reads and writes a real store. + data_dir: PathBuf, token: PathBuf, } @@ -88,15 +90,17 @@ impl Prepared { std::fs::write( config_dir.join("settings.yaml"), format!( - "info:\n name: Example\n relay_url: ws://127.0.0.1:8008\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" + "info:\n name: Example\n relay_url: ws://127.0.0.1:8008\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\neventStore:\n backend: lmdb\n" ), ) .unwrap(); let token = temp.path().join("admin-token.json"); write_private(&token, &token_document(&["write"])); + let data_dir = temp.path().join("data"); Self { _temp: temp, config_dir, + data_dir, token, } } @@ -114,7 +118,7 @@ impl Prepared { } /// The same fixture with a retention window configured: without one the purge's guard answers - /// three zeros and reaches no store, so the unwired store would never be seen. + /// three zeros and reaches no store, so the run would never touch the opened one. fn with_retention() -> Self { let prepared = Self::new(); let settings = prepared.config_dir.join("settings.yaml"); @@ -132,6 +136,8 @@ impl Prepared { self.config_dir.display().to_string(), "--log-level".to_owned(), "info".to_owned(), + "--data-dir".to_owned(), + self.data_dir.display().to_string(), "--mcp-stdio".to_owned(), "--admin-token-file".to_owned(), self.token.display().to_string(), @@ -518,29 +524,26 @@ async fn the_process_exits_zero_on_stdin_eof() { } #[tokio::test] -async fn the_store_backed_tools_report_the_unwired_store() { +async fn the_store_backed_tools_read_the_opened_store() { let prepared = Prepared::new(); let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; let response = daemon.call("list_events", json!({})).await; let outcome = daemon.finish().await; - assert_eq!(response["result"]["isError"], true, "{response}"); - let text = response["result"]["content"][0]["text"] - .as_str() - .unwrap_or_default(); - assert!( - text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), - "{text}" + assert_eq!(response["result"]["isError"], false, "{response}"); + assert_eq!( + response["result"]["structuredContent"], + json!({ "events": [], "truncated": false }), + "an empty store answers an empty page, not an error: {response}" ); assert!(outcome.status.success(), "{}", outcome.stderr); } -/// The two write tools exist in the real binary and reach the daemon's unwired bundle: their -/// answer is the store's own message, not the router's `tool not found` that was true before -/// this slice. +/// The two write tools reach the opened store: a delete of an id it does not hold is answered +/// `not_found` by the store, rather than by an unwired bundle's error. #[tokio::test] -async fn the_write_tools_report_the_unwired_store() { +async fn the_write_tools_reach_the_opened_store() { let prepared = Prepared::new(); let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; @@ -555,60 +558,78 @@ async fn the_write_tools_report_the_unwired_store() { .await; let outcome = daemon.finish().await; - for (tool, response) in [("delete_event", &deleted), ("reports_action", &acted)] { - assert_eq!(response["result"]["isError"], true, "{tool}: {response}"); - let text = response["result"]["content"][0]["text"] - .as_str() - .unwrap_or_default(); - assert!( - text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), - "{tool}: {text}" - ); - } + assert_eq!(deleted["result"]["isError"], false, "{deleted}"); + assert_eq!( + deleted["result"]["structuredContent"], + json!({ "event": null, "outcome": "not_found" }), + "{deleted}" + ); + assert_eq!(acted["result"]["isError"], false, "{acted}"); + assert_eq!( + acted["result"]["structuredContent"], + json!({ "reports": [], "changed": 0 }), + "an id no report names flips nothing and answers the empty rows: {acted}" + ); assert!(outcome.status.success(), "{}", outcome.stderr); } -/// The five store-family tools exist in the real binary and reach the daemon's unwired bundle: -/// their answer is the store's own message, not the router's `tool not found` that was true -/// before this slice. +/// The store-family tools reach the opened store, and what one process writes the next process +/// reads: a user admitted through one `--mcp-stdio` is admitted when a second one reads it. #[tokio::test] -async fn the_store_family_tools_report_the_unwired_store() { +async fn the_store_family_tools_write_through_to_the_opened_store() { let prepared = Prepared::new(); - let mut daemon = Daemon::start(&prepared, &[]); - daemon.initialize().await; let pubkey = "ab".repeat(32); - let admitted = daemon + + let mut first = Daemon::start(&prepared, &[]); + first.initialize().await; + let admitted = first .call("user_admin", json!({ "pubkey": pubkey, "action": "admit" })) .await; - let read = daemon.call("user_get", json!({ "pubkey": pubkey })).await; - let listed = daemon.call("invoices_list", json!({})).await; - let invoice = daemon.call("invoices_get", json!({ "id": "inv-1" })).await; - let queue = daemon.call("reports_list", json!({})).await; - let outcome = daemon.finish().await; + let listed = first.call("invoices_list", json!({})).await; + let invoice = first.call("invoices_get", json!({ "id": "inv-1" })).await; + let queue = first.call("reports_list", json!({})).await; + let outcome = first.finish().await; + assert!(outcome.status.success(), "{}", outcome.stderr); - for (tool, response) in [ - ("user_admin", &admitted), - ("user_get", &read), - ("invoices_list", &listed), - ("invoices_get", &invoice), - ("reports_list", &queue), + assert_eq!(admitted["result"]["isError"], false, "{admitted}"); + assert_eq!( + admitted["result"]["structuredContent"]["user"]["is_admitted"], true, + "{admitted}" + ); + // The empty store's own answers, not merely "some error that is not the stub": a tool that lost its + // store would answer `tool not found` or a wiring error and fail on the payload as well as on isError. + for (tool, response, expected) in [ + ("invoices_list", &listed, json!({ "invoices": [] })), + ("invoices_get", &invoice, json!({ "invoice": null })), + ("reports_list", &queue, json!({ "reports": [] })), ] { - assert_eq!(response["result"]["isError"], true, "{tool}: {response}"); - let text = response["result"]["content"][0]["text"] - .as_str() - .unwrap_or_default(); - assert!( - text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), - "{tool}: {text}" + assert_eq!( + response["result"]["isError"], false, + "{tool} answers the store, not an error: {response}" + ); + assert_eq!( + response["result"]["structuredContent"], expected, + "{tool} answers the opened store's empty result: {response}" ); } + + let mut second = Daemon::start(&prepared, &[]); + second.initialize().await; + let read = second.call("user_get", json!({ "pubkey": pubkey })).await; + let outcome = second.finish().await; assert!(outcome.status.success(), "{}", outcome.stderr); + + assert_eq!(read["result"]["isError"], false, "{read}"); + assert_eq!( + read["result"]["structuredContent"]["user"]["is_admitted"], true, + "the second process reads the first one's write: {read}" + ); } -/// The maintenance tools exist in the real binary and the run reaches the daemon's unwired bundle: -/// its answer is the store's own message, so no run record is written and the read stays `null`. +/// The maintenance run reaches the opened store: it completes, and its record is what the read +/// answers next. #[tokio::test] -async fn the_maintenance_tools_report_the_unwired_store() { +async fn the_maintenance_tools_run_against_the_opened_store() { let prepared = Prepared::with_retention(); let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; @@ -616,19 +637,17 @@ async fn the_maintenance_tools_report_the_unwired_store() { let record = daemon.call("maintenance_last_run", json!({})).await; let outcome = daemon.finish().await; - assert_eq!(run["result"]["isError"], true, "{run}"); - let text = run["result"]["content"][0]["text"] - .as_str() - .unwrap_or_default(); - assert!( - text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), - "{text}" - ); + assert_eq!(run["result"]["isError"], false, "{run}"); assert_eq!(record["result"]["isError"], false, "{record}"); + let recorded = &record["result"]["structuredContent"]["run"]; assert_eq!( - record["result"]["structuredContent"], - json!({ "run": null }), - "a failed run records nothing: {record}" + recorded["deleted"], 0, + "an empty store purges nothing: {record}" + ); + assert_eq!(recorded["expired"], 0, "{record}"); + assert!( + recorded["ranAt"].is_string(), + "a completed run is recorded: {record}" ); assert!(outcome.status.success(), "{}", outcome.stderr); } @@ -808,13 +827,14 @@ async fn an_inherited_descriptor_authenticates() { shell .arg("-c") .arg( - "exec 3<\"$TOKEN\"; exec \"$BIN\" --config-dir \"$CFG\" --log-level info \ - --mcp-stdio --admin-token-fd 3", + "exec 3<\"$TOKEN\"; exec \"$BIN\" --config-dir \"$CFG\" --data-dir \"$DATA\" \ + --log-level info --mcp-stdio --admin-token-fd 3", ) .current_dir(workspace_root()) .env("TOKEN", &prepared.token) .env("BIN", env!("CARGO_BIN_EXE_nostreamd")) .env("CFG", &prepared.config_dir) + .env("DATA", &prepared.data_dir) .env("SECRET", SECRET) .env("WORKER_COUNT", "1") .env_remove("NOSTREAM_ADMIN_TOKEN") diff --git a/crates/nostreamd/tests/services_wiring.rs b/crates/nostreamd/tests/services_wiring.rs index 8bf8a9b76..78105118e 100644 --- a/crates/nostreamd/tests/services_wiring.rs +++ b/crates/nostreamd/tests/services_wiring.rs @@ -1,8 +1,8 @@ //! The daemon supplies the real trust graph (R35, AC44). //! -//! With the shipped `wot.enabled: false` nothing changes; with it on and no backend wired the -//! graph fails to build, logs once and answers `None` — the same answer `UnavailableWotGraph` -//! gives — while the daemon keeps serving. +//! With the shipped `wot.enabled: false` nothing changes. With it on over an unavailable bundle +//! the graph fails to build, logs once and answers `None` — the same answer `UnavailableWotGraph` +//! gives — and the daemon itself, over the store it opens (#1206), serves with the graph on. //! //! These targets may unwrap and assert by panicking: a failed assertion is a failed test. @@ -171,6 +171,9 @@ fn run_daemon(config_dir: &Path) -> (Option, String, String) { "0", "--log-level", "info", + // The daemon opens a real store (#1206): a scratch LMDB root in the config dir. + "--data-dir", + config_dir.join("data").to_str().expect("utf-8"), ]) .current_dir(workspace_root()) .stdout(Stdio::piped()) @@ -216,7 +219,7 @@ fn the_daemon_serves_with_the_wot_graph_enabled() { let directory = tempfile::tempdir().expect("tempdir"); fs::write( directory.path().join("settings.yaml"), - "wot:\n enabled: true\n seedPubkey: \"0101010101010101010101010101010101010101010101010101010101010101\"\n", + "wot:\n enabled: true\n seedPubkey: \"0101010101010101010101010101010101010101010101010101010101010101\"\neventStore:\n backend: lmdb\n", ) .expect("write"); diff --git a/crates/nostreamd/tests/store_wiring.rs b/crates/nostreamd/tests/store_wiring.rs new file mode 100644 index 000000000..412238f3a --- /dev/null +++ b/crates/nostreamd/tests/store_wiring.rs @@ -0,0 +1,413 @@ +//! The daemon serves from a real store (#1206): an event one process accepts is there for the +//! next process that opens the same store. +//! +//! | case | Rust test | +//! |---|---| +//! | LMDB: an event published to one daemon is read back from a second after a restart | `an_event_survives_a_restart_on_lmdb` | +//! | Postgres: the same, from the same binary, selected by settings (needs `PARITY_ADMIN_URL`) | `an_event_survives_a_restart_on_postgres` | +//! | the lmdb backend without `--data-dir` refuses to start, naming the flag | `the_lmdb_backend_without_a_data_dir_refuses_to_start` | +//! | Postgres that cannot be reached refuses to start instead of serving an empty store | `an_unreachable_postgres_refuses_to_start` | +//! +//! These targets may unwrap and assert by panicking: a failed assertion is a failed test. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use futures_util::{SinkExt, StreamExt}; +use nostream_core::{Event, EventId, Kind, Pubkey, Signature}; +use tokio_tungstenite::tungstenite::Message; + +fn workspace_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../") + .canonicalize() + .expect("the workspace root exists") +} + +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0") + .expect("an ephemeral port") + .local_addr() + .expect("its address") + .port() +} + +/// A running daemon and the lines it has logged so far. +struct Daemon { + child: Child, + lines: mpsc::Receiver, + seen: Vec, +} + +impl Daemon { + fn spawn(config_dir: &Path, data_dir: Option<&Path>, port: u16, env: &[(&str, &str)]) -> Self { + let mut command = Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .args(["--config-dir", config_dir.to_str().expect("utf-8")]) + .args(["--listen-port", &port.to_string(), "--log-level", "info"]) + .current_dir(workspace_root()) + .env_remove("DB_URI") + .env_remove("DB_HOST") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(dir) = data_dir { + command.args(["--data-dir", dir.to_str().expect("utf-8")]); + } + for (key, value) in env { + command.env(key, value); + } + let mut child = command.spawn().expect("the binary spawns"); + + let (sender, lines) = mpsc::channel(); + for pipe in [ + Box::new(child.stdout.take().expect("stdout")) as Box, + Box::new(child.stderr.take().expect("stderr")), + ] { + let sender = sender.clone(); + std::thread::spawn(move || { + for line in BufReader::new(pipe).lines().map_while(Result::ok) { + if sender.send(line).is_err() { + break; + } + } + }); + } + + Self { + child, + lines, + seen: Vec::new(), + } + } + + /// Waits for a logged line containing `needle`, or for the process to exit. + fn wait_for(&mut self, needle: &str, deadline: Duration) -> bool { + let until = Instant::now() + deadline; + while Instant::now() < until { + match self.lines.recv_timeout(Duration::from_millis(100)) { + Ok(line) => { + let hit = line.contains(needle); + self.seen.push(line); + if hit { + return true; + } + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if self.child.try_wait().expect("wait works").is_some() { + self.drain(); + return self.seen.iter().any(|line| line.contains(needle)); + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => return false, + } + } + false + } + + fn drain(&mut self) { + while let Ok(line) = self.lines.recv_timeout(Duration::from_millis(200)) { + self.seen.push(line); + } + } + + fn logs(&self) -> String { + self.seen.join("\n") + } + + /// Sends SIGINT and waits for the drain, so the store is closed before the next open. + fn stop(mut self) -> (Option, String) { + if self.child.try_wait().expect("wait works").is_none() { + let status = Command::new("kill") + .args(["-INT", &self.child.id().to_string()]) + .status() + .expect("kill runs"); + assert!(status.success(), "SIGINT was delivered"); + } + let deadline = Instant::now() + Duration::from_secs(20); + let status = loop { + if let Some(status) = self.child.try_wait().expect("wait works") { + break status; + } + if Instant::now() > deadline { + let _ = self.child.kill(); + panic!("the daemon did not drain: {}", self.logs()); + } + std::thread::sleep(Duration::from_millis(50)); + }; + self.drain(); + (status.code(), self.logs()) + } + + /// Waits for the process to exit by itself. + fn exit(mut self, deadline: Duration) -> (Option, String) { + let until = Instant::now() + deadline; + let status = loop { + if let Some(status) = self.child.try_wait().expect("wait works") { + break status; + } + if Instant::now() > until { + let _ = self.child.kill(); + let _ = self.child.wait(); + self.drain(); + panic!("the daemon kept running: {}", self.logs()); + } + std::thread::sleep(Duration::from_millis(50)); + }; + self.drain(); + (status.code(), self.logs()) + } +} + +fn write_settings(config_dir: &Path, backend: &str) { + std::fs::write( + config_dir.join("settings.yaml"), + format!("eventStore:\n backend: {backend}\n"), + ) + .expect("settings written"); +} + +fn signed_note(content: &str) -> Event { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("after the epoch") + .as_secs() as i64; + let mut event = Event { + id: EventId::from_byte_array([0; 32]), + pubkey: Pubkey::from_byte_array([0; 32]), + created_at: now, + kind: Kind(1), + tags: Vec::new(), + content: content.to_owned(), + sig: Signature::from_byte_array([0; 64]), + }; + nostream_core::crypto::sign_event(&[0x42; 32], &mut event).expect("a valid key signs"); + event +} + +type Socket = + tokio_tungstenite::WebSocketStream>; + +async fn connect(port: u16) -> Socket { + let (socket, _response) = tokio::time::timeout( + Duration::from_secs(5), + tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}")), + ) + .await + .expect("connects in time") + .expect("the handshake succeeds"); + socket +} + +/// The next text frame, parsed, skipping the NIP-42 challenge. +async fn next_frame(socket: &mut Socket) -> serde_json::Value { + loop { + let message = tokio::time::timeout(Duration::from_secs(5), socket.next()) + .await + .expect("a frame in time") + .expect("the socket is open") + .expect("a frame"); + if let Message::Text(text) = message { + let frame: serde_json::Value = serde_json::from_str(&text).expect("json"); + if frame[0] == "AUTH" { + continue; + } + return frame; + } + } +} + +async fn publish(port: u16, event: &Event) -> serde_json::Value { + let mut socket = connect(port).await; + let frame = serde_json::json!(["EVENT", event]); + socket + .send(Message::Text(frame.to_string().into())) + .await + .expect("sent"); + next_frame(&mut socket).await +} + +async fn read_back(port: u16, id: &EventId) -> Vec { + let mut socket = connect(port).await; + let frame = serde_json::json!(["REQ", "read-back", { "ids": [id.to_string()] }]); + socket + .send(Message::Text(frame.to_string().into())) + .await + .expect("sent"); + let mut frames = Vec::new(); + loop { + let frame = next_frame(&mut socket).await; + let done = frame[0] != "EVENT"; + frames.push(frame); + if done { + return frames; + } + } +} + +fn runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime") +} + +/// Publishes to one daemon, stops it, and reads the event back from a second. +fn survives_a_restart(config_dir: &Path, data_dir: Option<&Path>, env: &[(&str, &str)]) { + // The relay refuses every EVENT without a signing key (`relay_key.rs`); any SECRET derives one. + let mut env = env.to_vec(); + env.push(("SECRET", "store-wiring-test-secret")); + let env = env.as_slice(); + let event = signed_note("stored by the first process"); + let runtime = runtime(); + + let port = free_port(); + let mut first = Daemon::spawn(config_dir, data_dir, port, env); + assert!( + first.wait_for("the acceptor is listening", Duration::from_secs(20)), + "the first daemon served: {}", + first.logs() + ); + let ok = runtime.block_on(publish(port, &event)); + let (code, logs) = first.stop(); + assert_eq!( + ok, + serde_json::json!(["OK", event.id.to_string(), true, ""]), + "the event is accepted and stored: {logs}" + ); + assert_eq!(code, Some(0), "the first daemon drained: {logs}"); + + let port = free_port(); + let mut second = Daemon::spawn(config_dir, data_dir, port, env); + assert!( + second.wait_for("the acceptor is listening", Duration::from_secs(20)), + "the second daemon served: {}", + second.logs() + ); + let frames = runtime.block_on(read_back(port, &event.id)); + let (code, logs) = second.stop(); + assert_eq!(code, Some(0), "the second daemon drained: {logs}"); + + assert_eq!(frames.len(), 2, "one event then EOSE: {frames:?}"); + assert_eq!(frames[0][0], "EVENT"); + assert_eq!(frames[0][2]["id"], event.id.to_string()); + assert_eq!(frames[0][2]["content"], "stored by the first process"); + assert_eq!(frames[1], serde_json::json!(["EOSE", "read-back"])); +} + +#[test] +fn an_event_survives_a_restart_on_lmdb() { + let config_dir = tempfile::tempdir().expect("tempdir"); + let data_dir = tempfile::tempdir().expect("tempdir"); + write_settings(config_dir.path(), "lmdb"); + + survives_a_restart(config_dir.path(), Some(data_dir.path()), &[]); + + assert!( + nostream_storage::backend::store_exists(data_dir.path()), + "the store is at /lmdb" + ); +} + +#[test] +fn the_lmdb_backend_without_a_data_dir_refuses_to_start() { + let config_dir = tempfile::tempdir().expect("tempdir"); + write_settings(config_dir.path(), "lmdb"); + + let daemon = Daemon::spawn(config_dir.path(), None, free_port(), &[]); + let (code, logs) = daemon.exit(Duration::from_secs(20)); + + assert_eq!(code, Some(1), "{logs}"); + assert!( + logs.contains("event store: the lmdb backend needs --data-dir "), + "the refusal names the flag: {logs}" + ); + assert!( + !logs.contains("the acceptor is listening"), + "nothing is served: {logs}" + ); +} + +#[test] +fn an_unreachable_postgres_refuses_to_start() { + let config_dir = tempfile::tempdir().expect("tempdir"); + write_settings(config_dir.path(), "postgres"); + // A port nothing listens on. + let uri = format!( + "postgres://postgres:postgres@127.0.0.1:{}/nostream", + free_port() + ); + + let daemon = Daemon::spawn( + config_dir.path(), + None, + free_port(), + &[("DB_URI", &uri), ("DB_ACQUIRE_CONNECTION_TIMEOUT", "2000")], + ); + let (code, logs) = daemon.exit(Duration::from_secs(30)); + + assert_eq!(code, Some(1), "{logs}"); + assert!( + logs.contains("event store: "), + "the refusal is the store's: {logs}" + ); + assert!( + !logs.contains("the acceptor is listening"), + "nothing is served: {logs}" + ); +} + +/// Creates a scratch database migrated to the schema and returns its URL. +async fn scratch_postgres(admin_url: &str, name: &str) -> String { + use sqlx::Connection; + let mut admin = sqlx::PgConnection::connect(admin_url) + .await + .expect("the admin database is reachable"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "DROP DATABASE IF EXISTS {name}" + ))) + .execute(&mut admin) + .await + .expect("drop"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) + .execute(&mut admin) + .await + .expect("create"); + let (base, _admin_db) = admin_url.rsplit_once('/').expect("a database path"); + let url = format!("{base}/{name}"); + nostream_storage::PostgresBackend::connect(&url) + .await + .expect("the scratch database is reachable") + .migrate() + .await + .expect("migrated"); + url +} + +#[test] +#[ignore = "needs PARITY_ADMIN_URL, a Postgres the test may create a database on"] +fn an_event_survives_a_restart_on_postgres() { + let admin_url = std::env::var("PARITY_ADMIN_URL").expect("PARITY_ADMIN_URL is set"); + let url = runtime().block_on(scratch_postgres(&admin_url, "nostreamd_store_wiring")); + let config_dir = tempfile::tempdir().expect("tempdir"); + write_settings(config_dir.path(), "postgres"); + + survives_a_restart(config_dir.path(), None, &[("DB_URI", &url)]); + + runtime().block_on(async { + use sqlx::{Connection, Executor}; + let mut admin = sqlx::PgConnection::connect(&admin_url) + .await + .expect("the admin database is reachable"); + admin + .execute(sqlx::AssertSqlSafe( + "DROP DATABASE IF EXISTS nostreamd_store_wiring WITH (FORCE)".to_owned(), + )) + .await + .expect("the scratch database drops"); + }); +} diff --git a/crates/nostreamd/tests/workers.rs b/crates/nostreamd/tests/workers.rs index 7f13db056..70ce46213 100644 --- a/crates/nostreamd/tests/workers.rs +++ b/crates/nostreamd/tests/workers.rs @@ -32,6 +32,9 @@ fn run_daemon(config_dir: &Path, control_port: u16) -> (Option, String) { "0", "--log-level", "info", + // The daemon opens a real store (#1206): a scratch LMDB root in the config dir. + "--data-dir", + config_dir.join("data").to_str().expect("utf-8"), ]) .env("TOR_HOST", "127.0.0.1") .env("TOR_CONTROL_PORT", control_port.to_string()) @@ -88,6 +91,11 @@ fn a_silent_control_port_does_not_hold_the_daemon_open_past_the_drain() { }); let directory = tempfile::tempdir().expect("tempdir"); + std::fs::write( + directory.path().join("settings.yaml"), + "eventStore:\n backend: lmdb\n", + ) + .expect("write"); let (code, logs) = run_daemon(directory.path(), control_port); assert_eq!(code, Some(0), "the daemon drained: {logs}"); diff --git a/docs/rewrite/decisions/0012-nip50-search-index.md b/docs/rewrite/decisions/0012-nip50-search-index.md index efbc16c05..c8ec951db 100644 --- a/docs/rewrite/decisions/0012-nip50-search-index.md +++ b/docs/rewrite/decisions/0012-nip50-search-index.md @@ -289,6 +289,20 @@ failure modes. With no second writer to justify it, the lock is the whole answer live store, or a relay started twice on one volume. The sentinel above, or a directory lock the operating system drops when its holder dies, then stops being optional. +**Amended by #1206 — the second process arrived.** The daemon now opens the store its settings name, +and `--mcp-stdio` is a sidecar that opens the same one, which is the first trigger above. The rejected +sentinel stays rejected; the second remedy is taken instead. `open` takes an exclusive `flock` +(`std::fs::File::lock`) on `/lmdb/search-index.lock` inside the per-path mutex and holds it +across the same section — the marker read, its comparison and the rebuild — so a second process waits +and then finds the marker current. The operating system drops the lock with its holder, so a process +killed mid-rebuild leaves nothing behind and the next open simply rebuilds. What it does not cover is +unchanged from the paragraph below: a writer in another process is not fenced from a rebuild, so the +contract is still that a rebuild must not overlap writes. Two processes of the same version satisfy +it, because whichever opens first makes the marker current before either serves a write; a sidecar +of a newer index version started against a running relay of an older one does not, and is a +deployment the operator must not run. Measured by +`lmdb::tests::an_open_waits_while_another_holder_has_the_rebuild_lock`. + **A second handle in the same process.** The lock closes the case the static stage found — two `open` calls rebuilding at once — but it is taken by `open`, not by writers. A second `LmdbBackend` over the same path (same heed `Env`) that *writes* while the first is inside its rebuild can therefore have its diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index e3faca336..728ecfb7d 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -128,11 +128,18 @@ A consequence, stated so it is not read as a defect: the daemon still wires `unavailable::stores()` (the store is not wired into `nostreamd` yet), so a storage-backed route answers `500` in the daemon until that job lands. The oracle proves those routes against a real LMDB store; the daemon's composition is what changes when the store is wired. - The one surface handed a bundle of its own is the MCP mode: `nostreamd --mcp-stdio` is a second process, so it composes its own `unavailable::stores()` rather than this `Arc` (D18). The two composition sites are independent, and wiring the store means wiring both. +**Amended by #1206 — the store is wired, and both sites were wired in one change.** `serve` opens +the backend the settings name (`crates/nostreamd/src/stores.rs`) and builds this bundle from it +(`ServiceStores::from(&Repositories)`), and `--mcp-stdio` opens the same store rather than a +`unavailable::stores()` of its own, so a storage-backed route answers from rows instead of `500`. +The MCP mode's bundle is still its own value in its own process (D18); what changed is only that +the two independent compositions now open the same backend the same way. LMDB needs +`--data-dir`, and each open takes the search-index file lock ADR 0012 D9 records. + ### D8 — Settings are read per request and written through a `nostream-config` store The capture's `createSettings()`/`loadMergedSettings()` re-reads the files on every call