diff --git a/CHANGELOG.md b/CHANGELOG.md index b47cb62..adba4a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. - **No features are enabled by default** (#92). `default` used to be `["metrics", "alerting", "webhooks"]`, which pulled `warp`, `reqwest`, `lettre` and `prometheus` into every build. It is now empty. Enable what you use, or the new `full` feature (`metrics`, `alerting`, `webhooks`, `streaming`, `tracing`, `encryption`; no database backend, KMS key source, event stream sink or `test-queue`). Code that uses `hammerwork::metrics`, `hammerwork::alerting` or `hammerwork::webhooks` must now enable those features. `cargo-hammerwork` and `hammerwork-web` enable the features they need themselves. - **`azure-kv` is renamed `azure-kms`**, to match `aws-kms`, `gcp-kms` and `vault-kms` (#92). There is no alias. The same rename applies to the `cargo-hammerwork` feature. - **`test` is renamed `test-queue`**, after the `TestQueue` it enables (#92). There is no alias. +- **`DatabaseQueue` is sealed** (#87). It can no longer be implemented outside Hammerwork; its implementations are `JobQueue`, `JobQueue` and `TestQueue`, and it stays usable as a bound (`impl DatabaseQueue`, `Q: DatabaseQueue`). Use `TestQueue` (feature `test-queue`) to test without a database. The default method bodies that existed only for implementations outside the crate are gone (the one-at-a-time fallback for batch claims, and the fallbacks of `release_job_run`, `finish_job_run`, `complete_job_run_with_children`, `heartbeat_job`, `start_claimed_run`, `requeue_stale_jobs`, `purge_expired_encrypted_jobs`, `purge_archived_jobs_in_queue` and `list_queue_names`); every backend implements these methods, so behaviour does not change. `queue::RELEASED_JOB_MESSAGE`, the error message of the removed `release_job_run` fallback, is removed. +- **One claim method** (#89). `DatabaseQueue::dequeue(queue, &DequeueOptions)` replaces `dequeue`, `dequeue_with_priority_weights`, `dequeue_leased`, `dequeue_batch` and `dequeue_batch_leased`. It returns `Vec`. The new `#[non_exhaustive]` `queue::DequeueOptions` (also `hammerwork::DequeueOptions`) has `priority_weights: Option`, `lease_duration: Option` (`None` is `DEFAULT_LEASE_DURATION`) and `max_jobs` (default 1), built with `DequeueOptions::new()`/`default()`, `DequeueOptions::batch(n)`, `with_priority_weights`, `with_lease_duration` and `with_max_jobs`. `DatabaseQueue::dequeue_one(queue)` keeps the common case short: it is the 2.x `dequeue(queue)` (one job, strict priority, default lease, `Option`). Claims behave as before: a `max_jobs` of 1 claims like the old single-job methods, larger values like the old batch claims. +- **`Worker::with_batch_processing_enabled` is removed** (#89). `with_batch_size(n)` enables batch mode, as it already did; `with_batch_size(1)` replaces `with_batch_processing_enabled(true)` (batch statistics, one job per poll). New optional `[worker]` settings `batch_size` and `batch_concurrency` (`WorkerConfig::batch_size`, `WorkerConfig::batch_concurrency`) set them from configuration through `Worker::with_config`; code that builds `WorkerConfig` with a struct literal must add them (or use `..Default::default()`). +- **`Worker::with_max_retries` is renamed `with_attempt_cap`** (#89), since it can only lower a job's own `max_attempts`. There is no alias. ### Fixed diff --git a/README.md b/README.md index fa6c41c..084f3c3 100644 --- a/README.md +++ b/README.md @@ -296,13 +296,13 @@ async fn test_delayed_job_processing() { let job_id = queue.enqueue(job).await.unwrap(); // Job shouldn't be available immediately - assert!(queue.dequeue("test_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("test_queue").await.unwrap().is_none()); // Advance time past scheduled time clock.advance(Duration::hours(2)); // Now job should be available for processing - let dequeued = queue.dequeue("test_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); // Complete the job diff --git a/cargo-hammerwork/src/integration_tests/job_state.rs b/cargo-hammerwork/src/integration_tests/job_state.rs index 1419a23..833e7ac 100644 --- a/cargo-hammerwork/src/integration_tests/job_state.rs +++ b/cargo-hammerwork/src/integration_tests/job_state.rs @@ -90,7 +90,7 @@ macro_rules! job_state_scenarios { "retry --queue must not touch other queues" ); // The retried job is actually runnable by the library's dequeue. - let dequeued = queue.dequeue(&qname).await.unwrap(); + let dequeued = queue.dequeue_one(&qname).await.unwrap(); assert!(dequeued.is_some(), "retried job should be dequeueable"); // --- retry of a single job in a state that cannot be retried is rejected --- diff --git a/docs/batch-operations.md b/docs/batch-operations.md index f82623b..cb0a14e 100644 --- a/docs/batch-operations.md +++ b/docs/batch-operations.md @@ -262,9 +262,9 @@ for (job_id, error) in &result.job_errors { A worker in batch mode claims up to `batch_size` jobs per poll in one round trip instead of one job per round trip, then runs them `batch_concurrency` at a time (one at a time by -default). `with_batch_size(n)` enables batch mode; `with_batch_processing_enabled(true)` -alone keeps the default batch size of 1, so it claims one job per poll as before and only -adds batch statistics: +default). `with_batch_size(n)` enables batch mode; `with_batch_size(1)` claims one job +per poll as without batch mode and only adds batch statistics. The `[worker]` settings +`batch_size` and `batch_concurrency` (`WorkerConfig`) set the same from configuration: ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; @@ -348,13 +348,12 @@ The queue API claims batches too, for custom consumers: # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; # #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] # async fn doc(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler, jobs: Vec, worker: hammerwork::Worker, batch_id: hammerwork::BatchId) -> std::result::Result<(), Box> { -use hammerwork::{JobOutcome, queue::DatabaseQueue}; +use hammerwork::{JobOutcome, queue::{DatabaseQueue, DequeueOptions}}; use std::time::Duration; // Up to 20 jobs, strict priority order, each leased for 2 minutes. -let jobs = queue - .dequeue_batch_leased("emails", None, Duration::from_secs(120), 20) - .await?; +let options = DequeueOptions::batch(20).with_lease_duration(Duration::from_secs(120)); +let jobs = queue.dequeue("emails", &options).await?; for job in jobs { let run = job.clone(); let job = queue.decrypt_job(job).await?; // a no-op for unencrypted jobs @@ -608,7 +607,7 @@ async fn main() -> Result<(), Box> { let batch_id = queue.enqueue_batch(batch).await?; println!("Enqueued batch: {}", batch_id); - // Worker with batch processing enabled + // Worker in batch mode: claims up to 20 jobs per poll let handler: JobHandler = Arc::new(|_job: Job| { Box::pin(async move { tokio::time::sleep(Duration::from_millis(100)).await; @@ -617,7 +616,7 @@ async fn main() -> Result<(), Box> { }); let worker = Worker::new(queue.clone(), "data_processing".to_string(), handler) - .with_batch_processing_enabled(true); + .with_batch_size(20); let mut worker_pool = WorkerPool::new(); worker_pool.add_worker(worker); diff --git a/docs/cron-scheduling.md b/docs/cron-scheduling.md index fa10a03..bb4f0eb 100644 --- a/docs/cron-scheduling.md +++ b/docs/cron-scheduling.md @@ -567,7 +567,7 @@ async fn setup_backup_system( let backup_worker = Worker::new(queue, "backup".to_string(), backup_handler) .with_default_timeout(Duration::from_secs(4 * 60 * 60)) - .with_max_retries(2) + .with_attempt_cap(2) .with_retry_delay(Duration::from_secs(30 * 60)); let mut pool = WorkerPool::new(); diff --git a/docs/job-types.md b/docs/job-types.md index 0ac04d6..7ce76a7 100644 --- a/docs/job-types.md +++ b/docs/job-types.md @@ -110,9 +110,9 @@ let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.co .with_max_attempts(5); // At most 5 attempts in total (the first run plus 4 retries) // Worker-level retry configuration. The job's max_attempts is the limit; -// with_max_retries only caps it for jobs processed by this worker. +// with_attempt_cap only caps it for jobs processed by this worker. let worker = Worker::new(queue, "default".to_string(), handler) - .with_max_retries(3) + .with_attempt_cap(3) .with_retry_delay(std::time::Duration::from_secs(30)); // Wait 30s between retries # Ok(()) # } diff --git a/docs/quick-start.md b/docs/quick-start.md index 64ac586..7129bb3 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -113,14 +113,14 @@ async fn main() -> std::result::Result<(), Box> { // Create workers with comprehensive configuration let email_worker = Worker::new(queue.clone(), "email".to_string(), handler.clone()) .with_poll_interval(Duration::from_secs(1)) - .with_max_retries(3) + .with_attempt_cap(3) .with_default_timeout(Duration::from_secs(30)) .with_rate_limit(RateLimit::per_second(2)) .with_stats_collector(Arc::clone(&stats_collector)); let data_worker = Worker::new(queue.clone(), "data_processing".to_string(), handler.clone()) .with_poll_interval(Duration::from_secs(2)) - .with_max_retries(2) + .with_attempt_cap(2) .with_default_timeout(Duration::from_secs(60)) .with_stats_collector(Arc::clone(&stats_collector)); @@ -263,13 +263,13 @@ async fn main() -> std::result::Result<(), Box> { // Create workers for different job types let image_worker = Worker::new(queue.clone(), "image_processing".to_string(), handler.clone()) .with_poll_interval(Duration::from_secs(1)) - .with_max_retries(2) + .with_attempt_cap(2) .with_default_timeout(Duration::from_secs(120)) // Longer timeout for images .with_stats_collector(Arc::clone(&stats_collector)); let email_worker = Worker::new(queue.clone(), "email_queue".to_string(), handler.clone()) .with_poll_interval(Duration::from_millis(500)) - .with_max_retries(3) + .with_attempt_cap(3) .with_default_timeout(Duration::from_secs(30)) .with_stats_collector(Arc::clone(&stats_collector)); @@ -329,7 +329,7 @@ let job = Job::with_delay("queue_name".to_string(), json!({"data": "value"}), ch # fn example(queue: Arc>, handler: JobHandler, stats_collector: Arc) { let worker = Worker::new(queue.clone(), "queue_name".to_string(), handler) .with_poll_interval(Duration::from_secs(1)) // How often to check for jobs - .with_max_retries(3) // Default retry attempts + .with_attempt_cap(3) // At most 3 attempts per job .with_default_timeout(Duration::from_secs(30)) // Default job timeout .with_rate_limit(RateLimit::per_second(2)) // Rate limiting .with_stats_collector(stats_collector); // Statistics collection diff --git a/docs/testing.md b/docs/testing.md index 75d5469..2cabdd8 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -2,6 +2,8 @@ The `TestQueue` provides a complete in-memory implementation of the `DatabaseQueue` trait, enabling fast, deterministic unit testing without requiring database connections. It includes time manipulation capabilities through `MockClock` for testing time-dependent features like delayed jobs, cron schedules, and timeouts. +`TestQueue` is the supported way to test code that uses a queue without a database. `DatabaseQueue` is sealed: the PostgreSQL and MySQL `JobQueue`s and `TestQueue` are its only implementations, so you cannot write your own mock queue. Write the code under test against `impl DatabaseQueue` (or a generic `Q: DatabaseQueue`) and pass it a `TestQueue` in tests. + ## Table of Contents - [Quick Start](#quick-start) @@ -45,7 +47,7 @@ async fn test_job_processing() { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue and process - let dequeued_job = queue.dequeue("test_queue").await.unwrap().unwrap(); + let dequeued_job = queue.dequeue_one("test_queue").await.unwrap().unwrap(); assert_eq!(dequeued_job.id, job_id); // Complete the job @@ -106,7 +108,7 @@ async fn test_job_lifecycle() { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue job - let dequeued = queue.dequeue("priority_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("priority_queue").await.unwrap().unwrap(); assert_eq!(dequeued.priority, JobPriority::High); // Complete job @@ -183,13 +185,13 @@ async fn test_time_dependent_processing() { queue.enqueue(job).await.unwrap(); // Job shouldn't be available yet - assert!(queue.dequeue("delayed_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed_queue").await.unwrap().is_none()); // Advance time past scheduled time clock.advance(Duration::hours(2)); // Now job should be available - let dequeued = queue.dequeue("delayed_queue").await.unwrap(); + let dequeued = queue.dequeue_one("delayed_queue").await.unwrap(); assert!(dequeued.is_some()); } ``` @@ -214,15 +216,15 @@ async fn test_delayed_job_execution() { queue.enqueue(job).await.unwrap(); // Verify job is not available immediately - assert!(queue.dequeue("delayed_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed_queue").await.unwrap().is_none()); // Advance time to just before scheduled time clock.advance(Duration::minutes(29)); - assert!(queue.dequeue("delayed_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed_queue").await.unwrap().is_none()); // Advance past scheduled time clock.advance(Duration::minutes(2)); - let dequeued = queue.dequeue("delayed_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("delayed_queue").await.unwrap().unwrap(); assert_eq!(dequeued.payload["data"], "delayed_payload"); } ``` @@ -247,7 +249,7 @@ async fn test_cron_job_scheduling() { // Process the first occurrence, as a worker does clock.advance(Duration::hours(1)); - let first_run = queue.dequeue("cron_queue").await.unwrap().unwrap(); + let first_run = queue.dequeue_one("cron_queue").await.unwrap().unwrap(); let recorded = queue .finish_job_run(&first_run, JobOutcome::Completed) .await @@ -262,7 +264,7 @@ async fn test_cron_job_scheduling() { // The next occurrence runs once its time comes clock.advance(Duration::hours(1)); - let second_run = queue.dequeue("cron_queue").await.unwrap().unwrap(); + let second_run = queue.dequeue_one("cron_queue").await.unwrap().unwrap(); assert_eq!(second_run.id, job_id); } ``` @@ -289,13 +291,13 @@ async fn test_priority_ordering() { queue.enqueue(critical_job).await.unwrap(); // Jobs should be dequeued in priority order (highest first) - let first = queue.dequeue("priority_queue").await.unwrap().unwrap(); + let first = queue.dequeue_one("priority_queue").await.unwrap().unwrap(); assert_eq!(first.priority, JobPriority::Critical); - let second = queue.dequeue("priority_queue").await.unwrap().unwrap(); + let second = queue.dequeue_one("priority_queue").await.unwrap().unwrap(); assert_eq!(second.priority, JobPriority::High); - let third = queue.dequeue("priority_queue").await.unwrap().unwrap(); + let third = queue.dequeue_one("priority_queue").await.unwrap().unwrap(); assert_eq!(third.priority, JobPriority::Low); } ``` @@ -329,11 +331,12 @@ async fn test_weighted_priority_selection() { } // Use weighted dequeue - let job = queue.dequeue_with_priority_weights("weighted_queue", &weights).await.unwrap(); - assert!(job.is_some()); + let options = DequeueOptions::new().with_priority_weights(weights); + let jobs = queue.dequeue("weighted_queue", &options).await.unwrap(); + assert_eq!(jobs.len(), 1); // With these weights, background jobs should be selected more frequently - let dequeued = job.unwrap(); + let dequeued = &jobs[0]; // Note: Weighted selection is probabilistic, so we can't assert specific priority // but we can verify the job was dequeued correctly assert!(matches!(dequeued.priority, JobPriority::Background | JobPriority::Critical)); @@ -366,7 +369,7 @@ async fn test_batch_operations() { // Process all batch jobs for _ in 0..3 { - if let Some(job) = queue.dequeue("batch_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("batch_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } } @@ -399,7 +402,7 @@ async fn test_batch_fail_fast() { let batch_id = batch_result.successful_jobs[0].batch_id.unwrap(); // Process first job and fail it - let first_job = queue.dequeue("fail_fast_queue").await.unwrap().unwrap(); + let first_job = queue.dequeue_one("fail_fast_queue").await.unwrap().unwrap(); queue.fail_job(first_job.id, "Intentional failure").await.unwrap(); // With FailFast, remaining jobs should be automatically failed @@ -433,21 +436,21 @@ async fn test_workflow_dependencies() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Only job1 should be available initially (no dependencies) - let first_available = queue.dequeue("workflow_queue").await.unwrap().unwrap(); + let first_available = queue.dequeue_one("workflow_queue").await.unwrap().unwrap(); assert_eq!(first_available.payload["step"], 1); // Complete job1 queue.complete_job(first_available.id).await.unwrap(); // Now job2 should be available - let second_available = queue.dequeue("workflow_queue").await.unwrap().unwrap(); + let second_available = queue.dequeue_one("workflow_queue").await.unwrap().unwrap(); assert_eq!(second_available.payload["step"], 2); // Complete job2 queue.complete_job(second_available.id).await.unwrap(); // Now job3 should be available - let third_available = queue.dequeue("workflow_queue").await.unwrap().unwrap(); + let third_available = queue.dequeue_one("workflow_queue").await.unwrap().unwrap(); assert_eq!(third_available.payload["step"], 3); // Complete job3 @@ -479,7 +482,7 @@ async fn test_workflow_fail_fast() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Dequeue any job and fail it - let job = queue.dequeue("fail_fast_workflow").await.unwrap().unwrap(); + let job = queue.dequeue_one("fail_fast_workflow").await.unwrap().unwrap(); queue.fail_job(job.id, "Intentional failure for testing").await.unwrap(); // With FailFast policy, the workflow should be marked as failed @@ -507,7 +510,7 @@ async fn test_job_retry_logic() { // worker retries a failed run with `retry_job` while the job has attempts left // (each dequeue counts as one) and marks it dead after the last one. for attempt in 1..=3 { - let job = queue.dequeue("retry_queue").await.unwrap().unwrap(); + let job = queue.dequeue_one("retry_queue").await.unwrap().unwrap(); assert_eq!(job.attempts, attempt); if job.attempts < job.max_attempts { queue.retry_job(job_id, queue.clock().now()).await.unwrap(); @@ -517,7 +520,7 @@ async fn test_job_retry_logic() { } // No more retries - assert!(queue.dequeue("retry_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("retry_queue").await.unwrap().is_none()); // Verify job is dead let final_job = queue.get_job(job_id).await.unwrap().unwrap(); @@ -541,7 +544,7 @@ async fn test_dead_job_purging() { .with_max_attempts(1); let job_id = queue.enqueue(job).await.unwrap(); - let dequeued = queue.dequeue("purge_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("purge_queue").await.unwrap().unwrap(); queue.mark_job_dead(dequeued.id, "Failed for purge test").await.unwrap(); } @@ -592,7 +595,7 @@ async fn test_job_processing_logic() { queue.enqueue(job).await.unwrap(); // Manually dequeue and test your processing logic - if let Some(job) = queue.dequeue("test_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("test_queue").await.unwrap() { // This is where you test your actual job processing logic let result = your_job_handler(job.clone()).await; assert!(result.is_ok()); @@ -640,9 +643,9 @@ async fn test_delayed_processing() { queue.enqueue(job).await.unwrap(); // Test before and after the scheduled time - assert!(queue.dequeue("delayed").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed").await.unwrap().is_none()); clock.advance(Duration::hours(2)); - assert!(queue.dequeue("delayed").await.unwrap().is_some()); + assert!(queue.dequeue_one("delayed").await.unwrap().is_some()); } ``` @@ -654,7 +657,7 @@ async fn test_edge_cases() { let queue = TestQueue::new(); // Test empty queue - assert!(queue.dequeue("nonexistent").await.unwrap().is_none()); + assert!(queue.dequeue_one("nonexistent").await.unwrap().is_none()); // Test invalid job operations let fake_id = JobId::new(); @@ -758,26 +761,26 @@ async fn test_email_service() { queue.enqueue(newsletter).await.unwrap(); // Process urgent email immediately - let urgent_job = queue.dequeue("email_queue").await.unwrap().unwrap(); + let urgent_job = queue.dequeue_one("email_queue").await.unwrap().unwrap(); assert_eq!(urgent_job.id, urgent_id); assert_eq!(urgent_job.priority, JobPriority::Critical); queue.complete_job(urgent_id).await.unwrap(); // Newsletter shouldn't be available yet - assert!(queue.dequeue("email_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("email_queue").await.unwrap().is_none()); // Advance time to newsletter time clock.advance(Duration::hours(25)); // Newsletter should now be available - let newsletter_job = queue.dequeue("email_queue").await.unwrap().unwrap(); + let newsletter_job = queue.dequeue_one("email_queue").await.unwrap().unwrap(); assert_eq!(newsletter_job.payload["template"], "newsletter"); // Simulate email sending failure and retry it, as a worker would queue.retry_job(newsletter_job.id, clock.now()).await.unwrap(); // Job should be available for retry; each dequeue counts as an attempt - let retry_job = queue.dequeue("email_queue").await.unwrap().unwrap(); + let retry_job = queue.dequeue_one("email_queue").await.unwrap().unwrap(); assert_eq!(retry_job.attempts, 2); queue.complete_job(retry_job.id).await.unwrap(); } @@ -824,22 +827,22 @@ async fn test_data_pipeline() { let workflow_id = queue.enqueue_workflow(pipeline).await.unwrap(); // Process extract stage - let extract = queue.dequeue("data_pipeline").await.unwrap().unwrap(); + let extract = queue.dequeue_one("data_pipeline").await.unwrap().unwrap(); assert_eq!(extract.payload["stage"], "extract"); queue.complete_job(extract.id).await.unwrap(); // Process transform stage - let transform = queue.dequeue("data_pipeline").await.unwrap().unwrap(); + let transform = queue.dequeue_one("data_pipeline").await.unwrap().unwrap(); assert_eq!(transform.payload["stage"], "transform"); queue.complete_job(transform.id).await.unwrap(); // Process load stage - let load = queue.dequeue("data_pipeline").await.unwrap().unwrap(); + let load = queue.dequeue_one("data_pipeline").await.unwrap().unwrap(); assert_eq!(load.payload["stage"], "load"); queue.complete_job(load.id).await.unwrap(); // Process notification - let notify = queue.dequeue("notifications").await.unwrap().unwrap(); + let notify = queue.dequeue_one("notifications").await.unwrap().unwrap(); assert_eq!(notify.payload["stage"], "notify"); queue.complete_job(notify.id).await.unwrap(); diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.md index ccf8695..259182e 100644 --- a/docs/upgrading-to-3.0.md +++ b/docs/upgrading-to-3.0.md @@ -185,3 +185,150 @@ Migrate imports as follows: | `hammerwork_web::config::WebSocketConfig` | `hammerwork_web::WebSocketConfig` | | `hammerwork_web::server::WebDashboard` | `hammerwork_web::WebDashboard` | | `hammerwork_web::server::app_routes`, `api::*`, `auth::*`, `security::*`, `websocket::*`, `live::*` | removed; mount the dashboard with `WebDashboard` | + +## DatabaseQueue is sealed + +`DatabaseQueue` is now a sealed trait (#87): only Hammerwork can implement it. Its +implementations are `JobQueue` (feature `postgres`), `JobQueue` +(feature `mysql`) and the in-memory `TestQueue` (feature `test-queue`). Because no +other implementations exist, new methods can be added in minor releases without +default bodies, and the defaults that existed only for implementations outside the +crate are gone. The built-in queues behave as before. + +Code that only *uses* a queue is unaffected: `DatabaseQueue` is still the bound for +generic code and the trait to import for its methods. + +```rust +use hammerwork::queue::DatabaseQueue; + +// Still works: generic over any built-in queue. +async fn pending_count(queue: &impl DatabaseQueue, name: &str) -> hammerwork::Result { + Ok(queue.get_queue_stats(name).await?.pending_count) +} +``` + +### What to change + +If you implemented `DatabaseQueue` yourself, usually as a mock for tests, that no +longer compiles (`the trait bound ...: Sealed is not satisfied`). Use `TestQueue` +instead. It implements the whole trait in memory, with the same claim, lease, retry, +workflow and archive behaviour as the database backends, and a `MockClock` for +delayed and cron jobs (see [Testing](testing.md)): + +```toml +[dev-dependencies] +hammerwork = { version = "3", features = ["test-queue"] } +``` + +```rust +// Before (2.x): a hand-written mock +// struct MockQueue { /* ... */ } +// #[async_trait] impl DatabaseQueue for MockQueue { /* ... */ } + +// After (3.0) +use hammerwork::queue::{DatabaseQueue, test::TestQueue}; + +# async fn example() -> hammerwork::Result<()> { +let queue = TestQueue::new(); +let id = queue + .enqueue(hammerwork::Job::new("emails".into(), serde_json::json!({}))) + .await?; +assert!(queue.get_job(id).await?.is_some()); +# Ok(()) +# } +``` + +`hammerwork::queue::RELEASED_JOB_MESSAGE` is removed: it was the error message of the +`release_job_run` fallback for queues outside the crate. The built-in queues release +a job without recording an error. + +## Claiming jobs and worker builders + +The claim API and two worker builders were consolidated (#89). + +### One claim method + +`DatabaseQueue::dequeue` now takes a [`DequeueOptions`](https://docs.rs/hammerwork/3/hammerwork/queue/struct.DequeueOptions.html) +and returns the claimed jobs as a `Vec`. It replaces `dequeue`, +`dequeue_with_priority_weights`, `dequeue_leased`, `dequeue_batch` and +`dequeue_batch_leased`. For the most common call, claiming one job with the defaults, +use `dequeue_one`, which is the 2.x `dequeue`: + +| 2.x | 3.0 | +| --- | --- | +| `dequeue(q)` | `dequeue_one(q)` | +| `dequeue_with_priority_weights(q, &w)` | `dequeue(q, &DequeueOptions::new().with_priority_weights(w.clone()))` | +| `dequeue_leased(q, None, lease)` | `dequeue(q, &DequeueOptions::new().with_lease_duration(lease))` | +| `dequeue_batch(q, n)` | `dequeue(q, &DequeueOptions::batch(n))` | +| `dequeue_batch_leased(q, Some(&w), lease, n)` | `dequeue(q, &DequeueOptions::batch(n).with_priority_weights(w.clone()).with_lease_duration(lease))` | + +The single-job forms returned `Option`; `dequeue` returns a `Vec` with at +most one job when `max_jobs` is 1 (the default). Claims behave exactly as before: the +same statements, priority selection, leases and pause checks. + +```rust +use hammerwork::queue::{DatabaseQueue, DequeueOptions}; +use hammerwork::PriorityWeights; +use std::time::Duration; + +# async fn example(queue: &impl DatabaseQueue) -> hammerwork::Result<()> { +// Before (2.x): +// let job = queue.dequeue("emails").await?; +// let job = queue.dequeue_with_priority_weights("emails", &weights).await?; +// let jobs = queue.dequeue_batch_leased("emails", None, Duration::from_secs(60), 20).await?; + +// After (3.0): +let job = queue.dequeue_one("emails").await?; + +let weights = PriorityWeights::new(); +let options = DequeueOptions::new().with_priority_weights(weights); +let job = queue.dequeue("emails", &options).await?.into_iter().next(); + +let options = DequeueOptions::batch(20).with_lease_duration(Duration::from_secs(60)); +let jobs = queue.dequeue("emails", &options).await?; +# let _ = (job, jobs); +# Ok(()) +# } +``` + +`DequeueOptions` is `#[non_exhaustive]`: build it with `DequeueOptions::new()` (or +`default()`) or `DequeueOptions::batch(n)` and the `with_*` methods. Its fields are +public, so you can still read them or assign them, for example +`options.priority_weights = maybe_weights;`. + +### Batch mode is set by the batch size + +`Worker::with_batch_processing_enabled` is removed. `with_batch_size(n)` already enabled +batch mode and is now the only switch. To keep `with_batch_processing_enabled(true)`'s +behaviour (batch statistics, one job claimed per poll), use `with_batch_size(1)`. To +turn batch mode off, do not call `with_batch_size`. + +Batch settings can now also come from configuration: the optional `[worker]` keys +`batch_size` and `batch_concurrency` (`WorkerConfig::batch_size` and +`WorkerConfig::batch_concurrency`, both `Option`) are applied by +`Worker::with_config` when set. If you build a `WorkerConfig` with a struct literal, add +the two fields or end it with `..WorkerConfig::default()`. + +### `with_max_retries` is now `with_attempt_cap` + +`Worker::with_max_retries(n)` is renamed `Worker::with_attempt_cap(n)`. Its behaviour +is unchanged: it caps the number of attempts this worker gives a job at +`min(job.max_attempts, n)`, and can only lower a job's own limit. There is no +deprecated alias. + +```rust,no_run +# async fn example(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler) { +use hammerwork::Worker; + +// Before (2.x): +// let worker = Worker::new(queue, "emails".into(), handler) +// .with_batch_processing_enabled(true) +// .with_max_retries(3); + +// After (3.0): +let worker = Worker::new(queue, "emails".into(), handler) + .with_batch_size(1) + .with_attempt_cap(3); +# let _ = worker; +# } +``` diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index 314ec1a..1201325 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -13,7 +13,7 @@ use std::time::Duration; let worker = Worker::new(queue, "email_queue".to_string(), handler) .with_poll_interval(Duration::from_millis(500)) // Check for jobs every 500ms - .with_max_retries(3) // At most 3 attempts per job (job max_attempts still applies) + .with_attempt_cap(3) // At most 3 attempts per job (job max_attempts still applies) .with_retry_delay(Duration::from_secs(30)); // Wait 30s between retries # Ok(()) # } @@ -370,7 +370,8 @@ A worker that crashes, is OOM-killed or loses its pod leaves its job in `Running Hammerwork recovers these jobs with leases (requires migration `015_add_job_leases`): - A worker takes the lease in the same statement that claims the job - (`DatabaseQueue::dequeue_leased`; plain `dequeue` takes the default 5 minute lease). + (`DequeueOptions::lease_duration` of `DatabaseQueue::dequeue`; `dequeue_one` takes the + default 5 minute lease). While the handler runs, the worker records a heartbeat and extends the lease every third of its lease duration (5 minutes by default). Jobs that finish sooner never write a heartbeat. @@ -489,7 +490,7 @@ let background_worker = Worker::new(queue.clone(), "cleanup".to_string(), handle // Email worker with retry configuration let email_worker = Worker::new(queue.clone(), "email".to_string(), handler.clone()) - .with_max_retries(5) + .with_attempt_cap(5) .with_retry_delay(Duration::from_secs(60)); let mut pool = WorkerPool::new(); @@ -557,7 +558,7 @@ runs. A failing run is retried while attempts remain; the last failure makes the `Dead`. A run that exceeds its timeout counts as a failed attempt too: it is retried while attempts remain and the job only ends `TimedOut` on its last attempt. -`Worker::with_max_retries(n)` can only lower that limit (`min(job.max_attempts, n)`); +`Worker::with_attempt_cap(n)` can only lower that limit (`min(job.max_attempts, n)`); by default workers set no cap. ```rust,no_run @@ -568,7 +569,7 @@ use hammerwork::Worker; use std::time::Duration; let worker = Worker::new(queue, "retry_queue".to_string(), handler) - .with_max_retries(5) // Never more than 5 attempts per job + .with_attempt_cap(5) // Never more than 5 attempts per job .with_retry_delay(Duration::from_secs(30)) // Wait 30s between attempts .with_default_timeout(Duration::from_secs(300)); // 5 minute timeout per attempt # Ok(()) @@ -675,6 +676,17 @@ assert_eq!(worker.batch_size(), 20); A worker holds the jobs it claimed until it gets to them, so other workers cannot take them meanwhile. Prefer small batches for slow jobs, or raise the batch concurrency. +In a configuration file, the `[worker]` keys `batch_size` and `batch_concurrency` set the +same (`WorkerConfig::batch_size`, `WorkerConfig::batch_concurrency`, applied by +`Worker::with_config`). Both are optional: without `batch_size` workers claim one job at a +time unless batch mode is enabled in code. + +```toml +[worker] +batch_size = 20 +batch_concurrency = 5 +``` + ### Resource-Intensive Jobs ```rust,no_run @@ -688,7 +700,7 @@ let worker = Worker::new(queue, "heavy_processing".to_string(), handler) .with_poll_interval(Duration::from_secs(5)) // Check less frequently .with_rate_limit(RateLimit::per_minute(10)) // Limit load .with_default_timeout(Duration::from_secs(1800)) // 30 minute timeout - .with_max_retries(1); // Minimal retries + .with_attempt_cap(1); // One attempt per job, no retries # Ok(()) # } ``` @@ -741,7 +753,7 @@ use std::time::Duration; let api_worker = Worker::new(queue, "api_calls".to_string(), handler) .with_rate_limit(RateLimit::per_second(5).with_burst_limit(10)) - .with_max_retries(3) + .with_attempt_cap(3) .with_retry_delay(Duration::from_secs(60)) .with_default_timeout(Duration::from_secs(30)); # Ok(()) @@ -785,7 +797,7 @@ use std::time::Duration; let critical_worker = Worker::new(queue, "system".to_string(), handler) .with_strict_priority() .with_poll_interval(Duration::from_millis(100)) - .with_max_retries(5) + .with_attempt_cap(5) .with_retry_delay(Duration::from_secs(5)) .with_default_timeout(Duration::from_secs(120)); # Ok(()) diff --git a/examples/batch_example.rs b/examples/batch_example.rs index 1191067..46bc157 100644 --- a/examples/batch_example.rs +++ b/examples/batch_example.rs @@ -257,7 +257,7 @@ async fn batch_worker_demo( // Create workers for different notification channels let email_worker = Worker::new(queue.clone(), "notifications".to_string(), handler.clone()) .with_poll_interval(std::time::Duration::from_millis(100)) - .with_max_retries(3) + .with_attempt_cap(3) .with_stats_collector(stats_collector.clone()); // Start worker pool diff --git a/examples/cron_example.rs b/examples/cron_example.rs index fe863a9..eb1c2a4 100644 --- a/examples/cron_example.rs +++ b/examples/cron_example.rs @@ -83,13 +83,13 @@ async fn main() -> std::result::Result<(), Box> { // Create workers for different types of jobs let report_worker = Worker::new(queue.clone(), "reports".to_string(), report_handler) .with_poll_interval(tokio::time::Duration::from_secs(2)) - .with_max_retries(3) + .with_attempt_cap(3) .with_default_timeout(tokio::time::Duration::from_secs(60)) .with_stats_collector(Arc::clone(&stats_collector)); let cleanup_worker = Worker::new(queue.clone(), "cleanup".to_string(), cleanup_handler) .with_poll_interval(tokio::time::Duration::from_secs(3)) - .with_max_retries(2) + .with_attempt_cap(2) .with_default_timeout(tokio::time::Duration::from_secs(30)) .with_stats_collector(Arc::clone(&stats_collector)); diff --git a/examples/mysql_example.rs b/examples/mysql_example.rs index ffe7565..19e9229 100644 --- a/examples/mysql_example.rs +++ b/examples/mysql_example.rs @@ -87,13 +87,13 @@ async fn main() -> std::result::Result<(), Box> { // Create workers for different queues with statistics collection and timeout configuration let image_worker = Worker::new(queue.clone(), "image_processing".to_string(), image_handler) .with_poll_interval(tokio::time::Duration::from_secs(1)) - .with_max_retries(2) + .with_attempt_cap(2) .with_default_timeout(tokio::time::Duration::from_secs(120)) // 2-minute timeout for image processing .with_stats_collector(Arc::clone(&stats_collector)); let email_worker = Worker::new(queue.clone(), "email_queue".to_string(), email_handler) .with_poll_interval(tokio::time::Duration::from_millis(500)) - .with_max_retries(3) + .with_attempt_cap(3) .with_default_timeout(tokio::time::Duration::from_secs(30)) // 30-second timeout for emails .with_stats_collector(Arc::clone(&stats_collector)); diff --git a/examples/postgres_example.rs b/examples/postgres_example.rs index 2f41c23..f7b707e 100644 --- a/examples/postgres_example.rs +++ b/examples/postgres_example.rs @@ -56,14 +56,14 @@ async fn main() -> std::result::Result<(), Box> { // Create and start workers with statistics collection, timeout, and rate limiting configuration let worker1 = Worker::new(queue.clone(), "email".to_string(), handler.clone()) .with_poll_interval(tokio::time::Duration::from_secs(1)) - .with_max_retries(3) + .with_attempt_cap(3) .with_default_timeout(tokio::time::Duration::from_secs(30)) // 30 second default timeout .with_rate_limit(RateLimit::per_second(2)) // Limit to 2 emails per second .with_stats_collector(Arc::clone(&stats_collector)); let worker2 = Worker::new(queue.clone(), "notifications".to_string(), handler.clone()) .with_poll_interval(tokio::time::Duration::from_secs(2)) - .with_max_retries(2) + .with_attempt_cap(2) .with_default_timeout(tokio::time::Duration::from_secs(60)) // 60 second default timeout .with_throttle_config( ThrottleConfig::new() diff --git a/examples/test_queue_example.rs b/examples/test_queue_example.rs index a9fc80f..37e0bc4 100644 --- a/examples/test_queue_example.rs +++ b/examples/test_queue_example.rs @@ -11,6 +11,7 @@ //! - Testing error scenarios and edge cases use chrono::Duration; +use hammerwork::queue::DequeueOptions; use hammerwork::{ Job, JobPriority, JobStatus, batch::JobBatch, @@ -170,7 +171,7 @@ async fn basic_usage() -> Result<(), Box> { println!("๐Ÿ“Š Pending jobs: {}", pending_count); // Dequeue and process - if let Some(job) = queue.dequeue("email_queue").await? { + if let Some(job) = queue.dequeue_one("email_queue").await? { println!("๐Ÿ”„ Processing job: {}", job.id); // Simulate processing @@ -218,8 +219,8 @@ async fn time_control_example() -> Result<(), Box> { println!("โณ Enqueued delayed job: {} (1 hour delay)", delayed_id); // Only immediate job should be available - assert!(queue.dequeue("delayed_queue").await?.is_some()); - assert!(queue.dequeue("delayed_queue").await?.is_none()); + assert!(queue.dequeue_one("delayed_queue").await?.is_some()); + assert!(queue.dequeue_one("delayed_queue").await?.is_none()); println!("โœ… Only immediate job was available"); // Advance time by 1 hour @@ -227,7 +228,7 @@ async fn time_control_example() -> Result<(), Box> { println!("๐Ÿ• Advanced time by 1 hour"); // Now delayed job should be available - if let Some(job) = queue.dequeue("delayed_queue").await? { + if let Some(job) = queue.dequeue_one("delayed_queue").await? { assert_eq!(job.id, delayed_id); queue.complete_job(job.id).await?; println!("โœ… Delayed job is now available and processed"); @@ -268,7 +269,7 @@ async fn priority_example() -> Result<(), Box> { // Dequeue in priority order let order = [critical_id, high_id, normal_id, low_id]; for (i, expected_id) in order.iter().enumerate() { - if let Some(job) = queue.dequeue("priority_queue").await? { + if let Some(job) = queue.dequeue_one("priority_queue").await? { assert_eq!(job.id, *expected_id); queue.complete_job(job.id).await?; println!(" {}. Processed: {} ({:?})", i + 1, job.id, job.priority); @@ -295,8 +296,12 @@ async fn priority_example() -> Result<(), Box> { // Process with weighted selection while let Some(job) = queue - .dequeue_with_priority_weights("weighted_queue", &weights) - .await? + .dequeue( + "weighted_queue", + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) + .await + .map(|jobs| jobs.into_iter().next())? { println!(" Selected: {:?} priority job", job.priority); queue.complete_job(job.id).await?; @@ -338,7 +343,7 @@ async fn batch_example() -> Result<(), Box> { // Process batch jobs let mut processed = 0; - while let Some(job) = queue.dequeue("image_queue").await? { + while let Some(job) = queue.dequeue_one("image_queue").await? { println!("๐Ÿ–ผ๏ธ Processing image job: {}", job.id); match image_handler(job.clone()).await { @@ -435,7 +440,7 @@ async fn workflow_example() -> Result<(), Box> { for (i, step) in job_steps.iter().enumerate() { println!("\n๐Ÿ“ Step {}: {}", i + 1, step); - if let Some(job) = queue.dequeue("data_pipeline").await? { + if let Some(job) = queue.dequeue_one("data_pipeline").await? { let job_step = job.payload["step"].as_str().unwrap(); assert_eq!(job_step, *step); @@ -502,7 +507,7 @@ async fn error_handling_example() -> Result<(), Box> { println!("๐Ÿ“ง Enqueued failing job: {}", job_id); // Attempt 1 - if let Some(job) = queue.dequeue("email_queue").await? { + if let Some(job) = queue.dequeue_one("email_queue").await? { println!("\n๐Ÿ”„ Attempt 1:"); match email_handler(job.clone()).await { Err(e) => { @@ -528,7 +533,7 @@ async fn error_handling_example() -> Result<(), Box> { clock.advance(Duration::minutes(5)); // Attempt 2 - if let Some(job) = queue.dequeue("email_queue").await? { + if let Some(job) = queue.dequeue_one("email_queue").await? { println!("\n๐Ÿ”„ Attempt 2:"); match email_handler(job.clone()).await { Err(e) => { @@ -547,7 +552,7 @@ async fn error_handling_example() -> Result<(), Box> { } // Attempt 3 (final) - if let Some(job) = queue.dequeue("email_queue").await? { + if let Some(job) = queue.dequeue_one("email_queue").await? { println!("\n๐Ÿ”„ Attempt 3 (final):"); match email_handler(job.clone()).await { Err(e) => { @@ -608,7 +613,7 @@ async fn cron_job_example() -> Result<(), Box> { clock.advance(Duration::hours(1)); // Process the job - if let Some(job) = queue.dequeue("maintenance_queue").await? { + if let Some(job) = queue.dequeue_one("maintenance_queue").await? { println!(" ๐Ÿงน Running maintenance task"); tokio::time::sleep(std::time::Duration::from_millis(100)).await; queue.complete_job(job.id).await?; @@ -651,7 +656,7 @@ async fn result_storage_example() -> Result<(), Box> { println!("๐Ÿงฎ Enqueued computation job: {}", job_id); // Process the job - if let Some(job) = queue.dequeue("compute_queue").await? { + if let Some(job) = queue.dequeue_one("compute_queue").await? { println!("๐Ÿ”„ Computing fibonacci(20)..."); // Simulate computation @@ -725,7 +730,7 @@ async fn worker_integration_example() -> Result<(), Box> println!("๐Ÿ”„ Processing jobs manually (TestQueue doesn't support Worker):"); let mut processed_count = 0; - while let Some(job) = queue.dequeue("worker_queue").await? { + while let Some(job) = queue.dequeue_one("worker_queue").await? { let batch_id = job.payload["batch_id"].as_u64().unwrap(); let data = job.payload["data"].as_str().unwrap(); @@ -789,7 +794,7 @@ async fn performance_testing_example() -> Result<(), Box> let process_start = std::time::Instant::now(); let mut processed = 0; - while let Some(job) = queue.dequeue("perf_queue").await? { + while let Some(job) = queue.dequeue_one("perf_queue").await? { // Minimal processing queue.complete_job(job.id).await?; processed += 1; diff --git a/examples/worker_batch_example.rs b/examples/worker_batch_example.rs index 74154a6..8b68fde 100644 --- a/examples/worker_batch_example.rs +++ b/examples/worker_batch_example.rs @@ -161,7 +161,7 @@ async fn batch_worker_demo( .with_batch_size(10) // Claim up to 10 jobs per poll (enables batch processing) .with_batch_concurrency(4) // and run up to 4 of them at once .with_poll_interval(Duration::from_millis(100)) - .with_max_retries(3) + .with_attempt_cap(3) .with_stats_collector(stats_collector.clone()) .with_priority_weights( hammerwork::PriorityWeights::new() diff --git a/hammerwork-web/src/api/jobs.rs b/hammerwork-web/src/api/jobs.rs index 9431049..343c74f 100644 --- a/hammerwork-web/src/api/jobs.rs +++ b/hammerwork-web/src/api/jobs.rs @@ -1026,7 +1026,7 @@ mod tests { let failed = queue.enqueue(mk("failed")).await.unwrap(); // Claim the jobs that are due so each can end in the wanted status. let mut claimed = Vec::new(); - while let Some(job) = queue.dequeue("q").await.unwrap() { + while let Some(job) = queue.dequeue_one("q").await.unwrap() { claimed.push(job.id); } for id in [done, running, timed_out, dead, failed] { @@ -1081,7 +1081,7 @@ mod tests { )) .await .unwrap(); - let claimed = queue.dequeue("q").await.unwrap().unwrap(); + let claimed = queue.dequeue_one("q").await.unwrap().unwrap(); assert_eq!(claimed.id, now_job); queue.fail_job(now_job, "bad needle").await.unwrap(); diff --git a/hammerwork-web/src/live.rs b/hammerwork-web/src/live.rs index 13bf779..bc75b42 100644 --- a/hammerwork-web/src/live.rs +++ b/hammerwork-web/src/live.rs @@ -591,7 +591,7 @@ mod tests { let pending = wait_for(&mut live, &mut jobs, id, "Pending").await; assert_eq!(pending["job"]["queue_name"], queue_name.as_str()); - let run = queue.dequeue(&queue_name).await.unwrap().expect("job"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("job"); queue .finish_job_run(&run, hammerwork::queue::JobOutcome::Completed) .await @@ -628,14 +628,14 @@ mod tests { id, }; - let run = queue.dequeue(&queue_name).await.unwrap().expect("job"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("job"); wait_for(&mut live, &mut jobs, id, "Running").await; assert!(queue.release_job_run(&run).await.unwrap()); let released = wait_for(&mut live, &mut jobs, id, "Pending").await; assert_eq!(released["job"]["attempts"], 0); // A retry of a run goes back to Pending too. - let run = queue.dequeue(&queue_name).await.unwrap().expect("job"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("job"); wait_for(&mut live, &mut jobs, id, "Running").await; queue .finish_job_run( diff --git a/hammerwork-web/tests/api_tests.rs b/hammerwork-web/tests/api_tests.rs index 681ccd4..f605d79 100644 --- a/hammerwork-web/tests/api_tests.rs +++ b/hammerwork-web/tests/api_tests.rs @@ -439,7 +439,7 @@ async fn job_endpoints(app: &App) { let dead = enqueue(app.queue.as_ref(), &q, json!({"kind": "doomed"})).await; let claimed = app .queue - .dequeue(&q) + .dequeue_one(&q) .await .unwrap() .expect("a job to claim"); @@ -548,9 +548,9 @@ async fn queue_endpoints(app: &App) { enqueue(app.queue.as_ref(), &q, json!({"i": 2})).await, ]; // one completed job, one dead job - let done = app.queue.dequeue(&q).await.unwrap().unwrap(); + let done = app.queue.dequeue_one(&q).await.unwrap().unwrap(); app.queue.complete_job(done.id).await.unwrap(); - let doomed = app.queue.dequeue(&q).await.unwrap().unwrap(); + let doomed = app.queue.dequeue_one(&q).await.unwrap().unwrap(); app.queue .mark_job_dead(doomed.id, "queue test failure") .await @@ -690,11 +690,11 @@ async fn queue_endpoints(app: &App) { async fn stats_endpoints(app: &App) { let q = unique("stats"); let done = enqueue(app.queue.as_ref(), &q, json!({})).await; - let claimed = app.queue.dequeue(&q).await.unwrap().unwrap(); + let claimed = app.queue.dequeue_one(&q).await.unwrap().unwrap(); assert_eq!(claimed.id, done); app.queue.complete_job(done).await.unwrap(); let failing = enqueue(app.queue.as_ref(), &q, json!({})).await; - let claimed = app.queue.dequeue(&q).await.unwrap().unwrap(); + let claimed = app.queue.dequeue_one(&q).await.unwrap().unwrap(); app.queue .mark_job_dead(claimed.id, "TimeoutError: upstream timed out after 30s") .await @@ -949,7 +949,7 @@ async fn archive_one(queue: &Q, q: &str, payload: Value, by: & .enqueue(Job::new(q.to_string(), payload).with_priority(JobPriority::Normal)) .await .unwrap(); - let claimed = queue.dequeue(q).await.unwrap().unwrap(); + let claimed = queue.dequeue_one(q).await.unwrap().unwrap(); assert_eq!(claimed.id, id); queue.complete_job(id).await.unwrap(); let policy = ArchivalPolicy::new().archive_completed_after(chrono::Duration::zero()); @@ -1086,7 +1086,7 @@ async fn archive_endpoints(app: &App) { .enqueue(Job::new(q.clone(), json!({"later": true}))) .await .unwrap(); - app.queue.dequeue(&q).await.unwrap(); + app.queue.dequeue_one(&q).await.unwrap(); app.queue.complete_job(completed).await.unwrap(); let policy = serde_json::to_value( ArchivalPolicy::new().archive_completed_after(chrono::Duration::zero()), diff --git a/integrations/mysql-integration/src/main.rs b/integrations/mysql-integration/src/main.rs index 7a227ff..91cb63e 100644 --- a/integrations/mysql-integration/src/main.rs +++ b/integrations/mysql-integration/src/main.rs @@ -133,7 +133,7 @@ async fn test_json_operations( queue.enqueue(job).await?; info!("โœ… Complex JSON job enqueued"); - let dequeued_job = queue.dequeue("json_test").await?; + let dequeued_job = queue.dequeue_one("json_test").await?; assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); @@ -178,7 +178,7 @@ async fn test_mysql_transactions( for worker_id in 0..2 { let queue_clone = queue.clone(); let handle = tokio::spawn(async move { - let result = queue_clone.dequeue("transaction_test").await; + let result = queue_clone.dequeue_one("transaction_test").await; (worker_id, result) }); handles.push(handle); @@ -250,7 +250,7 @@ async fn test_mysql_character_handling( queue.enqueue(job).await?; info!("โœ… Special character job enqueued"); - let dequeued_job = queue.dequeue("encoding_test").await?; + let dequeued_job = queue.dequeue_one("encoding_test").await?; assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); @@ -310,7 +310,7 @@ async fn run_performance_tests( let mut dequeued_count = 0; for _ in 0..job_count { - if let Ok(Some(job)) = queue.dequeue("mysql_performance_test").await { + if let Ok(Some(job)) = queue.dequeue_one("mysql_performance_test").await { dequeued_count += 1; let _ = queue.complete_job(job.id).await; } diff --git a/integrations/postgres-integration/src/main.rs b/integrations/postgres-integration/src/main.rs index aa422e8..edc15ea 100644 --- a/integrations/postgres-integration/src/main.rs +++ b/integrations/postgres-integration/src/main.rs @@ -130,7 +130,7 @@ async fn test_jsonb_operations( queue.enqueue(job).await?; info!("โœ… Complex JSONB job enqueued"); - let dequeued_job = queue.dequeue("jsonb_test").await?; + let dequeued_job = queue.dequeue_one("jsonb_test").await?; assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); @@ -175,7 +175,7 @@ async fn test_postgres_features( for worker_id in 0..3 { let queue_clone = queue.clone(); let handle = tokio::spawn(async move { - let result = queue_clone.dequeue("postgres_concurrent").await; + let result = queue_clone.dequeue_one("postgres_concurrent").await; (worker_id, result) }); handles.push(handle); @@ -260,7 +260,7 @@ async fn run_performance_tests( let mut dequeued_count = 0; for _ in 0..job_count { - if let Ok(Some(job)) = queue.dequeue("performance_test").await { + if let Ok(Some(job)) = queue.dequeue_one("performance_test").await { dequeued_count += 1; let _ = queue.complete_job(job.id).await; } diff --git a/integrations/shared/test_scenarios.rs b/integrations/shared/test_scenarios.rs index 977d8bb..0cef217 100644 --- a/integrations/shared/test_scenarios.rs +++ b/integrations/shared/test_scenarios.rs @@ -45,7 +45,7 @@ where info!("โœ… Job enqueued: {}", job_id); // Dequeue the job - let dequeued_job = self.queue.dequeue("test_basic").await?; + let dequeued_job = self.queue.dequeue_one("test_basic").await?; assert!(dequeued_job.is_some(), "Job should be dequeued"); let dequeued_job = dequeued_job.unwrap(); assert_eq!(dequeued_job.id, job_id); @@ -89,7 +89,7 @@ where info!("โœ… Delayed job enqueued: {}", job_id); // Try to dequeue immediately - should get nothing - let immediate_result = self.queue.dequeue("test_delayed").await?; + let immediate_result = self.queue.dequeue_one("test_delayed").await?; assert!( immediate_result.is_none(), "Delayed job should not be available immediately" @@ -100,7 +100,7 @@ where sleep(Duration::from_secs(3)).await; // Now try to dequeue - should get the job - let delayed_result = self.queue.dequeue("test_delayed").await?; + let delayed_result = self.queue.dequeue_one("test_delayed").await?; assert!( delayed_result.is_some(), "Delayed job should be available after delay" @@ -136,7 +136,7 @@ where info!("โœ… Retry test job enqueued: {}", job_id); // Dequeue and fail the job - let dequeued_job = self.queue.dequeue("test_retry").await?; + let dequeued_job = self.queue.dequeue_one("test_retry").await?; assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); assert_eq!(dequeued_job.attempts, 1); @@ -191,7 +191,7 @@ where handler.clone(), ) .with_poll_interval(Duration::from_millis(100)) - .with_max_retries(2); + .with_attempt_cap(2); let worker2 = Worker::new( self.queue.clone(), @@ -199,7 +199,7 @@ where handler.clone(), ) .with_poll_interval(Duration::from_millis(100)) - .with_max_retries(2); + .with_attempt_cap(2); // Enqueue test jobs for i in 0..5 { @@ -264,7 +264,7 @@ where for _ in 0..3 { let queue_clone = self.queue.clone(); let handle = tokio::spawn(async move { - if let Ok(Some(job)) = queue_clone.dequeue("concurrent_test").await { + if let Ok(Some(job)) = queue_clone.dequeue_one("concurrent_test").await { // Simulate processing sleep(Duration::from_millis(50)).await; let _ = queue_clone.complete_job(job.id).await; @@ -303,7 +303,7 @@ where info!("๐Ÿงช Testing error handling and edge cases"); // Test dequeue from empty queue - let empty_result = self.queue.dequeue("nonexistent_queue").await?; + let empty_result = self.queue.dequeue_one("nonexistent_queue").await?; assert!(empty_result.is_none(), "Empty queue should return None"); info!("โœ… Empty queue correctly returns None"); @@ -350,7 +350,7 @@ where // Dequeue and fail the job multiple times to exhaust retries for attempt in 1..=2 { - let dequeued_job = self.queue.dequeue("dead_job_test").await?; + let dequeued_job = self.queue.dequeue_one("dead_job_test").await?; assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); assert_eq!(dequeued_job.attempts, attempt); @@ -457,7 +457,7 @@ where // Create worker with stats collector let worker = Worker::new(self.queue.clone(), "stats_test".to_string(), handler) .with_poll_interval(Duration::from_millis(100)) - .with_max_retries(2) + .with_attempt_cap(2) .with_stats_collector(Arc::clone(&stats_collector)); // Enqueue test jobs (mix of successful and failing) @@ -561,10 +561,10 @@ where info!("โœ… Enqueued jobs in multiple queues"); // Complete some jobs to generate statistics - if let Some(job) = self.queue.dequeue("email_queue").await? { + if let Some(job) = self.queue.dequeue_one("email_queue").await? { self.queue.complete_job(job.id).await?; } - if let Some(job) = self.queue.dequeue("notification_queue").await? { + if let Some(job) = self.queue.dequeue_one("notification_queue").await? { self.queue.complete_job(job.id).await?; } diff --git a/src/config.rs b/src/config.rs index ec42210..5a335d6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -614,6 +614,18 @@ pub struct WorkerConfig { /// Must be greater than zero when `result_cleanup_enabled`. #[serde(default = "default_result_cleanup_interval", with = "serde_duration")] pub result_cleanup_interval: StdDuration, + + /// Claim up to this many jobs per poll (batch mode; see + /// [`Worker::with_batch_size`](crate::Worker::with_batch_size)). Unset (the default), + /// workers claim one job at a time, unless batch mode is enabled in code. + #[serde(default)] + pub batch_size: Option, + + /// In batch mode, run up to this many claimed jobs at once (see + /// [`Worker::with_batch_concurrency`](crate::Worker::with_batch_concurrency)). + /// Unset (the default), the worker's own setting applies (one by default). + #[serde(default)] + pub batch_concurrency: Option, } /// Default [`WorkerConfig::result_cleanup_interval`]: five minutes. @@ -644,6 +656,8 @@ impl Default for WorkerConfig { max_workers: 16, result_cleanup_enabled: true, result_cleanup_interval: DEFAULT_RESULT_CLEANUP_INTERVAL, + batch_size: None, + batch_concurrency: None, } } } @@ -2707,6 +2721,14 @@ retry_strategy = { type = "Fixed", duration_ms = 1000 } "#; let worker: WorkerConfig = toml::from_str(old).unwrap(); assert!(worker.result_cleanup_enabled); + // Without batch keys, batch mode stays off. + assert_eq!((worker.batch_size, worker.batch_concurrency), (None, None)); + let batched: WorkerConfig = + toml::from_str(&format!("{old}batch_size = 50\nbatch_concurrency = 8\n")).unwrap(); + assert_eq!( + (batched.batch_size, batched.batch_concurrency), + (Some(50), Some(8)) + ); assert_eq!(worker.result_cleanup_interval, StdDuration::from_secs(300)); assert_eq!( WorkerConfig::default().result_cleanup_interval, diff --git a/src/lib.rs b/src/lib.rs index 2de8082..d84a95b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -335,7 +335,8 @@ pub use priority::{ JobPriority, PriorityError, PrioritySelectionStrategy, PriorityStats, PriorityWeights, }; pub use queue::{ - EncryptedJobPurge, JobOutcome, JobQueue, JobTransition, RecordedOutcome, StaleJobRecovery, + DequeueOptions, EncryptedJobPurge, JobOutcome, JobQueue, JobTransition, RecordedOutcome, + StaleJobRecovery, }; pub use rate_limit::{RateLimit, RateLimiter, ThrottleConfig}; pub use retry::{JitterType, RetryStrategy, fibonacci}; diff --git a/src/queue/backend.rs b/src/queue/backend.rs index 8725c3b..b1b5eb4 100644 --- a/src/queue/backend.rs +++ b/src/queue/backend.rs @@ -408,7 +408,7 @@ pub(crate) fn pick_weighted_priority( } /// Fill a weighted batch claim of up to `max_jobs` jobs of `queue_name` -/// ([`DatabaseQueue::dequeue_batch_leased`] with weights): pick one of `candidates` (the +/// ([`DatabaseQueue::dequeue`] of several jobs with weights): pick one of `candidates` (the /// levels with runnable jobs) by weight, claim up to the room left with /// `claim(level, room)`, and repeat with the remaining levels until the batch is full or /// no level is left. @@ -470,7 +470,7 @@ pub(crate) fn weighted_seed(queue_name: &str, attempt: usize) -> u64 { } /// Put claimed jobs in claim order: highest priority first, then oldest (`priority -/// DESC, scheduled_at ASC`), as [`DatabaseQueue::dequeue_batch_leased`] returns them. +/// DESC, scheduled_at ASC`), as [`DatabaseQueue::dequeue`] returns them. #[cfg_attr(not(feature = "postgres"), allow(dead_code))] pub(crate) fn sort_in_claim_order(jobs: &mut [Job]) { jobs.sort_by(|a, b| { diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 190dbdb..f82ef03 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -42,6 +42,22 @@ mod memory_results; pub use memory_results::DEFAULT_MEMORY_RESULT_CAPACITY; pub(crate) use memory_results::MemoryResultStore; +/// Seals [`DatabaseQueue`]: only types in this crate can implement [`private::Sealed`], +/// so only they can implement the trait. +mod private { + /// The supertrait that seals [`DatabaseQueue`](super::DatabaseQueue). + pub trait Sealed {} + + #[cfg(feature = "postgres")] + impl Sealed for super::JobQueue {} + + #[cfg(feature = "mysql")] + impl Sealed for super::JobQueue {} + + #[cfg(feature = "test-queue")] + impl Sealed for super::test::TestQueue {} +} + /// Information about a queue's pause state #[derive(Debug, Clone, Serialize, Deserialize)] pub struct QueuePauseInfo { @@ -61,8 +77,21 @@ pub struct QueuePauseInfo { /// including job management, batch operations, statistics, and result storage. /// Each database backend implements this trait with optimizations specific to /// that database system. +/// +/// # Sealed +/// +/// This trait is sealed: it is implemented by [`JobQueue`](JobQueue) (feature +/// `postgres`), [`JobQueue`](JobQueue) (feature `mysql`) and +/// [`TestQueue`](crate::queue::test::TestQueue) (feature `test-queue`), and cannot be +/// implemented outside Hammerwork. New methods can therefore be added in minor +/// releases. Use it as a bound (`Q: DatabaseQueue`, `&impl DatabaseQueue`) to write +/// code that works with any of these queues. +/// +/// To test code that uses a queue without a database, use +/// [`TestQueue`](crate::queue::test::TestQueue), an in-memory implementation with the +/// same behaviour as the database backends and a mock clock (see `docs/testing.md`). #[async_trait] -pub trait DatabaseQueue: Send + Sync { +pub trait DatabaseQueue: private::Sealed + Send + Sync { type Database: Database; // Core job operations @@ -77,131 +106,93 @@ pub trait DatabaseQueue: Send + Sync { /// concurrently is applied either way. async fn enqueue(&self, job: Job) -> Result; - /// Claim the next runnable job of `queue_name`: `Pending`, due (by the database - /// clock), not waiting on dependencies, highest priority first, then oldest. - /// Returns `None` when there is none or the queue is paused. - /// - /// The claim holds a lease of [`DEFAULT_LEASE_DURATION`] (see - /// [`dequeue_leased`](Self::dequeue_leased)). - async fn dequeue(&self, queue_name: &str) -> Result>; - - /// Like [`dequeue`](Self::dequeue), but picks the priority level by weight among - /// the levels that have runnable jobs, then claims that level's oldest job (see - /// [`PriorityWeights`](crate::priority::PriorityWeights)). Every level with - /// runnable jobs and a non-zero weight is picked regularly, however many jobs of - /// other levels are queued. - async fn dequeue_with_priority_weights( - &self, - queue_name: &str, - weights: &crate::priority::PriorityWeights, - ) -> Result>; - - /// Claim the next runnable job of `queue_name` and hold a lease on it until - /// `now + lease` (by the database clock). + /// Claim up to [`max_jobs`](DequeueOptions::max_jobs) runnable jobs of `queue_name` + /// and hold a lease on each until `now + lease` (by the database clock). /// - /// Picks the job like - /// [`dequeue_with_priority_weights`](Self::dequeue_with_priority_weights) when - /// `weights` is given, otherwise like [`dequeue`](Self::dequeue). The lease - /// (`lease_expires_at`, with `last_heartbeat_at`) is written by the statement that - /// claims the job, so a claimed job is never without a lease: + /// A job is runnable when it is `Pending`, due (by the database clock), not waiting + /// on dependencies and not a disabled recurring job's held occurrence, and its queue + /// is not paused. Each claimed job becomes `Running`, its `attempts` is incremented, + /// and its lease (`lease_expires_at`, with `last_heartbeat_at`) is written by the + /// statement that claims it, so a claimed job is never without a lease: /// [`requeue_stale_jobs`](Self::requeue_stale_jobs) leaves it alone until the lease /// expires, and the worker extends it with [`heartbeat_job`](Self::heartbeat_job). + /// Concurrent callers never claim the same job (`FOR UPDATE SKIP LOCKED` on the + /// database backends). + /// + /// Returns fewer than `max_jobs` jobs (possibly none) when fewer are runnable or the + /// queue is paused, and none for a `max_jobs` of zero. The built-in backends claim at + /// most [`MAX_DEQUEUE_BATCH_SIZE`] jobs per call. The jobs are returned in claim + /// order: highest priority first, then oldest (`priority DESC, scheduled_at ASC`). + /// For the common case of one job with the default options, see + /// [`dequeue_one`](Self::dequeue_one). + /// + /// Options (see [`DequeueOptions`]): + /// - **Lease.** [`lease_duration`](DequeueOptions::lease_duration), or + /// [`DEFAULT_LEASE_DURATION`] when it is `None`. A zero lease never expires: the + /// reaper never reclaims the job, even if its worker dies, so an operator has to + /// (see + /// [`Worker::with_lease_duration`](crate::worker::Worker::with_lease_duration)). + /// - **Priority.** Without [`priority_weights`](DequeueOptions::priority_weights), or + /// with strict [`PriorityWeights`](crate::priority::PriorityWeights), jobs are + /// claimed in strict priority order: the highest priority level first, then the + /// next, and so on. With weighted `priority_weights`, a priority level is picked by + /// weight among the levels that have runnable jobs, and its oldest jobs are + /// claimed. Every level with runnable jobs and a non-zero weight is picked + /// regularly, however many jobs of other levels are queued. If the picked level has + /// fewer runnable jobs than there is room for (or other workers hold them all), + /// another level is picked by weight among the remaining ones to fill the rest, and + /// so on, so no claim comes back short while other levels have runnable jobs. + /// + /// Each claimed job stays `Running` under its own lease until its outcome is + /// recorded with [`finish_job_run`](Self::finish_job_run) or it is handed back with + /// [`release_job_run`](Self::release_job_run). A caller that holds several jobs + /// before running them must keep their leases alive with + /// [`heartbeat_job`](Self::heartbeat_job), or the reaper reclaims them once their + /// lease expires, and should record each one's actual start with + /// [`start_claimed_run`](Self::start_claimed_run). /// - /// A zero `lease` never expires: the reaper never reclaims the job, even if its - /// worker dies, so an operator has to (see - /// [`Worker::with_lease_duration`](crate::worker::Worker::with_lease_duration)). + /// When several jobs are claimed, a row that cannot be decoded is skipped and logged + /// rather than failing the claim (it stays `Running` until its lease expires), and if + /// a weighted claim fails after some jobs were claimed, those jobs are returned + /// rather than the error, so no claimed job is lost to the caller. A claim of one job + /// returns these errors. /// - /// The default implementation ignores `lease`, for backends that predate leases. - async fn dequeue_leased( - &self, - queue_name: &str, - weights: Option<&crate::priority::PriorityWeights>, - lease: std::time::Duration, - ) -> Result> { - let _ = lease; - match weights { - Some(weights) => { - self.dequeue_with_priority_weights(queue_name, weights) - .await - } - None => self.dequeue(queue_name).await, - } - } - - /// Claim up to `max_jobs` runnable jobs of `queue_name` at once, highest priority - /// first, then oldest, each with a lease of [`DEFAULT_LEASE_DURATION`]. + /// Jobs with encrypted payloads come back with their stored, encrypted payload; + /// decrypt them with [`JobQueue::decrypt_job`](crate::queue::JobQueue::decrypt_job) + /// before running. /// - /// See [`dequeue_batch_leased`](Self::dequeue_batch_leased). - async fn dequeue_batch(&self, queue_name: &str, max_jobs: usize) -> Result> { - self.dequeue_batch_leased(queue_name, None, DEFAULT_LEASE_DURATION, max_jobs) - .await - } + /// # Examples + /// + /// ```rust,no_run + /// use hammerwork::queue::{DatabaseQueue, DequeueOptions}; + /// use hammerwork::PriorityWeights; + /// use std::time::Duration; + /// + /// # async fn example(queue: &impl DatabaseQueue) -> hammerwork::Result<()> { + /// // Up to 10 jobs, picked by priority weight, each with a 1 minute lease. + /// let options = DequeueOptions::batch(10) + /// .with_priority_weights(PriorityWeights::new()) + /// .with_lease_duration(Duration::from_secs(60)); + /// for job in queue.dequeue("emails", &options).await? { + /// println!("claimed {}", job.id); + /// } + /// # Ok(()) + /// # } + /// ``` + async fn dequeue(&self, queue_name: &str, options: &DequeueOptions) -> Result>; - /// Claim up to `max_jobs` runnable jobs of `queue_name` at once and hold a lease on - /// each until `now + lease` (by the database clock). + /// Claim the next runnable job of `queue_name` with the default + /// [`DequeueOptions`]: strict priority order (highest priority first, then oldest) + /// and a lease of [`DEFAULT_LEASE_DURATION`]. Returns `None` when there is none or + /// the queue is paused. /// - /// Every claimed job is claimed exactly as [`dequeue_leased`](Self::dequeue_leased) - /// claims one: it is `Pending`, due, not waiting on dependencies and not a disabled - /// recurring job's held occurrence; its queue is not paused; its `attempts` is - /// incremented; and its lease is written by the statement that claims it. - /// Concurrent callers never claim the same job (`FOR UPDATE SKIP LOCKED` on the - /// database backends). Returns fewer than `max_jobs` jobs (possibly none) when fewer - /// are runnable, and none for a `max_jobs` of zero. - /// - /// The jobs are returned in claim order: highest priority first, then oldest - /// (`priority DESC, scheduled_at ASC`). Each stays `Running` under its own lease - /// until its outcome is recorded with [`finish_job_run`](Self::finish_job_run) or - /// it is handed back with [`release_job_run`](Self::release_job_run); a caller that - /// holds jobs before running them must keep their leases alive with - /// [`heartbeat_job`](Self::heartbeat_job), or the reaper reclaims them once their - /// lease expires. - /// - /// Priority selection: - /// - without `weights`, or with strict [`PriorityWeights`](crate::priority::PriorityWeights), - /// jobs are claimed in strict priority order: the batch is filled from the highest - /// priority level first, then the next, and so on; - /// - with weighted `weights`, a priority level is picked by weight among the levels - /// that have runnable jobs, exactly as a single weighted claim picks one, and the - /// batch is filled with that level's oldest jobs. If the level has fewer runnable - /// jobs than the batch has room for, another level is picked by weight among the - /// remaining ones to fill the rest, and so on. So over many batches each level gets - /// batches in proportion to its weight, and no batch comes back short while other - /// levels have runnable jobs. - /// - /// Jobs with encrypted payloads come back as a single dequeue returns them (with - /// their stored, encrypted payload); decrypt them with - /// [`JobQueue::decrypt_job`](crate::queue::JobQueue::decrypt_job) before running. - /// - /// The default implementation claims the jobs one at a time with - /// [`dequeue_leased`](Self::dequeue_leased) (so with weights each job picks its own - /// level), for backends that predate batch claims. If a claim fails after some - /// jobs were claimed, it returns those jobs rather than the error, so no claimed - /// job is lost to the caller. - async fn dequeue_batch_leased( - &self, - queue_name: &str, - weights: Option<&crate::priority::PriorityWeights>, - lease: std::time::Duration, - max_jobs: usize, - ) -> Result> { - let mut jobs = Vec::new(); - while jobs.len() < max_jobs { - match self.dequeue_leased(queue_name, weights, lease).await { - Ok(Some(job)) => jobs.push(job), - Ok(None) => break, - Err(error) if jobs.is_empty() => return Err(error), - Err(error) => { - tracing::warn!( - "claiming a job of queue {} failed after {} were claimed: {}", - queue_name, - jobs.len(), - error - ); - break; - } - } - } - Ok(jobs) + /// Shorthand for [`dequeue`](Self::dequeue) with [`DequeueOptions::new`]. + async fn dequeue_one(&self, queue_name: &str) -> Result> { + Ok(self + .dequeue(queue_name, &DequeueOptions::new()) + .await? + .into_iter() + .next()) } /// Hand a claimed job that was never run back to its queue. @@ -216,18 +207,7 @@ pub trait DatabaseQueue: Send + Sync { /// Workers in batch mode ([`Worker::with_batch_size`](crate::worker::Worker::with_batch_size)) /// call this on shutdown for the claimed jobs they have not started, so those jobs /// can run elsewhere at once instead of waiting for their leases to expire. - /// - /// The default implementation records a retry due now through - /// [`finish_job_run`](Self::finish_job_run), for backends that predate this method: - /// the job is runnable again at once, but the claim still counts as an attempt. - async fn release_job_run(&self, run: &Job) -> Result { - let outcome = JobOutcome::Retry { - retry_at: Utc::now(), - error: RELEASED_JOB_MESSAGE.to_string(), - timed_out: false, - }; - Ok(self.finish_job_run(run, outcome).await?.is_some()) - } + async fn release_job_run(&self, run: &Job) -> Result; /// Manually mark a job `Completed`. /// @@ -760,39 +740,20 @@ pub trait DatabaseQueue: Send + Sync { /// for a single queue. /// /// [`JobArchiver::run_scheduled_pass`](crate::archive::JobArchiver::run_scheduled_pass) - /// uses it to apply each queue's own `purge_archived_after`. The default - /// implementation returns an error, for backends that predate per-queue purging. + /// uses it to apply each queue's own `purge_archived_after`. async fn purge_archived_jobs_in_queue( &self, queue_name: &str, older_than: DateTime, - ) -> Result { - let _ = (queue_name, older_than); - Err(crate::HammerworkError::Queue { - message: "purging the archive of a single queue is not supported by this queue \ - backend" - .to_string(), - }) - } + ) -> Result; /// The names of the queues that have jobs, in `hammerwork_jobs` or in the archive, /// sorted. /// /// [`JobArchiver::run_scheduled_pass`](crate::archive::JobArchiver::run_scheduled_pass) /// uses it to apply the default archival policy to every queue without a policy of - /// its own. The default implementation lists the queues of - /// [`get_all_queue_stats`](Self::get_all_queue_stats) (live jobs only). - async fn list_queue_names(&self) -> Result> { - let mut names: Vec = self - .get_all_queue_stats() - .await? - .into_iter() - .map(|stats| stats.queue_name) - .collect(); - names.sort(); - names.dedup(); - Ok(names) - } + /// its own. + async fn list_queue_names(&self) -> Result>; /// Get statistics about archived jobs. /// @@ -828,7 +789,7 @@ pub trait DatabaseQueue: Send + Sync { /// Pause job processing for a specific queue. /// /// When a queue is paused, [`dequeue`](Self::dequeue) and - /// [`dequeue_with_priority_weights`](Self::dequeue_with_priority_weights) return + /// [`dequeue_one`](Self::dequeue_one) return /// no jobs from it (the check is part of the dequeue query, so it also applies to /// callers other than workers), but jobs already in progress continue to /// completion. This allows for graceful queue management without interrupting @@ -973,55 +934,11 @@ pub trait DatabaseQueue: Send + Sync { /// this one, `Manual` leaves them waiting) and a `FailFast` batch fails its /// pending jobs; /// - workflow counters and status, and batch status, are updated. - /// - /// The default implementation composes the manual methods without a transaction, - /// for backends that predate this method. async fn finish_job_run( &self, run: &Job, outcome: JobOutcome, - ) -> Result> { - let Some(current) = self.get_job(run.id).await? else { - return Ok(None); - }; - if !lifecycle::Guard::Run(run).admits(¤t) { - return Ok(None); - } - let next_run_at = match outcome.terminal_status() { - Some(_) if current.recurring => lifecycle::next_cron_run(¤t, Utc::now()), - _ => None, - }; - let mut recorded = match outcome { - JobOutcome::Completed => { - if next_run_at.is_none() { - self.complete_job(run.id).await?; - } - RecordedOutcome::new(crate::job::JobStatus::Completed) - } - JobOutcome::Retry { retry_at, .. } => { - self.retry_job(run.id, retry_at).await?; - RecordedOutcome::new(crate::job::JobStatus::Pending) - } - JobOutcome::Dead { error } => { - self.mark_job_dead(run.id, &error).await?; - RecordedOutcome::new(crate::job::JobStatus::Dead) - } - JobOutcome::TimedOut { error } => { - self.mark_job_timed_out(run.id, &error).await?; - RecordedOutcome::new(crate::job::JobStatus::TimedOut) - } - }; - if let Some(next) = next_run_at { - self.reschedule_cron_job(run.id, next).await?; - recorded.status = crate::job::JobStatus::Pending; - recorded.next_run_at = Some(next); - } else if recorded.status == crate::job::JobStatus::Completed { - recorded.unblocked = self.resolve_job_dependencies(run.id).await?; - } else if recorded.status != crate::job::JobStatus::Pending { - recorded.cancelled = self.fail_job_dependencies(run.id).await?; - } - Ok(Some(recorded)) - } + ) -> Result>; /// Record that a run completed and enqueue the child jobs it spawned, as one unit. /// @@ -1042,38 +959,17 @@ pub trait DatabaseQueue: Send + Sync { /// they have finished. Each child is checked against the dependency limits /// ([`Job::validate_dependencies`](crate::Job::validate_dependencies)) before /// anything is written. - /// - /// The default implementation, for backends without transactions, enqueues the - /// children first and then records the completion, so a failure part-way leaves the - /// parent `Running` (to be retried) rather than completed without its children; a - /// retry may then enqueue the children again. It does not change workflow totals. async fn complete_job_run_with_children( &self, run: &Job, children: Vec, - ) -> Result> { - let Some(current) = self.get_job(run.id).await? else { - return Ok(None); - }; - if !lifecycle::Guard::Run(run).admits(¤t) { - return Ok(None); - } - let mut spawned = Vec::with_capacity(children.len()); - for child in children { - spawned.push(self.enqueue(child).await?); - } - let recorded = self.finish_job_run(run, JobOutcome::Completed).await?; - Ok(recorded.map(|mut recorded| { - recorded.spawned = spawned; - recorded - })) - } + ) -> Result>; // Lease / stale job recovery /// Record a heartbeat for a run of a `Running` job and extend its lease to /// `now + lease` (a zero `lease` never expires, as in - /// [`dequeue_leased`](Self::dequeue_leased)). + /// [`dequeue`](Self::dequeue)). /// /// `run` is the job as returned by the dequeue. Workers call this periodically while /// a handler runs. The lease tells [`requeue_stale_jobs`](Self::requeue_stale_jobs) @@ -1085,18 +981,12 @@ pub trait DatabaseQueue: Send + Sync { /// worker is running it again: the caller has lost its lease, and its heartbeat does /// not extend the new run's lease. /// - /// The default implementation returns an error, for backends that predate leases. - async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result { - let _ = (run, lease); - Err(crate::HammerworkError::Queue { - message: "job leases are not supported by this queue backend".to_string(), - }) - } + async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result; /// Record that a claimed run is starting now, after it waited for its turn. /// - /// `run` is the job as returned by the dequeue. A batch claim - /// ([`dequeue_batch_leased`](Self::dequeue_batch_leased)) stamps every job's + /// `run` is the job as returned by the dequeue. A claim of several jobs + /// ([`dequeue`](Self::dequeue)) stamps every job's /// `started_at` with the claim time, so a job that waits in the batch would have its /// wait counted as processing time. If the job is still `Running` that run (as in /// [`heartbeat_job`](Self::heartbeat_job)), this sets its `started_at` to the current @@ -1106,19 +996,13 @@ pub trait DatabaseQueue: Send + Sync { /// `Running` that run. /// /// Workers in batch mode call this for a held job when it starts. - /// - /// The default implementation only renews the lease with - /// [`heartbeat_job`](Self::heartbeat_job) and leaves `started_at` at the claim time, - /// for backends that predate this method. - async fn start_claimed_run(&self, run: &mut Job, lease: std::time::Duration) -> Result { - self.heartbeat_job(run, lease).await - } + async fn start_claimed_run(&self, run: &mut Job, lease: std::time::Duration) -> Result; /// Reclaim jobs left in `Running` by workers that crashed or were killed. /// /// A `Running` job is stale when: /// - it has a lease from its current run and that lease has expired. Every job - /// claimed by [`dequeue`](Self::dequeue) or [`dequeue_leased`](Self::dequeue_leased) + /// claimed by [`dequeue`](Self::dequeue) or [`dequeue_one`](Self::dequeue_one) /// holds a lease from the moment it is claimed, so it is reclaimed only once its /// worker stopped renewing it, whatever `older_than` is; or /// - it has no lease from its current run, because it was claimed by an older @@ -1150,17 +1034,8 @@ pub trait DatabaseQueue: Send + Sync { /// # Ok(()) /// # } /// ``` - /// - /// The default implementation returns an error, for backends that predate leases. - async fn requeue_stale_jobs( - &self, - older_than: std::time::Duration, - ) -> Result { - let _ = older_than; - Err(crate::HammerworkError::Queue { - message: "stale job recovery is not supported by this queue backend".to_string(), - }) - } + async fn requeue_stale_jobs(&self, older_than: std::time::Duration) + -> Result; /// Enforces the retention policies of encrypted jobs: deletes finished encrypted jobs /// whose retention period has ended. @@ -1176,14 +1051,7 @@ pub trait DatabaseQueue: Send + Sync { /// /// Run it periodically, e.g. from a cron job or with /// `cargo hammerwork maintenance purge-encrypted`. It needs no encryption key. - /// - /// The default implementation returns an error, for backends without encryption - /// support. - async fn purge_expired_encrypted_jobs(&self) -> Result { - Err(crate::HammerworkError::Queue { - message: "encrypted job retention is not supported by this queue backend".to_string(), - }) - } + async fn purge_expired_encrypted_jobs(&self) -> Result; } /// The outcome of [`DatabaseQueue::purge_expired_encrypted_jobs`]. @@ -1227,22 +1095,100 @@ impl StaleJobRecovery { pub const STALE_JOB_ERROR_MESSAGE: &str = "Job lease expired while Running; the worker is presumed dead and the job was reclaimed"; -/// Error message recorded on a job handed back by the default -/// [`DatabaseQueue::release_job_run`] (the built-in backends release a job without one). -pub const RELEASED_JOB_MESSAGE: &str = - "Job was claimed but not started; released back to its queue"; - -/// The most jobs one [`DatabaseQueue::dequeue_batch_leased`] call claims on the built-in +/// The most jobs one [`DatabaseQueue::dequeue`] call claims on the built-in /// backends; larger requests are capped at this. Keeps the claim statement (and, on /// MySQL, its list of ids) bounded. pub const MAX_DEQUEUE_BATCH_SIZE: usize = 1000; -/// The lease a claim holds when the caller does not choose one: -/// [`DatabaseQueue::dequeue`] and [`DatabaseQueue::dequeue_with_priority_weights`], and -/// workers by default +/// The lease a claim holds when the caller does not choose one +/// ([`DequeueOptions::lease_duration`] is `None`, as with [`DatabaseQueue::dequeue_one`]), +/// and workers by default /// ([`Worker::with_lease_duration`](crate::worker::Worker::with_lease_duration)). pub const DEFAULT_LEASE_DURATION: std::time::Duration = std::time::Duration::from_secs(300); +/// What [`DatabaseQueue::dequeue`] claims: how many jobs, how it picks them by priority, +/// and the lease it holds on them. +/// +/// The [default](DequeueOptions::new) claims one job in strict priority order with a +/// lease of [`DEFAULT_LEASE_DURATION`]. Build other options with the constructors and +/// `with_*` methods: +/// +/// ```rust +/// use hammerwork::queue::DequeueOptions; +/// use hammerwork::PriorityWeights; +/// use std::time::Duration; +/// +/// let one = DequeueOptions::new(); +/// assert_eq!(one.max_jobs, 1); +/// +/// let batch = DequeueOptions::batch(25) +/// .with_priority_weights(PriorityWeights::new()) +/// .with_lease_duration(Duration::from_secs(60)); +/// assert_eq!(batch.max_jobs, 25); +/// ``` +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct DequeueOptions { + /// Pick the priority level by weight (see [`DatabaseQueue::dequeue`]). `None`, or + /// strict weights, claims in strict priority order: highest priority first, then + /// oldest. + pub priority_weights: Option, + /// The lease each claimed job holds, from the claim on. `None` uses + /// [`DEFAULT_LEASE_DURATION`]; zero never expires. + pub lease_duration: Option, + /// The most jobs to claim. Zero claims none; the built-in backends claim at most + /// [`MAX_DEQUEUE_BATCH_SIZE`]. + pub max_jobs: usize, +} + +impl Default for DequeueOptions { + fn default() -> Self { + Self { + priority_weights: None, + lease_duration: None, + max_jobs: 1, + } + } +} + +impl DequeueOptions { + /// Claim one job, in strict priority order, with a lease of + /// [`DEFAULT_LEASE_DURATION`]. + pub fn new() -> Self { + Self::default() + } + + /// Claim up to `max_jobs` jobs, in strict priority order, each with a lease of + /// [`DEFAULT_LEASE_DURATION`]. + pub fn batch(max_jobs: usize) -> Self { + Self::new().with_max_jobs(max_jobs) + } + + /// Claim up to `max_jobs` jobs. + pub fn with_max_jobs(mut self, max_jobs: usize) -> Self { + self.max_jobs = max_jobs; + self + } + + /// Pick priority levels by `weights` (see [`DatabaseQueue::dequeue`]). + pub fn with_priority_weights(mut self, weights: crate::priority::PriorityWeights) -> Self { + self.priority_weights = Some(weights); + self + } + + /// Hold a lease of `lease` on each claimed job (zero never expires). + pub fn with_lease_duration(mut self, lease: std::time::Duration) -> Self { + self.lease_duration = Some(lease); + self + } + + /// The lease each claimed job holds: [`lease_duration`](Self::lease_duration), or + /// [`DEFAULT_LEASE_DURATION`] when it is `None`. + pub fn lease(&self) -> std::time::Duration { + self.lease_duration.unwrap_or(DEFAULT_LEASE_DURATION) + } +} + /// Convert a `std::time::Duration` to a `chrono::Duration`, saturating on overflow. pub(crate) fn saturating_chrono_duration(duration: std::time::Duration) -> chrono::Duration { chrono::Duration::from_std(duration).unwrap_or(chrono::Duration::MAX) @@ -1807,6 +1753,23 @@ impl JobQueue { #[cfg(test)] mod tests { + #[test] + fn dequeue_options_default_to_one_job_strict_default_lease() { + let options = super::DequeueOptions::default(); + assert_eq!(options.max_jobs, 1); + assert!(options.priority_weights.is_none()); + assert_eq!(options.lease_duration, None); + assert_eq!(options.lease(), super::DEFAULT_LEASE_DURATION); + + let options = super::DequeueOptions::batch(7) + .with_priority_weights(crate::priority::PriorityWeights::strict()) + .with_lease_duration(std::time::Duration::ZERO); + assert_eq!(options.max_jobs, 7); + assert!(options.priority_weights.as_ref().unwrap().is_strict()); + assert_eq!(options.lease(), std::time::Duration::ZERO); + assert_eq!(options.with_max_jobs(2).max_jobs, 2); + } + #[test] fn sort_in_claim_order_is_priority_then_oldest() { use crate::priority::JobPriority; diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index b0afad0..ab40561 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -11,7 +11,8 @@ use super::row::{ result_storage_str, }; use super::{ - DatabaseQueue, DeadJobSummary, JobOutcome, JobTransition, QueueStats, RecordedOutcome, + DatabaseQueue, DeadJobSummary, DequeueOptions, JobOutcome, JobTransition, QueueStats, + RecordedOutcome, }; use crate::{ Result, @@ -535,46 +536,9 @@ impl crate::queue::JobQueue { } } -#[async_trait] -impl DatabaseQueue for crate::queue::JobQueue { - type Database = MySql; - - async fn enqueue(&self, mut job: Job) -> Result { - job.validate_dependencies()?; - self.seal_for_insert(std::slice::from_mut(&mut job)).await?; - if job.depends_on.is_empty() { - let mut conn = self.pool.acquire().await?; - insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; - return Ok(job.id); - } - // A job with dependencies is inserted together with a check of its - // dependencies' current state (see `insert_dependent_jobs`). - super::retry_on_conflict(|| async { - let mut conn = self.pool.acquire().await?; - let mut tx = Self::begin_claim_transaction(&mut conn).await?; - let mut jobs = vec![job.clone()]; - let result = insert_dependent_jobs(&mut tx, &mut jobs).await; - super::end_transaction(tx, result).await - }) - .await?; - Ok(job.id) - } - - async fn dequeue(&self, queue_name: &str) -> Result> { - self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_with_priority_weights( - &self, - queue_name: &str, - weights: &crate::priority::PriorityWeights, - ) -> Result> { - self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_leased( +impl crate::queue::JobQueue { + /// Claim one job ([`DatabaseQueue::dequeue`] with a `max_jobs` of 1). + async fn claim_one( &self, queue_name: &str, weights: Option<&crate::priority::PriorityWeights>, @@ -590,7 +554,8 @@ impl DatabaseQueue for crate::queue::JobQueue { } } - async fn dequeue_batch_leased( + /// Claim up to `max_jobs` jobs ([`DatabaseQueue::dequeue`]). + async fn claim_many( &self, queue_name: &str, weights: Option<&crate::priority::PriorityWeights>, @@ -613,7 +578,7 @@ impl DatabaseQueue for crate::queue::JobQueue { } }; - // Which priority levels have a runnable job (see `dequeue_leased`). + // Which priority levels have a runnable job (see `claim_one`). let levels: Vec = sqlx::query_scalar(AssertSqlSafe(super::runnable_priorities_sql( RUNNABLE_IN_QUEUE_SQL, ))) @@ -642,6 +607,48 @@ impl DatabaseQueue for crate::queue::JobQueue { ) .await } +} + +#[async_trait] +impl DatabaseQueue for crate::queue::JobQueue { + type Database = MySql; + + async fn enqueue(&self, mut job: Job) -> Result { + job.validate_dependencies()?; + self.seal_for_insert(std::slice::from_mut(&mut job)).await?; + if job.depends_on.is_empty() { + let mut conn = self.pool.acquire().await?; + insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; + return Ok(job.id); + } + // A job with dependencies is inserted together with a check of its + // dependencies' current state (see `insert_dependent_jobs`). + super::retry_on_conflict(|| async { + let mut conn = self.pool.acquire().await?; + let mut tx = Self::begin_claim_transaction(&mut conn).await?; + let mut jobs = vec![job.clone()]; + let result = insert_dependent_jobs(&mut tx, &mut jobs).await; + super::end_transaction(tx, result).await + }) + .await?; + Ok(job.id) + } + + async fn dequeue(&self, queue_name: &str, options: &DequeueOptions) -> Result> { + let weights = options.priority_weights.as_ref(); + match options.max_jobs { + 0 => Ok(Vec::new()), + 1 => Ok(self + .claim_one(queue_name, weights, options.lease()) + .await? + .into_iter() + .collect()), + max_jobs => { + self.claim_many(queue_name, weights, options.lease(), max_jobs) + .await + } + } + } async fn release_job_run(&self, run: &Job) -> Result { // Undo this run's claim only: a job reclaimed and claimed again is left alone. diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 387955f..d91630e 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -11,7 +11,8 @@ use super::row::{ result_storage_str, }; use super::{ - DatabaseQueue, DeadJobSummary, JobOutcome, JobTransition, QueueStats, RecordedOutcome, + DatabaseQueue, DeadJobSummary, DequeueOptions, JobOutcome, JobTransition, QueueStats, + RecordedOutcome, }; use crate::{ Result, @@ -303,45 +304,9 @@ impl crate::queue::JobQueue { } } -#[async_trait] -impl DatabaseQueue for crate::queue::JobQueue { - type Database = Postgres; - - async fn enqueue(&self, mut job: Job) -> Result { - job.validate_dependencies()?; - self.seal_for_insert(std::slice::from_mut(&mut job)).await?; - if job.depends_on.is_empty() { - let mut conn = self.pool.acquire().await?; - insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; - return Ok(job.id); - } - // A job with dependencies is inserted together with a check of its - // dependencies' current state (see `insert_dependent_jobs`). - super::retry_on_conflict(|| async { - let mut tx = self.pool.begin().await?; - let mut jobs = vec![job.clone()]; - let result = insert_dependent_jobs(&mut tx, &mut jobs).await; - super::end_transaction(tx, result).await - }) - .await?; - Ok(job.id) - } - - async fn dequeue(&self, queue_name: &str) -> Result> { - self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_with_priority_weights( - &self, - queue_name: &str, - weights: &crate::priority::PriorityWeights, - ) -> Result> { - self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_leased( +impl crate::queue::JobQueue { + /// Claim one job ([`DatabaseQueue::dequeue`] with a `max_jobs` of 1). + async fn claim_one( &self, queue_name: &str, weights: Option<&crate::priority::PriorityWeights>, @@ -397,7 +362,8 @@ impl DatabaseQueue for crate::queue::JobQueue { Ok(None) } - async fn dequeue_batch_leased( + /// Claim up to `max_jobs` jobs ([`DatabaseQueue::dequeue`]). + async fn claim_many( &self, queue_name: &str, weights: Option<&crate::priority::PriorityWeights>, @@ -423,7 +389,7 @@ impl DatabaseQueue for crate::queue::JobQueue { } }; - // Which priority levels have a runnable job (see `dequeue_leased`). + // Which priority levels have a runnable job (see `claim_one`). let levels: Vec = sqlx::query_scalar(AssertSqlSafe(super::runnable_priorities_sql( RUNNABLE_IN_QUEUE_SQL, ))) @@ -455,6 +421,47 @@ impl DatabaseQueue for crate::queue::JobQueue { ) .await } +} + +#[async_trait] +impl DatabaseQueue for crate::queue::JobQueue { + type Database = Postgres; + + async fn enqueue(&self, mut job: Job) -> Result { + job.validate_dependencies()?; + self.seal_for_insert(std::slice::from_mut(&mut job)).await?; + if job.depends_on.is_empty() { + let mut conn = self.pool.acquire().await?; + insert_jobs(&mut conn, std::slice::from_ref(&job)).await?; + return Ok(job.id); + } + // A job with dependencies is inserted together with a check of its + // dependencies' current state (see `insert_dependent_jobs`). + super::retry_on_conflict(|| async { + let mut tx = self.pool.begin().await?; + let mut jobs = vec![job.clone()]; + let result = insert_dependent_jobs(&mut tx, &mut jobs).await; + super::end_transaction(tx, result).await + }) + .await?; + Ok(job.id) + } + + async fn dequeue(&self, queue_name: &str, options: &DequeueOptions) -> Result> { + let weights = options.priority_weights.as_ref(); + match options.max_jobs { + 0 => Ok(Vec::new()), + 1 => Ok(self + .claim_one(queue_name, weights, options.lease()) + .await? + .into_iter() + .collect()), + max_jobs => { + self.claim_many(queue_name, weights, options.lease(), max_jobs) + .await + } + } + } async fn release_job_run(&self, run: &Job) -> Result { // Undo this run's claim only: a job reclaimed and claimed again is left alone. diff --git a/src/queue/test.rs b/src/queue/test.rs index 019f1db..613a679 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -28,7 +28,7 @@ //! let job_id = queue.enqueue(job).await?; //! //! // Process the job -//! if let Some(mut job) = queue.dequeue("test_queue").await? { +//! if let Some(mut job) = queue.dequeue_one("test_queue").await? { //! // Process the job... //! queue.complete_job(job.id).await?; //! } @@ -41,7 +41,7 @@ use crate::{ batch::{BatchId, BatchResult, BatchStatus, JobBatch}, job::{Job, JobId, JobStatus}, priority::{JobPriority, PriorityWeights}, - queue::{DatabaseQueue, PayloadEncryption, QueuePauseInfo, lifecycle}, + queue::{DatabaseQueue, DequeueOptions, PayloadEncryption, QueuePauseInfo, lifecycle}, rate_limit::ThrottleConfig, stats::{DeadJobSummary, QueueStats}, workflow::{ @@ -114,13 +114,13 @@ type TestDatabaseType = sqlx::Any; // Fallback /// let job_id = queue.enqueue(delayed_job).await?; /// /// // Job should not be available immediately -/// assert!(queue.dequeue("delayed_queue").await?.is_none()); +/// assert!(queue.dequeue_one("delayed_queue").await?.is_none()); /// /// // Advance time by 2 hours /// clock.advance(Duration::hours(2)); /// /// // Now the job should be available -/// let job = queue.dequeue("delayed_queue").await?.unwrap(); +/// let job = queue.dequeue_one("delayed_queue").await?.unwrap(); /// assert_eq!(job.id, job_id); /// # Ok(()) /// # } @@ -707,7 +707,7 @@ impl TestStorage { } /// Up to `max_jobs` jobs to claim at once, in claim order, chosen like the database - /// backends' `dequeue_batch_leased`: in strict priority order, or with weighted + /// backends' `dequeue` of several jobs: in strict priority order, or with weighted /// `weights` filled from a level picked by weight, then from the other levels. fn get_next_jobs( &self, @@ -858,7 +858,7 @@ impl TestStorage { /// let job_id = queue.enqueue(job).await?; /// /// // Dequeue and process the job -/// let job = queue.dequeue("test_queue").await?.unwrap(); +/// let job = queue.dequeue_one("test_queue").await?.unwrap(); /// assert_eq!(job.status, JobStatus::Running); /// /// // Mark job as completed @@ -892,11 +892,11 @@ impl TestStorage { /// let high_id = queue.enqueue(high_job).await?; /// /// // High priority job should be dequeued first -/// let first_job = queue.dequeue("priority_queue").await?.unwrap(); +/// let first_job = queue.dequeue_one("priority_queue").await?.unwrap(); /// assert_eq!(first_job.id, high_id); /// assert_eq!(first_job.priority, JobPriority::High); /// -/// let second_job = queue.dequeue("priority_queue").await?.unwrap(); +/// let second_job = queue.dequeue_one("priority_queue").await?.unwrap(); /// assert_eq!(second_job.id, low_id); /// assert_eq!(second_job.priority, JobPriority::Low); /// # Ok(()) @@ -922,7 +922,7 @@ impl TestStorage { /// // Each dequeue counts as an attempt. Like a worker, retry the job while it has /// // attempts left and mark it dead once they are used up. /// for attempt in 1..=3 { -/// let job = queue.dequeue("retry_queue").await?.unwrap(); +/// let job = queue.dequeue_one("retry_queue").await?.unwrap(); /// assert_eq!(job.attempts, attempt); /// if job.attempts < job.max_attempts { /// queue.retry_job(job_id, queue.clock().now()).await?; @@ -939,7 +939,7 @@ impl TestStorage { /// let job_id = queue /// .enqueue(Job::new("retry_queue".to_string(), json!({"data": "other"}))) /// .await?; -/// queue.dequeue("retry_queue").await?.unwrap(); +/// queue.dequeue_one("retry_queue").await?.unwrap(); /// queue.fail_job(job_id, "Permanent error").await?; /// assert_eq!(queue.get_job(job_id).await?.unwrap().status, JobStatus::Failed); /// # Ok(()) @@ -1154,7 +1154,7 @@ impl TestQueue { /// assert_eq!(queue.get_job_count("test_queue", &JobStatus::Pending).await, 5); /// /// // Process one job - /// let job = queue.dequeue("test_queue").await?.unwrap(); + /// let job = queue.dequeue_one("test_queue").await?.unwrap(); /// queue.complete_job(job.id).await?; /// /// // Should have 4 pending and 1 completed @@ -1288,41 +1288,9 @@ impl Default for TestQueue { } } -#[async_trait] -impl DatabaseQueue for TestQueue { - type Database = TestDatabaseType; - - async fn enqueue(&self, mut job: Job) -> Result { - job.validate_dependencies()?; - self.encryption.seal(std::slice::from_mut(&mut job)).await?; - let mut storage = self.storage.write().await; - - let now = storage.clock.now(); - TestStorage::stamp_enqueued(&mut job, now); - storage.settle_new_dependents(std::slice::from_mut(&mut job), now); - - // Store the job - storage.jobs.insert(job.id, job.clone()); - storage.add_job_to_queue(&job); - - Ok(job.id) - } - - async fn dequeue(&self, queue_name: &str) -> Result> { - self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_with_priority_weights( - &self, - queue_name: &str, - weights: &PriorityWeights, - ) -> Result> { - self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) - .await - } - - async fn dequeue_leased( +impl TestQueue { + /// Claim one job ([`DatabaseQueue::dequeue`] with a `max_jobs` of 1). + async fn claim_one( &self, queue_name: &str, weights: Option<&PriorityWeights>, @@ -1348,7 +1316,8 @@ impl DatabaseQueue for TestQueue { })) } - async fn dequeue_batch_leased( + /// Claim up to `max_jobs` jobs ([`DatabaseQueue::dequeue`]). + async fn claim_many( &self, queue_name: &str, weights: Option<&PriorityWeights>, @@ -1375,6 +1344,43 @@ impl DatabaseQueue for TestQueue { } Ok(jobs) } +} + +#[async_trait] +impl DatabaseQueue for TestQueue { + type Database = TestDatabaseType; + + async fn enqueue(&self, mut job: Job) -> Result { + job.validate_dependencies()?; + self.encryption.seal(std::slice::from_mut(&mut job)).await?; + let mut storage = self.storage.write().await; + + let now = storage.clock.now(); + TestStorage::stamp_enqueued(&mut job, now); + storage.settle_new_dependents(std::slice::from_mut(&mut job), now); + + // Store the job + storage.jobs.insert(job.id, job.clone()); + storage.add_job_to_queue(&job); + + Ok(job.id) + } + + async fn dequeue(&self, queue_name: &str, options: &DequeueOptions) -> Result> { + let weights = options.priority_weights.as_ref(); + match options.max_jobs { + 0 => Ok(Vec::new()), + 1 => Ok(self + .claim_one(queue_name, weights, options.lease()) + .await? + .into_iter() + .collect()), + max_jobs => { + self.claim_many(queue_name, weights, options.lease(), max_jobs) + .await + } + } + } async fn release_job_run(&self, run: &Job) -> Result { let mut storage = self.storage.write().await; @@ -3174,7 +3180,10 @@ mod tests { .await .unwrap(); - let claimed = queue.dequeue_batch("batch", 2).await.unwrap(); + let claimed = queue + .dequeue("batch", &DequeueOptions::batch(2)) + .await + .unwrap(); let ids: Vec = claimed.iter().map(|job| job.id).collect(); assert_eq!(ids, [high, normal]); assert!(claimed.iter().all(|job| job.attempts == 1)); @@ -3188,13 +3197,64 @@ mod tests { // Paused queues hand out nothing. queue.pause_queue("batch", None).await.unwrap(); - assert!(queue.dequeue_batch("batch", 5).await.unwrap().is_empty()); + assert!( + queue + .dequeue("batch", &DequeueOptions::batch(5)) + .await + .unwrap() + .is_empty() + ); queue.resume_queue("batch", None).await.unwrap(); - let rest = queue.dequeue_batch("batch", 5).await.unwrap(); + let rest = queue + .dequeue("batch", &DequeueOptions::batch(5)) + .await + .unwrap(); assert_eq!(rest.len(), 1); assert_eq!(rest[0].id, low); } + #[tokio::test] + async fn dequeue_options_choose_count_and_lease() { + let queue = TestQueue::new(); + for _ in 0..3 { + queue + .enqueue(Job::new("options".to_string(), json!({}))) + .await + .unwrap(); + } + + // Zero jobs claims nothing; the default claims one. + let none = queue + .dequeue("options", &DequeueOptions::batch(0)) + .await + .unwrap(); + assert!(none.is_empty()); + let one = queue + .dequeue("options", &DequeueOptions::default()) + .await + .unwrap(); + assert_eq!(one.len(), 1); + assert!(queue.dequeue_one("options").await.unwrap().is_some()); + + // The lease option sets the claimed job's lease: once it expires, the reaper + // reclaims the job, while the default (5 minute) leases are still held. + let short = queue + .dequeue( + "options", + &DequeueOptions::new().with_lease_duration(std::time::Duration::from_secs(10)), + ) + .await + .unwrap(); + assert_eq!(short.len(), 1); + queue.clock().advance(chrono::Duration::seconds(30)); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(3600)) + .await + .unwrap(); + assert_eq!(recovery.requeued, [short[0].id]); + assert!(queue.dequeue_one("missing").await.unwrap().is_none()); + } + #[tokio::test] async fn release_job_run_returns_the_job_unclaimed() { let queue = TestQueue::new(); @@ -3202,14 +3262,25 @@ mod tests { .enqueue(Job::new("release".to_string(), json!({}))) .await .unwrap(); - let run = queue.dequeue_batch("release", 1).await.unwrap().remove(0); + let run = queue + .dequeue("release", &DequeueOptions::batch(1)) + .await + .unwrap() + .remove(0); assert!(queue.release_job_run(&run).await.unwrap()); let job = queue.get_job(id).await.unwrap().unwrap(); assert_eq!(job.status, JobStatus::Pending); assert_eq!(job.attempts, 0); assert_eq!(job.started_at, None); assert!(!queue.release_job_run(&run).await.unwrap()); - assert_eq!(queue.dequeue_batch("release", 1).await.unwrap().len(), 1); + assert_eq!( + queue + .dequeue("release", &DequeueOptions::batch(1)) + .await + .unwrap() + .len(), + 1 + ); } #[tokio::test] @@ -3227,7 +3298,7 @@ mod tests { ); // Dequeue the job - let dequeued = queue.dequeue("test_queue").await.unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap(); assert!(dequeued.is_some()); assert_eq!(dequeued.unwrap().id, job_id); @@ -3251,17 +3322,24 @@ mod tests { .unwrap(); queue.pause_queue("paused", Some("test")).await.unwrap(); - assert!(queue.dequeue("paused").await.unwrap().is_none()); + assert!(queue.dequeue_one("paused").await.unwrap().is_none()); assert!( queue - .dequeue_with_priority_weights("paused", &PriorityWeights::new()) + .dequeue( + "paused", + &DequeueOptions::new().with_priority_weights(PriorityWeights::new()) + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .is_none() ); queue.resume_queue("paused", None).await.unwrap(); - assert_eq!(queue.dequeue("paused").await.unwrap().unwrap().id, job_id); + assert_eq!( + queue.dequeue_one("paused").await.unwrap().unwrap().id, + job_id + ); } #[tokio::test] @@ -3280,7 +3358,7 @@ mod tests { let _normal_id = queue.enqueue(normal_job).await.unwrap(); // Dequeue should get the high priority job first - let dequeued = queue.dequeue("test_queue").await.unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap(); assert_eq!(dequeued.unwrap().id, high_id); } @@ -3295,14 +3373,14 @@ mod tests { let job_id = queue.enqueue(job).await.unwrap(); // Should not be able to dequeue immediately - let dequeued = queue.dequeue("test_queue").await.unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap(); assert!(dequeued.is_none()); // Advance time clock.advance(chrono::Duration::hours(2)); // Now should be able to dequeue - let dequeued = queue.dequeue("test_queue").await.unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap(); assert_eq!(dequeued.unwrap().id, job_id); } @@ -3313,7 +3391,7 @@ mod tests { // Enqueue and dequeue a job let job = Job::new("test_queue".to_string(), json!({"test": true})); let job_id = queue.enqueue(job).await.unwrap(); - let _dequeued = queue.dequeue("test_queue").await.unwrap(); + let _dequeued = queue.dequeue_one("test_queue").await.unwrap(); // Complete the job queue.complete_job(job_id).await.unwrap(); @@ -3333,7 +3411,7 @@ mod tests { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue and fail the job: a terminal failure, not retried automatically. - let dequeued = queue.dequeue("test_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap().unwrap(); assert_eq!(dequeued.attempts, 1); queue.fail_job(job_id, "Test error").await.unwrap(); @@ -3375,7 +3453,7 @@ mod tests { // Process all jobs for _ in 0..3 { - if let Some(job) = queue.dequeue("batch_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("batch_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } } @@ -3412,24 +3490,24 @@ mod tests { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Only job1 should be available initially - let dequeued = queue.dequeue("workflow_queue").await.unwrap(); + let dequeued = queue.dequeue_one("workflow_queue").await.unwrap(); assert_eq!(dequeued.unwrap().id, job1_id); // Job2 and job3 should not be available - assert!(queue.dequeue("workflow_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("workflow_queue").await.unwrap().is_none()); // Complete job1 queue.complete_job(job1_id).await.unwrap(); // Now job2 should be available - let dequeued = queue.dequeue("workflow_queue").await.unwrap(); + let dequeued = queue.dequeue_one("workflow_queue").await.unwrap(); assert_eq!(dequeued.unwrap().id, job2_id); // Complete job2 queue.complete_job(job2_id).await.unwrap(); // Now job3 should be available - let dequeued = queue.dequeue("workflow_queue").await.unwrap(); + let dequeued = queue.dequeue_one("workflow_queue").await.unwrap(); assert_eq!(dequeued.unwrap().id, job3_id); // Complete job3 @@ -3467,7 +3545,7 @@ mod tests { clock.advance(chrono::Duration::hours(1)); // Now the job should be available for dequeue - let run = queue.dequeue("cron_queue").await.unwrap().unwrap(); + let run = queue.dequeue_one("cron_queue").await.unwrap().unwrap(); let recorded = queue .finish_job_run(&run, crate::queue::JobOutcome::Completed) .await @@ -3548,7 +3626,7 @@ mod tests { .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(); + queue.dequeue_one("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); @@ -3587,13 +3665,13 @@ mod tests { // Process some jobs for _ in 0..2 { - if let Some(job) = queue.dequeue("stats_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("stats_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } } // One job runs out of attempts and dies, as a worker would record it. - if let Some(job) = queue.dequeue("stats_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("stats_queue").await.unwrap() { queue.mark_job_dead(job.id, "Test failure").await.unwrap(); } @@ -3627,8 +3705,9 @@ mod tests { let mut runs = HashMap::new(); for _ in 0..3 { let run = queue - .dequeue_leased("stale", None, lease) + .dequeue("stale", &DequeueOptions::new().with_lease_duration(lease)) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); runs.insert(run.id, run); @@ -3683,8 +3762,9 @@ mod tests { .unwrap(); let first = queue - .dequeue_leased("rerun", None, lease) + .dequeue("rerun", &DequeueOptions::new().with_lease_duration(lease)) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); clock.advance(chrono::Duration::seconds(60)); @@ -3695,8 +3775,9 @@ mod tests { assert_eq!(recovery.requeued, vec![id]); let second = queue - .dequeue_leased("rerun", None, lease) + .dequeue("rerun", &DequeueOptions::new().with_lease_duration(lease)) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); assert_eq!(second.attempts, 2); @@ -3726,8 +3807,9 @@ mod tests { .await .unwrap(); let claimed = queue - .dequeue_leased("held", None, lease) + .dequeue("held", &DequeueOptions::new().with_lease_duration(lease)) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); clock.advance(chrono::Duration::seconds(20)); @@ -3770,8 +3852,12 @@ mod tests { .await .unwrap(); let run = queue - .dequeue_leased("forever", None, std::time::Duration::ZERO) + .dequeue( + "forever", + &DequeueOptions::new().with_lease_duration(std::time::Duration::ZERO), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); queue.clock().advance(chrono::Duration::days(365)); @@ -3812,7 +3898,7 @@ mod tests { ) .await .unwrap(); - let run = queue.dequeue("policy").await.unwrap().unwrap(); + let run = queue.dequeue_one("policy").await.unwrap().unwrap(); let failed_id = run.id; if timed_out { queue @@ -3859,7 +3945,7 @@ mod tests { ) .await .unwrap(); - let run = queue.dequeue("finish_policy").await.unwrap().unwrap(); + let run = queue.dequeue_one("finish_policy").await.unwrap().unwrap(); assert_eq!(run.id, a_id); let recorded = queue .finish_job_run( @@ -3921,7 +4007,7 @@ mod tests { assert_eq!(stored.payload, json!({"ssn": "[ENCRYPTED]", "amount": 5})); assert!(stored.encrypted_payload.is_some()); - let dequeued = queue.dequeue("q").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("q").await.unwrap().unwrap(); assert_eq!( dequeued.payload, stored.payload, "dequeue returns the stored form" @@ -4041,7 +4127,7 @@ mod tests { .enqueue(Job::new("q".into(), json!({"secret": 1})).with_encryption(config())) .await .unwrap(); - queue.dequeue("q").await.unwrap(); + queue.dequeue_one("q").await.unwrap(); queue.complete_job(id).await.unwrap(); queue.clock().advance(chrono::Duration::seconds(10)); let stats = queue @@ -4159,10 +4245,10 @@ mod tests { .await .unwrap(); - let run = queue.dequeue("deps").await.unwrap().unwrap(); + let run = queue.dequeue_one("deps").await.unwrap().unwrap(); assert_eq!(run.id, parent); assert!( - queue.dequeue("deps").await.unwrap().is_none(), + queue.dequeue_one("deps").await.unwrap().is_none(), "a job ran before its dependency finished" ); @@ -4172,7 +4258,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!(recorded.unblocked, vec![child]); - let run = queue.dequeue("deps").await.unwrap().unwrap(); + let run = queue.dequeue_one("deps").await.unwrap().unwrap(); assert_eq!(run.id, child); assert_eq!(run.dependency_status, DependencyStatus::Satisfied); @@ -4181,7 +4267,7 @@ mod tests { .enqueue(Job::new("deps".to_string(), json!({"n": 3})).depends_on(&parent)) .await .unwrap(); - assert_eq!(queue.dequeue("deps").await.unwrap().unwrap().id, late); + assert_eq!(queue.dequeue_one("deps").await.unwrap().unwrap().id, late); // Enqueued after its dependency failed: failed at once. let failed = queue @@ -4207,7 +4293,7 @@ mod tests { .enqueue(Job::new("retry_err".to_string(), json!({}))) .await .unwrap(); - let run = queue.dequeue("retry_err").await.unwrap().unwrap(); + let run = queue.dequeue_one("retry_err").await.unwrap().unwrap(); let retry_at = Utc::now() + chrono::Duration::seconds(30); let recorded = queue .finish_job_run( @@ -4242,7 +4328,7 @@ mod tests { .enqueue(Job::new("retry_clock".to_string(), json!({}))) .await .unwrap(); - let run = queue.dequeue("retry_clock").await.unwrap().unwrap(); + let run = queue.dequeue_one("retry_clock").await.unwrap().unwrap(); queue.clock().advance(chrono::Duration::hours(2)); let mock_now = queue.clock().now(); queue @@ -4261,9 +4347,9 @@ mod tests { let after = (job.scheduled_at - mock_now).num_seconds(); assert!((28..=30).contains(&after), "due {after}s after mock now"); // Not yet due on the mock clock, due once it passes. - assert!(queue.dequeue("retry_clock").await.unwrap().is_none()); + assert!(queue.dequeue_one("retry_clock").await.unwrap().is_none()); queue.clock().advance(chrono::Duration::seconds(31)); - assert!(queue.dequeue("retry_clock").await.unwrap().is_some()); + assert!(queue.dequeue_one("retry_clock").await.unwrap().is_some()); } /// Unknown ids and queues fail (or succeed) as on the database backends. @@ -4304,7 +4390,7 @@ mod tests { let workflow = JobGroup::new("unblock").add_job(first).then(second); queue.enqueue_workflow(workflow).await.unwrap(); - let run = queue.dequeue("wf_unblock").await.unwrap().unwrap(); + let run = queue.dequeue_one("wf_unblock").await.unwrap().unwrap(); assert_eq!(run.id, first_id); let recorded = queue .finish_job_run(&run, JobOutcome::Completed) @@ -4313,7 +4399,7 @@ mod tests { .unwrap(); assert_eq!(recorded.unblocked, vec![second_id]); assert_eq!( - queue.dequeue("wf_unblock").await.unwrap().unwrap().id, + queue.dequeue_one("wf_unblock").await.unwrap().unwrap().id, second_id ); } @@ -4338,8 +4424,12 @@ mod tests { clock.advance(chrono::Duration::hours(1)); let lease = std::time::Duration::from_secs(30); let run = queue - .dequeue_leased("stale_cron", None, lease) + .dequeue( + "stale_cron", + &DequeueOptions::new().with_lease_duration(lease), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .unwrap(); assert_eq!(run.id, id); @@ -4390,7 +4480,7 @@ mod tests { .enqueue(Job::new("dead_q".to_string(), json!({"n": 1}))) .await .unwrap(); - queue.dequeue("dead_q").await.unwrap().unwrap(); + queue.dequeue_one("dead_q").await.unwrap().unwrap(); queue.mark_job_timed_out(timed_out, "slow").await.unwrap(); let dead = queue .enqueue(Job::new("dead_q".to_string(), json!({"n": 2}))) @@ -4451,8 +4541,12 @@ mod tests { .with_weight(JobPriority::High, 0) .with_weight(JobPriority::Critical, 0); let job = queue - .dequeue_with_priority_weights("zero_w", &weights) + .dequeue( + "zero_w", + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap(); assert_eq!(job.map(|job| job.id), Some(id)); } @@ -4467,8 +4561,12 @@ mod tests { .unwrap(); let weights = PriorityWeights::new().with_weight(JobPriority::Normal, u32::MAX); let job = queue - .dequeue_with_priority_weights("huge_w", &weights) + .dequeue( + "huge_w", + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap(); assert_eq!(job.map(|job| job.id), Some(id)); } @@ -4555,7 +4653,11 @@ mod tests { let restored = queue.restore_archived_job(id).await.unwrap(); assert_eq!(restored.scheduled_at, clock.now()); assert_eq!( - queue.dequeue("restore_clock").await.unwrap().map(|j| j.id), + queue + .dequeue_one("restore_clock") + .await + .unwrap() + .map(|j| j.id), Some(id) ); } diff --git a/src/worker.rs b/src/worker.rs index b13dc42..bbd3844 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -11,7 +11,7 @@ use crate::{ error::HammerworkError, job::Job, priority::PriorityWeights, - queue::{DatabaseQueue, JobOutcome, JobQueue, RecordedOutcome}, + queue::{DatabaseQueue, DequeueOptions, JobOutcome, JobQueue, RecordedOutcome}, rate_limit::{RateLimit, RateLimiter, ThrottleConfig}, retry::RetryStrategy, stats::{JobEvent, JobEventType, StatisticsCollector}, @@ -88,9 +88,8 @@ pub const MIN_POLL_INTERVAL: Duration = Duration::from_millis(10); /// Floor on the heartbeat interval derived from the lease duration. const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(100); -/// Default number of jobs a worker in batch mode claims per poll: one, so -/// `with_batch_processing_enabled(true)` alone keeps claiming one job at a time (as before -/// 2.1) and only adds batch statistics. Set a larger size with [`Worker::with_batch_size`]. +/// The batch size a worker reports ([`Worker::batch_size`]) until +/// [`Worker::with_batch_size`] enables batch mode: one job per poll. pub const DEFAULT_BATCH_SIZE: usize = 1; /// Default number of claimed jobs a worker in batch mode runs at once @@ -176,7 +175,7 @@ fn batch_counts_as_successful(result: &crate::batch::BatchResult) -> bool { } /// How many attempts a job gets: its own `max_attempts`, lowered by the worker's cap -/// (`Worker::with_max_retries`) when one is set. +/// (`Worker::with_attempt_cap`) when one is set. fn effective_attempt_limit(job_max_attempts: i32, worker_cap: Option) -> i32 { match worker_cap { Some(cap) => job_max_attempts.min(cap), @@ -507,7 +506,7 @@ pub enum JobHandlerType { /// /// let worker = Worker::new(queue, "email_queue".to_string(), handler) /// .with_poll_interval(std::time::Duration::from_millis(500)) -/// .with_max_retries(5); +/// .with_attempt_cap(5); /// /// // Start processing jobs /// let mut pool = hammerwork::WorkerPool::new(); @@ -557,7 +556,7 @@ pub struct Worker { /// How often to poll for new jobs poll_interval: Duration, /// Maximum number of retry attempts for failed jobs - max_retries: Option, + attempt_cap: Option, /// Delay between retry attempts retry_delay: Duration, /// Default retry strategy for failed jobs (overrides retry_delay if specified) @@ -618,7 +617,7 @@ where queue_name: self.queue_name.clone(), handler: self.handler.clone(), poll_interval: self.poll_interval, - max_retries: self.max_retries, + attempt_cap: self.attempt_cap, retry_delay: self.retry_delay, default_retry_strategy: self.default_retry_strategy.clone(), default_timeout: self.default_timeout, @@ -659,7 +658,7 @@ where /// - 1 second polling interval /// - no cap on attempts: each job runs up to its own /// [`max_attempts`](crate::Job::with_max_attempts) (3 unless set); see - /// [`with_max_retries`](Self::with_max_retries) + /// [`with_attempt_cap`](Self::with_attempt_cap) /// - 30 second retry delay /// - a [lease](Self::with_lease_duration) of [`DEFAULT_LEASE_DURATION`] (5 minutes) /// - No timeout, rate limiting, or priority configuration @@ -709,7 +708,7 @@ where queue_name, handler: JobHandlerType::Legacy(handler), poll_interval: Duration::from_secs(1), - max_retries: None, + attempt_cap: None, retry_delay: Duration::from_secs(30), default_retry_strategy: None, default_timeout: None, @@ -788,7 +787,7 @@ where queue_name, handler: JobHandlerType::WithResult(handler), poll_interval: Duration::from_secs(1), - max_retries: None, + attempt_cap: None, retry_delay: Duration::from_secs(30), default_retry_strategy: None, default_timeout: None, @@ -899,16 +898,13 @@ where /// A job's own [`max_attempts`](crate::Job::with_max_attempts) is the source of /// truth: a failing (or timing-out) job runs up to `max_attempts` times and then /// becomes `Dead` (or `TimedOut`). This setting only lowers that limit: the - /// effective limit is `min(job.max_attempts, max_retries)`. By default there is no - /// cap. + /// effective limit is `min(job.max_attempts, cap)`. By default there is no cap. /// - /// Previously this value replaced the job's `max_attempts` (default 3), so jobs - /// with `with_max_attempts(5)` stopped after 3 runs in a non-retried `Failed` - /// state, and `with_max_attempts(1)` still ran 3 times. + /// Before 3.0 this was `with_max_retries`. /// /// # Arguments /// - /// * `max_retries` - Maximum number of attempts per job on this worker + /// * `cap` - Maximum number of attempts per job on this worker /// /// # Examples /// @@ -925,12 +921,12 @@ where /// // job itself allows more attempts. To give jobs *more* attempts, raise their own /// // limit with `Job::with_max_attempts`; this setting can only lower it. /// let expensive_worker = Worker::new(queue, "expensive".to_string(), handler) - /// .with_max_retries(2); + /// .with_attempt_cap(2); /// # Ok(()) /// # } /// ``` - pub fn with_max_retries(mut self, max_retries: i32) -> Self { - self.max_retries = Some(max_retries); + pub fn with_attempt_cap(mut self, cap: i32) -> Self { + self.attempt_cap = Some(cap); self } @@ -1073,8 +1069,8 @@ where /// Set the lease the worker holds on a running job. /// /// The lease is taken in the same statement that claims the job - /// ([`DatabaseQueue::dequeue_leased`]). While the handler runs, the worker records a - /// heartbeat and extends the lease every third of this duration (via + /// ([`DequeueOptions::lease_duration`]). While the handler runs, the worker records + /// a heartbeat and extends the lease every third of this duration (via /// [`DatabaseQueue::heartbeat_job`]). If the worker process dies, the lease stops /// being renewed and [`DatabaseQueue::requeue_stale_jobs`] reclaims the job once it /// expires; a reaper never reclaims a job whose lease is still valid, whatever its @@ -1117,13 +1113,23 @@ where /// Apply a [`WorkerConfig`](crate::config::WorkerConfig). /// /// Sets the poll interval, default job timeout, priority weights and default retry - /// strategy. `pool_size` and the autoscaling settings apply to a [`WorkerPool`]; see - /// [`WorkerPool::from_config`]. + /// strategy, and the batch size ([`with_batch_size`](Self::with_batch_size)) and + /// batch concurrency ([`with_batch_concurrency`](Self::with_batch_concurrency)) when + /// the configuration sets them. `pool_size` and the autoscaling settings apply to a + /// [`WorkerPool`]; see [`WorkerPool::from_config`]. pub fn with_config(self, config: &crate::config::WorkerConfig) -> Self { - self.with_poll_interval(config.polling_interval) + let mut worker = self + .with_poll_interval(config.polling_interval) .with_default_timeout(config.job_timeout) .with_priority_weights(config.priority_weights.clone()) - .with_default_retry_strategy(config.retry_strategy.clone()) + .with_default_retry_strategy(config.retry_strategy.clone()); + if let Some(size) = config.batch_size { + worker = worker.with_batch_size(size); + } + if let Some(concurrency) = config.batch_concurrency { + worker = worker.with_batch_concurrency(concurrency); + } + worker } /// Apply the worker-related sections of a [`HammerworkConfig`](crate::HammerworkConfig). @@ -1274,14 +1280,21 @@ where self } - /// Enable batch processing: claim jobs in batches, and track statistics of jobs that - /// belong to a [`JobBatch`](crate::batch::JobBatch) ([`get_batch_stats`](Self::get_batch_stats)). + /// Enable batch mode: claim up to `size` jobs per poll in one round trip + /// ([`DatabaseQueue::dequeue`]), and track statistics of jobs that belong to a + /// [`JobBatch`](crate::batch::JobBatch) ([`get_batch_stats`](Self::get_batch_stats)). /// - /// In batch mode the worker claims up to [`batch_size`](Self::with_batch_size) jobs - /// per poll in one round trip ([`DatabaseQueue::dequeue_batch_leased`]) and runs them - /// [`batch_concurrency`](Self::with_batch_concurrency) at a time, one at a time by - /// default. Every claimed job goes through the same path as a single claim: its own - /// timeout, retries, hooks, events, spawning, result storage and statistics. + /// Without this (the default), the worker claims and runs one job at a time and + /// keeps no batch statistics. Values below 1 are raised to 1: `with_batch_size(1)` + /// keeps claiming one job at a time but adds batch statistics. The built-in backends + /// claim at most [`MAX_DEQUEUE_BATCH_SIZE`](crate::queue::MAX_DEQUEUE_BATCH_SIZE) + /// jobs at once. [`WorkerConfig::batch_size`](crate::config::WorkerConfig::batch_size) + /// sets it from configuration. + /// + /// The claimed jobs run [`batch_concurrency`](Self::with_batch_concurrency) at a + /// time, one at a time by default. Every claimed job goes through the same path as a + /// single claim: its own timeout, retries, hooks, events, spawning, result storage + /// and statistics. /// /// - **Leases.** Each claimed job holds its own lease from the moment it is claimed. /// While a job waits for its turn, the worker renews its lease with heartbeats @@ -1319,38 +1332,7 @@ where /// /// Batch claims cut the database round trips per job; holding jobs a worker has not /// started yet keeps them from idle workers, so keep batches small relative to the - /// queue when jobs are slow. With batch processing off (the default), the worker - /// claims and runs one job at a time. - /// - /// # Examples - /// - #[cfg_attr(feature = "postgres", doc = "```rust,no_run")] - #[cfg_attr(not(feature = "postgres"), doc = "```rust,ignore")] - /// use hammerwork::Worker; - /// # use std::sync::Arc; - /// # async fn example() -> Result<(), Box> { - /// # let pool = sqlx::PgPool::connect("postgresql://localhost/test").await?; - /// # let queue = Arc::new(hammerwork::JobQueue::new(pool)); - /// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) })); - /// - /// // Keep statistics for job batches; jobs are still claimed one at a time. Use - /// // `with_batch_size` to claim several jobs per poll. - /// let worker = Worker::new(queue, "batch_queue".to_string(), handler) - /// .with_batch_processing_enabled(true); - /// # Ok(()) - /// # } - /// ``` - pub fn with_batch_processing_enabled(mut self, enabled: bool) -> Self { - self.batch_processing_enabled = enabled; - self - } - - /// Claim up to `size` jobs per poll, and enable batch processing (see - /// [`with_batch_processing_enabled`](Self::with_batch_processing_enabled)). - /// - /// Defaults to [`DEFAULT_BATCH_SIZE`] (1). Values below 1 are raised to 1, and the - /// built-in backends claim at most - /// [`MAX_DEQUEUE_BATCH_SIZE`](crate::queue::MAX_DEQUEUE_BATCH_SIZE) jobs at once. + /// queue when jobs are slow. /// /// # Examples /// @@ -1388,8 +1370,7 @@ where self } - /// Whether batch processing is enabled (see - /// [`with_batch_processing_enabled`](Self::with_batch_processing_enabled)). + /// Whether batch mode is enabled (see [`with_batch_size`](Self::with_batch_size)). pub fn is_batch_processing_enabled(&self) -> bool { self.batch_processing_enabled } @@ -1882,13 +1863,20 @@ where return Ok(None); } - self.queue - .dequeue_leased( - &self.queue_name, - self.priority_weights.as_ref(), - self.lease_duration, - ) - .await + Ok(self + .queue + .dequeue(&self.queue_name, &self.dequeue_options(1)) + .await? + .into_iter() + .next()) + } + + /// The options of this worker's claims: its priority weights and lease, for up to + /// `max_jobs` jobs. + fn dequeue_options(&self, max_jobs: usize) -> DequeueOptions { + let mut options = DequeueOptions::batch(max_jobs).with_lease_duration(self.lease_duration); + options.priority_weights = self.priority_weights.clone(); + options } /// Whether this worker's queue is paused, so the dequeue can be skipped. A failed @@ -1966,12 +1954,7 @@ where Ok(Vec::new()) } else { self.queue - .dequeue_batch_leased( - &self.queue_name, - self.priority_weights.as_ref(), - self.lease_duration, - capacity, - ) + .dequeue(&self.queue_name, &self.dequeue_options(capacity)) .await }; if let Some(rate_limiter) = &self.rate_limiter { @@ -2408,9 +2391,9 @@ where } /// The number of attempts `job` gets on this worker: its own `max_attempts`, - /// lowered by [`with_max_retries`](Self::with_max_retries) when that is set. + /// lowered by [`with_attempt_cap`](Self::with_attempt_cap) when that is set. fn attempt_limit(&self, job: &Job) -> i32 { - effective_attempt_limit(job.max_attempts, self.max_retries) + effective_attempt_limit(job.max_attempts, self.attempt_cap) } /// When a failed or timed-out run of `job` should be retried. @@ -3897,8 +3880,8 @@ mod tests { assert_eq!(worker.batch_size(), DEFAULT_BATCH_SIZE); assert_eq!(worker.batch_concurrency(), DEFAULT_BATCH_CONCURRENCY); - // The old builder alone enables batch mode with the default size of one job. - let enabled = lazy_worker("batch").with_batch_processing_enabled(true); + // A size of one enables batch mode (statistics) while claiming one job a poll. + let enabled = lazy_worker("batch").with_batch_size(1); assert!(enabled.is_batch_processing_enabled()); assert_eq!(enabled.batch_size(), DEFAULT_BATCH_SIZE); @@ -3917,12 +3900,26 @@ mod tests { assert_eq!(clone.batch_size(), 25); assert_eq!(clone.batch_concurrency(), 5); assert!(clone.is_batch_processing_enabled()); - // Batch mode can still be switched off afterwards. - assert!( - !worker - .with_batch_processing_enabled(false) - .is_batch_processing_enabled() - ); + + // `WorkerConfig` sets batch mode only when it has a batch size. + let config = crate::config::WorkerConfig::default(); + let unbatched = lazy_worker("batch").with_config(&config); + assert!(!unbatched.is_batch_processing_enabled()); + assert_eq!(unbatched.batch_concurrency(), DEFAULT_BATCH_CONCURRENCY); + let config = crate::config::WorkerConfig { + batch_size: Some(40), + batch_concurrency: Some(4), + ..crate::config::WorkerConfig::default() + }; + let batched = lazy_worker("batch").with_config(&config); + assert!(batched.is_batch_processing_enabled()); + assert_eq!(batched.batch_size(), 40); + assert_eq!(batched.batch_concurrency(), 4); + // A configuration without batch settings leaves those set in code. + let kept = worker.with_config(&crate::config::WorkerConfig::default()); + assert!(kept.is_batch_processing_enabled()); + assert_eq!(kept.batch_size(), 25); + assert_eq!(kept.batch_concurrency(), 5); } #[tokio::test] diff --git a/tests/archive_workflow_regression_tests.rs b/tests/archive_workflow_regression_tests.rs index 206b404..3a58a0d 100644 --- a/tests/archive_workflow_regression_tests.rs +++ b/tests/archive_workflow_regression_tests.rs @@ -85,7 +85,7 @@ where { let deadline = std::time::Instant::now() + Duration::from_secs(10); loop { - if let Some(job) = queue.dequeue(queue_name).await.unwrap() { + if let Some(job) = queue.dequeue_one(queue_name).await.unwrap() { return job; } assert!( diff --git a/tests/batch_dequeue_tests.rs b/tests/batch_dequeue_tests.rs index 78c4b84..e1bb00d 100644 --- a/tests/batch_dequeue_tests.rs +++ b/tests/batch_dequeue_tests.rs @@ -1,4 +1,4 @@ -//! Batch claims (`DatabaseQueue::dequeue_batch_leased`) and batch-mode workers +//! Batch claims (`DatabaseQueue::dequeue` with `max_jobs` above one) and batch-mode workers //! (`Worker::with_batch_size`). //! //! The queue scenarios run against PostgreSQL, MySQL and `TestQueue`, so the in-memory @@ -12,6 +12,7 @@ mod test_utils; use chrono::Utc; +use hammerwork::queue::DequeueOptions; use hammerwork::{ Job, JobId, JobPriority, JobStatus, PriorityWeights, cron::CronSchedule, queue::DatabaseQueue, workflow::JobGroup, @@ -58,13 +59,16 @@ where assert!( queue - .dequeue_batch(&queue_name, 0) + .dequeue(&queue_name, &DequeueOptions::batch(0)) .await .unwrap() .is_empty() ); - let first = queue.dequeue_batch(&queue_name, 4).await.unwrap(); + let first = queue + .dequeue(&queue_name, &DequeueOptions::batch(4)) + .await + .unwrap(); let order: Vec<(JobPriority, i64)> = first.iter().map(|job| ids[&job.id]).collect(); assert_eq!( order, @@ -85,12 +89,15 @@ where } // The rest, then nothing. - let rest = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let rest = queue + .dequeue(&queue_name, &DequeueOptions::batch(10)) + .await + .unwrap(); let order: Vec<(JobPriority, i64)> = rest.iter().map(|job| ids[&job.id]).collect(); assert_eq!(order, [(JobPriority::Normal, 50), (JobPriority::Low, 90)]); assert!( queue - .dequeue_batch(&queue_name, 10) + .dequeue(&queue_name, &DequeueOptions::batch(10)) .await .unwrap() .is_empty() @@ -105,11 +112,11 @@ where .unwrap(); } let strict = queue - .dequeue_batch_leased( + .dequeue( &strict_queue, - Some(&PriorityWeights::strict()), - Duration::from_secs(60), - 3, + &DequeueOptions::batch(3) + .with_lease_duration(Duration::from_secs(60)) + .with_priority_weights(PriorityWeights::strict()), ) .await .unwrap(); @@ -145,7 +152,12 @@ where let lease = Duration::from_secs(60); let first = queue - .dequeue_batch_leased(&queue_name, Some(&weights), lease, 3) + .dequeue( + &queue_name, + &DequeueOptions::batch(3) + .with_lease_duration(lease) + .with_priority_weights(weights.clone()), + ) .await .unwrap(); assert_eq!(first.len(), 3); @@ -163,7 +175,12 @@ where // Seven are left (2 of the picked level, 5 of the other): a batch of 7 takes all. let rest = queue - .dequeue_batch_leased(&queue_name, Some(&weights), lease, 10) + .dequeue( + &queue_name, + &DequeueOptions::batch(10) + .with_lease_duration(lease) + .with_priority_weights(weights.clone()), + ) .await .unwrap(); assert_eq!(rest.len(), 7); @@ -207,14 +224,17 @@ where queue.pause_queue(&queue_name, Some("test")).await.unwrap(); assert!( queue - .dequeue_batch(&queue_name, 10) + .dequeue(&queue_name, &DequeueOptions::batch(10)) .await .unwrap() .is_empty() ); queue.resume_queue(&queue_name, Some("test")).await.unwrap(); - let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let claimed = queue + .dequeue(&queue_name, &DequeueOptions::batch(10)) + .await + .unwrap(); let ids: HashSet = claimed.iter().map(|job| job.id).collect(); assert_eq!(ids, HashSet::from([parent_id, plain])); @@ -225,7 +245,10 @@ where .await .unwrap() .expect("the parent run is recorded"); - let next = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let next = queue + .dequeue(&queue_name, &DequeueOptions::batch(10)) + .await + .unwrap(); let ids: Vec = next.iter().map(|job| job.id).collect(); assert_eq!(ids, [child_id]); assert_eq!( @@ -251,7 +274,10 @@ where .unwrap(); } let claimed = queue - .dequeue_batch_leased(&queue_name, None, Duration::from_secs(600), 3) + .dequeue( + &queue_name, + &DequeueOptions::batch(3).with_lease_duration(Duration::from_secs(600)), + ) .await .unwrap(); assert_eq!(claimed.len(), 3); @@ -283,7 +309,10 @@ where .await .unwrap(); } - let claimed = queue.dequeue_batch(&queue_name, 2).await.unwrap(); + let claimed = queue + .dequeue(&queue_name, &DequeueOptions::batch(2)) + .await + .unwrap(); assert_eq!(claimed.len(), 2); let released = &claimed[0]; @@ -303,7 +332,10 @@ where // It keeps its place and is claimed again. tokio::time::sleep(Duration::from_millis(5)).await; - let again = queue.dequeue_batch(&queue_name, 5).await.unwrap(); + let again = queue + .dequeue(&queue_name, &DequeueOptions::batch(5)) + .await + .unwrap(); let ids: Vec = again.iter().map(|job| job.id).collect(); assert_eq!(ids, [released.id]); assert_eq!(again[0].attempts, 1); @@ -355,22 +387,29 @@ where while empty_polls < 3 { let batch = match task % 4 { 0 => queue - .dequeue_leased(&queue_name, None, Duration::from_secs(600)) + .dequeue( + &queue_name, + &DequeueOptions::new().with_lease_duration(Duration::from_secs(600)), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .into_iter() .collect(), 1 => queue - .dequeue_batch_leased( + .dequeue( &queue_name, - Some(&weights), - Duration::from_secs(600), - 5 + task, + &DequeueOptions::batch(5 + task) + .with_lease_duration(Duration::from_secs(600)) + .with_priority_weights(weights.clone()), ) .await .unwrap(), _ => queue - .dequeue_batch_leased(&queue_name, None, Duration::from_secs(600), 7) + .dequeue( + &queue_name, + &DequeueOptions::batch(7).with_lease_duration(Duration::from_secs(600)), + ) .await .unwrap(), }; @@ -688,7 +727,10 @@ mod worker { } // The released jobs run normally afterwards. - let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let claimed = queue + .dequeue(&queue_name, &DequeueOptions::batch(10)) + .await + .unwrap(); assert_eq!(claimed.len(), 4); } @@ -1103,7 +1145,7 @@ mod worker { enqueue_jobs(&queue, &single_queue, JOBS).await; let began = Instant::now(); let mut claimed = 0; - while queue.dequeue(&single_queue).await.unwrap().is_some() { + while queue.dequeue_one(&single_queue).await.unwrap().is_some() { claimed += 1; } let single = claimed as f64 / began.elapsed().as_secs_f64(); @@ -1115,7 +1157,10 @@ mod worker { let began = Instant::now(); let mut claimed = 0; loop { - let batch = queue.dequeue_batch(&batch_queue, size).await.unwrap(); + let batch = queue + .dequeue(&batch_queue, &DequeueOptions::batch(size)) + .await + .unwrap(); if batch.is_empty() { break; } diff --git a/tests/dequeue_concurrency_tests.rs b/tests/dequeue_concurrency_tests.rs index e557a80..c5fcdbc 100644 --- a/tests/dequeue_concurrency_tests.rs +++ b/tests/dequeue_concurrency_tests.rs @@ -7,6 +7,7 @@ mod test_utils; +use hammerwork::queue::DequeueOptions; use hammerwork::{ Job, JobQueue, JobStatus, PriorityWeights, ResultStorage, priority::JobPriority, queue::DatabaseQueue, @@ -44,8 +45,12 @@ where let weights = PriorityWeights::new(); let mut claimed = Vec::new(); while let Some(job) = queue - .dequeue_with_priority_weights(&queue_name, &weights) + .dequeue( + &queue_name, + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() { assert_eq!(job.status, JobStatus::Running); @@ -83,8 +88,12 @@ where let job_id = queue.enqueue(job).await.unwrap(); let dequeued = queue - .dequeue_with_priority_weights(&queue_name, &PriorityWeights::new()) + .dequeue( + &queue_name, + &DequeueOptions::new().with_priority_weights(PriorityWeights::new()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .expect("job should be dequeued"); @@ -110,13 +119,17 @@ where let child_id = queue.enqueue(child).await.unwrap(); assert!( - queue.dequeue(&child_queue).await.unwrap().is_none(), + queue.dequeue_one(&child_queue).await.unwrap().is_none(), "dequeue returned a job whose dependency has not completed" ); assert!( queue - .dequeue_with_priority_weights(&child_queue, &PriorityWeights::new()) + .dequeue( + &child_queue, + &DequeueOptions::new().with_priority_weights(PriorityWeights::new()) + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .is_none(), "weighted dequeue returned a job whose dependency has not completed" @@ -182,7 +195,7 @@ mod mysql_tests { } let job = queue - .dequeue(&queue_name) + .dequeue_one(&queue_name) .await .expect("dequeue must recover the abandoned transaction") .expect("the job must be claimable once the abandoned locks are released"); diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 9fc11a8..e06c160 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -23,7 +23,7 @@ mod postgres_tests { queue.enqueue(job).await.unwrap(); // Dequeue the job - let dequeued_job = queue.dequeue(&queue_name).await.unwrap(); + let dequeued_job = queue.dequeue_one(&queue_name).await.unwrap(); assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); assert_eq!(dequeued_job.id, job_id); @@ -55,7 +55,7 @@ mod postgres_tests { queue.enqueue(job).await.unwrap(); // Dequeue and fail the job - let dequeued_job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let dequeued_job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); queue .fail_job(dequeued_job.id, "Intentional failure") .await @@ -87,12 +87,12 @@ mod postgres_tests { queue.enqueue(job).await.unwrap(); // Try to dequeue immediately - should get nothing - let immediate_dequeue = queue.dequeue(&queue_name).await.unwrap(); + let immediate_dequeue = queue.dequeue_one(&queue_name).await.unwrap(); assert!(immediate_dequeue.is_none()); // Wait for the delay and try again sleep(Duration::from_secs(2)).await; - let delayed_dequeue = queue.dequeue(&queue_name).await.unwrap(); + let delayed_dequeue = queue.dequeue_one(&queue_name).await.unwrap(); assert!(delayed_dequeue.is_some()); let dequeued_job = delayed_dequeue.unwrap(); @@ -124,7 +124,7 @@ mod mysql_tests { queue.enqueue(job).await.unwrap(); // Dequeue the job - let dequeued_job = queue.dequeue(&queue_name).await.unwrap(); + let dequeued_job = queue.dequeue_one(&queue_name).await.unwrap(); assert!(dequeued_job.is_some()); let dequeued_job = dequeued_job.unwrap(); assert_eq!(dequeued_job.id, job_id); @@ -161,7 +161,7 @@ mod mysql_tests { for _ in 0..3 { let queue_clone = queue.clone(); let queue_name = queue_name.clone(); - let handle = tokio::spawn(async move { queue_clone.dequeue(&queue_name).await }); + let handle = tokio::spawn(async move { queue_clone.dequeue_one(&queue_name).await }); handles.push(handle); } diff --git a/tests/job_lifecycle_tests.rs b/tests/job_lifecycle_tests.rs index 6176586..ac2752d 100644 --- a/tests/job_lifecycle_tests.rs +++ b/tests/job_lifecycle_tests.rs @@ -106,7 +106,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({}))) .await .unwrap(); - queue.dequeue(&queue_name).await.unwrap().expect("job"); + queue.dequeue_one(&queue_name).await.unwrap().expect("job"); queue.mark_job_timed_out(id, "too slow").await.unwrap(); assert_invalid_transition(queue.complete_job(id).await, "complete TimedOut"); assert_invalid_transition(queue.fail_job(id, "x").await, "fail TimedOut"); @@ -182,7 +182,7 @@ where // and another worker runs the job to completion. queue.retry_job(id, Utc::now()).await.unwrap(); let rerun = queue - .dequeue(&queue_name) + .dequeue_one(&queue_name) .await .unwrap() .expect("requeued job"); @@ -225,7 +225,7 @@ where queue.delete_job(id).await.unwrap(); } -/// H3: the job's `max_attempts` is the retry limit; `with_max_retries` only caps it. +/// H3: the job's `max_attempts` is the retry limit; `with_attempt_cap` only caps it. async fn job_max_attempts_is_the_retry_limit(queue: Arc>) where DB: sqlx::Database + Send + Sync + 'static, @@ -242,7 +242,7 @@ where let runs = Arc::new(AtomicUsize::new(0)); let mut w = worker(&queue, &queue_name, failing_handler(Arc::clone(&runs))); if let Some(cap) = worker_cap { - w = w.with_max_retries(cap); + w = w.with_attempt_cap(cap); } let running = RunningWorker::start(w); let job = test_utils::wait_for_job(&queue, id, Duration::from_secs(15), |job| { @@ -661,7 +661,7 @@ where let queue = Arc::clone(&queue); let queue_name = queue_name.clone(); tokio::spawn(async move { - while let Some(job) = queue.dequeue(&queue_name).await.unwrap() { + while let Some(job) = queue.dequeue_one(&queue_name).await.unwrap() { queue.complete_job(job.id).await.unwrap(); } }) @@ -679,7 +679,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({ "probe": true }))) .await .unwrap(); - let dequeued = queue.dequeue(&queue_name).await.unwrap(); + let dequeued = queue.dequeue_one(&queue_name).await.unwrap(); assert_eq!(dequeued.map(|job| job.id), Some(probe)); ids.push(probe); tokio::time::timeout(Duration::from_secs(10), async { @@ -804,7 +804,7 @@ where .unwrap(); let job = queue.get_job(id).await.unwrap().unwrap(); assert_eq!(job.retry_strategy, Some(strategy.clone())); - let dequeued = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let dequeued = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(dequeued.retry_strategy, Some(strategy.clone())); queue.delete_job(id).await.unwrap(); @@ -855,7 +855,7 @@ where assert_eq!(stored.depends_on, vec![parent]); assert_eq!(stored.dependency_status, DependencyStatus::Waiting); // The unresolved dependency keeps it from running. - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); queue.delete_batch(batch_id).await.unwrap(); } diff --git a/tests/job_spawning_tests.rs b/tests/job_spawning_tests.rs index af07319..2526cfa 100644 --- a/tests/job_spawning_tests.rs +++ b/tests/job_spawning_tests.rs @@ -27,7 +27,7 @@ use tokio::sync::mpsc; /// Every job of `queue_name`, by claiming them all. async fn drain(queue: &Arc, queue_name: &str) -> Vec { let mut jobs = Vec::new(); - while let Some(job) = queue.dequeue(queue_name).await.unwrap() { + while let Some(job) = queue.dequeue_one(queue_name).await.unwrap() { jobs.push(job); } jobs @@ -239,7 +239,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({}))) .await .unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let run = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); let child = |i: u32| Job::new(child_queue.clone(), json!({ "i": i })).depends_on(&id); // A failing child rolls back the completion and the children before it. diff --git a/tests/jobrow_query_tests.rs b/tests/jobrow_query_tests.rs index e53e0c3..9ec6ff3 100644 --- a/tests/jobrow_query_tests.rs +++ b/tests/jobrow_query_tests.rs @@ -6,6 +6,8 @@ mod test_utils; +#[cfg(any(feature = "postgres", feature = "mysql"))] +use hammerwork::queue::DequeueOptions; #[cfg(any(feature = "postgres", feature = "mysql"))] use hammerwork::{Job, JobPriority, queue::DatabaseQueue, workflow::DependencyStatus}; #[cfg(any(feature = "postgres", feature = "mysql"))] @@ -69,7 +71,7 @@ mod jobrow_field_tests { queue.enqueue(job).await.unwrap(); // This should not panic with missing field errors - let dequeued = queue.dequeue(&unique_queue).await.unwrap(); + let dequeued = queue.dequeue_one(&unique_queue).await.unwrap(); assert!(dequeued.is_some()); let job = dequeued.unwrap(); @@ -96,8 +98,12 @@ mod jobrow_field_tests { // This should not panic with missing field errors let dequeued = queue - .dequeue_with_priority_weights(&unique_queue, &weights) + .dequeue( + &unique_queue, + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap(); assert!(dequeued.is_some()); @@ -148,7 +154,7 @@ mod jobrow_field_tests { let job = Job::new(unique_queue.clone(), json!({"test": "dequeue"})); queue.enqueue(job).await.unwrap(); - let dequeued = queue.dequeue(&unique_queue).await.unwrap(); + let dequeued = queue.dequeue_one(&unique_queue).await.unwrap(); assert!(dequeued.is_some()); let job = dequeued.unwrap(); @@ -170,8 +176,12 @@ mod jobrow_field_tests { queue.enqueue(job).await.unwrap(); let dequeued = queue - .dequeue_with_priority_weights(&unique_queue, &weights) + .dequeue( + &unique_queue, + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap(); assert!(dequeued.is_some()); diff --git a/tests/payload_encryption_tests.rs b/tests/payload_encryption_tests.rs index 7e48c65..f5aa6bb 100644 --- a/tests/payload_encryption_tests.rs +++ b/tests/payload_encryption_tests.rs @@ -9,6 +9,7 @@ mod test_utils; use chrono::Utc; +use hammerwork::queue::DequeueOptions; use hammerwork::{ HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, WorkerPool, archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason}, @@ -1385,7 +1386,7 @@ where let mut children = Vec::new(); let deadline = Instant::now() + Duration::from_secs(15); while children.len() < 2 && Instant::now() < deadline { - match queue.dequeue(&child_queue).await.unwrap() { + match queue.dequeue_one(&child_queue).await.unwrap() { Some(child) => children.push(child), None => tokio::time::sleep(Duration::from_millis(50)).await, } @@ -1419,7 +1420,10 @@ where payloads.push(payload); } - let claimed = queue.dequeue_batch(&queue_name, 10).await.unwrap(); + let claimed = queue + .dequeue(&queue_name, &DequeueOptions::batch(10)) + .await + .unwrap(); assert_eq!(claimed.len(), 3); let mut decrypted = Vec::new(); for job in claimed { diff --git a/tests/queue_api_tests.rs b/tests/queue_api_tests.rs index 4a2a27f..e9e903c 100644 --- a/tests/queue_api_tests.rs +++ b/tests/queue_api_tests.rs @@ -111,7 +111,11 @@ where queue.fail_job(failed, &error).await.unwrap(); // Complete one job through the normal path so it has timings. let job = loop { - let job = queue.dequeue(&queue_name).await.unwrap().expect("a job"); + let job = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("a job"); if job.id == done { break job; } @@ -266,7 +270,7 @@ where assert_eq!(job.next_run_at, None); assert_eq!(job.status, JobStatus::Pending); assert!( - queue.dequeue(&queue_name).await.unwrap().is_none(), + queue.dequeue_one(&queue_name).await.unwrap().is_none(), "a disabled recurring job ran" ); @@ -280,12 +284,16 @@ where "{job:?}" ); assert_eq!(job.next_run_at, Some(job.scheduled_at)); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); queue.delete_job(held).await.unwrap(); // A run in progress finishes; without `recurring` it is not rescheduled. let finished = queue.enqueue(due_cron_job()).await.unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("due job"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("due job"); assert_eq!(run.id, finished); queue.disable_recurring_job(finished).await.unwrap(); queue @@ -323,7 +331,11 @@ where assert!(queue.enable_recurring_job(plain).await.is_err()); // A plain job (no cron schedule) is not held. assert_eq!( - queue.dequeue(&queue_name).await.unwrap().map(|job| job.id), + queue + .dequeue_one(&queue_name) + .await + .unwrap() + .map(|job| job.id), Some(plain) ); queue.delete_job(plain).await.unwrap(); @@ -349,7 +361,11 @@ where let only_this_job = |jobs: Vec| jobs.iter().map(|j| j.id).collect::>() == [id]; // A successful run: the same job goes back to Pending for its next slot. - let run = queue.dequeue(&queue_name).await.unwrap().expect("due job"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("due job"); assert_eq!(run.id, id); let recorded = queue .finish_job_run(&run, JobOutcome::Completed) @@ -384,7 +400,11 @@ where )); // A failed run: also rescheduled in place, keeping the error until the next run. - let run = queue.dequeue(&queue_name).await.unwrap().expect("due job"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("due job"); assert_eq!(run.id, id); let recorded = queue .finish_job_run( @@ -543,7 +563,7 @@ where ); // Completing `a` (as a worker would) and resolving makes `b` ready. - let job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(job.id, a_id); queue.complete_job(a_id).await.unwrap(); queue.resolve_job_dependencies(a_id).await.unwrap(); diff --git a/tests/queue_followup_tests.rs b/tests/queue_followup_tests.rs index 877d332..ea88fa4 100644 --- a/tests/queue_followup_tests.rs +++ b/tests/queue_followup_tests.rs @@ -11,6 +11,7 @@ mod test_utils; use chrono::{DateTime, Duration as ChronoDuration, DurationRound, Utc}; +use hammerwork::queue::DequeueOptions; use hammerwork::{ CronSchedule, Job, JobId, JobOutcome, JobQueue, JobStatus, PriorityWeights, batch::JobBatch, @@ -108,7 +109,7 @@ where // The satisfied jobs are dequeued; nothing else is let mut dequeued = Vec::new(); - while let Some(job) = queue.dequeue(&queue_name).await.unwrap() { + while let Some(job) = queue.dequeue_one(&queue_name).await.unwrap() { dequeued.push(job.id); } dequeued.sort_unstable(); @@ -161,7 +162,11 @@ where let queue_name = test_utils::unique_queue("late_race"); for _ in 0..25 { let parent = queue.enqueue(job(&queue_name, "parent")).await.unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("parent"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("parent"); let child = job(&queue_name, "child").depends_on(&parent); let (finished, enqueued) = tokio::join!( queue.finish_job_run(&run, JobOutcome::Completed), @@ -190,11 +195,15 @@ where let id = queue.enqueue(job(&queue_name, "paused")).await.unwrap(); queue.pause_queue(&queue_name, Some("test")).await.unwrap(); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); assert!( queue - .dequeue_with_priority_weights(&queue_name, &PriorityWeights::new()) + .dequeue( + &queue_name, + &DequeueOptions::new().with_priority_weights(PriorityWeights::new()) + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .is_none() ); @@ -202,7 +211,10 @@ where queue.resume_queue(&queue_name, None).await.unwrap(); let other = test_utils::unique_queue("paused_other"); queue.pause_queue(&other, None).await.unwrap(); - assert_eq!(queue.dequeue(&queue_name).await.unwrap().unwrap().id, id); + assert_eq!( + queue.dequeue_one(&queue_name).await.unwrap().unwrap().id, + id + ); queue.resume_queue(&other, None).await.unwrap(); queue.delete_job(id).await.unwrap(); @@ -236,8 +248,12 @@ where let mut picked = Vec::new(); for _ in 0..3 { let job = queue - .dequeue_with_priority_weights(&queue_name, &weights) + .dequeue( + &queue_name, + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .expect("a job"); picked.push(job.priority); @@ -250,8 +266,12 @@ where // Every job is still handed out exactly once let mut remaining = 0; while queue - .dequeue_with_priority_weights(&queue_name, &weights) + .dequeue( + &queue_name, + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .is_some() { @@ -277,7 +297,7 @@ where let id = queue.enqueue(delayed).await.unwrap(); let run = queue - .dequeue(&queue_name) + .dequeue_one(&queue_name) .await .unwrap() .expect("due by the database clock"); @@ -302,7 +322,7 @@ where .await .unwrap() .expect("recorded"); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); let job = queue.get_job(id).await.unwrap().unwrap(); assert!(job.scheduled_at > Utc::now() + ChronoDuration::minutes(50)); @@ -336,7 +356,11 @@ where .enqueue_workflow(JobGroup::new("cancel").add_job(a).add_job(b)) .await .unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("a runs"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("a runs"); assert_eq!(run.id, a_id); queue.cancel_workflow(workflow_id).await.unwrap(); @@ -401,7 +425,7 @@ where let id = queue.enqueue(daily).await.unwrap(); // The late run is the catch-up run... - let run = queue.dequeue(&queue_name).await.unwrap().expect("due"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("due"); let recorded = queue .finish_job_run(&run, JobOutcome::Completed) .await @@ -415,7 +439,7 @@ where (job.scheduled_at, job.next_run_at), (tomorrow, Some(tomorrow)) ); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); queue.delete_job(id).await.unwrap(); } @@ -432,7 +456,7 @@ where .enqueue(job(&queue_name, "timed").with_priority(JobPriority::High)) .await .unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("job"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("job"); tokio::time::sleep(Duration::from_millis(30)).await; queue .finish_job_run(&run, JobOutcome::Completed) @@ -494,7 +518,11 @@ where .await .unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("parent"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("parent"); let recorded = queue .finish_job_run(&run, JobOutcome::Completed) .await @@ -703,7 +731,7 @@ mod mysql_tests { } let id = queue.enqueue(job(&queue_name, "on time")).await.unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("job"); + let run = queue.dequeue_one(&queue_name).await.unwrap().expect("job"); assert!(matches!( queue.retry_job(id, after_2038).await, Err(HammerworkError::InvalidJobPayload { .. }) @@ -749,14 +777,18 @@ mod mysql_tests { let delayed = queue.enqueue(delayed).await.unwrap(); let now = queue.enqueue(job(&queue_name, "now")).await.unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("due job"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("due job"); assert_eq!(run.id, now); let started_at = run.started_at.unwrap(); assert!( (started_at - Utc::now()).num_seconds().abs() < 60, "{started_at}" ); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); queue.pause_queue(&queue_name, None).await.unwrap(); let paused_at = queue diff --git a/tests/queue_regression_tests.rs b/tests/queue_regression_tests.rs index f063496..fb80d9d 100644 --- a/tests/queue_regression_tests.rs +++ b/tests/queue_regression_tests.rs @@ -98,7 +98,7 @@ async fn huge_result_settings_stay_readable(queue: &Q) { stored.result_config.max_size_bytes, Some(usize::try_from(i64::MAX).unwrap_or(usize::MAX)) ); - let claimed = queue.dequeue(&name).await.unwrap().unwrap(); + let claimed = queue.dequeue_one(&name).await.unwrap().unwrap(); assert_eq!(claimed.id, id); queue.delete_job(id).await.unwrap(); } @@ -195,10 +195,18 @@ where .unwrap(); // a completes, so b's dependencies are satisfied, then x fails the workflow. - let run_a = queue.dequeue(&format!("{name}_a")).await.unwrap().unwrap(); + let run_a = queue + .dequeue_one(&format!("{name}_a")) + .await + .unwrap() + .unwrap(); assert_eq!(run_a.id, a_id); queue.complete_job(a_id).await.unwrap(); - let run_x = queue.dequeue(&format!("{name}_x")).await.unwrap().unwrap(); + let run_x = queue + .dequeue_one(&format!("{name}_x")) + .await + .unwrap() + .unwrap(); assert_eq!(run_x.id, x_id); queue.fail_job(x_id, "boom").await.unwrap(); assert_eq!( @@ -211,7 +219,7 @@ where .await .unwrap(); let retried = queue - .dequeue(&format!("{name}_b")) + .dequeue_one(&format!("{name}_b")) .await .unwrap() .expect("a retried job whose dependencies completed is runnable"); @@ -294,21 +302,21 @@ async fn retry_reevaluates_dependencies(queue: &Q) { assert_eq!(waiting.dependency_status, DependencyStatus::Waiting); assert!( queue - .dequeue(&format!("{name}_child")) + .dequeue_one(&format!("{name}_child")) .await .unwrap() .is_none() ); let run = queue - .dequeue(&format!("{name}_parent")) + .dequeue_one(&format!("{name}_parent")) .await .unwrap() .unwrap(); assert_eq!(run.id, parent_id); queue.complete_job(parent_id).await.unwrap(); let run = queue - .dequeue(&format!("{name}_child")) + .dequeue_one(&format!("{name}_child")) .await .unwrap() .expect("released when its dependency completed"); @@ -380,11 +388,11 @@ async fn restore_reevaluates_dependencies(queue: &Q) { DependencyStatus::Waiting ); - let run = queue.dequeue(&name).await.unwrap().unwrap(); + let run = queue.dequeue_one(&name).await.unwrap().unwrap(); assert_eq!(run.id, parent_id, "the dependent waits for its dependency"); queue.complete_job(parent_id).await.unwrap(); let run = queue - .dequeue(&name) + .dequeue_one(&name) .await .unwrap() .expect("released when its dependency completed"); diff --git a/tests/result_config_test.rs b/tests/result_config_test.rs index 4d472ae..1a32992 100644 --- a/tests/result_config_test.rs +++ b/tests/result_config_test.rs @@ -29,7 +29,7 @@ async fn test_postgres_result_config_persistence() { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue the job to verify result_config is preserved - let dequeued_job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let dequeued_job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(dequeued_job.id, job_id); assert_eq!(dequeued_job.result_config.storage, ResultStorage::Database); @@ -62,7 +62,7 @@ async fn test_mysql_result_config_persistence() { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue the job to verify result_config is preserved - let dequeued_job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let dequeued_job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(dequeued_job.id, job_id); assert_eq!(dequeued_job.result_config.storage, ResultStorage::Database); diff --git a/tests/result_storage_tests.rs b/tests/result_storage_tests.rs index 1a7d690..0b6f1b1 100644 --- a/tests/result_storage_tests.rs +++ b/tests/result_storage_tests.rs @@ -49,7 +49,7 @@ async fn assert_result_survives_job_completion( .with_result_storage(ResultStorage::Database); let job_id = queue.enqueue(job).await.unwrap(); - let dequeued = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let dequeued = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); assert_eq!(dequeued.result_config.storage, ResultStorage::Database); diff --git a/tests/test_queue_parity_tests.rs b/tests/test_queue_parity_tests.rs index 12bcebe..2ac0e0a 100644 --- a/tests/test_queue_parity_tests.rs +++ b/tests/test_queue_parity_tests.rs @@ -79,7 +79,11 @@ where .enqueue(Job::new(queue_name.clone(), json!({})).with_max_attempts(1)) .await .unwrap(); - let run = queue.dequeue(&queue_name).await.unwrap().expect("job runs"); + let run = queue + .dequeue_one(&queue_name) + .await + .unwrap() + .expect("job runs"); assert_eq!(run.id, id); queue.mark_job_dead(id, "out of attempts").await.unwrap(); finished_in_the_past(queue.as_ref(), id).await; @@ -98,7 +102,7 @@ where } let run = queue - .dequeue(&queue_name) + .dequeue_one(&queue_name) .await .unwrap() .expect("the restored job runs again"); @@ -325,7 +329,7 @@ where .unwrap(); let run = queue - .dequeue(&format!("{name}_running")) + .dequeue_one(&format!("{name}_running")) .await .unwrap() .expect("job runs"); diff --git a/tests/test_queue_tests.rs b/tests/test_queue_tests.rs index 6d8e171..9d9428a 100644 --- a/tests/test_queue_tests.rs +++ b/tests/test_queue_tests.rs @@ -3,6 +3,7 @@ #![cfg(feature = "test-queue")] use chrono::Duration; +use hammerwork::queue::DequeueOptions; use hammerwork::{ Job, JobPriority, JobStatus, batch::{BatchStatus, JobBatch, PartialFailureMode}, @@ -22,13 +23,13 @@ async fn test_queue_basic_operations() { let queue = TestQueue::new(); // Test empty queue - assert!(queue.dequeue("empty_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("empty_queue").await.unwrap().is_none()); // Enqueue and dequeue let job = Job::new("test_queue".to_string(), json!({"test": "data"})); let job_id = queue.enqueue(job.clone()).await.unwrap(); - let dequeued = queue.dequeue("test_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("test_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); assert_eq!(dequeued.status, JobStatus::Running); assert!(dequeued.started_at.is_some()); @@ -62,23 +63,23 @@ async fn test_priority_ordering() { // Dequeue should follow priority order assert_eq!( - queue.dequeue("prio_queue").await.unwrap().unwrap().id, + queue.dequeue_one("prio_queue").await.unwrap().unwrap().id, critical_id ); assert_eq!( - queue.dequeue("prio_queue").await.unwrap().unwrap().id, + queue.dequeue_one("prio_queue").await.unwrap().unwrap().id, high_id ); assert_eq!( - queue.dequeue("prio_queue").await.unwrap().unwrap().id, + queue.dequeue_one("prio_queue").await.unwrap().unwrap().id, normal_id ); assert_eq!( - queue.dequeue("prio_queue").await.unwrap().unwrap().id, + queue.dequeue_one("prio_queue").await.unwrap().unwrap().id, low_id ); assert_eq!( - queue.dequeue("prio_queue").await.unwrap().unwrap().id, + queue.dequeue_one("prio_queue").await.unwrap().unwrap().id, background_id ); } @@ -116,8 +117,12 @@ async fn test_weighted_priority_selection() { // Dequeue with weights and count priorities let mut priority_counts = HashMap::new(); while let Some(job) = queue - .dequeue_with_priority_weights("weighted_queue", &weights) + .dequeue( + "weighted_queue", + &DequeueOptions::new().with_priority_weights(weights.clone()), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() { *priority_counts.entry(job.priority).or_insert(0) += 1; @@ -152,27 +157,42 @@ async fn test_delayed_jobs_with_time_control() { // Only immediate job should be available assert_eq!( - queue.dequeue("delayed_queue").await.unwrap().unwrap().id, + queue + .dequeue_one("delayed_queue") + .await + .unwrap() + .unwrap() + .id, immediate_id ); - assert!(queue.dequeue("delayed_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed_queue").await.unwrap().is_none()); // Advance time by 1 hour clock.advance(Duration::hours(1)); // Now 1h delayed job should be available assert_eq!( - queue.dequeue("delayed_queue").await.unwrap().unwrap().id, + queue + .dequeue_one("delayed_queue") + .await + .unwrap() + .unwrap() + .id, delayed_1h_id ); - assert!(queue.dequeue("delayed_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("delayed_queue").await.unwrap().is_none()); // Advance time by another hour clock.advance(Duration::hours(1)); // Now 2h delayed job should be available assert_eq!( - queue.dequeue("delayed_queue").await.unwrap().unwrap().id, + queue + .dequeue_one("delayed_queue") + .await + .unwrap() + .unwrap() + .id, delayed_2h_id ); } @@ -190,7 +210,7 @@ async fn test_job_retry_mechanism() { // job has attempts left and mark it dead once they are used up. // First attempt - dequeue and fail - let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("retry_queue").await.unwrap().unwrap(); assert_eq!(dequeued.attempts, 1); assert!(dequeued.attempts < dequeued.max_attempts); @@ -202,19 +222,19 @@ async fn test_job_retry_mechanism() { assert_eq!(job.attempts, 1); // Job should not be available immediately - assert!(queue.dequeue("retry_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("retry_queue").await.unwrap().is_none()); // Advance time clock.advance(Duration::minutes(10)); // Second attempt - fail again - let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("retry_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); assert_eq!(dequeued.attempts, 2); queue.retry_job(job_id, clock.now()).await.unwrap(); // Third attempt - the last one: mark as dead - let dequeued = queue.dequeue("retry_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("retry_queue").await.unwrap().unwrap(); assert_eq!(dequeued.attempts, dequeued.max_attempts); queue.mark_job_dead(job_id, "Third failure").await.unwrap(); @@ -256,7 +276,7 @@ async fn test_batch_operations() { // Process jobs for i in 0..4 { - if let Some(job) = queue.dequeue("batch_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("batch_queue").await.unwrap() { if i == 2 { // Fail the third job (a terminal failure) queue.fail_job(job.id, "Planned failure").await.unwrap(); @@ -293,12 +313,12 @@ async fn test_batch_fail_fast() { let batch_id = queue.enqueue_batch(batch).await.unwrap(); // Process first job successfully - if let Some(job) = queue.dequeue("failfast_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("failfast_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } // Fail second job - if let Some(job) = queue.dequeue("failfast_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("failfast_queue").await.unwrap() { queue.fail_job(job.id, "Failure").await.unwrap(); } @@ -307,7 +327,7 @@ async fn test_batch_fail_fast() { assert_eq!(status.status, BatchStatus::Failed); assert_eq!(status.completed_jobs, 1); assert_eq!(status.failed_jobs, 2); - assert!(queue.dequeue("failfast_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("failfast_queue").await.unwrap().is_none()); } #[tokio::test] @@ -341,27 +361,41 @@ async fn test_workflow_with_dependencies() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Only A should be available - let dequeued = queue.dequeue("workflow_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("workflow_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, id_a); - assert!(queue.dequeue("workflow_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("workflow_queue").await.unwrap().is_none()); // Complete A queue.complete_job(id_a).await.unwrap(); // B and C should now be available let mut dequeued_ids = vec![]; - dequeued_ids.push(queue.dequeue("workflow_queue").await.unwrap().unwrap().id); - dequeued_ids.push(queue.dequeue("workflow_queue").await.unwrap().unwrap().id); + dequeued_ids.push( + queue + .dequeue_one("workflow_queue") + .await + .unwrap() + .unwrap() + .id, + ); + dequeued_ids.push( + queue + .dequeue_one("workflow_queue") + .await + .unwrap() + .unwrap() + .id, + ); assert!(dequeued_ids.contains(&id_b)); assert!(dequeued_ids.contains(&id_c)); - assert!(queue.dequeue("workflow_queue").await.unwrap().is_none()); + assert!(queue.dequeue_one("workflow_queue").await.unwrap().is_none()); // Complete B and C queue.complete_job(id_b).await.unwrap(); queue.complete_job(id_c).await.unwrap(); // D should now be available - let dequeued = queue.dequeue("workflow_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("workflow_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, id_d); // Complete D @@ -394,7 +428,7 @@ async fn test_workflow_failure_policies() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Fail the first job (a terminal failure) - let dequeued = queue.dequeue("failfast_wf").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("failfast_wf").await.unwrap().unwrap(); queue.fail_job(dequeued.id, "Test failure").await.unwrap(); // Other jobs should have been failed due to fail-fast policy @@ -445,7 +479,7 @@ async fn test_cron_job_scheduling() { // Process the first run clock.advance(Duration::hours(1)); - let dequeued = queue.dequeue("cron_queue").await.unwrap().unwrap(); + let dequeued = queue.dequeue_one("cron_queue").await.unwrap().unwrap(); assert_eq!(dequeued.id, job_id); queue .finish_job_run(&dequeued, hammerwork::queue::JobOutcome::Completed) @@ -497,7 +531,7 @@ async fn test_dead_job_management() { // Dequeue and mark as dead queue - .dequeue(&format!("dead_queue_{}", i % 2)) + .dequeue_one(&format!("dead_queue_{}", i % 2)) .await .unwrap(); queue @@ -559,7 +593,7 @@ async fn test_timeout_handling() { let job_id = queue.enqueue(job).await.unwrap(); // Dequeue and mark as timed out - queue.dequeue("timeout_queue").await.unwrap(); + queue.dequeue_one("timeout_queue").await.unwrap(); queue .mark_job_timed_out(job_id, "Operation timed out") .await @@ -583,7 +617,7 @@ async fn test_job_result_storage() { let job = Job::new("result_queue".to_string(), json!({"compute": "fibonacci"})); let job_id = queue.enqueue(job).await.unwrap(); - queue.dequeue("result_queue").await.unwrap(); + queue.dequeue_one("result_queue").await.unwrap(); queue.complete_job(job_id).await.unwrap(); // Store job result with expiration @@ -682,7 +716,7 @@ async fn test_queue_statistics() { // Process some jobs for i in 0..5 { - if let Some(job) = queue.dequeue("stats_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("stats_queue").await.unwrap() { // Simulate processing time clock.advance(Duration::milliseconds(100 + i * 50)); @@ -752,7 +786,7 @@ async fn test_queue_depth() { // Process some jobs for _ in 0..2 { - if let Some(job) = queue.dequeue("depth_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("depth_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } } @@ -794,7 +828,7 @@ async fn test_concurrent_operations() { for _ in 0..5 { let queue_clone = queue.clone(); let handle = tokio::spawn(async move { - if let Some(job) = queue_clone.dequeue("concurrent_queue").await.unwrap() { + if let Some(job) = queue_clone.dequeue_one("concurrent_queue").await.unwrap() { // Simulate processing tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; queue_clone.complete_job(job.id).await @@ -841,7 +875,7 @@ async fn test_workflow_cancellation() { let workflow_id = queue.enqueue_workflow(workflow).await.unwrap(); // Process one job - if let Some(job) = queue.dequeue("cancel_queue").await.unwrap() { + if let Some(job) = queue.dequeue_one("cancel_queue").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } @@ -883,7 +917,7 @@ async fn test_get_all_jobs() { // Process some jobs for _ in 0..2 { - if let Some(job) = queue.dequeue("queue_0").await.unwrap() { + if let Some(job) = queue.dequeue_one("queue_0").await.unwrap() { queue.complete_job(job.id).await.unwrap(); } } diff --git a/tests/undecodable_row_tests.rs b/tests/undecodable_row_tests.rs index 4b02ddb..1ac475a 100644 --- a/tests/undecodable_row_tests.rs +++ b/tests/undecodable_row_tests.rs @@ -7,6 +7,7 @@ mod test_utils; use chrono::Duration; +use hammerwork::queue::DequeueOptions; use hammerwork::{ Job, JobId, archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason}, @@ -181,7 +182,10 @@ where // Claim all three with a lease that has expired by the time the reaper runs. let claimed = queue - .dequeue_batch_leased(&name, None, std::time::Duration::from_millis(1), 10) + .dequeue( + &name, + &DequeueOptions::batch(10).with_lease_duration(std::time::Duration::from_millis(1)), + ) .await .unwrap(); assert_eq!(claimed.len(), 3); @@ -244,10 +248,10 @@ where let mut claimed: Vec = Vec::new(); for _ in 0..3 { let jobs = if batch { - queue.dequeue_batch(&name, 1).await + queue.dequeue(&name, &DequeueOptions::batch(1)).await } else { queue - .dequeue(&name) + .dequeue_one(&name) .await .map(|job| job.into_iter().collect()) }; diff --git a/tests/worker_batch_tests.rs b/tests/worker_batch_tests.rs index 1c3b717..dd85dc5 100644 --- a/tests/worker_batch_tests.rs +++ b/tests/worker_batch_tests.rs @@ -54,11 +54,11 @@ mod postgres_worker_batch_tests { // Create worker with batch processing enabled let worker = Worker::new(queue.clone(), queue_name.clone(), handler) - .with_batch_processing_enabled(true) + .with_batch_size(1) // Batch mode (statistics), one job per poll .with_stats_collector(stats_collector.clone()) .with_poll_interval(Duration::from_millis(50)) // Fail for good on the first attempt instead of waiting out retry delays - .with_max_retries(1); + .with_attempt_cap(1); // Verify initial batch stats let initial_stats = worker.get_batch_stats(); @@ -146,7 +146,7 @@ mod postgres_worker_batch_tests { // Create worker with batch processing enabled let worker = Worker::new(queue.clone(), queue_name.clone(), handler) - .with_batch_processing_enabled(true) + .with_batch_size(1) // Batch mode (statistics), one job per poll .with_poll_interval(Duration::from_millis(50)); // Create a small batch diff --git a/tests/worker_robustness_tests.rs b/tests/worker_robustness_tests.rs index 2fc337b..90989e7 100644 --- a/tests/worker_robustness_tests.rs +++ b/tests/worker_robustness_tests.rs @@ -8,6 +8,7 @@ mod test_utils; +use hammerwork::queue::DequeueOptions; use hammerwork::{ HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, WorkerPool, queue::DatabaseQueue, worker::JobHandler, @@ -48,7 +49,7 @@ where }); let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) .with_poll_interval(Duration::from_millis(50)) - .with_max_retries(1); + .with_attempt_cap(1); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); @@ -104,7 +105,7 @@ where Arc::new(|_job: Job| Box::pin(async move { panic!("transient explosion") })); let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) .with_poll_interval(Duration::from_millis(50)) - .with_max_retries(5) + .with_attempt_cap(5) .with_retry_delay(Duration::from_secs(3600)); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); @@ -257,7 +258,6 @@ where let worker = Arc::new( Worker::new(Arc::clone(&queue), queue_name.clone(), handler) .with_poll_interval(Duration::from_millis(20)) - .with_batch_processing_enabled(true) .with_batch_size(JOBS) .with_batch_concurrency(JOBS), ); @@ -389,8 +389,12 @@ where let queue_name = job.queue_name.clone(); let id = queue.enqueue(job).await.unwrap(); let claimed = queue - .dequeue_leased(&queue_name, None, lease) + .dequeue( + &queue_name, + &DequeueOptions::new().with_lease_duration(lease), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .expect("job claimed"); assert_eq!(claimed.id, id); @@ -492,7 +496,7 @@ where assert!(job.started_at.is_none()); assert!(job.error_message.unwrap().contains("lease expired")); // The requeued job can be claimed again. - let reclaimed = queue.dequeue(&job.queue_name).await.unwrap().unwrap(); + let reclaimed = queue.dequeue_one(&job.queue_name).await.unwrap().unwrap(); assert_eq!(reclaimed.id, expiring.id); assert_eq!(reclaimed.attempts, 2); @@ -545,7 +549,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({}))) .await .unwrap(); - let default = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let default = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(default.id, id); let short = start_job( &queue, @@ -619,8 +623,12 @@ where assert!(recovery.requeued.contains(&first.id), "{recovery:?}"); let second = queue - .dequeue_leased(&first.queue_name, None, lease) + .dequeue( + &first.queue_name, + &DequeueOptions::new().with_lease_duration(lease), + ) .await + .map(|jobs| jobs.into_iter().next()) .unwrap() .expect("requeued job"); assert_eq!(second.id, first.id); diff --git a/tests/workflow_failure_policy_tests.rs b/tests/workflow_failure_policy_tests.rs index 693d2a1..501d03a 100644 --- a/tests/workflow_failure_policy_tests.rs +++ b/tests/workflow_failure_policy_tests.rs @@ -94,7 +94,7 @@ where Q: DatabaseQueue + Send + Sync + 'static, { let job = queue - .dequeue(&graph.queue_of(step)) + .dequeue_one(&graph.queue_of(step)) .await .unwrap() .unwrap_or_else(|| panic!("job {step} is runnable")); @@ -190,7 +190,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({})).with_max_attempts(3)) .await .unwrap(); - let job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(job.attempts, 1); queue.fail_job(id, "permanent").await.unwrap(); @@ -199,14 +199,14 @@ where assert_eq!(job.attempts, 1); assert_eq!(job.error_message.as_deref(), Some("permanent")); assert!(job.failed_at.is_some()); - assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + assert!(queue.dequeue_one(&queue_name).await.unwrap().is_none()); assert!( queue.fail_job(id, "again").await.is_err(), "a Failed job cannot fail again" ); queue.retry_job(id, past()).await.unwrap(); - let job = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let job = queue.dequeue_one(&queue_name).await.unwrap().unwrap(); assert_eq!(job.id, id); assert_eq!(job.attempts, 2); queue.delete_job(id).await.unwrap(); @@ -365,7 +365,7 @@ where queue.enqueue(parent).await.unwrap(); queue.enqueue(child).await.unwrap(); - queue.dequeue(&queue_name).await.unwrap().unwrap(); + queue.dequeue_one(&queue_name).await.unwrap().unwrap(); let failed = queue.fail_job_dependencies(parent_id).await.unwrap(); assert_eq!(failed, [child_id]); let child = queue.get_job(child_id).await.unwrap().unwrap();