diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e05e41..41acaeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,8 +15,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `WorkerPool::from_config` creates `pool_size` workers and configures autoscaling from `WorkerConfig` - `WebhookManager::from_config` and `StreamManager::from_config` build managers from the `webhooks` and `streaming` sections - `ArchiveConfig::archival_policy` / `archival_config`, `RateLimitingConfig::throttle_for`, `WorkerConfig::autoscale_config`, `DatabaseConfig::connection_timeout` +- **🩺 Job leases and stale job recovery** ([#19](https://github.com/CodingAnarchy/hammerwork/issues/19) C2): jobs left `Running` by a crashed or killed worker are no longer stuck forever + - Migration `015_add_job_leases` adds `last_heartbeat_at` and `lease_expires_at` to `hammerwork_jobs` (PostgreSQL and MySQL). Run `cargo hammerwork migration run` before upgrading workers. + - Workers heartbeat running jobs every third of their lease (`Worker::with_lease_duration`, default 5 minutes) + - `DatabaseQueue::heartbeat_job` and `DatabaseQueue::requeue_stale_jobs(older_than)` (returns `StaleJobRecovery`). Expired jobs go back to `Pending`, or to `Dead` when out of attempts. Safe to run concurrently (`FOR UPDATE SKIP LOCKED` plus a `status = 'Running'` guard). Both methods have default implementations, so custom `DatabaseQueue` implementations keep compiling. + - `WorkerPool` runs the reaper every 60 seconds (`with_stale_job_reaper`, `without_stale_job_reaper`) + - CLI: `cargo hammerwork job requeue-stale [--older-than-secs N]` +- `Worker::with_shutdown_grace_period` (default 30 seconds) and `RetryStrategy::validate` ### Changed +- **Breaking:** `RetryStrategy::Custom` now holds an `Arc Duration + Send + Sync>` (`retry::CustomRetryFn`) instead of a `Box`, so it can be cloned. Code using `RetryStrategy::custom(..)` is unaffected; code constructing the variant directly must switch `Box::new` to `Arc::new`. Two `Custom` strategies now compare equal when they share the same function. +- `WorkerPool::shutdown` now waits until every worker has stopped (bounded by each worker's shutdown grace period) instead of returning as soon as the signal is sent - **CI**: replaced the disabled `Integration Tests` workflow with `.github/workflows/ci.yml`: rustfmt, clippy (`--all-targets --all-features -D warnings`), unit tests, PostgreSQL 16 and MySQL 8 integration jobs, and a `cargo audit` job. Runs on pushes and pull requests to `master` and on demand (#7). - `DatabaseConfig::create_tables` is deprecated; tables are created by migrations (`auto_migrate`) - AWS KMS clients (`aws-kms` feature) now load config with `BehaviorVersion::latest()` instead of the deprecated `v2025_01_17`, matching the Kinesis client. This picks up the SDK's newer defaults, including HTTP(S) proxy settings from the environment. @@ -45,6 +54,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - MySQL dequeues and the PostgreSQL weighted dequeue ignored `dependency_status` and could run a job before its dependencies completed. - MySQL dequeues now use `FOR UPDATE SKIP LOCKED` (MySQL 8.0+), so concurrent workers skip rows being claimed instead of blocking on them. - MySQL job claims run at READ COMMITTED and retry when InnoDB aborts them as deadlock victims (error 1213), which concurrent workers otherwise hit intermittently. +- **Worker robustness** ([#17](https://github.com/CodingAnarchy/hammerwork/issues/17), [#19](https://github.com/CodingAnarchy/hammerwork/issues/19)) + - Errors from completing, failing or retrying a job (and from dequeuing) are logged and followed by an exponential backoff that honours `ThrottleConfig::backoff_on_error`, instead of being discarded with the worker spinning hot (H1) + - A panicking job handler no longer kills the worker: the panic fails the job with `Job handler panicked: ` and goes through the normal retry / dead path (H2) + - `WorkerPool` supervises its workers: a worker that dies is logged and restarted instead of the pool returning on the first failure and detaching the rest (H3) + - `WorkerPool::shutdown` is graceful: in-flight jobs finish (up to the grace period) and record their outcome before workers stop, and `shutdown` waits for them. Dropping the pool also shuts it down. Previously shutdown cancelled the running handler and left the job `Running` (C2) + - Huge retry delays no longer panic in `chrono::Duration::from_std(..).unwrap()`; retry delays are clamped to 365 days (H4) + - `RetryStrategy::calculate_delay` no longer panics on overflow (exponential from attempt ~65, Fibonacci ~94, huge linear values) or on a NaN / negative multiplier; it saturates and clamps to `max_delay`. Jitter with an invalid factor no longer panics (H5) + - Cloning a `RetryStrategy::Custom` (e.g. through `Worker::clone` for autoscaling) no longer panics (H6) + - Webhook delivery no longer panics when truncating a response body in the middle of a multi-byte UTF-8 character (H7) + - The autoscaler no longer panics on a zero `evaluation_window` - **Archiving ([#14](https://github.com/CodingAnarchy/hammerwork/issues/14))**, PostgreSQL and MySQL: - `archive_jobs` now moves jobs: the archive insert and the delete from `hammerwork_jobs` run in one transaction, and candidates are selected with `FOR UPDATE SKIP LOCKED` so concurrent archivers do not collide. Previously the row stayed in `hammerwork_jobs` with its old status. - `get_job` falls back to the archive table and returns archived jobs with `JobStatus::Archived` (previously it returned the stale pre-archive row) diff --git a/cargo-hammerwork/README.md b/cargo-hammerwork/README.md index e8a9bfd..dbb181c 100644 --- a/cargo-hammerwork/README.md +++ b/cargo-hammerwork/README.md @@ -92,8 +92,15 @@ cargo hammerwork job enqueue --queue QUEUE --payload JSON [OPTIONS] cargo hammerwork job retry # Retry a failed job cargo hammerwork job cancel # Cancel a pending job cargo hammerwork job delete # Remove a job +cargo hammerwork job requeue-stale [--older-than-secs N] # Reclaim jobs stuck in Running ``` +`job requeue-stale` moves `Running` jobs whose lease has expired (their worker crashed +or was killed) back to `Pending`, or to `Dead` when they have no attempts left. Jobs +that never recorded a lease are reclaimed once they started more than +`--older-than-secs` ago (default 3600). It is safe to run alongside workers, and needs +migration `015_add_job_leases`. + ### Worker Management Commands ```bash @@ -218,6 +225,7 @@ cargo-hammerwork/ - List jobs with advanced filtering (queue, status, priority, time-based) - Job enqueueing with priority, delays, timeouts, and retry configuration - Bulk operations (retry, cancel, purge) with safety confirmations +- Stale job recovery (`requeue-stale`) for jobs orphaned by crashed workers - Detailed job inspection with full lifecycle tracking #### Queue Management diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index e4ba7d1..e29f920 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -94,6 +94,26 @@ pub enum JobCommand { #[arg(long, help = "Confirm the purge operation")] confirm: bool, }, + #[command( + about = "Reclaim jobs stuck in Running after a worker crashed", + long_about = "Reclaim jobs left in Running by workers that crashed or were killed.\n\n\ + A Running job is stale when its lease (renewed by worker heartbeats) has \ + expired, or, if it never recorded a lease, when it started more than \ + --older-than-secs ago. Stale jobs with attempts left go back to Pending; \ + the rest are marked Dead. Safe to run while workers and other reapers are \ + running. Requires migration 015_add_job_leases.\n\n\ + Example: cargo hammerwork job requeue-stale --older-than-secs 3600" + )] + RequeueStale { + #[arg(short = 'u', long, help = "Database connection URL")] + database_url: Option, + #[arg( + long, + default_value_t = 3600, + help = "For jobs without a lease: reclaim if started more than N seconds ago" + )] + older_than_secs: u64, + }, } impl JobCommand { @@ -180,6 +200,11 @@ impl JobCommand { ) .await?; } + JobCommand::RequeueStale { + older_than_secs, .. + } => { + requeue_stale_jobs(pool, *older_than_secs).await?; + } } Ok(()) } @@ -192,6 +217,7 @@ impl JobCommand { JobCommand::Retry { database_url, .. } => database_url, JobCommand::Cancel { database_url, .. } => database_url, JobCommand::Purge { database_url, .. } => database_url, + JobCommand::RequeueStale { database_url, .. } => database_url, }; url_option @@ -572,6 +598,32 @@ async fn enqueue_job( Ok(()) } +async fn requeue_stale_jobs(pool: DatabasePool, older_than_secs: u64) -> Result<()> { + let older_than = std::time::Duration::from_secs(older_than_secs); + let recovery = match pool.create_job_queue() { + crate::utils::database::JobQueueWrapper::Postgres(queue) => { + queue.requeue_stale_jobs(older_than).await? + } + crate::utils::database::JobQueueWrapper::MySQL(queue) => { + queue.requeue_stale_jobs(older_than).await? + } + }; + + for id in &recovery.requeued { + info!("↩️ Requeued stale job {}", id); + } + for id in &recovery.dead { + info!("💀 Marked stale job {} dead (no attempts left)", id); + } + info!( + "✅ Reclaimed {} stale jobs ({} requeued, {} dead)", + recovery.total(), + recovery.requeued.len(), + recovery.dead.len() + ); + Ok(()) +} + async fn retry_jobs( pool: DatabasePool, job_id: Option, @@ -786,6 +838,52 @@ async fn purge_jobs( #[cfg(test)] mod tests { use super::*; + use clap::Parser; + + #[derive(Parser)] + struct TestCli { + #[command(subcommand)] + command: JobCommand, + } + + #[test] + fn test_requeue_stale_parses_with_default_threshold() { + let cli = TestCli::try_parse_from(["test", "requeue-stale"]).unwrap(); + match cli.command { + JobCommand::RequeueStale { + database_url, + older_than_secs, + } => { + assert!(database_url.is_none()); + assert_eq!(older_than_secs, 3600); + } + _ => panic!("expected RequeueStale"), + } + + let cli = TestCli::try_parse_from([ + "test", + "requeue-stale", + "--older-than-secs", + "120", + "-u", + "postgres://localhost/db", + ]) + .unwrap(); + match cli.command { + JobCommand::RequeueStale { + database_url, + older_than_secs, + } => { + assert_eq!(database_url.as_deref(), Some("postgres://localhost/db")); + assert_eq!(older_than_secs, 120); + } + _ => panic!("expected RequeueStale"), + } + + assert!( + TestCli::try_parse_from(["test", "requeue-stale", "--older-than-secs", "-5"]).is_err() + ); + } #[test] fn test_list_jobs_query_postgres_binds_typed_params() { diff --git a/docs/migrations.md b/docs/migrations.md index 4a1cc7c..f1ab9ba 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -26,6 +26,11 @@ Migrations are organized chronologically and represent the evolution of Hammerwo 8. **008_add_result_config** - Add result configuration storage fields 9. **009_add_tracing** - Add distributed tracing and correlation fields 10. **010_add_archival** - Add job archival support and archive table +11. **011_add_encryption** - Add encryption fields and key storage +12. **012_optimize_dependencies** - Optimize dependency lookups +13. **013_add_key_audit** - Add encryption key audit table +14. **014_add_queue_pause** - Add queue pause state table +15. **015_add_job_leases** - Add `last_heartbeat_at` and `lease_expires_at` for job leases and stale job recovery ## Running Migrations diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index 013ecf9..bbd6dc8 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -156,6 +156,76 @@ pool.start().await?; pool.shutdown().await?; ``` +`start` spawns every worker and a supervisor, then waits until the pool shuts down. +The workers run in their own tasks, so you can drop the `start` future (for example +in a `tokio::select!` on a shutdown signal) and then call `shutdown`: + +```rust +tokio::select! { + result = pool.start() => result?, + _ = tokio::signal::ctrl_c() => pool.shutdown().await?, +} +``` + +Dropping the pool also shuts its workers down gracefully. + +### Supervision + +If a worker task stops unexpectedly (a bug that panics outside a job handler, for +example), the pool logs it and restarts the worker after one second. A panic inside +a job handler never reaches this point: the worker catches it and fails the job +with the error `Job handler panicked: `, which then goes through the +normal retry / dead-letter path. + +Errors in the worker loop itself (the database failing while a job is dequeued or +its outcome recorded) are logged, and the worker backs off exponentially, starting +at the throttle's `backoff_on_error` (or the poll interval, at least 100ms) and +capped at 60 seconds. + +### Graceful Shutdown + +On `shutdown`, idle workers stop immediately. A worker in the middle of a job stops +polling but lets the job finish and record its outcome, for up to its shutdown grace +period (30 seconds by default). Only then is the handler cancelled. `shutdown` +returns once every worker has stopped. + +```rust +let worker = Worker::new(queue.clone(), "reports".to_string(), handler) + .with_shutdown_grace_period(Duration::from_secs(120)); +``` + +### Job Leases and Stale Job Recovery + +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`): + +- While a handler runs, the worker records a heartbeat and extends the job's lease + every third of its lease duration (5 minutes by default). Jobs that finish sooner + never write a heartbeat. +- `DatabaseQueue::requeue_stale_jobs(older_than)` reclaims `Running` jobs whose + lease has expired. Jobs that never recorded a lease (they had not reached their + first heartbeat, or were started by an older Hammerwork version) count as stale + once they started more than `older_than` ago. +- A reclaimed job goes back to `Pending` and runs again immediately. The interrupted + run already counted as an attempt; a job with no attempts left is moved to `Dead`. +- Every `WorkerPool` runs this reaper every 60 seconds, with `older_than` set to the + longest lease of its workers. Several pools or processes can reap at once safely. + +```rust +let worker = Worker::new(queue.clone(), "video".to_string(), handler) + .with_lease_duration(Duration::from_secs(60)); // detect crashed workers within ~1 min + +let mut pool = WorkerPool::new() + // Reap every 30s; jobs without a lease are stale after 10 minutes + .with_stale_job_reaper(Duration::from_secs(30), Duration::from_secs(600)); +// Or turn it off and run `cargo hammerwork job requeue-stale` from a scheduler: +// let mut pool = WorkerPool::new().without_stale_job_reaper(); +``` + +If a lease expires while the handler is still running (for example after a long +stop-the-world pause), the job can be reclaimed and run again elsewhere, so handlers +should be idempotent. The worker logs a warning when it notices it lost a lease. + ### Mixed Configuration Pools ```rust diff --git a/src/lib.rs b/src/lib.rs index 5e59d47..6966823 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -310,7 +310,7 @@ pub use job::{Job, JobId, JobStatus, ResultConfig, ResultStorage}; pub use priority::{ JobPriority, PriorityError, PrioritySelectionStrategy, PriorityStats, PriorityWeights, }; -pub use queue::JobQueue; +pub use queue::{JobQueue, StaleJobRecovery}; pub use rate_limit::{RateLimit, RateLimiter, ThrottleConfig}; pub use retry::{JitterType, RetryStrategy, fibonacci}; pub use spawn::{JobSpawnExt, SpawnConfig, SpawnHandler, SpawnManager, SpawnResult}; diff --git a/src/migrations/015_add_job_leases.mysql.sql b/src/migrations/015_add_job_leases.mysql.sql new file mode 100644 index 0000000..2bc2d9f --- /dev/null +++ b/src/migrations/015_add_job_leases.mysql.sql @@ -0,0 +1,11 @@ +-- Migration 015: Add job leases for stale job recovery (MySQL) +-- Workers record a heartbeat and extend a lease while a job is Running. +-- A reaper (DatabaseQueue::requeue_stale_jobs) reclaims Running jobs whose +-- lease has expired, e.g. because the worker crashed or was killed. + +ALTER TABLE hammerwork_jobs +ADD COLUMN last_heartbeat_at TIMESTAMP(6) NULL DEFAULT NULL, +ADD COLUMN lease_expires_at TIMESTAMP(6) NULL DEFAULT NULL; + +-- Index so the reaper only scans Running jobs +CREATE INDEX idx_hammerwork_jobs_status_lease ON hammerwork_jobs (status, lease_expires_at); diff --git a/src/migrations/015_add_job_leases.postgres.sql b/src/migrations/015_add_job_leases.postgres.sql new file mode 100644 index 0000000..bfd21c4 --- /dev/null +++ b/src/migrations/015_add_job_leases.postgres.sql @@ -0,0 +1,15 @@ +-- Migration 015: Add job leases for stale job recovery (PostgreSQL) +-- Workers record a heartbeat and extend a lease while a job is Running. +-- A reaper (DatabaseQueue::requeue_stale_jobs) reclaims Running jobs whose +-- lease has expired, e.g. because the worker crashed or was killed. + +ALTER TABLE hammerwork_jobs +ADD COLUMN IF NOT EXISTS last_heartbeat_at TIMESTAMPTZ; + +ALTER TABLE hammerwork_jobs +ADD COLUMN IF NOT EXISTS lease_expires_at TIMESTAMPTZ; + +-- Partial index so the reaper only scans Running jobs +CREATE INDEX IF NOT EXISTS idx_hammerwork_jobs_running_lease + ON hammerwork_jobs (lease_expires_at, started_at) + WHERE status = 'Running'; diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs index e58d6c9..bdbd88a 100644 --- a/src/migrations/mod.rs +++ b/src/migrations/mod.rs @@ -405,5 +405,20 @@ impl MigrationManager { include_str!("014_add_queue_pause.postgres.sql").to_string(), include_str!("014_add_queue_pause.mysql.sql").to_string(), ); + + // Migration 015: Add job leases for stale job recovery + self.register_migration( + Migration { + id: "015_add_job_leases".to_string(), + description: "Add job heartbeat and lease columns for stale job recovery" + .to_string(), + version: 15, + created_at: chrono::DateTime::parse_from_rfc3339("2026-10-08T00:00:00Z") + .unwrap() + .with_timezone(&Utc), + }, + include_str!("015_add_job_leases.postgres.sql").to_string(), + include_str!("015_add_job_leases.mysql.sql").to_string(), + ); } } diff --git a/src/queue/mod.rs b/src/queue/mod.rs index e5979f4..d64fe21 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -622,6 +622,122 @@ pub trait DatabaseQueue: Send + Sync { /// # } /// ``` async fn get_paused_queues(&self) -> Result>; + + // Lease / stale job recovery + + /// Record a heartbeat for a `Running` job and extend its lease to `now + lease`. + /// + /// Workers call this periodically while a handler runs. The lease tells + /// [`requeue_stale_jobs`](Self::requeue_stale_jobs) that the job is still owned by a + /// live worker. + /// + /// Returns `false` when the job is no longer `Running` (for example because a reaper + /// already reclaimed it), which means the caller has lost its lease. + /// + /// The default implementation returns an error, for backends that predate leases. + async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + let _ = (job_id, lease); + Err(crate::HammerworkError::Queue { + message: "job leases are not supported by this queue backend".to_string(), + }) + } + + /// 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 (a heartbeat recorded after `started_at`) + /// and that lease has expired, or + /// - it has no lease from its current run (it has not heartbeated yet, or was + /// started by a worker that predates leases) and it started more than + /// `older_than` ago. + /// + /// Stale jobs whose `attempts` have reached `max_attempts` are moved to `Dead`; + /// the others go back to `Pending` and are scheduled immediately. The interrupted + /// run already counted as an attempt when the job was dequeued. + /// + /// Safe to call from several processes at once: rows are claimed with row locks + /// (`FOR UPDATE SKIP LOCKED`) and only updated while still `Running`, so each stale + /// job is reclaimed exactly once. + /// + /// # Examples + /// + /// ```rust,no_run + /// use hammerwork::queue::DatabaseQueue; + /// use std::time::Duration; + /// + /// # async fn example(queue: &impl DatabaseQueue) -> hammerwork::Result<()> { + /// let recovery = queue.requeue_stale_jobs(Duration::from_secs(300)).await?; + /// println!( + /// "requeued {} jobs, marked {} dead", + /// recovery.requeued.len(), + /// recovery.dead.len() + /// ); + /// # 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(), + }) + } +} + +/// The outcome of [`DatabaseQueue::requeue_stale_jobs`]. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StaleJobRecovery { + /// Stale jobs moved back to `Pending` to be retried. + pub requeued: Vec, + /// Stale jobs that had no attempts left and were moved to `Dead`. + pub dead: Vec, +} + +impl StaleJobRecovery { + /// Total number of jobs reclaimed. + pub fn total(&self) -> usize { + self.requeued.len() + self.dead.len() + } + + /// Whether no stale jobs were found. + pub fn is_empty(&self) -> bool { + self.total() == 0 + } +} + +/// Error message recorded on a job reclaimed by [`DatabaseQueue::requeue_stale_jobs`]. +pub const STALE_JOB_ERROR_MESSAGE: &str = + "Job lease expired while Running; the worker is presumed dead and the job was reclaimed"; + +/// 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) +} + +/// `now - duration`, saturating at the minimum representable timestamp. +#[cfg_attr( + not(any(feature = "postgres", feature = "mysql", feature = "test")), + allow(dead_code) +)] +pub(crate) fn saturating_sub_from( + now: DateTime, + duration: std::time::Duration, +) -> DateTime { + now.checked_sub_signed(saturating_chrono_duration(duration)) + .unwrap_or(DateTime::::MIN_UTC) +} + +/// `now + duration`, saturating at the maximum representable timestamp. +pub(crate) fn saturating_add_to( + now: DateTime, + duration: std::time::Duration, +) -> DateTime { + now.checked_add_signed(saturating_chrono_duration(duration)) + .unwrap_or(DateTime::::MAX_UTC) } /// A generic job queue implementation that works with multiple database backends. diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index e7471c0..d034839 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -2451,6 +2451,112 @@ impl DatabaseQueue for crate::queue::JobQueue { Ok(paused_queues) } + + async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + let now = Utc::now(); + let result = sqlx::query( + "UPDATE hammerwork_jobs SET last_heartbeat_at = ?, lease_expires_at = ? \ + WHERE id = ? AND status = ?", + ) + .bind(now) + .bind(super::saturating_add_to(now, lease)) + .bind(job_id.to_string()) + .bind(JobStatus::Running) + .execute(&self.pool) + .await?; + + // MySQL reports "rows changed", not "rows matched"; the timestamps always change + // (microsecond precision), so 0 means the job is no longer Running. + Ok(result.rows_affected() > 0) + } + + async fn requeue_stale_jobs( + &self, + older_than: std::time::Duration, + ) -> Result { + let now = Utc::now(); + let cutoff = super::saturating_sub_from(now, older_than); + let mut tx = self.pool.begin().await?; + + // Claim stale rows with SKIP LOCKED so concurrent reapers never wait on (or + // double-process) the same row. Each UPDATE re-checks `status` as well. + let candidates = sqlx::query( + r#" + SELECT id, attempts, max_attempts FROM hammerwork_jobs + WHERE status = ? + AND ( + (last_heartbeat_at IS NOT NULL + AND last_heartbeat_at >= started_at + AND lease_expires_at < ?) + OR ((last_heartbeat_at IS NULL OR last_heartbeat_at < started_at) + AND started_at < ?) + ) + FOR UPDATE SKIP LOCKED + "#, + ) + .bind(JobStatus::Running) + .bind(now) + .bind(cutoff) + .fetch_all(&mut *tx) + .await?; + + let mut recovery = super::StaleJobRecovery::default(); + for row in candidates { + let id_str: String = row.get("id"); + let id = uuid::Uuid::parse_str(&id_str)?; + let attempts: i32 = row.get("attempts"); + let max_attempts: i32 = row.get("max_attempts"); + + let exhausted = attempts >= max_attempts; + let result = if exhausted { + sqlx::query( + "UPDATE hammerwork_jobs SET status = ?, failed_at = ?, error_message = ?, \ + last_heartbeat_at = NULL, lease_expires_at = NULL \ + WHERE id = ? AND status = ?", + ) + .bind(JobStatus::Dead) + .bind(now) + .bind(super::STALE_JOB_ERROR_MESSAGE) + .bind(&id_str) + .bind(JobStatus::Running) + .execute(&mut *tx) + .await? + } else { + sqlx::query( + "UPDATE hammerwork_jobs SET status = ?, scheduled_at = ?, started_at = NULL, \ + error_message = ?, last_heartbeat_at = NULL, lease_expires_at = NULL \ + WHERE id = ? AND status = ?", + ) + .bind(JobStatus::Pending) + .bind(now) + .bind(super::STALE_JOB_ERROR_MESSAGE) + .bind(&id_str) + .bind(JobStatus::Running) + .execute(&mut *tx) + .await? + }; + + if result.rows_affected() == 1 { + if exhausted { + recovery.dead.push(id); + } else { + recovery.requeued.push(id); + } + } + } + + tx.commit().await?; + + if !recovery.is_empty() { + tracing::warn!( + requeued = recovery.requeued.len(), + dead = recovery.dead.len(), + "Reclaimed stale Running jobs whose lease expired" + ); + } + + Ok(recovery) + } } // Helper method for enqueueing with an existing transaction diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 993284f..a1bb665 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -2453,6 +2453,93 @@ impl DatabaseQueue for crate::queue::JobQueue { Ok(paused_queues) } + + async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + let now = Utc::now(); + let result = sqlx::query( + "UPDATE hammerwork_jobs SET last_heartbeat_at = $1, lease_expires_at = $2 \ + WHERE id = $3 AND status = $4", + ) + .bind(now) + .bind(super::saturating_add_to(now, lease)) + .bind(job_id) + .bind(JobStatus::Running) + .execute(&self.pool) + .await?; + + Ok(result.rows_affected() > 0) + } + + async fn requeue_stale_jobs( + &self, + older_than: std::time::Duration, + ) -> Result { + let now = Utc::now(); + let cutoff = super::saturating_sub_from(now, older_than); + + // The CTE claims stale rows with SKIP LOCKED so concurrent reapers never wait on + // (or double-process) the same row; the outer UPDATE re-checks `status` so a row + // that changed state after the snapshot is left alone. All SET expressions read + // the pre-update row, so `attempts >= max_attempts` picks Dead vs Pending. + let rows = sqlx::query( + r#" + WITH stale AS ( + SELECT id FROM hammerwork_jobs + WHERE status = $1 + AND ( + (last_heartbeat_at IS NOT NULL + AND last_heartbeat_at >= started_at + AND lease_expires_at < $2) + OR ((last_heartbeat_at IS NULL OR last_heartbeat_at < started_at) + AND started_at < $3) + ) + FOR UPDATE SKIP LOCKED + ) + UPDATE hammerwork_jobs AS j + SET status = CASE WHEN j.attempts >= j.max_attempts THEN $4 ELSE $5 END, + failed_at = CASE WHEN j.attempts >= j.max_attempts THEN $2 ELSE j.failed_at END, + scheduled_at = CASE WHEN j.attempts >= j.max_attempts + THEN j.scheduled_at ELSE $2 END, + started_at = CASE WHEN j.attempts >= j.max_attempts + THEN j.started_at ELSE NULL END, + error_message = $6, + last_heartbeat_at = NULL, + lease_expires_at = NULL + FROM stale + WHERE j.id = stale.id AND j.status = $1 + RETURNING j.id, j.status + "#, + ) + .bind(JobStatus::Running) + .bind(now) + .bind(cutoff) + .bind(JobStatus::Dead) + .bind(JobStatus::Pending) + .bind(super::STALE_JOB_ERROR_MESSAGE) + .fetch_all(&self.pool) + .await?; + + let mut recovery = super::StaleJobRecovery::default(); + for row in rows { + let id: uuid::Uuid = row.get("id"); + let status: String = row.get("status"); + if status == "Dead" { + recovery.dead.push(id); + } else { + recovery.requeued.push(id); + } + } + + if !recovery.is_empty() { + tracing::warn!( + requeued = recovery.requeued.len(), + dead = recovery.dead.len(), + "Reclaimed stale Running jobs whose lease expired" + ); + } + + Ok(recovery) + } } // Helper method for enqueueing with an existing transaction diff --git a/src/queue/test.rs b/src/queue/test.rs index 8f6b357..a478384 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -258,6 +258,8 @@ struct TestStorage { job_results: HashMap>)>, /// Paused queues information paused_queues: HashMap, + /// Job leases: job_id -> (last heartbeat, lease expiry) + leases: HashMap, DateTime)>, /// Mock clock for time control clock: MockClock, } @@ -275,6 +277,7 @@ impl TestStorage { throttle_configs: HashMap::new(), job_results: HashMap::new(), paused_queues: HashMap::new(), + leases: HashMap::new(), clock, } } @@ -2459,6 +2462,68 @@ impl DatabaseQueue for TestQueue { let storage = self.storage.read().await; Ok(storage.paused_queues.values().cloned().collect()) } + + async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + let mut storage = self.storage.write().await; + let running = storage + .jobs + .get(&job_id) + .is_some_and(|job| job.status == JobStatus::Running); + if !running { + return Ok(false); + } + let now = storage.clock.now(); + storage + .leases + .insert(job_id, (now, super::saturating_add_to(now, lease))); + Ok(true) + } + + async fn requeue_stale_jobs( + &self, + older_than: std::time::Duration, + ) -> Result { + let mut storage = self.storage.write().await; + let now = storage.clock.now(); + let cutoff = super::saturating_sub_from(now, older_than); + + let stale: Vec<(JobId, bool)> = storage + .jobs + .values() + .filter(|job| job.status == JobStatus::Running) + .filter_map(|job| { + let started_at = job.started_at?; + let is_stale = match storage.leases.get(&job.id) { + Some((heartbeat, expires)) if *heartbeat >= started_at => *expires < now, + _ => started_at < cutoff, + }; + is_stale.then_some((job.id, job.attempts >= job.max_attempts)) + }) + .collect(); + + let mut recovery = super::StaleJobRecovery::default(); + for (job_id, exhausted) in stale { + storage.leases.remove(&job_id); + if exhausted { + storage.update_job_status(job_id, JobStatus::Dead)?; + if let Some(job) = storage.jobs.get_mut(&job_id) { + job.failed_at = Some(now); + job.error_message = Some(super::STALE_JOB_ERROR_MESSAGE.to_string()); + } + recovery.dead.push(job_id); + } else { + storage.update_job_status(job_id, JobStatus::Pending)?; + if let Some(job) = storage.jobs.get_mut(&job_id) { + job.scheduled_at = now; + job.started_at = None; + job.error_message = Some(super::STALE_JOB_ERROR_MESSAGE.to_string()); + } + recovery.requeued.push(job_id); + } + } + + Ok(recovery) + } } #[cfg(test)] @@ -2790,4 +2855,72 @@ mod tests { assert_eq!(stats.statistics.dead, 1); // One job marked as dead assert_eq!(stats.statistics.total_processed, 3); // 2 completed + 1 dead } + + #[tokio::test] + async fn test_requeue_stale_jobs_uses_leases_and_fallback() { + let queue = TestQueue::new(); + let clock = queue.clock(); + + let leased = queue + .enqueue(Job::new("stale".to_string(), json!({"n": 1}))) + .await + .unwrap(); + let unleased = queue + .enqueue(Job::new("stale".to_string(), json!({"n": 2}))) + .await + .unwrap(); + let exhausted = queue + .enqueue(Job::new("stale".to_string(), json!({"n": 3})).with_max_attempts(0)) + .await + .unwrap(); + for _ in 0..3 { + queue.dequeue("stale").await.unwrap().unwrap(); + } + assert!( + queue + .heartbeat_job(leased, std::time::Duration::from_secs(30)) + .await + .unwrap() + ); + + // Nothing is stale yet. + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(600)) + .await + .unwrap(); + assert!(recovery.is_empty()); + + // After 60s the lease has expired but the 600s fallback has not. + clock.advance(chrono::Duration::seconds(60)); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(600)) + .await + .unwrap(); + assert_eq!(recovery.requeued, vec![leased]); + assert!(recovery.dead.is_empty()); + + // After the fallback window the un-leased jobs are reclaimed too. + clock.advance(chrono::Duration::seconds(600)); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(600)) + .await + .unwrap(); + assert_eq!(recovery.requeued, vec![unleased]); + assert_eq!(recovery.dead, vec![exhausted]); + + let job = queue.get_job(leased).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Pending); + assert_eq!( + queue.get_job(exhausted).await.unwrap().unwrap().status, + JobStatus::Dead + ); + + // A heartbeat for a job that is no longer Running reports a lost lease. + assert!( + !queue + .heartbeat_job(exhausted, std::time::Duration::from_secs(30)) + .await + .unwrap() + ); + } } diff --git a/src/retry.rs b/src/retry.rs index 286444a..4bcd7a9 100644 --- a/src/retry.rs +++ b/src/retry.rs @@ -51,6 +51,7 @@ use rand::Rng; use serde::{Deserialize, Serialize}; +use std::sync::Arc; use std::time::Duration; /// Types of jitter that can be applied to retry delays. @@ -119,15 +120,20 @@ impl JitterType { // Randomly add or subtract jitter if rng.gen_bool(0.5) { - delay + jitter + delay.saturating_add(jitter) } else { delay.saturating_sub(jitter) } } JitterType::Multiplicative(factor) => { + // A NaN, infinite, zero or negative factor means "no jitter"; factors + // above 1.0 are clamped so the lower bound never goes negative. + if !factor.is_finite() || *factor <= 0.0 { + return delay; + } + let factor = factor.min(1.0); let jitter_factor = rng.gen_range((1.0 - factor)..=(1.0 + factor)); - let jittered_millis = (delay.as_millis() as f64 * jitter_factor) as u64; - Duration::from_millis(jittered_millis) + saturating_mul_f64(delay, jitter_factor) } } } @@ -417,8 +423,10 @@ pub enum RetryStrategy { /// use hammerwork::retry::RetryStrategy; /// use std::time::Duration; /// + /// use std::sync::Arc; + /// /// // Custom strategy: short delays for first few attempts, then longer - /// let strategy = RetryStrategy::Custom(Box::new(|attempt| { + /// let strategy = RetryStrategy::Custom(Arc::new(|attempt| { /// if attempt <= 3 { /// Duration::from_secs(5) // Quick retries for transient issues /// } else if attempt <= 6 { @@ -432,7 +440,11 @@ pub enum RetryStrategy { /// assert_eq!(strategy.calculate_delay(4), Duration::from_secs(60)); /// assert_eq!(strategy.calculate_delay(7), Duration::from_secs(300)); /// ``` - Custom(Box Duration + Send + Sync>), + /// + /// The function is reference-counted so that cloning a strategy (for example when a + /// [`Worker`](crate::Worker) is cloned for autoscaling) is cheap and never fails. + /// Prefer the [`RetryStrategy::custom`] constructor, which wraps the closure for you. + Custom(CustomRetryFn), } impl RetryStrategy { @@ -465,6 +477,9 @@ impl RetryStrategy { /// assert_eq!(strategy.calculate_delay(4), Duration::from_secs(8)); /// ``` pub fn calculate_delay(&self, attempt: u32) -> Duration { + // All arithmetic below saturates instead of panicking: huge attempt numbers, + // huge bases and invalid multipliers (NaN, negative) all produce a bounded + // delay, clamped to `max_delay` when one is configured. let base_delay = match self { RetryStrategy::Fixed(delay) => *delay, @@ -473,12 +488,8 @@ impl RetryStrategy { increment, max_delay, } => { - let delay = *base + increment.mul_f64(attempt as f64); - if let Some(max) = max_delay { - delay.min(*max) - } else { - delay - } + let step = increment.checked_mul(attempt).unwrap_or(Duration::MAX); + cap_delay(base.saturating_add(step), *max_delay) } RetryStrategy::Exponential { @@ -487,17 +498,15 @@ impl RetryStrategy { max_delay, jitter, } => { - let delay_multiplier = multiplier.powi((attempt.saturating_sub(1)) as i32); - let delay = base.mul_f64(delay_multiplier); - - let capped_delay = if let Some(max) = max_delay { - delay.min(*max) - } else { - delay - }; + let exponent = attempt.saturating_sub(1).min(i32::MAX as u32) as i32; + let delay_multiplier = sanitize_multiplier(*multiplier).powi(exponent); + let capped_delay = + cap_delay(saturating_mul_f64(*base, delay_multiplier), *max_delay); if let Some(jitter_type) = jitter { - return jitter_type.apply(capped_delay); + return jitter_type + .apply(capped_delay) + .max(Duration::from_millis(1)); } capped_delay @@ -505,13 +514,7 @@ impl RetryStrategy { RetryStrategy::Fibonacci { base, max_delay } => { let fib_number = fibonacci(attempt); - let delay = base.mul_f64(fib_number as f64); - - if let Some(max) = max_delay { - delay.min(*max) - } else { - delay - } + cap_delay(saturating_mul_f64(*base, fib_number as f64), *max_delay) } RetryStrategy::Custom(func) => func(attempt), @@ -521,6 +524,46 @@ impl RetryStrategy { base_delay.max(Duration::from_millis(1)) } + /// Check that the strategy's parameters are sensible. + /// + /// [`calculate_delay`](Self::calculate_delay) never panics, even for invalid + /// parameters (a NaN or negative multiplier is treated as `1.0`), but such values + /// are almost certainly configuration mistakes. Call this when loading a strategy + /// from configuration to surface them early. + /// + /// # Examples + /// + /// ```rust + /// use hammerwork::retry::RetryStrategy; + /// use std::time::Duration; + /// + /// assert!(RetryStrategy::exponential(Duration::from_secs(1), 2.0, None).validate().is_ok()); + /// assert!(RetryStrategy::exponential(Duration::from_secs(1), f64::NAN, None).validate().is_err()); + /// ``` + pub fn validate(&self) -> crate::Result<()> { + let invalid = |message: String| crate::HammerworkError::Worker { message }; + match self { + RetryStrategy::Exponential { + multiplier, jitter, .. + } => { + if !multiplier.is_finite() || *multiplier <= 0.0 { + return Err(invalid(format!( + "exponential retry multiplier must be finite and > 0, got {multiplier}" + ))); + } + if let Some(JitterType::Multiplicative(factor)) = jitter { + if !factor.is_finite() || !(0.0..=1.0).contains(factor) { + return Err(invalid(format!( + "multiplicative jitter factor must be within 0.0..=1.0, got {factor}" + ))); + } + } + Ok(()) + } + _ => Ok(()), + } + } + /// Create a fixed delay retry strategy. /// /// # Arguments @@ -678,7 +721,38 @@ impl RetryStrategy { where F: Fn(u32) -> Duration + Send + Sync + 'static, { - RetryStrategy::Custom(Box::new(func)) + RetryStrategy::Custom(Arc::new(func)) + } +} + +/// The function type stored by [`RetryStrategy::Custom`]. +pub type CustomRetryFn = Arc Duration + Send + Sync>; + +/// Replace a NaN or negative exponential multiplier with `1.0` (constant delay). +fn sanitize_multiplier(multiplier: f64) -> f64 { + if multiplier.is_nan() || multiplier < 0.0 { + 1.0 + } else { + multiplier + } +} + +/// Multiply a duration by a float without panicking. +/// +/// Non-positive and NaN factors yield zero; results too large for a `Duration` +/// (including an infinite factor) saturate to `Duration::MAX`. +fn saturating_mul_f64(delay: Duration, factor: f64) -> Duration { + if factor.is_nan() || factor <= 0.0 { + return Duration::ZERO; + } + Duration::try_from_secs_f64(delay.as_secs_f64() * factor).unwrap_or(Duration::MAX) +} + +/// Clamp a delay to an optional maximum. +fn cap_delay(delay: Duration, max_delay: Option) -> Duration { + match max_delay { + Some(max) => delay.min(max), + None => delay, } } @@ -793,9 +867,7 @@ impl Clone for RetryStrategy { base: *base, max_delay: *max_delay, }, - RetryStrategy::Custom(_) => { - panic!("Cannot clone custom retry strategy functions") - } + RetryStrategy::Custom(func) => RetryStrategy::Custom(Arc::clone(func)), } } } @@ -840,7 +912,8 @@ impl PartialEq for RetryStrategy { max_delay: b_max, }, ) => a_base == b_base && a_max == b_max, - (RetryStrategy::Custom(_), RetryStrategy::Custom(_)) => false, // Custom functions can't be compared + // Closures can't be compared; two strategies sharing the same function are equal. + (RetryStrategy::Custom(a), RetryStrategy::Custom(b)) => Arc::ptr_eq(a, b), _ => false, } } @@ -1128,7 +1201,7 @@ mod tests { #[test] fn test_custom_retry_strategy() { - let strategy = RetryStrategy::Custom(Box::new(|attempt| match attempt { + let strategy = RetryStrategy::Custom(Arc::new(|attempt| match attempt { 1..=3 => Duration::from_secs(5), 4..=6 => Duration::from_secs(30), _ => Duration::from_secs(300), @@ -1212,7 +1285,7 @@ mod tests { #[test] fn test_minimum_delay_enforcement() { // Test that zero delays are converted to 1ms minimum - let strategy = RetryStrategy::Custom(Box::new(|_| Duration::from_millis(0))); + let strategy = RetryStrategy::Custom(Arc::new(|_| Duration::from_millis(0))); assert_eq!(strategy.calculate_delay(1), Duration::from_millis(1)); } @@ -1249,4 +1322,121 @@ mod tests { } } } + + #[test] + fn test_exponential_huge_attempt_saturates_instead_of_panicking() { + let uncapped = RetryStrategy::exponential(Duration::from_secs(1), 2.0, None); + assert_eq!(uncapped.calculate_delay(65), Duration::MAX); + assert_eq!(uncapped.calculate_delay(u32::MAX), Duration::MAX); + + let capped = + RetryStrategy::exponential(Duration::from_secs(1), 2.0, Some(Duration::from_secs(600))); + assert_eq!(capped.calculate_delay(1_000), Duration::from_secs(600)); + assert_eq!(capped.calculate_delay(u32::MAX), Duration::from_secs(600)); + } + + #[test] + fn test_exponential_invalid_multipliers_do_not_panic() { + for multiplier in [f64::NAN, -2.0, -0.5] { + let strategy = RetryStrategy::exponential(Duration::from_secs(3), multiplier, None); + // Invalid multipliers are treated as 1.0 (constant delay). + assert_eq!(strategy.calculate_delay(1), Duration::from_secs(3)); + assert_eq!(strategy.calculate_delay(50), Duration::from_secs(3)); + assert!(strategy.validate().is_err()); + } + + let infinite = RetryStrategy::exponential( + Duration::from_secs(1), + f64::INFINITY, + Some(Duration::from_secs(60)), + ); + assert_eq!(infinite.calculate_delay(2), Duration::from_secs(60)); + assert!(infinite.validate().is_err()); + + let zero = RetryStrategy::exponential(Duration::from_secs(1), 0.0, None); + assert_eq!(zero.calculate_delay(5), Duration::from_millis(1)); + + assert!( + RetryStrategy::exponential(Duration::from_secs(1), 2.0, None) + .validate() + .is_ok() + ); + } + + #[test] + fn test_jitter_with_invalid_factors_does_not_panic() { + let base = Duration::from_secs(10); + for factor in [f64::NAN, -1.0, f64::INFINITY, 0.0] { + assert_eq!(JitterType::Multiplicative(factor).apply(base), base); + } + // Factors above 1.0 are clamped to 1.0: the result stays within [0, 2 * base]. + for _ in 0..50 { + let jittered = JitterType::Multiplicative(5.0).apply(base); + assert!(jittered <= base * 2); + } + // Additive jitter on a huge delay saturates instead of overflowing. + for _ in 0..50 { + let jittered = JitterType::Additive(Duration::from_secs(5)).apply(Duration::MAX); + assert!(jittered >= Duration::MAX - Duration::from_secs(5)); + } + let strategy = RetryStrategy::exponential_with_jitter( + Duration::from_secs(1), + 2.0, + None, + JitterType::Multiplicative(0.1), + ); + assert!(strategy.calculate_delay(u32::MAX) > Duration::from_secs(1)); + assert!( + RetryStrategy::exponential_with_jitter( + Duration::from_secs(1), + 2.0, + None, + JitterType::Multiplicative(2.0), + ) + .validate() + .is_err() + ); + } + + #[test] + fn test_fibonacci_huge_attempt_saturates() { + let uncapped = RetryStrategy::fibonacci(Duration::from_secs(2), None); + assert_eq!(uncapped.calculate_delay(200), Duration::MAX); + let capped = + RetryStrategy::fibonacci(Duration::from_secs(2), Some(Duration::from_secs(300))); + assert_eq!( + capped.calculate_delay(u32::MAX - 1), + Duration::from_secs(300) + ); + } + + #[test] + fn test_linear_overflow_saturates() { + let strategy = RetryStrategy::linear(Duration::MAX, Duration::from_secs(1), None); + assert_eq!(strategy.calculate_delay(10), Duration::MAX); + let strategy = RetryStrategy::linear( + Duration::from_secs(1), + Duration::from_secs(u64::MAX / 2), + Some(Duration::from_secs(120)), + ); + assert_eq!(strategy.calculate_delay(u32::MAX), Duration::from_secs(120)); + } + + #[test] + fn test_custom_strategy_clone_is_total_and_shares_function() { + let strategy = RetryStrategy::custom(|attempt| Duration::from_secs(attempt as u64 * 7)); + let cloned = strategy.clone(); + assert_eq!(cloned.calculate_delay(3), Duration::from_secs(21)); + assert_eq!(strategy, cloned); + assert_ne!(strategy, RetryStrategy::custom(|_| Duration::from_secs(1))); + assert!(strategy.validate().is_ok()); + + // Cloning through Option, as Worker::clone does, must not panic either. + let as_option = Some(strategy); + let cloned_option = as_option.clone(); + assert_eq!( + cloned_option.unwrap().calculate_delay(1), + Duration::from_secs(7) + ); + } } diff --git a/src/webhooks.rs b/src/webhooks.rs index 903c93c..cc664d5 100644 --- a/src/webhooks.rs +++ b/src/webhooks.rs @@ -866,16 +866,7 @@ impl WebhookManager { // Read response body let response_body = match response.text().await { - Ok(body) => { - if body.len() > config.max_response_body_size { - Some(format!( - "{}... [truncated]", - &body[..config.max_response_body_size] - )) - } else { - Some(body) - } - } + Ok(body) => Some(truncate_response_body(body, config.max_response_body_size)), Err(_) => None, }; @@ -1164,6 +1155,22 @@ pub fn verify_hmac_signature(secret: &str, payload: &[u8], signature: &str) -> b && expected.bytes().zip(signature.bytes()).all(|(a, b)| a == b) } +/// Truncate a webhook response body to at most `max_bytes` bytes (plus a marker). +/// +/// The response comes from a remote endpoint, so the cut point can fall inside a +/// multi-byte UTF-8 character. Back up to the nearest character boundary instead of +/// slicing at the raw byte offset, which would panic. +fn truncate_response_body(body: String, max_bytes: usize) -> String { + if body.len() <= max_bytes { + return body; + } + let mut end = max_bytes; + while !body.is_char_boundary(end) { + end -= 1; + } + format!("{}... [truncated]", &body[..end]) +} + #[cfg(test)] mod tests { use super::*; @@ -1669,4 +1676,21 @@ mod tests { assert_eq!(stats.successful_deliveries, 8); assert!((stats.success_rate - 8.0 / 11.0).abs() < f64::EPSILON); } + + #[test] + fn test_truncate_response_body_respects_utf8_boundaries() { + // Short bodies are returned unchanged. + assert_eq!(truncate_response_body("ok".to_string(), 10), "ok"); + + // "é" is 2 bytes and "😀" is 4; cutting inside either must not panic. + let body = "aé😀b".to_string(); // bytes: a(1) é(2) 😀(4) b(1) = 8 + assert_eq!(truncate_response_body(body.clone(), 2), "a... [truncated]"); + assert_eq!(truncate_response_body(body.clone(), 3), "aé... [truncated]"); + for max in 0..body.len() { + let truncated = truncate_response_body(body.clone(), max); + assert!(truncated.ends_with("... [truncated]")); + assert!(truncated.len() <= max + "... [truncated]".len()); + } + assert_eq!(truncate_response_body(body.clone(), body.len()), body); + } } diff --git a/src/worker.rs b/src/worker.rs index 77b470b..b9a3fc2 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -28,10 +28,106 @@ use crate::events::{EventManager, JobError, JobLifecycleEvent, JobLifecycleEvent use chrono::{DateTime, Utc}; use sqlx::Database; -use std::{sync::Arc, time::Duration}; -use tokio::{sync::mpsc, time::sleep}; +use std::{ + future::Future, + panic::AssertUnwindSafe, + pin::Pin, + sync::Arc, + task::{Context, Poll}, + time::Duration, +}; +use tokio::{ + sync::{mpsc, watch}, + task::JoinSet, + time::sleep, +}; use tracing::{debug, error, info, warn}; +/// Default time a worker waits for an in-flight job to finish after shutdown is requested. +pub const DEFAULT_SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(30); + +/// Default lease a worker holds on a running job. The worker renews it every third of +/// this period; if the worker dies, the job becomes eligible for +/// [`DatabaseQueue::requeue_stale_jobs`] once the lease expires. +pub const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(300); + +/// Default interval at which a [`WorkerPool`] runs the stale job reaper. +pub const DEFAULT_STALE_JOB_REAPER_INTERVAL: Duration = Duration::from_secs(60); + +/// Upper bound on a computed retry delay. Larger values (from a custom strategy or an +/// unbounded backoff) are clamped so the retry timestamp stays representable in both +/// databases. +pub const MAX_RETRY_DELAY: Duration = Duration::from_secs(365 * 24 * 60 * 60); + +/// Cap on the exponential backoff applied after consecutive worker loop errors. +const MAX_ERROR_BACKOFF: Duration = Duration::from_secs(60); + +/// Floor on the error backoff so a zero poll interval can never cause a hot loop. +const MIN_ERROR_BACKOFF: Duration = Duration::from_millis(100); + +/// Floor on the heartbeat interval derived from the lease duration. +const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(100); + +/// Delay before a [`WorkerPool`] restarts a worker that died unexpectedly. +const WORKER_RESTART_DELAY: Duration = Duration::from_secs(1); + +type HandlerFuture = Pin> + Send>>; + +/// Future adapter that turns a panic during `poll` into an `Err` carrying the payload. +struct CatchUnwind { + inner: F, +} + +impl Future for CatchUnwind { + type Output = std::thread::Result; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let inner = &mut self.inner; + match std::panic::catch_unwind(AssertUnwindSafe(|| Pin::new(&mut *inner).poll(cx))) { + Ok(Poll::Pending) => Poll::Pending, + Ok(Poll::Ready(output)) => Poll::Ready(Ok(output)), + Err(payload) => Poll::Ready(Err(payload)), + } + } +} + +/// Describe a panic payload for an error message. +fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { + if let Some(message) = payload.downcast_ref::<&str>() { + (*message).to_string() + } else if let Some(message) = payload.downcast_ref::() { + message.clone() + } else { + "non-string panic payload".to_string() + } +} + +/// Build the error used when a job handler panics. +fn handler_panic_error(payload: &(dyn std::any::Any + Send)) -> HammerworkError { + HammerworkError::Worker { + message: format!("Job handler panicked: {}", panic_message(payload)), + } +} + +/// Convert a retry delay into the timestamp at which the job should run again. +/// +/// The delay is clamped to [`MAX_RETRY_DELAY`] and the conversion never panics. +fn retry_at_from_delay(now: DateTime, retry_delay: Duration) -> DateTime { + let delay = chrono::Duration::from_std(retry_delay.min(MAX_RETRY_DELAY)) + .unwrap_or(chrono::Duration::MAX); + now.checked_add_signed(delay) + .unwrap_or(DateTime::::MAX_UTC) +} + +/// Exponential backoff after `consecutive_errors` failed loop iterations. +fn error_backoff(base: Duration, consecutive_errors: u32) -> Duration { + let base = base.max(MIN_ERROR_BACKOFF); + let exponent = consecutive_errors.saturating_sub(1).min(16); + base.checked_mul(1u32 << exponent) + .unwrap_or(MAX_ERROR_BACKOFF) + .min(MAX_ERROR_BACKOFF.max(base)) +} + /// Event data for job lifecycle event hooks. #[derive(Debug, Clone)] pub struct JobHookEvent { @@ -609,6 +705,10 @@ pub struct Worker { /// Event manager for publishing job lifecycle events #[cfg(feature = "webhooks")] event_manager: Option>, + /// How long to wait for an in-flight job to finish after shutdown is requested + shutdown_grace_period: Duration, + /// Lease held on a running job, renewed by heartbeats + lease_duration: Duration, } impl Clone for Worker @@ -641,6 +741,8 @@ where spawn_manager: self.spawn_manager.clone(), #[cfg(feature = "webhooks")] event_manager: self.event_manager.clone(), + shutdown_grace_period: self.shutdown_grace_period, + lease_duration: self.lease_duration, } } } @@ -720,6 +822,8 @@ where spawn_manager: None, #[cfg(feature = "webhooks")] event_manager: None, + shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, + lease_duration: DEFAULT_LEASE_DURATION, } } @@ -791,6 +895,8 @@ where spawn_manager: None, #[cfg(feature = "webhooks")] event_manager: None, + shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, + lease_duration: DEFAULT_LEASE_DURATION, } } @@ -999,6 +1105,56 @@ where self } + /// Set how long the worker waits for an in-flight job after shutdown is requested. + /// + /// When [`WorkerPool::shutdown`] (or the worker's shutdown channel) fires while a + /// job is running, the worker stops polling but lets the job finish for up to this + /// long. Only after the grace period is the handler cancelled; the job then stays + /// `Running` until its lease expires and the stale job reaper reclaims it. + /// + /// Defaults to [`DEFAULT_SHUTDOWN_GRACE_PERIOD`] (30 seconds). + /// + /// # Examples + /// + /// ```rust,no_run + /// use hammerwork::{Worker, JobQueue}; + /// use std::{sync::Arc, time::Duration}; + /// + /// # async fn example() -> Result<(), Box> { + /// # let pool = sqlx::PgPool::connect("postgresql://localhost/test").await?; + /// # let queue = Arc::new(JobQueue::new(pool)); + /// # let handler: hammerwork::worker::JobHandler = Arc::new(|_job| Box::pin(async { Ok(()) })); + /// let worker = Worker::new(queue, "emails".to_string(), handler) + /// .with_shutdown_grace_period(Duration::from_secs(120)); + /// # Ok(()) + /// # } + /// ``` + pub fn with_shutdown_grace_period(mut self, grace_period: Duration) -> Self { + self.shutdown_grace_period = grace_period; + self + } + + /// Set the lease the worker holds on a running job. + /// + /// While a handler runs, the worker records a heartbeat and extends the job's 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. Shorter + /// leases recover crashed jobs faster at the cost of more heartbeat writes for + /// long-running jobs; jobs that finish within a third of the lease never write one. + /// + /// Defaults to [`DEFAULT_LEASE_DURATION`] (5 minutes). Requires migration + /// `015_add_job_leases`. + pub fn with_lease_duration(mut self, lease: Duration) -> Self { + self.lease_duration = lease; + self + } + + /// The lease this worker holds on running jobs. See [`Worker::with_lease_duration`]. + pub fn lease_duration(&self) -> Duration { + self.lease_duration + } + /// Apply a [`WorkerConfig`](crate::config::WorkerConfig). /// /// Sets the poll interval, default job timeout, priority weights and default retry @@ -1410,6 +1566,19 @@ where self } + /// Run the worker until a shutdown signal arrives on `shutdown_rx` (or its sender + /// is dropped). + /// + /// Shutdown is graceful: while idle the worker stops immediately, but a job that is + /// already running gets up to the configured + /// [shutdown grace period](Worker::with_shutdown_grace_period) to finish and record + /// its outcome before it is cancelled. + /// + /// Errors inside the loop (database failures while dequeuing or recording a job's + /// outcome) are logged and followed by an exponential backoff starting at the + /// throttle's `backoff_on_error` (or the poll interval), so a failing database never + /// causes a hot loop. A panicking job handler fails the job instead of killing the + /// worker. pub async fn run(&self, mut shutdown_rx: mpsc::Receiver<()>) -> Result<()> { info!("Worker started for queue: {}", self.queue_name); @@ -1417,16 +1586,55 @@ where #[cfg(any(feature = "metrics", feature = "alerting"))] let monitoring_task = self.start_monitoring_task(); + let mut consecutive_errors: u32 = 0; + loop { - tokio::select! { + // Idle phase: polling (and the sleeps between polls) is cancelled promptly + // when shutdown is requested. + let acquired = tokio::select! { + biased; _ = shutdown_rx.recv() => { info!("Worker shutting down for queue: {}", self.queue_name); break; } - _ = self.process_jobs() => { - // Continue processing + acquired = self.acquire_job() => acquired, + }; + + let (outcome, shutting_down) = match acquired { + Ok(Some(job)) => self.run_job_until_done(job, &mut shutdown_rx).await, + Ok(None) => (Ok(()), false), + Err(e) => { + error!("Error dequeuing job from queue {}: {}", self.queue_name, e); + (Err(e), false) + } + }; + + match outcome { + Ok(()) => consecutive_errors = 0, + Err(e) => { + consecutive_errors = consecutive_errors.saturating_add(1); + if !shutting_down { + let backoff = error_backoff(self.error_backoff_base(), consecutive_errors); + warn!( + "Worker for queue {} hit an error ({} in a row), backing off for {:?}: {}", + self.queue_name, consecutive_errors, backoff, e + ); + tokio::select! { + biased; + _ = shutdown_rx.recv() => { + info!("Worker shutting down for queue: {}", self.queue_name); + break; + } + _ = sleep(backoff) => {} + } + } } } + + if shutting_down { + info!("Worker shutting down for queue: {}", self.queue_name); + break; + } } // Stop monitoring task @@ -1436,7 +1644,73 @@ where Ok(()) } - async fn process_jobs(&self) -> Result<()> { + /// Process `job` to completion. If shutdown is requested meanwhile, keep going for + /// up to the shutdown grace period, then cancel. + /// + /// Returns the processing outcome and whether shutdown was requested. + async fn run_job_until_done( + &self, + job: Job, + shutdown_rx: &mut mpsc::Receiver<()>, + ) -> (Result<()>, bool) { + let job_id = job.id; + let processing = self.process_job(job); + tokio::pin!(processing); + + let outcome = tokio::select! { + biased; + outcome = &mut processing => return (self.log_process_outcome(job_id, outcome), false), + _ = shutdown_rx.recv() => { + info!( + "Shutdown requested while job {} is running; waiting up to {:?} for it to finish", + job_id, self.shutdown_grace_period + ); + tokio::time::timeout(self.shutdown_grace_period, &mut processing).await + } + }; + + match outcome { + Ok(outcome) => (self.log_process_outcome(job_id, outcome), true), + Err(_) => { + warn!( + "Job {} did not finish within the {:?} shutdown grace period and was \ + cancelled; it stays Running until its lease expires and the stale job \ + reaper reclaims it", + job_id, self.shutdown_grace_period + ); + (Ok(()), true) + } + } + } + + fn log_process_outcome(&self, job_id: crate::job::JobId, outcome: Result<()>) -> Result<()> { + if let Err(ref e) = outcome { + error!( + "Failed to record the outcome of job {} on queue {}: {}", + job_id, self.queue_name, e + ); + } + outcome + } + + /// Base delay for the error backoff: the throttle's `backoff_on_error` if set, + /// otherwise the poll interval. + fn error_backoff_base(&self) -> Duration { + self.throttle_config + .as_ref() + .and_then(|throttle| throttle.backoff_on_error) + .unwrap_or(self.poll_interval) + } + + /// Wait for capacity and try to dequeue a job. + /// + /// Returns `Ok(None)` after sleeping for the poll interval when the queue is empty + /// or paused, and `Err` when the dequeue itself fails. + async fn acquire_job(&self) -> Result> { + // Check statistics and alert thresholds periodically + #[cfg(feature = "alerting")] + self.check_alert_thresholds().await; + // Check rate limit before dequeuing jobs if let Some(ref rate_limiter) = self.rate_limiter { // Check if we can process a job (non-blocking) @@ -1449,7 +1723,7 @@ where if let Err(e) = rate_limiter.acquire().await { warn!("Rate limiter error: {}", e); sleep(self.poll_interval).await; - return Ok(()); + return Ok(None); } } } @@ -1462,7 +1736,7 @@ where self.queue_name ); sleep(self.poll_interval).await; - return Ok(()); + return Ok(None); } Ok(false) => { // Queue is not paused, continue with normal processing @@ -1486,25 +1760,25 @@ where } } - let job_result = if let Some(ref weights) = self.priority_weights { + let job = if let Some(ref weights) = self.priority_weights { // Use priority-aware dequeuing self.queue .dequeue_with_priority_weights(&self.queue_name, weights) - .await + .await? } else { // Use regular dequeuing - self.queue.dequeue(&self.queue_name).await + self.queue.dequeue(&self.queue_name).await? }; - match job_result { - Ok(Some(job)) => { + match job { + Some(job) => { debug!( "Processing job: {} with priority: {:?}", job.id, job.priority ); - self.process_job(job).await?; + Ok(Some(job)) } - Ok(None) => { + None => { // No jobs available, check for worker starvation #[cfg(feature = "alerting")] if let Some(alert_manager) = &self.alert_manager { @@ -1527,25 +1801,13 @@ where // Wait before polling again sleep(self.poll_interval).await; - } - Err(e) => { - error!("Error dequeuing job: {}", e); - - // If throttle config specifies backoff on error, apply it - let backoff_duration = if let Some(ref throttle_config) = self.throttle_config { - throttle_config - .backoff_on_error - .unwrap_or(self.poll_interval) - } else { - self.poll_interval - }; - - sleep(backoff_duration).await; + Ok(None) } } + } - // Check statistics and alert thresholds periodically - #[cfg(feature = "alerting")] + #[cfg(feature = "alerting")] + async fn check_alert_thresholds(&self) { if let (Some(alert_manager), Some(stats_collector)) = (&self.alert_manager, &self.stats_collector) { @@ -1566,8 +1828,6 @@ where } } } - - Ok(()) } async fn process_job(&self, job: Job) -> Result<()> { @@ -1882,8 +2142,7 @@ where self.retry_delay }; - let retry_at = - chrono::Utc::now() + chrono::Duration::from_std(retry_delay).unwrap(); + let retry_at = retry_at_from_delay(Utc::now(), retry_delay); info!( "Retrying job {} at {} (attempt {} of {})", job_id, @@ -1915,16 +2174,74 @@ where Ok(()) } - /// Execute a job handler based on its type, returning a unified result - async fn execute_handler(&self, job: Job) -> Result { + /// Create the handler future for `job`, unifying both handler types. + fn start_handler(&self, job: Job) -> HandlerFuture { match &self.handler { JobHandlerType::Legacy(handler) => { // Execute legacy handler and convert () to JobResult - handler(job).await.map(|_| JobResult::success()) + let future = handler(job); + Box::pin(async move { future.await.map(|_| JobResult::success()) }) } - JobHandlerType::WithResult(handler) => { - // Execute enhanced handler directly - handler(job).await + // Execute enhanced handler directly + JobHandlerType::WithResult(handler) => handler(job), + } + } + + /// Execute a job handler, returning a unified result. + /// + /// A panic in the handler (while creating or polling its future) is caught and + /// turned into an error, so the job goes through the normal retry/failure path + /// instead of killing the worker. While the handler runs, the job's lease is + /// renewed in the background. + async fn execute_handler(&self, job: Job) -> Result { + let job_id = job.id; + let handler_future = + match std::panic::catch_unwind(AssertUnwindSafe(|| self.start_handler(job))) { + Ok(future) => future, + Err(payload) => { + error!("Handler for job {} panicked", job_id); + return Err(handler_panic_error(payload.as_ref())); + } + }; + + let guarded = CatchUnwind { + inner: handler_future, + }; + + tokio::select! { + biased; + outcome = guarded => outcome.unwrap_or_else(|payload| { + error!("Handler for job {} panicked", job_id); + Err(handler_panic_error(payload.as_ref())) + }), + () = self.maintain_lease(job_id) => Err(HammerworkError::Worker { + message: "job lease heartbeat stopped unexpectedly".to_string(), + }), + } + } + + /// Renew the lease on a running job until the surrounding future is dropped. + /// + /// Heartbeats every third of the lease duration; the first one is sent after that + /// interval, so short jobs never pay for a heartbeat write. Never completes. + async fn maintain_lease(&self, job_id: crate::job::JobId) { + if self.lease_duration.is_zero() { + return std::future::pending().await; + } + let interval = (self.lease_duration / 3).max(MIN_HEARTBEAT_INTERVAL); + loop { + sleep(interval).await; + match self.queue.heartbeat_job(job_id, self.lease_duration).await { + Ok(true) => debug!("Renewed lease on job {}", job_id), + Ok(false) => { + warn!( + "Lost the lease on job {}: it is no longer Running (it may have been \ + reclaimed as stale); the handler keeps running", + job_id + ); + return std::future::pending().await; + } + Err(e) => warn!("Failed to renew the lease on job {}: {}", job_id, e), } } } @@ -2191,9 +2508,28 @@ where } } +/// A pool of [`Worker`]s run and supervised together. +/// +/// [`WorkerPool::start`] spawns every worker plus a supervisor. A worker that dies +/// unexpectedly (for example because of a bug that panics outside a job handler) is +/// logged and restarted. [`WorkerPool::shutdown`] (or dropping the pool) stops all +/// workers gracefully: each finishes its in-flight job within its shutdown grace period. +/// +/// The pool also runs a stale job reaper that periodically calls +/// [`DatabaseQueue::requeue_stale_jobs`] to reclaim jobs left `Running` by workers +/// that crashed. Configure it with [`WorkerPool::with_stale_job_reaper`] or disable it +/// with [`WorkerPool::without_stale_job_reaper`]. pub struct WorkerPool { workers: Vec>, - shutdown_tx: Vec>, + /// Signals shutdown to the supervisor started by `start` (dropping it also does) + shutdown_signal: Option>, + /// Becomes `true` once every worker has stopped after a shutdown + supervisor_done: Option>, + /// How often the stale job reaper runs (`None` disables it) + reaper_interval: Option, + /// Fallback staleness threshold for jobs without a lease (`None`: the longest + /// worker lease duration) + reaper_older_than: Option, stats_collector: Option>, /// Worker template for creating new workers during autoscaling worker_template: Option>, @@ -2214,7 +2550,10 @@ where pub fn new() -> Self { Self { workers: Vec::new(), - shutdown_tx: Vec::new(), + shutdown_signal: None, + supervisor_done: None, + reaper_interval: Some(DEFAULT_STALE_JOB_REAPER_INTERVAL), + reaper_older_than: None, stats_collector: None, worker_template: None, autoscale_config: AutoscaleConfig::default(), @@ -2258,6 +2597,30 @@ where self } + /// Configure the stale job reaper. + /// + /// Every `interval` the pool calls + /// [`DatabaseQueue::requeue_stale_jobs`]`(older_than)`, which moves `Running` jobs + /// whose lease expired back to `Pending` (or to `Dead` when they have no attempts + /// left). `older_than` only applies to jobs that never recorded a lease; by default + /// it is the longest [lease duration](Worker::with_lease_duration) of the pool's + /// workers. The reaper is enabled by default with a 60 second interval. + /// + /// Requires migration `015_add_job_leases`. Running reapers in several pools or + /// processes at once is safe. + pub fn with_stale_job_reaper(mut self, interval: Duration, older_than: Duration) -> Self { + self.reaper_interval = Some(interval); + self.reaper_older_than = Some(older_than); + self + } + + /// Disable the stale job reaper (for example when it runs elsewhere, such as a + /// scheduled `cargo hammerwork job requeue-stale`). + pub fn without_stale_job_reaper(mut self) -> Self { + self.reaper_interval = None; + self + } + /// Set a worker template for autoscaling /// This worker will be cloned when creating new workers pub fn with_worker_template(mut self, worker: Worker) -> Self { @@ -2282,6 +2645,12 @@ where self.workers.push(worker); } + /// Start all workers and supervise them until the pool shuts down. + /// + /// Returns once every worker has stopped after [`WorkerPool::shutdown`] (or after + /// the pool is dropped). Workers run in their own tasks, so dropping the returned + /// future (for example in a `tokio::select!`) does not stop them; call + /// [`WorkerPool::shutdown`] afterwards to stop them gracefully. pub async fn start(&mut self) -> Result<()> { info!("Starting worker pool with {} workers", self.workers.len()); @@ -2290,36 +2659,171 @@ where metrics.active_workers = self.workers.len(); } - let mut handles = Vec::new(); - self.shutdown_tx.clear(); - - for worker in self.workers.drain(..) { - let (shutdown_tx, shutdown_rx) = mpsc::channel(1); - self.shutdown_tx.push(shutdown_tx); + let (signal_tx, signal_rx) = watch::channel(false); + let (done_tx, done_rx) = watch::channel(false); + self.shutdown_signal = Some(signal_tx); + self.supervisor_done = Some(done_rx); - let handle = tokio::spawn(async move { - if let Err(e) = worker.run(shutdown_rx).await { - error!("Worker error: {}", e); - } - }); - handles.push(handle); - } + let workers = std::mem::take(&mut self.workers); + let reaper = self.start_stale_job_reaper(&workers, signal_rx.clone()); // Start autoscaling task if enabled if self.autoscale_config.enabled { self.start_autoscaling_task().await?; } - // Wait for all workers to complete - for handle in handles { - handle.await.map_err(|e| HammerworkError::Worker { - message: format!("Worker task failed: {}", e), - })?; + let supervisor = tokio::spawn(Self::supervise(workers, signal_rx, done_tx, reaper)); + + // Dropping a JoinHandle detaches the task, so the supervisor keeps running + // even if this future is dropped. + supervisor.await.map_err(|e| HammerworkError::Worker { + message: format!("Worker pool supervisor failed: {}", e), + })? + } + + /// Spawn one worker task with its own shutdown channel. + fn spawn_worker( + set: &mut JoinSet<(usize, std::thread::Result>)>, + index: usize, + worker: Worker, + delay: Option, + ) -> mpsc::Sender<()> { + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + set.spawn(async move { + if let Some(delay) = delay { + sleep(delay).await; + } + // Catch panics so the supervisor always knows which worker stopped. + let run = CatchUnwind { + inner: Box::pin(async move { worker.run(shutdown_rx).await }), + }; + (index, run.await) + }); + shutdown_tx + } + + /// Supervise worker tasks: restart workers that stop unexpectedly, and on + /// shutdown signal every worker and wait for all of them to stop. + async fn supervise( + workers: Vec>, + mut signal_rx: watch::Receiver, + done_tx: watch::Sender, + reaper: Option>, + ) -> Result<()> { + let templates: Vec> = workers.to_vec(); + let mut set = JoinSet::new(); + let mut senders: Vec> = workers + .into_iter() + .enumerate() + .map(|(index, worker)| Self::spawn_worker(&mut set, index, worker, None)) + .collect(); + + let mut shutting_down = *signal_rx.borrow(); + if shutting_down { + for tx in &senders { + let _ = tx.try_send(()); + } } + loop { + tokio::select! { + // An error means the pool (and its signal sender) was dropped: treat it + // as a shutdown request too. + _ = signal_rx.changed(), if !shutting_down => { + info!("Worker pool shutting down; waiting for in-flight jobs"); + shutting_down = true; + for tx in &senders { + let _ = tx.try_send(()); + } + } + joined = set.join_next() => { + let Some(joined) = joined else { break }; + let index = match joined { + Ok((index, Ok(Ok(())))) => { + if shutting_down { + continue; + } + warn!("Worker {} stopped unexpectedly", index); + index + } + Ok((index, Ok(Err(e)))) => { + error!("Worker {} failed: {}", index, e); + index + } + Ok((index, Err(payload))) => { + error!( + "Worker {} panicked: {}", + index, + panic_message(payload.as_ref()) + ); + index + } + Err(e) => { + // Only reachable if a worker task is aborted externally. + error!("Worker task ended abnormally: {}", e); + continue; + } + }; + if !shutting_down { + info!("Restarting worker {} in {:?}", index, WORKER_RESTART_DELAY); + senders[index] = Self::spawn_worker( + &mut set, + index, + templates[index].clone(), + Some(WORKER_RESTART_DELAY), + ); + } + } + } + } + + if let Some(reaper) = reaper { + reaper.abort(); + } + info!("All workers stopped"); + done_tx.send_replace(true); Ok(()) } + /// Spawn the periodic stale job reaper, if enabled. + fn start_stale_job_reaper( + &self, + workers: &[Worker], + mut signal_rx: watch::Receiver, + ) -> Option> { + let interval = self.reaper_interval?; + let queue = Arc::clone(&workers.first()?.queue); + let older_than = self.reaper_older_than.unwrap_or_else(|| { + workers + .iter() + .map(|worker| worker.lease_duration) + .max() + .filter(|lease| !lease.is_zero()) + .unwrap_or(DEFAULT_LEASE_DURATION) + }); + + Some(tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval.max(Duration::from_millis(1))); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tokio::select! { + _ = signal_rx.changed() => break, + _ = ticker.tick() => { + match queue.requeue_stale_jobs(older_than).await { + Ok(recovery) if !recovery.is_empty() => info!( + "Stale job reaper requeued {} and marked {} dead", + recovery.requeued.len(), + recovery.dead.len() + ), + Ok(_) => {} + Err(e) => warn!("Stale job reaper failed: {}", e), + } + } + } + } + })) + } + /// Start the autoscaling background task async fn start_autoscaling_task(&mut self) -> Result<()> { if let Some(worker_template) = &self.worker_template { @@ -2352,7 +2856,9 @@ where metrics: Arc>, history: QueueDepthHistory, ) { - let mut interval = tokio::time::interval(config.evaluation_window / 2); + // `interval` panics on a zero period, so never pass one through. + let mut interval = + tokio::time::interval((config.evaluation_window / 2).max(Duration::from_millis(1))); loop { interval.tick().await; @@ -2487,6 +2993,11 @@ where } } + /// Shut the pool down gracefully. + /// + /// Signals every worker to stop polling, then waits until all of them have + /// stopped. Each worker lets its in-flight job finish within its + /// [shutdown grace period](Worker::with_shutdown_grace_period). pub async fn shutdown(&self) -> Result<()> { info!("Shutting down worker pool"); @@ -2496,10 +3007,14 @@ where info!("Autoscaling task stopped"); } - for tx in &self.shutdown_tx { - if tx.send(()).await.is_err() { - warn!("Failed to send shutdown signal to worker"); - } + if let Some(signal) = &self.shutdown_signal { + signal.send_replace(true); + } + + if let Some(done) = &self.supervisor_done { + let mut done = done.clone(); + // An error means the supervisor is gone, so there is nothing to wait for. + let _ = done.wait_for(|finished| *finished).await; } Ok(()) @@ -3368,4 +3883,63 @@ mod tests { assert!(captured_events[0].starts_with("cloned:")); assert!(captured_events[1].starts_with("cloned:")); } + + #[test] + fn test_retry_at_from_delay_never_panics_and_clamps() { + let now = Utc::now(); + assert_eq!( + retry_at_from_delay(now, Duration::from_secs(30)), + now + chrono::Duration::seconds(30) + ); + let max = now + chrono::Duration::from_std(MAX_RETRY_DELAY).unwrap(); + assert_eq!(retry_at_from_delay(now, Duration::MAX), max); + assert_eq!(retry_at_from_delay(now, MAX_RETRY_DELAY * 2), max); + assert_eq!( + retry_at_from_delay(DateTime::::MAX_UTC, Duration::from_secs(1)), + DateTime::::MAX_UTC + ); + } + + #[test] + fn test_error_backoff_grows_is_capped_and_never_zero() { + assert_eq!(error_backoff(Duration::ZERO, 1), MIN_ERROR_BACKOFF); + assert_eq!( + error_backoff(Duration::from_secs(1), 1), + Duration::from_secs(1) + ); + assert_eq!( + error_backoff(Duration::from_secs(1), 3), + Duration::from_secs(4) + ); + assert_eq!( + error_backoff(Duration::from_secs(1), u32::MAX), + MAX_ERROR_BACKOFF + ); + // A base above the cap is honoured rather than shortened. + assert_eq!( + error_backoff(Duration::from_secs(120), 5), + Duration::from_secs(120) + ); + } + + #[tokio::test] + async fn test_catch_unwind_turns_panics_into_errors() { + let ok: HandlerFuture = Box::pin(async { Ok(JobResult::success()) }); + assert!(CatchUnwind { inner: ok }.await.unwrap().is_ok()); + + let panicking: HandlerFuture = Box::pin(async { + tokio::task::yield_now().await; + panic!("boom") + }); + let payload = CatchUnwind { inner: panicking }.await.unwrap_err(); + let error = handler_panic_error(payload.as_ref()); + assert_eq!( + error.to_string(), + "Worker error: Job handler panicked: boom" + ); + + let formatted: HandlerFuture = Box::pin(async { panic!("code {}", 42) }); + let payload = CatchUnwind { inner: formatted }.await.unwrap_err(); + assert_eq!(panic_message(payload.as_ref()), "code 42"); + } } diff --git a/tests/worker_robustness_tests.rs b/tests/worker_robustness_tests.rs new file mode 100644 index 0000000..3f05596 --- /dev/null +++ b/tests/worker_robustness_tests.rs @@ -0,0 +1,518 @@ +//! Worker robustness and stale job recovery tests. +//! +//! Covers handler panics, graceful shutdown with in-flight jobs, job leases and the +//! stale job reaper (`DatabaseQueue::requeue_stale_jobs`). Each scenario is written +//! once against the `DatabaseQueue` trait and run against both backends. + +mod test_utils; + +use hammerwork::{ + HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, WorkerPool, queue::DatabaseQueue, + worker::JobHandler, +}; +use serde_json::json; +use std::{ + collections::HashSet, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; +use tokio::sync::mpsc; + +/// Poll `get_job` until `predicate` holds or `timeout` elapses; returns the last job. +async fn wait_for_job( + queue: &Arc>, + id: JobId, + timeout: Duration, + predicate: F, +) -> Job +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, + F: Fn(&Job) -> bool, +{ + let deadline = Instant::now() + timeout; + loop { + let job = queue.get_job(id).await.unwrap().expect("job exists"); + if predicate(&job) || Instant::now() >= deadline { + return job; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +/// A panicking handler must fail the job through the normal path (not leave it +/// `Running`) and must not kill the worker. +async fn handler_panic_fails_job_and_worker_survives(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + // The reaper tests reclaim stale jobs across all queues; keep them apart. + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("panic_handler"); + let panicking = queue + .enqueue(Job::new(queue_name.clone(), json!({ "panic": true })).with_max_attempts(1)) + .await + .unwrap(); + + let handler: JobHandler = Arc::new(|job: Job| { + Box::pin(async move { + if job.payload["panic"].as_bool() == Some(true) { + panic!("handler exploded"); + } + Ok(()) + }) + }); + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_max_retries(1); + + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + let job = wait_for_job(&queue, panicking, Duration::from_secs(10), |job| { + job.status != JobStatus::Running && job.status != JobStatus::Pending + }) + .await; + assert_eq!(job.status, JobStatus::Dead, "panicked job must be failed"); + let error = job.error_message.unwrap_or_default(); + assert!( + error.contains("Job handler panicked: handler exploded"), + "unexpected error message: {error}" + ); + + // The same worker keeps processing jobs after the panic. + let healthy = queue + .enqueue(Job::new(queue_name.clone(), json!({ "panic": false }))) + .await + .unwrap(); + let job = wait_for_job(&queue, healthy, Duration::from_secs(10), |job| { + job.status == JobStatus::Completed + }) + .await; + assert_eq!(job.status, JobStatus::Completed, "worker died after panic"); + assert!( + !worker_task.is_finished(), + "worker task must still be running" + ); + + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + + queue.delete_job(panicking).await.unwrap(); + queue.delete_job(healthy).await.unwrap(); +} + +/// A panicking handler with retries left must be rescheduled, not left `Running`. +async fn handler_panic_is_retried(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + // The reaper tests reclaim stale jobs across all queues; keep them apart. + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("panic_retry"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({})).with_max_attempts(5)) + .await + .unwrap(); + + let handler: JobHandler = + 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_retry_delay(Duration::from_secs(3600)); + + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + let job = wait_for_job(&queue, id, Duration::from_secs(10), |job| { + job.attempts >= 1 && job.status == JobStatus::Pending + }) + .await; + assert_eq!( + job.status, + JobStatus::Pending, + "panicked job must be retried" + ); + assert_eq!(job.attempts, 1); + assert!(job.scheduled_at > chrono::Utc::now() + chrono::Duration::minutes(30)); + + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + queue.delete_job(id).await.unwrap(); +} + +/// `WorkerPool::shutdown` must let an in-flight job finish (within the grace period) +/// and record its outcome, instead of cancelling it mid-run. +async fn graceful_shutdown_completes_in_flight_job(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + // The reaper tests reclaim stale jobs across all queues; keep them apart. + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("graceful_shutdown"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + + let started = Arc::new(AtomicBool::new(false)); + let finished = Arc::new(AtomicBool::new(false)); + let handler: JobHandler = { + let started = Arc::clone(&started); + let finished = Arc::clone(&finished); + Arc::new(move |_job: Job| { + let started = Arc::clone(&started); + let finished = Arc::clone(&finished); + Box::pin(async move { + started.store(true, Ordering::SeqCst); + tokio::time::sleep(Duration::from_secs(2)).await; + finished.store(true, Ordering::SeqCst); + Ok(()) + }) + }) + }; + + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_shutdown_grace_period(Duration::from_secs(20)); + let mut pool = WorkerPool::new() + .without_autoscaling() + .without_stale_job_reaper(); + pool.add_worker(worker); + + // Run the pool until the job has started, then drop the `start` future: the + // workers keep running in their own tasks. + tokio::select! { + result = pool.start() => panic!("pool stopped early: {result:?}"), + _ = async { + while !started.load(Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(20)).await; + } + } => {} + } + assert!(!finished.load(Ordering::SeqCst)); + + let shutdown_started = Instant::now(); + pool.shutdown().await.unwrap(); + assert!( + finished.load(Ordering::SeqCst), + "shutdown must wait for the in-flight job" + ); + assert!(shutdown_started.elapsed() < Duration::from_secs(15)); + + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!( + job.status, + JobStatus::Completed, + "in-flight job must complete" + ); + queue.delete_job(id).await.unwrap(); +} + +/// Enqueue a job and claim it, leaving it `Running` as a crashed worker would. +async fn start_job(queue: &Arc>, job: Job) -> JobId +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = job.queue_name.clone(); + let id = queue.enqueue(job).await.unwrap(); + let claimed = queue + .dequeue(&queue_name) + .await + .unwrap() + .expect("job claimed"); + assert_eq!(claimed.id, id); + id +} + +/// Jobs whose lease expired go back to `Pending` (or `Dead` when out of attempts); +/// jobs with a live lease, or without a lease but younger than `older_than`, stay. +async fn reaper_requeues_expired_leases(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let hour = Duration::from_secs(3600); + + let expiring = start_job( + &queue, + Job::new(test_utils::unique_queue("reaper_expiring"), json!({})).with_max_attempts(3), + ) + .await; + let exhausted = start_job( + &queue, + Job::new(test_utils::unique_queue("reaper_exhausted"), json!({})).with_max_attempts(1), + ) + .await; + let live = start_job( + &queue, + Job::new(test_utils::unique_queue("reaper_live"), json!({})), + ) + .await; + let unleased = start_job( + &queue, + Job::new(test_utils::unique_queue("reaper_unleased"), json!({})), + ) + .await; + + assert!( + queue + .heartbeat_job(expiring, Duration::from_millis(500)) + .await + .unwrap() + ); + assert!( + queue + .heartbeat_job(exhausted, Duration::from_millis(500)) + .await + .unwrap() + ); + assert!(queue.heartbeat_job(live, hour).await.unwrap()); + + tokio::time::sleep(Duration::from_millis(1500)).await; + + let recovery = queue.requeue_stale_jobs(hour).await.unwrap(); + assert!(recovery.requeued.contains(&expiring), "{recovery:?}"); + assert!(recovery.dead.contains(&exhausted), "{recovery:?}"); + for id in [live, unleased] { + assert!( + !recovery.requeued.contains(&id) && !recovery.dead.contains(&id), + "job {id} must not be reclaimed: {recovery:?}" + ); + } + + let job = queue.get_job(expiring).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Pending); + assert_eq!(job.attempts, 1, "the interrupted run counts as an attempt"); + 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(); + assert_eq!(reclaimed.id, expiring); + assert_eq!(reclaimed.attempts, 2); + + let job = queue.get_job(exhausted).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Dead); + assert!(job.failed_at.is_some()); + // A worker that lost its lease finds out on its next heartbeat. + assert!( + !queue + .heartbeat_job(exhausted, Duration::from_secs(1)) + .await + .unwrap() + ); + + // Without a lease, `older_than` (measured from `started_at`) decides. + let recovery = queue + .requeue_stale_jobs(Duration::from_millis(500)) + .await + .unwrap(); + assert!(recovery.requeued.contains(&unleased), "{recovery:?}"); + assert!(!recovery.requeued.contains(&live), "{recovery:?}"); + + for id in [expiring, exhausted, live, unleased] { + queue.delete_job(id).await.unwrap(); + } +} + +/// Concurrent reapers must reclaim every stale job exactly once. +async fn concurrent_reapers_never_double_requeue(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("reaper_concurrency"); + let mut stale = HashSet::new(); + for i in 0..40 { + let id = start_job( + &queue, + Job::new(queue_name.clone(), json!({ "index": i })).with_max_attempts(3), + ) + .await; + assert!( + queue + .heartbeat_job(id, Duration::from_millis(200)) + .await + .unwrap() + ); + stale.insert(id); + } + tokio::time::sleep(Duration::from_millis(800)).await; + + let mut reapers = Vec::new(); + for _ in 0..8 { + let queue = Arc::clone(&queue); + reapers.push(tokio::spawn(async move { + queue + .requeue_stale_jobs(Duration::from_secs(3600)) + .await + .unwrap() + })); + } + + let mut reclaimed = HashSet::new(); + for reaper in reapers { + let recovery = reaper.await.unwrap(); + for id in recovery.requeued.into_iter().chain(recovery.dead) { + if stale.contains(&id) { + assert!(reclaimed.insert(id), "job {id} was reclaimed twice"); + } + } + } + assert_eq!(reclaimed, stale, "every stale job must be reclaimed"); + + for id in stale { + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Pending); + assert_eq!(job.attempts, 1); + queue.delete_job(id).await.unwrap(); + } +} + +/// A worker heartbeats long-running jobs, so a reaper never reclaims a live job even +/// when the job outlives its original lease. +async fn worker_heartbeat_keeps_long_job_leased(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("heartbeat"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + + let runs = Arc::new(AtomicUsize::new(0)); + let handler: JobHandler = { + let runs = Arc::clone(&runs); + Arc::new(move |_job: Job| { + let runs = Arc::clone(&runs); + Box::pin(async move { + runs.fetch_add(1, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(2500)).await; + Ok::<(), HammerworkError>(()) + }) + }) + }; + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_lease_duration(Duration::from_millis(900)); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + let worker_task = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let recovery = queue + .requeue_stale_jobs(Duration::from_secs(3600)) + .await + .unwrap(); + assert!( + !recovery.requeued.contains(&id) && !recovery.dead.contains(&id), + "a live, heartbeating job was reclaimed" + ); + let job = queue.get_job(id).await.unwrap().unwrap(); + if job.status == JobStatus::Completed || Instant::now() >= deadline { + assert_eq!(job.status, JobStatus::Completed); + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + assert_eq!(runs.load(Ordering::SeqCst), 1); + + shutdown_tx.send(()).await.unwrap(); + worker_task.await.unwrap().unwrap(); + queue.delete_job(id).await.unwrap(); +} + +#[cfg(feature = "postgres")] +mod postgres_tests { + use super::*; + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_handler_panic_fails_job_and_worker_survives() { + handler_panic_fails_job_and_worker_survives(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_handler_panic_is_retried() { + handler_panic_is_retried(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_graceful_shutdown_completes_in_flight_job() { + graceful_shutdown_completes_in_flight_job(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_reaper_requeues_expired_leases() { + reaper_requeues_expired_leases(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_concurrent_reapers_never_double_requeue() { + concurrent_reapers_never_double_requeue(test_utils::setup_postgres_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_postgres_worker_heartbeat_keeps_long_job_leased() { + worker_heartbeat_keeps_long_job_leased(test_utils::setup_postgres_queue().await).await; + } +} + +#[cfg(feature = "mysql")] +mod mysql_tests { + use super::*; + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_handler_panic_fails_job_and_worker_survives() { + handler_panic_fails_job_and_worker_survives(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_handler_panic_is_retried() { + handler_panic_is_retried(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_graceful_shutdown_completes_in_flight_job() { + graceful_shutdown_completes_in_flight_job(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_reaper_requeues_expired_leases() { + reaper_requeues_expired_leases(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_concurrent_reapers_never_double_requeue() { + concurrent_reapers_never_double_requeue(test_utils::setup_mysql_queue().await).await; + } + + #[tokio::test] + #[ignore] // Requires database connection + async fn test_mysql_worker_heartbeat_keeps_long_job_leased() { + worker_heartbeat_keeps_long_job_leased(test_utils::setup_mysql_queue().await).await; + } +}