From 19916d69335a3c2282d1f8c3ad871db56668dc44 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 23:04:18 -0400 Subject: [PATCH] fix(worker): store ResultStorage::Memory results instead of discarding them Workers only stored results for jobs configured with ResultStorage::Database; a job configured with ResultStorage::Memory had its result silently dropped. JobQueue now owns a bounded, TTL-aware in-memory result store, shared by its clones and so by every worker given the same Arc. The worker stores Memory results there before recording the completion (keeping the #50 guarantee), and get_job_result checks it before the database. delete_job_result, cleanup_expired_results and delete_job also act on it. Entries expire on read and are pruned from the front of an expiry-ordered index as new results are stored, so writes stay O(log n) amortised. The store holds at most DEFAULT_MEMORY_RESULT_CAPACITY (10,000) results, evicting the soonest-to-expire (then oldest) entry; JobQueue::with_memory_result_capacity changes the limit. max_size_bytes is not enforced, as on the database path. TestQueue::delete_job now also deletes the job's result. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 ++ README.md | 2 +- docs/job-types.md | 70 ++++++ src/queue/memory_results.rs | 355 +++++++++++++++++++++++++++++++ src/queue/mod.rs | 55 ++++- src/queue/mysql.rs | 7 +- src/queue/postgres.rs | 7 +- src/queue/test.rs | 48 +++++ src/worker.rs | 31 ++- tests/result_storage_tests.rs | 92 ++++++++ tests/result_visibility_tests.rs | 41 +++- 11 files changed, 702 insertions(+), 21 deletions(-) create mode 100644 src/queue/memory_results.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fb24b4..41a9432 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **In-memory result storage works.** A job configured with `ResultStorage::Memory` had + its result silently discarded: workers only stored `ResultStorage::Database` results. + Workers now store them in an in-memory store owned by the `JobQueue` and shared by its + clones, before the job is marked Completed, and `get_job_result`, `delete_job_result`, + `cleanup_expired_results` and `delete_job` use it. Results expire at their TTL (checked + on read and pruned as results are stored), and the store holds at most 10,000 results + by default (`queue::DEFAULT_MEMORY_RESULT_CAPACITY`), evicting the one that expires + soonest, or the oldest; set the limit with the new + `JobQueue::with_memory_result_capacity`. In-memory results are per process: other + processes, including `cargo hammerwork` and the web dashboard, don't see them, and + they are lost on restart. See [Job Results](docs/job-types.md#job-results). + `TestQueue::delete_job` now also deletes the job's result. + ## [2.0.0] - 2026-10-09 A hardening release ([#7](https://github.com/CodingAnarchy/hammerwork/issues/7)). It fixes diff --git a/README.md b/README.md index 744ee72..5c08b90 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ A high-performance, database-driven job queue for Rust with comprehensive featur - **Multi-database support**: PostgreSQL and MySQL backends with optimized dependency queries - **Advanced retry strategies**: Exponential backoff, linear, Fibonacci, and custom retry patterns with jitter - **Job prioritization**: Five priority levels with weighted and strict scheduling algorithms -- **Result storage**: Database and in-memory result storage with TTL and automatic cleanup +- **Result storage**: Database and in-memory (per-process, bounded) result storage with TTL and automatic cleanup ([Job Results](docs/job-types.md#job-results)) - **Worker autoscaling**: Dynamic worker pool scaling based on queue depth and configurable thresholds - **Batch operations**: High-performance bulk job enqueuing with optimized worker processing - **Cron scheduling**: Full cron expression support with timezone awareness diff --git a/docs/job-types.md b/docs/job-types.md index 00fac78..900b58b 100644 --- a/docs/job-types.md +++ b/docs/job-types.md @@ -211,6 +211,76 @@ let handler: JobHandler = Arc::new(|job: Job| { }); ``` +## Job Results + +A handler created with `Worker::new_with_result_handler` can return data with +`JobResult::with_data`. The job's result configuration decides what happens to it: + +| `ResultStorage` | Where the result goes | Who can read it | +|---|---|---| +| `None` (default) | Discarded | Nobody | +| `Database` | The job's row in `hammerwork_jobs` | Any process with database access | +| `Memory` | The `JobQueue`'s in-memory store | Only this process, through the same `JobQueue` (or its clones) | + +The worker stores the result before it marks the job Completed, so whoever sees the job as +Completed can read its result with `get_job_result`. `Job::with_result_ttl` sets how long +the result is kept; without a TTL it is kept until it is deleted (`delete_job_result`, +or deleting the job). `cleanup_expired_results` removes expired results from the +database and from the in-memory store. + +```rust,no_run +# #[allow(unused_imports)] use hammerwork::{*, queue::*, worker::*}; +# #[allow(unused_imports)] use serde_json::json; +# #[allow(unused_imports)] use std::sync::Arc; +# #[allow(unused_variables)] +# async fn doc(pool: sqlx::PgPool) -> std::result::Result<(), Box> { +use hammerwork::{Job, JobQueue, ResultStorage, Worker, WorkerPool}; +use hammerwork::worker::{JobHandlerWithResult, JobResult}; +use std::time::Duration; + +// Keep up to 50,000 in-memory results (the default is 10,000). +let queue = Arc::new(JobQueue::new(pool).with_memory_result_capacity(50_000)); + +let handler: JobHandlerWithResult = Arc::new(|job: Job| { + Box::pin(async move { Ok(JobResult::with_data(json!({"total": job.payload["n"]}))) }) +}); +let mut pool = WorkerPool::new(); +pool.add_worker(Worker::new_with_result_handler(queue.clone(), "reports".to_string(), handler)); + +let job = Job::new("reports".to_string(), json!({"n": 42})) + .with_result_storage(ResultStorage::Memory) + .with_result_ttl(Duration::from_secs(600)); +let job_id = queue.enqueue(job).await?; + +// ...once the job has completed, in the same process: +if let Some(result) = queue.get_job_result(job_id).await? { + println!("total = {}", result["total"]); +} +# Ok(()) +# } +``` + +In-memory results are faster to store than database results, but: + +- **They are per process.** A worker in one process stores them in its own `JobQueue`. + Another process (another worker host, `cargo hammerwork`, the web dashboard) reads + only the database, so for it the job has no stored result. A separately created + `JobQueue` in the same process has its own store too: share one `Arc`. +- **They are lost when the process exits.** +- **They are bounded.** Each `JobQueue` keeps at most `DEFAULT_MEMORY_RESULT_CAPACITY` + (10,000) results, or the number set with `JobQueue::with_memory_result_capacity`. When + it is full, storing a result evicts the one that expires soonest, or the oldest if + none expire. Expired results are removed when read and pruned as new results are + stored. +- They don't appear in `Job::result_data` (from `get_job`), which reflects the database + columns; read them with `get_job_result`. + +`ResultConfig::with_max_size` is recorded with the job but not enforced, for database +and in-memory results alike. + +The `TestQueue` (feature `test`) keeps all results in memory regardless of +`ResultStorage`, expiring them by its mock clock. + ## Error Handling Jobs can fail and be retried automatically: diff --git a/src/queue/memory_results.rs b/src/queue/memory_results.rs new file mode 100644 index 0000000..f2ff6ee --- /dev/null +++ b/src/queue/memory_results.rs @@ -0,0 +1,355 @@ +//! In-memory storage for job results configured with +//! [`ResultStorage::Memory`](crate::job::ResultStorage::Memory). +//! +//! Each [`JobQueue`](super::JobQueue) owns one store, shared by all its clones and so by +//! every worker running on that queue. Results kept here live only in this process: other +//! processes (the CLI, the web dashboard, workers in other processes) cannot see them, and +//! they are lost when the process exits. +//! +//! The store is bounded. Entries expire at their TTL (checked on read, and pruned as new +//! results are stored), and when the store is full the entry that expires soonest is +//! evicted, the oldest first among entries without a TTL. Every operation is +//! `O(log n)` amortised: pruning only removes entries that have already expired, from +//! the front of an ordered index, so a write never scans the whole store. + +// Only the database backends read results back. +#![cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + +use crate::job::JobId; +use chrono::{DateTime, Utc}; +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Mutex, MutexGuard}; + +/// The number of results a [`JobQueue`](super::JobQueue) keeps in memory by default. +/// +/// Change it with +/// [`JobQueue::with_memory_result_capacity`](super::JobQueue::with_memory_result_capacity). +pub const DEFAULT_MEMORY_RESULT_CAPACITY: usize = 10_000; + +/// Eviction order: soonest expiry first (entries without a TTL sort last), then oldest +/// insertion first. The sequence number makes every key unique. +type EvictionKey = (DateTime, u64); + +#[derive(Debug)] +struct Entry { + value: serde_json::Value, + expires_at: Option>, + key: EvictionKey, +} + +#[derive(Debug, Default)] +struct Inner { + entries: HashMap, + order: BTreeMap, + next_seq: u64, +} + +impl Inner { + fn remove(&mut self, job_id: &JobId) -> Option { + let entry = self.entries.remove(job_id)?; + self.order.remove(&entry.key); + Some(entry) + } + + /// Removes the entries that have expired at `now`. Expired entries are at the front + /// of `order`, so this only touches entries it removes (plus one). + fn prune_expired(&mut self, now: DateTime) -> u64 { + let mut removed = 0; + while let Some((&(expiry, _), _)) = self.order.first_key_value() { + // Entries without a TTL sort at `MAX_UTC` and never expire. + if expiry == DateTime::::MAX_UTC || expiry > now { + break; + } + if let Some((_, job_id)) = self.order.pop_first() { + self.entries.remove(&job_id); + removed += 1; + } + } + removed + } +} + +/// A bounded, TTL-aware map from job id to result. See the [module docs](self). +#[derive(Debug)] +pub(crate) struct MemoryResultStore { + capacity: usize, + inner: Mutex, +} + +impl Default for MemoryResultStore { + fn default() -> Self { + Self::with_capacity(DEFAULT_MEMORY_RESULT_CAPACITY) + } +} + +impl MemoryResultStore { + /// A store that keeps at most `capacity` results (none when `capacity` is 0). + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { + capacity, + inner: Mutex::new(Inner::default()), + } + } + + #[cfg(test)] + pub(crate) fn capacity(&self) -> usize { + self.capacity + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + // The critical sections cannot leave `Inner` inconsistent, so a panic in another + // thread holding the lock is no reason to fail here. + self.inner.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Stores `value` as the result of `job_id`, replacing any earlier result. It expires + /// at `expires_at` (never when `None`). + pub(crate) fn store( + &self, + job_id: JobId, + value: serde_json::Value, + expires_at: Option>, + ) { + self.store_at(Utc::now(), job_id, value, expires_at); + } + + fn store_at( + &self, + now: DateTime, + job_id: JobId, + value: serde_json::Value, + expires_at: Option>, + ) { + if self.capacity == 0 { + return; + } + let mut inner = self.lock(); + inner.remove(&job_id); + if expires_at.is_some_and(|exp| exp <= now) { + return; + } + inner.prune_expired(now); + while inner.entries.len() >= self.capacity { + match inner.order.pop_first() { + Some((_, evicted)) => { + inner.entries.remove(&evicted); + } + None => break, + } + } + let seq = inner.next_seq; + inner.next_seq = inner.next_seq.wrapping_add(1); + let key = (expires_at.unwrap_or(DateTime::::MAX_UTC), seq); + inner.order.insert(key, job_id); + inner.entries.insert( + job_id, + Entry { + value, + expires_at, + key, + }, + ); + } + + /// The unexpired result of `job_id`, if any. An expired result is removed. + pub(crate) fn get(&self, job_id: JobId) -> Option { + self.get_at(Utc::now(), job_id) + } + + fn get_at(&self, now: DateTime, job_id: JobId) -> Option { + let mut inner = self.lock(); + let entry = inner.entries.get(&job_id)?; + if entry.expires_at.is_some_and(|exp| exp <= now) { + inner.remove(&job_id); + return None; + } + Some(entry.value.clone()) + } + + /// Removes the result of `job_id`. Returns whether there was one. + pub(crate) fn remove(&self, job_id: JobId) -> bool { + self.lock().remove(&job_id).is_some() + } + + /// Removes every expired result and returns how many were removed. + pub(crate) fn cleanup_expired(&self) -> u64 { + self.lock().prune_expired(Utc::now()) + } + + #[cfg(test)] + fn cleanup_expired_at(&self, now: DateTime) -> u64 { + self.lock().prune_expired(now) + } + + /// The number of results held, including expired ones not yet pruned. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.lock().entries.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Duration; + use serde_json::json; + use uuid::Uuid; + + fn t0() -> DateTime { + DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z") + .unwrap() + .with_timezone(&Utc) + } + + #[test] + fn stores_and_reads_a_result() { + let store = MemoryResultStore::default(); + let id = Uuid::new_v4(); + store.store(id, json!({"ok": true}), None); + assert_eq!(store.get(id), Some(json!({"ok": true}))); + assert_eq!(store.get(Uuid::new_v4()), None); + assert_eq!(store.capacity(), DEFAULT_MEMORY_RESULT_CAPACITY); + } + + #[test] + fn expires_on_read_after_ttl() { + let store = MemoryResultStore::with_capacity(10); + let id = Uuid::new_v4(); + store.store_at(t0(), id, json!(1), Some(t0() + Duration::seconds(10))); + assert_eq!( + store.get_at(t0() + Duration::seconds(9), id), + Some(json!(1)) + ); + assert_eq!(store.get_at(t0() + Duration::seconds(10), id), None); + // The expired entry was removed by the read. + assert_eq!(store.len(), 0); + } + + #[test] + fn already_expired_result_is_not_stored() { + let store = MemoryResultStore::with_capacity(10); + let id = Uuid::new_v4(); + store.store_at(t0(), id, json!(1), Some(t0())); + assert_eq!(store.len(), 0); + } + + #[test] + fn writes_prune_expired_entries() { + let store = MemoryResultStore::with_capacity(10); + let short = Uuid::new_v4(); + let long = Uuid::new_v4(); + let forever = Uuid::new_v4(); + store.store_at(t0(), short, json!(1), Some(t0() + Duration::seconds(1))); + store.store_at(t0(), long, json!(2), Some(t0() + Duration::hours(1))); + store.store_at(t0(), forever, json!(3), None); + assert_eq!(store.len(), 3); + + store.store_at(t0() + Duration::seconds(5), Uuid::new_v4(), json!(4), None); + assert_eq!(store.len(), 3, "the expired entry is pruned by the write"); + assert_eq!(store.get_at(t0() + Duration::seconds(5), short), None); + assert_eq!( + store.get_at(t0() + Duration::seconds(5), long), + Some(json!(2)) + ); + assert_eq!( + store.get_at(t0() + Duration::days(365), forever), + Some(json!(3)) + ); + } + + #[test] + fn cleanup_removes_only_expired_entries() { + let store = MemoryResultStore::with_capacity(10); + for secs in [1, 2, 3] { + store.store_at( + t0(), + Uuid::new_v4(), + json!(secs), + Some(t0() + Duration::seconds(secs)), + ); + } + store.store_at(t0(), Uuid::new_v4(), json!("forever"), None); + assert_eq!(store.cleanup_expired_at(t0() + Duration::seconds(2)), 2); + assert_eq!(store.len(), 2); + assert_eq!(store.cleanup_expired_at(t0() + Duration::days(1)), 1); + assert_eq!(store.len(), 1); + assert_eq!(store.cleanup_expired(), 0); + } + + #[test] + fn full_store_evicts_soonest_to_expire_first() { + let store = MemoryResultStore::with_capacity(3); + let soon = Uuid::new_v4(); + let later = Uuid::new_v4(); + let never = Uuid::new_v4(); + store.store_at(t0(), never, json!("never"), None); + store.store_at(t0(), later, json!("later"), Some(t0() + Duration::hours(2))); + store.store_at(t0(), soon, json!("soon"), Some(t0() + Duration::hours(1))); + + let new = Uuid::new_v4(); + store.store_at(t0(), new, json!("new"), Some(t0() + Duration::hours(3))); + assert_eq!(store.len(), 3); + assert_eq!( + store.get_at(t0(), soon), + None, + "soonest to expire is evicted" + ); + assert!(store.get_at(t0(), later).is_some()); + assert!(store.get_at(t0(), never).is_some()); + assert!(store.get_at(t0(), new).is_some()); + } + + #[test] + fn full_store_without_ttls_evicts_oldest_first() { + let store = MemoryResultStore::with_capacity(2); + let ids: Vec<_> = (0..4).map(|_| Uuid::new_v4()).collect(); + for (n, id) in ids.iter().enumerate() { + store.store_at(t0(), *id, json!(n), None); + } + assert_eq!(store.len(), 2); + assert_eq!(store.get_at(t0(), ids[0]), None); + assert_eq!(store.get_at(t0(), ids[1]), None); + assert_eq!(store.get_at(t0(), ids[2]), Some(json!(2))); + assert_eq!(store.get_at(t0(), ids[3]), Some(json!(3))); + } + + #[test] + fn overwrite_replaces_value_and_expiry() { + let store = MemoryResultStore::with_capacity(2); + let id = Uuid::new_v4(); + store.store_at(t0(), id, json!("old"), Some(t0() + Duration::seconds(1))); + store.store_at(t0(), id, json!("new"), None); + assert_eq!(store.len(), 1); + assert_eq!( + store.get_at(t0() + Duration::days(1), id), + Some(json!("new")) + ); + + // The overwritten entry's old eviction key is gone: filling the store evicts + // the (refreshed) entry only by its new position. + let other = Uuid::new_v4(); + store.store_at(t0(), other, json!("other"), Some(t0() + Duration::hours(1))); + store.store_at(t0(), Uuid::new_v4(), json!("third"), None); + assert_eq!(store.get_at(t0(), other), None); + assert_eq!(store.get_at(t0(), id), Some(json!("new"))); + } + + #[test] + fn remove_deletes_a_result() { + let store = MemoryResultStore::with_capacity(2); + let id = Uuid::new_v4(); + store.store(id, json!(1), None); + assert!(store.remove(id)); + assert!(!store.remove(id)); + assert_eq!(store.get(id), None); + assert_eq!(store.len(), 0); + } + + #[test] + fn zero_capacity_keeps_nothing() { + let store = MemoryResultStore::with_capacity(0); + let id = Uuid::new_v4(); + store.store(id, json!(1), None); + assert_eq!(store.get(id), None); + } +} diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 03792a2..a5b0af7 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -33,6 +33,10 @@ pub mod test; mod payload_encryption; pub(crate) use payload_encryption::PayloadEncryption; +mod memory_results; +pub use memory_results::DEFAULT_MEMORY_RESULT_CAPACITY; +pub(crate) use memory_results::MemoryResultStore; + /// Information about a queue's pause state #[derive(Debug, Clone, Serialize, Deserialize)] pub struct QueuePauseInfo { @@ -335,6 +339,11 @@ pub trait DatabaseQueue: Send + Sync { /// /// Returns the result data if it exists and hasn't expired, otherwise returns `None`. /// + /// On a [`JobQueue`], this first looks in the queue's in-memory store, which holds + /// the results of jobs configured with + /// [`ResultStorage::Memory`](crate::job::ResultStorage::Memory) that workers on this + /// queue (or its clones) completed in this process, and then in the database. + /// /// # Arguments /// /// * `job_id` - The unique identifier of the job @@ -357,7 +366,8 @@ pub trait DatabaseQueue: Send + Sync { /// Delete the stored result data for a job. /// - /// This is useful for manual cleanup or when results are no longer needed. + /// This is useful for manual cleanup or when results are no longer needed. On a + /// [`JobQueue`], this removes the result from the in-memory store too. /// /// # Arguments /// @@ -379,6 +389,8 @@ pub trait DatabaseQueue: Send + Sync { /// /// This method removes all job results that have passed their expiration time. /// It should be called periodically to prevent the database from growing indefinitely. + /// On a [`JobQueue`], expired in-memory results are removed and counted too (they are + /// also pruned as new results are stored). /// /// # Returns /// @@ -1545,6 +1557,9 @@ pub struct JobQueue { pub(crate) throttle_configs: Arc>>, /// Encrypts and decrypts job payloads (see [`JobQueue::with_encryption`]) pub(crate) encryption: PayloadEncryption, + /// Results of jobs with `ResultStorage::Memory`, shared by all clones of this queue + /// (see [`JobQueue::with_memory_result_capacity`]) + pub(crate) memory_results: Arc, } impl Clone for JobQueue { @@ -1554,6 +1569,7 @@ impl Clone for JobQueue { _phantom: PhantomData, throttle_configs: self.throttle_configs.clone(), encryption: self.encryption.clone(), + memory_results: self.memory_results.clone(), } } } @@ -1586,9 +1602,46 @@ impl JobQueue { _phantom: PhantomData, throttle_configs: Arc::new(RwLock::new(HashMap::new())), encryption: PayloadEncryption::default(), + memory_results: Arc::new(MemoryResultStore::default()), } } + /// Sets how many results of jobs configured with + /// [`ResultStorage::Memory`](crate::job::ResultStorage::Memory) this queue keeps in + /// memory. The default is [`DEFAULT_MEMORY_RESULT_CAPACITY`] (10,000); 0 keeps none. + /// + /// Workers store such results in the queue's in-memory store instead of the + /// database, and [`get_job_result`](DatabaseQueue::get_job_result) reads them from + /// there. The store is shared by every clone of the queue (and so by every worker + /// given the same `Arc`), but not by queues created separately with + /// [`JobQueue::new`]. Results expire at their TTL + /// ([`Job::with_result_ttl`](crate::Job::with_result_ttl)). When the store is full, + /// storing a result evicts the one that expires soonest, or the oldest if none + /// expire. + /// + /// In-memory results are local to this process: other processes, such as + /// `cargo hammerwork` or the web dashboard, don't see them, and they are lost when + /// the process exits. Use [`ResultStorage::Database`](crate::job::ResultStorage::Database) + /// for results that must be shared or survive a restart. + /// + /// This replaces the store, dropping the results it held, so call it when building + /// the queue, before cloning it or starting workers. + /// + /// # Examples + /// + /// ```rust,no_run + /// # #[cfg(feature = "postgres")] + /// # async fn example(pool: sqlx::PgPool) { + /// use hammerwork::JobQueue; + /// + /// let queue = JobQueue::new(pool).with_memory_result_capacity(50_000); + /// # } + /// ``` + pub fn with_memory_result_capacity(mut self, capacity: usize) -> Self { + self.memory_results = Arc::new(MemoryResultStore::with_capacity(capacity)); + self + } + /// Encrypts job payloads at rest with `engine`. /// /// Jobs with an encryption config ([`Job::with_encryption`](crate::Job::with_encryption)) diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 519e394..509a1dc 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -913,6 +913,7 @@ impl DatabaseQueue for crate::queue::JobQueue { .execute(&self.pool) .await?; + self.memory_results.remove(job_id); Ok(()) } @@ -1682,6 +1683,9 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn get_job_result(&self, job_id: JobId) -> Result> { + if let Some(result) = self.memory_results.get(job_id) { + return Ok(Some(result)); + } let row = sqlx::query( "SELECT result_data FROM hammerwork_jobs WHERE id = ? AND result_data IS NOT NULL AND (result_expires_at IS NULL OR result_expires_at > UTC_TIMESTAMP(6))" ) @@ -1696,6 +1700,7 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn delete_job_result(&self, job_id: JobId) -> Result<()> { + self.memory_results.remove(job_id); sqlx::query( "UPDATE hammerwork_jobs SET result_data = NULL, result_stored_at = NULL, result_expires_at = NULL WHERE id = ?" ) @@ -1713,7 +1718,7 @@ impl DatabaseQueue for crate::queue::JobQueue { .execute(&self.pool) .await?; - Ok(result.rows_affected()) + Ok(result.rows_affected() + self.memory_results.cleanup_expired()) } // Workflow and dependency management methods diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index a78db77..0683407 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -765,6 +765,7 @@ impl DatabaseQueue for crate::queue::JobQueue { .execute(&self.pool) .await?; + self.memory_results.remove(job_id); Ok(()) } @@ -1530,6 +1531,9 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn get_job_result(&self, job_id: JobId) -> Result> { + if let Some(result) = self.memory_results.get(job_id) { + return Ok(Some(result)); + } let row = sqlx::query( "SELECT result_data FROM hammerwork_jobs WHERE id = $1 AND result_data IS NOT NULL AND (result_expires_at IS NULL OR result_expires_at > now())" ) @@ -1544,6 +1548,7 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn delete_job_result(&self, job_id: JobId) -> Result<()> { + self.memory_results.remove(job_id); sqlx::query( "UPDATE hammerwork_jobs SET result_data = NULL, result_stored_at = NULL, result_expires_at = NULL WHERE id = $1" ) @@ -1561,7 +1566,7 @@ impl DatabaseQueue for crate::queue::JobQueue { .execute(&self.pool) .await?; - Ok(result.rows_affected()) + Ok(result.rows_affected() + self.memory_results.cleanup_expired()) } // Workflow and dependency management methods diff --git a/src/queue/test.rs b/src/queue/test.rs index 1594c6e..1616c84 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -736,6 +736,13 @@ impl TestStorage { /// # Ok(()) /// # } /// ``` +/// +/// ## Job results +/// +/// `TestQueue` keeps every stored result in memory, whatever the job's +/// [`ResultStorage`](crate::job::ResultStorage): `store_job_result` and +/// `get_job_result` behave the same for `Database` and `Memory` jobs, and results expire +/// at their `expires_at` by the [`MockClock`]. Deleting a job deletes its result. #[derive(Clone)] pub struct TestQueue { storage: Arc>, @@ -1237,6 +1244,8 @@ impl DatabaseQueue for TestQueue { batch_jobs.retain(|id| *id != job_id); } + storage.job_results.remove(&job_id); + // Clean up dependencies storage.dependencies.remove(&job_id); for deps in storage.dependents.values_mut() { @@ -3151,6 +3160,45 @@ mod tests { assert_eq!(cleaned, 1); } + #[tokio::test] + async fn test_memory_result_storage_follows_ttl_and_delete() { + use crate::job::ResultStorage; + + let queue = TestQueue::new(); + let clock = queue.clock(); + + let job = Job::new("memory_results".to_string(), json!({})) + .with_result_storage(ResultStorage::Memory) + .with_result_ttl(std::time::Duration::from_secs(60)); + let ttl = job.result_config.ttl.unwrap(); + let job_id = queue.enqueue(job).await.unwrap(); + queue.dequeue("memory_results").await.unwrap().unwrap(); + + // What a worker does: store the result with its TTL, then complete the job. + let expires_at = crate::queue::saturating_add_to(clock.now(), ttl); + queue + .store_job_result(job_id, json!({"n": 1}), Some(expires_at)) + .await + .unwrap(); + queue.complete_job(job_id).await.unwrap(); + + assert_eq!( + queue.get_job_result(job_id).await.unwrap(), + Some(json!({"n": 1})) + ); + clock.advance(chrono::Duration::seconds(61)); + assert_eq!(queue.get_job_result(job_id).await.unwrap(), None); + + // Deleting a job deletes its result. + queue + .store_job_result(job_id, json!({"n": 2}), None) + .await + .unwrap(); + queue.delete_job(job_id).await.unwrap(); + assert_eq!(queue.get_job_result(job_id).await.unwrap(), None); + assert_eq!(queue.cleanup_expired_results().await.unwrap(), 0); + } + #[tokio::test] async fn test_queue_stats() { let queue = TestQueue::new(); diff --git a/src/worker.rs b/src/worker.rs index 538f3c3..0ddd616 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -2177,22 +2177,31 @@ where // Store the result before recording the completion, so that anyone who sees the // job as Completed can also read its result. - if let Some(result_data) = job_result.data - && let crate::job::ResultStorage::Database = job.result_config.storage - { + if let Some(result_data) = job_result.data { let expires_at = job .result_config .ttl .map(|ttl| crate::queue::saturating_add_to(Utc::now(), ttl)); - if let Err(e) = self - .queue - .store_job_result(job_id, result_data, expires_at) - .await - { - error!("Failed to store result for job {}: {}", job_id, e); - } else { - debug!("Stored result for job {}", job_id); + match job.result_config.storage { + crate::job::ResultStorage::Database => { + if let Err(e) = self + .queue + .store_job_result(job_id, result_data, expires_at) + .await + { + error!("Failed to store result for job {}: {}", job_id, e); + } else { + debug!("Stored result for job {}", job_id); + } + } + crate::job::ResultStorage::Memory => { + self.queue + .memory_results + .store(job_id, result_data, expires_at); + debug!("Stored result for job {} in memory", job_id); + } + crate::job::ResultStorage::None => {} } } diff --git a/tests/result_storage_tests.rs b/tests/result_storage_tests.rs index 95c3220..902944c 100644 --- a/tests/result_storage_tests.rs +++ b/tests/result_storage_tests.rs @@ -64,6 +64,86 @@ async fn assert_result_survives_job_completion(queue: &Q) { ); } +/// A worker stores a `Memory` job's result in the queue's in-memory store: the queue +/// reads it back, it expires at its TTL, it can be deleted, and it is never written to +/// the database (a queue with its own store, like another process, doesn't see it). +#[cfg(any(feature = "postgres", feature = "mysql"))] +async fn assert_worker_stores_memory_result(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + hammerwork::JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("memory_result"); + let handler: JobHandlerWithResult = Arc::new(|job| { + Box::pin(async move { Ok(JobResult::with_data(json!({ "echo": job.payload["n"] }))) }) + }); + + let ttl = Duration::from_secs(2); + let expiring = Job::new(queue_name.clone(), json!({"n": 1})) + .with_result_storage(ResultStorage::Memory) + .with_result_ttl(ttl); + let lasting = + Job::new(queue_name.clone(), json!({"n": 2})).with_result_storage(ResultStorage::Memory); + let expiring_id = queue.enqueue(expiring).await.unwrap(); + let lasting_id = queue.enqueue(lasting).await.unwrap(); + + let worker = Worker::new_with_result_handler(queue.clone(), queue_name, handler) + .with_poll_interval(Duration::from_millis(10)); + let mut pool = WorkerPool::new(); + pool.add_worker(worker); + // The results are stored after this, so they expire no earlier than `started + ttl`. + let started = tokio::time::Instant::now(); + let pool_task = tokio::spawn(async move { pool.start().await }); + + for id in [expiring_id, lasting_id] { + assert!( + wait_for_completion(queue.as_ref(), id, Duration::from_secs(20)).await, + "job {id} did not complete" + ); + } + // Measured after completion, so the results expire no later than `completed_at + ttl`. + let completed_at = tokio::time::Instant::now(); + pool_task.abort(); + + assert_eq!( + queue.get_job_result(lasting_id).await.unwrap(), + Some(json!({"echo": 2})) + ); + if started.elapsed() < ttl { + assert_eq!( + queue.get_job_result(expiring_id).await.unwrap(), + Some(json!({"echo": 1})) + ); + } + + // Nothing was written to the result columns. + for id in [expiring_id, lasting_id] { + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Completed); + assert_eq!( + job.result_data, None, + "job {id} result written to the database" + ); + assert_eq!(job.result_stored_at, None); + } + let other_process = hammerwork::JobQueue::::new(queue.get_pool().clone()); + assert_eq!( + other_process.get_job_result(lasting_id).await.unwrap(), + None + ); + + // The result with a TTL expires; the one without stays until it is deleted. + tokio::time::sleep_until(completed_at + ttl + Duration::from_millis(200)).await; + assert_eq!(queue.get_job_result(expiring_id).await.unwrap(), None); + assert!(queue.get_job_result(lasting_id).await.unwrap().is_some()); + queue.delete_job_result(lasting_id).await.unwrap(); + assert_eq!(queue.get_job_result(lasting_id).await.unwrap(), None); + + for id in [expiring_id, lasting_id] { + queue.delete_job(id).await.unwrap(); + } +} + #[cfg(feature = "postgres")] mod postgres_tests { use super::*; @@ -75,6 +155,12 @@ mod postgres_tests { assert_result_survives_job_completion(queue.as_ref()).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_worker_stores_memory_result() { + assert_worker_stores_memory_result(test_utils::setup_postgres_queue().await).await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_job_result_storage_and_retrieval() { @@ -348,6 +434,12 @@ mod mysql_tests { assert_result_survives_job_completion(queue.as_ref()).await; } + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_worker_stores_memory_result() { + assert_worker_stores_memory_result(test_utils::setup_mysql_queue().await).await; + } + #[tokio::test] #[ignore] // Requires database connection async fn test_mysql_result_storage() { diff --git a/tests/result_visibility_tests.rs b/tests/result_visibility_tests.rs index 9a592d8..28c39d0 100644 --- a/tests/result_visibility_tests.rs +++ b/tests/result_visibility_tests.rs @@ -12,8 +12,10 @@ use hammerwork::{ use serde_json::json; use std::{sync::Arc, time::Duration}; -async fn result_is_stored_before_completion_is_visible(queue: Arc>) -where +async fn result_is_stored_before_completion_is_visible( + queue: Arc>, + storage: ResultStorage, +) where DB: sqlx::Database + Send + Sync + 'static, JobQueue: DatabaseQueue + Send + Sync + 'static, { @@ -25,7 +27,7 @@ where let mut job_ids = Vec::new(); for n in 0..20 { let job = Job::new(queue_name.clone(), json!({ "n": n })) - .with_result_storage(ResultStorage::Database) + .with_result_storage(storage.clone()) .with_result_ttl(Duration::from_secs(3600)); job_ids.push(queue.enqueue(job).await.unwrap()); } @@ -74,8 +76,21 @@ mod postgres_tests { #[tokio::test] #[ignore] // Requires database connection async fn test_postgres_result_is_stored_before_completion_is_visible() { - result_is_stored_before_completion_is_visible(test_utils::setup_postgres_queue().await) - .await; + result_is_stored_before_completion_is_visible( + test_utils::setup_postgres_queue().await, + ResultStorage::Database, + ) + .await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_memory_result_is_stored_before_completion_is_visible() { + result_is_stored_before_completion_is_visible( + test_utils::setup_postgres_queue().await, + ResultStorage::Memory, + ) + .await; } } @@ -86,6 +101,20 @@ mod mysql_tests { #[tokio::test] #[ignore] // Requires database connection async fn test_mysql_result_is_stored_before_completion_is_visible() { - result_is_stored_before_completion_is_visible(test_utils::setup_mysql_queue().await).await; + result_is_stored_before_completion_is_visible( + test_utils::setup_mysql_queue().await, + ResultStorage::Database, + ) + .await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_memory_result_is_stored_before_completion_is_visible() { + result_is_stored_before_completion_is_visible( + test_utils::setup_mysql_queue().await, + ResultStorage::Memory, + ) + .await; } }