From 5e08fdff9dd572718276f73d89d90051435c32a5 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 22 Nov 2026 00:21:27 -0500 Subject: [PATCH 01/10] feat(services): answer the retention purge's counts through the trait MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MaintenanceService::clear_old_events answers EventPurgeCounts; the guard's arm answers three zeros without calling the store. The MaintenanceTasks future carries the counts, MaintenanceRunner passes them through, and PassOutcome gains counts: Option — None on the error, panic and timeout arms, because zeros there would be a fake. --- .../src/services/maintenance_service.rs | 11 +-- crates/nostream-services/src/testing.rs | 15 +++- .../src/workers/maintenance.rs | 27 ++++--- crates/nostream-services/tests/maintenance.rs | 77 ++++++++++++++++--- 4 files changed, 104 insertions(+), 26 deletions(-) diff --git a/crates/nostream-services/src/services/maintenance_service.rs b/crates/nostream-services/src/services/maintenance_service.rs index 29c6dea5d..ca84df258 100644 --- a/crates/nostream-services/src/services/maintenance_service.rs +++ b/crates/nostream-services/src/services/maintenance_service.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use nostream_config::Settings; -use nostream_storage::repositories::{EventRepository, EventRetentionOptions}; +use nostream_storage::repositories::{EventPurgeCounts, EventRepository, EventRetentionOptions}; use crate::error::ServicesError; @@ -19,8 +19,9 @@ impl MaintenanceService { Self { events, settings } } - /// `clearOldEvents`: one retention call, or none when `maxDays` is absent or `<= 0`. - pub async fn clear_old_events(&self) -> Result<(), ServicesError> { + /// `clearOldEvents`: one retention call, or none when `maxDays` is absent or `<= 0` — the + /// guard's answer is three zeros with no call, because a skip is not a purge of nothing. + pub async fn clear_old_events(&self) -> Result { let retention = self .settings .limits @@ -31,7 +32,7 @@ impl MaintenanceService { .and_then(|retention| retention.max_days) .filter(|max_days| *max_days > 0) else { - return Ok(()); + return Ok(EventPurgeCounts::default()); }; let options = EventRetentionOptions { @@ -56,6 +57,6 @@ impl MaintenanceService { ); } - Ok(()) + Ok(counts) } } diff --git a/crates/nostream-services/src/testing.rs b/crates/nostream-services/src/testing.rs index 2842799b2..13fd3f2f9 100644 --- a/crates/nostream-services/src/testing.rs +++ b/crates/nostream-services/src/testing.rs @@ -329,6 +329,7 @@ pub struct InMemoryEventRepository { address_deletes: Mutex>, reads: Mutex, purge_calls: Mutex>, + purge_answer: Mutex, read_gate: Mutex>>, } @@ -420,6 +421,15 @@ impl InMemoryEventRepository { .clone() } + /// Makes the next retention calls answer `counts`. Defaults to + /// [`EventPurgeCounts::default`], so a case that does not ask reads zeros. + pub fn answers_purge_counts(&self, counts: EventPurgeCounts) { + *self + .purge_answer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) = counts; + } + /// Makes every `find_by_filters` wait for one permit. Releases with /// `Semaphore::add_permits`. pub fn gate_reads(&self) -> Arc { @@ -654,7 +664,10 @@ impl EventRepository for InMemoryEventRepository { .unwrap_or_else(|poisoned| poisoned.into_inner()) .push(options.clone()); - Ok(EventPurgeCounts::default()) + Ok(*self + .purge_answer + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner())) }) } diff --git a/crates/nostream-services/src/workers/maintenance.rs b/crates/nostream-services/src/workers/maintenance.rs index 1aa5c6afe..1140129fa 100644 --- a/crates/nostream-services/src/workers/maintenance.rs +++ b/crates/nostream-services/src/workers/maintenance.rs @@ -18,7 +18,7 @@ use nostream_config::settings::Nip05Mode; use nostream_core::clock::Clock; use nostream_core::lifecycle::ShutdownState; use nostream_core::nip05::{Nip05Fetch, VerificationOutcome, verify}; -use nostream_storage::repositories::Nip05Verification; +use nostream_storage::repositories::{EventPurgeCounts, Nip05Verification}; use crate::context::ServiceContext; use crate::error::ServicesError; @@ -52,17 +52,20 @@ pub const DEFAULT_NIP05_MAX_CONSECUTIVE_FAILURES: i32 = 20; /// The delivery-log retention when settings omit it (`src/app/maintenance-worker.ts:288`). pub const DEFAULT_DELIVERY_LOG_RETENTION_DAYS: i64 = 30; -/// What one pass did, for the loop's log line and for the tests that pin the steps. +/// What one pass did, for the loop's log line and for the tests that pin the steps: whether the +/// purge outlived its cap, and the counts the store answered when it completed. A failed or +/// timed-out purge has no counts — zeros there would read as a pass that found nothing to do. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct PassOutcome { pub purge_timed_out: bool, + pub counts: Option, } /// The four steps, so a test can instrument their order without a store or a network. pub trait MaintenanceTasks: Send + Sync { fn clear_old_events( &self, - ) -> Pin> + Send + '_>>; + ) -> Pin> + Send + '_>>; fn reverify_nip05( &self, ) -> Pin> + Send + '_>>; @@ -122,26 +125,30 @@ impl MaintenanceWorker { tracing::error!(error = %error, "Unable to walk pending invoices"); } - let purge_timed_out = match tokio::time::timeout(self.purge_timeout, purge).await { - Ok(Ok(Ok(()))) => false, + let (purge_timed_out, counts) = match tokio::time::timeout(self.purge_timeout, purge).await + { + Ok(Ok(Ok(counts))) => (false, Some(counts)), Ok(Ok(Err(error))) => { tracing::error!(error = %error, "unable to clear old events"); - false + (false, None) } Ok(Err(error)) => { tracing::error!(error = %error, "the retention task ended abnormally"); - false + (false, None) } Err(_) => { tracing::error!( timeout_ms = self.purge_timeout.as_millis(), "unable to clear old events: clearOldEvents timed out" ); - true + (true, None) } }; - PassOutcome { purge_timed_out } + PassOutcome { + purge_timed_out, + counts, + } } fn payments_enabled(&self) -> bool { @@ -217,7 +224,7 @@ impl MaintenanceRunner { impl MaintenanceTasks for MaintenanceRunner { fn clear_old_events( &self, - ) -> Pin> + Send + '_>> { + ) -> Pin> + Send + '_>> { Box::pin(async move { MaintenanceService::new(Arc::clone(&self.stores.events), Arc::clone(&self.settings)) .clear_old_events() diff --git a/crates/nostream-services/tests/maintenance.rs b/crates/nostream-services/tests/maintenance.rs index fb0b327d5..cf03740af 100644 --- a/crates/nostream-services/tests/maintenance.rs +++ b/crates/nostream-services/tests/maintenance.rs @@ -30,7 +30,8 @@ use nostream_services::workers::maintenance::{ MaintenanceRunner, MaintenanceTasks, MaintenanceWorker, NIP05_REVERIFICATION_BATCH_SIZE, }; use nostream_storage::repositories::{ - EventRepository, NotificationDeliveryLogRepository, NotificationOutboxRepository, + EventPurgeCounts, EventRepository, NotificationDeliveryLogRepository, + NotificationOutboxRepository, }; use tokio::sync::{Semaphore, broadcast}; @@ -66,10 +67,20 @@ impl ScriptedTasks { } } +/// The counts [`ScriptedTasks`] answers, and the ones the cases assert: not all zeros, so a pass +/// that dropped the value or answered a default is visible. +fn scripted_counts() -> EventPurgeCounts { + EventPurgeCounts { + deleted: 2, + expired: 3, + retained: 5, + } +} + impl MaintenanceTasks for ScriptedTasks { fn clear_old_events( &self, - ) -> Pin> + Send + '_>> { + ) -> Pin> + Send + '_>> { Box::pin(async move { self.record("purge started"); @@ -86,7 +97,7 @@ impl MaintenanceTasks for ScriptedTasks { self.record("purge finished"); - Ok(()) + Ok(scripted_counts()) }) } @@ -179,16 +190,23 @@ async fn an_overlapping_tick_during_a_pass_is_skipped() { #[tokio::test] async fn the_retention_guard_skips_every_disabled_value_and_forwards_the_whitelists() { let events = testing::InMemoryEventRepository::new(); + // The double would answer these; the guard's arms must answer zeros without asking it. + events.answers_purge_counts(scripted_counts()); let event_store: Arc = Arc::clone(&events) as Arc; for max_days in [None, Some(-1i64), Some(0i64)] { let mut settings = testing::settings(); settings.limits = Some(retention_limits(max_days)); - MaintenanceService::new(Arc::clone(&event_store), Arc::new(settings)) + let counts = MaintenanceService::new(Arc::clone(&event_store), Arc::new(settings)) .clear_old_events() .await .expect("the pass"); + assert_eq!( + counts, + EventPurgeCounts::default(), + "max_days {max_days:?} answers the guard's zeros, not the double's answer" + ); assert!( events.purge_calls().is_empty(), "max_days {max_days:?} must not call the repository" @@ -197,10 +215,15 @@ async fn the_retention_guard_skips_every_disabled_value_and_forwards_the_whiteli let mut settings = testing::settings(); settings.limits = Some(retention_limits(Some(7))); - MaintenanceService::new(Arc::clone(&event_store), Arc::new(settings)) + let counts = MaintenanceService::new(Arc::clone(&event_store), Arc::new(settings)) .clear_old_events() .await .expect("the pass"); + assert_eq!( + counts, + scripted_counts(), + "the enabled arm answers the store" + ); let calls = events.purge_calls(); assert_eq!(calls.len(), 1); @@ -249,6 +272,10 @@ async fn a_slow_purge_that_outlives_the_timeout_does_not_fail_the_pass() { let outcome = worker.run_pass().await; assert!(outcome.purge_timed_out); + assert_eq!( + outcome.counts, None, + "a timed-out purge has no counts to report" + ); assert_eq!( tasks.entries(), vec!["purge started", "nip05", "outbox", "invoices"] @@ -268,6 +295,7 @@ async fn the_pass_order_is_the_captures() { let outcome = worker.run_pass().await; assert!(!outcome.purge_timed_out); + assert_eq!(outcome.counts, Some(scripted_counts())); assert_eq!( tasks.entries(), vec![ @@ -388,10 +416,15 @@ async fn the_relay_restarted_notification_is_one_enqueue_and_obeys_its_toggle() fn runner( settings: nostream_config::Settings, fetch: Arc, -) -> (MaintenanceRunner, Arc) { +) -> ( + MaintenanceRunner, + Arc, + Arc, +) { let nip05 = testing::InMemoryNip05Repository::new(); + let events = testing::InMemoryEventRepository::new(); let stores = ServiceStores { - events: testing::InMemoryEventRepository::new(), + events: Arc::clone(&events) as Arc, users: testing::InMemoryUserRepository::new(), invoices: testing::InMemoryInvoiceRepository::new(), nip05: Arc::clone(&nip05) @@ -437,9 +470,33 @@ fn runner( payments, ), nip05, + events, ) } +/// R2: the production arm answers what the service answers, counts and all — the value the trait +/// used to drop at its own signature. +#[tokio::test] +async fn the_trait_arm_answers_the_services_counts() { + let mut settings = testing::settings(); + settings.limits = Some(retention_limits(Some(7))); + let (runner, _, events) = self::runner(settings, testing::FakeNip05Fetch::new()); + events.answers_purge_counts(scripted_counts()); + + let counts = runner.clear_old_events().await.expect("the purge"); + + assert_eq!( + counts, + scripted_counts(), + "the service's answer, through the trait" + ); + assert_eq!( + events.purge_calls().len(), + 1, + "the enabled arm reached the store once" + ); +} + #[tokio::test] async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_defaults() { let fetch = testing::FakeNip05Fetch::new(); @@ -453,7 +510,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def domain_whitelist: None, domain_blacklist: None, }); - let (runner, repository) = self::runner(settings, Arc::clone(&fetch)); + let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch)); runner.reverify_nip05().await.expect("the pass"); assert!(repository.pending_calls().is_empty()); @@ -466,7 +523,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def domain_whitelist: None, domain_blacklist: None, }); - let (runner, repository) = self::runner(settings, Arc::clone(&fetch)); + let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch)); fetch.respond( 200, @@ -507,7 +564,7 @@ async fn the_nip05_batch_is_skipped_when_disabled_and_read_with_the_captures_def domain_whitelist: None, domain_blacklist: None, }); - let (runner, repository) = self::runner(settings, Arc::clone(&fetch)); + let (runner, repository, _) = self::runner(settings, Arc::clone(&fetch)); repository.set_pending(vec![verified]); (runner, repository) }; From 92b099c8deb218b1c9c8b3d1e637af42044a17b6 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 22 Nov 2026 00:21:27 -0500 Subject: [PATCH 02/10] feat(admin): record the last maintenance run in process memory MaintenanceRun holds ranAt and the three purge counts; record_maintenance_run replaces the previous value and answers the record it stored, latest_maintenance_run reads it, and the field sits on AdminRuntime beside the heartbeats and the probe ring. WorkerHeartbeat and the status document are untouched. --- crates/nostream-admin/src/lib.rs | 2 +- crates/nostream-admin/src/state.rs | 47 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/nostream-admin/src/lib.rs b/crates/nostream-admin/src/lib.rs index ff9c73252..f4ad293b3 100644 --- a/crates/nostream-admin/src/lib.rs +++ b/crates/nostream-admin/src/lib.rs @@ -49,7 +49,7 @@ pub mod utils; pub use error::AdminError; pub use routes::{ADMIN_ROUTES, AdminRoute, PREFIX_MIDDLEWARE, mount}; -pub use state::{AdminState, AdminStateConfig, GrafanaSettings}; +pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun}; /// The CSP nonce the page's `