Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/daemon-opens-its-store.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
6 changes: 6 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
14 changes: 11 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 13 additions & 25 deletions crates/nostream-cli/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<LmdbBackend>),
Postgres(Box<nostream_storage::PostgresBackend>),
}
/// 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()
}
}

Expand Down Expand Up @@ -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) {
Expand All @@ -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)))
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions crates/nostream-relay/src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ pub struct Stores {
pub reports: Arc<dyn ReportRepository>,
}

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
Expand Down
15 changes: 7 additions & 8 deletions crates/nostream-relay/src/unavailable.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
8 changes: 8 additions & 0 deletions crates/nostream-services/src/services/payments_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
22 changes: 20 additions & 2 deletions crates/nostream-services/src/unavailable.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -35,6 +37,22 @@ pub struct ServiceStores {
pub reports: Arc<dyn ReportRepository>,
}

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",
Expand Down
10 changes: 10 additions & 0 deletions crates/nostream-storage/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions crates/nostream-storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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};

Expand Down
63 changes: 63 additions & 0 deletions crates/nostream-storage/src/lmdb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,26 @@ fn rebuild_lock(path: &Path) -> Arc<Mutex<()>> {
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 `<path>/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<std::fs::File, StorageError> {
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 {
Expand Down Expand Up @@ -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
Expand All @@ -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))
Expand Down Expand Up @@ -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");
Expand Down
Loading
Loading