From bbe943634b67639c92a7bd7a63b9f0126b8ec3d9 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:35:48 -0400 Subject: [PATCH 1/8] refactor(queue): share row decoding and the transition driver between backends The PostgreSQL and MySQL backends each carried a copy of the backend-independent parts of reading a job row and of a lifecycle transition. - queue/row.rs: the job column lists, status/result-storage/dependency-status decoding and the encryption column decoding (EncryptionRow), used by both JobRow::into_job implementations. - lifecycle.rs: a TransitionStore trait for the dialect-specific statements, and one generic transition_in_tx / after_terminal / apply_failure_policy / fail_job_dependencies plus manual_transition and finish_run, replacing the per-backend copies and the five manual-transition wrappers in each backend. - lifecycle.rs: one module-level dead_code allowance instead of 18 per-item cfg_attr lines. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- src/queue/lifecycle.rs | 286 ++++++++++++- src/queue/mod.rs | 2 + src/queue/mysql.rs | 934 ++++++++++++----------------------------- src/queue/postgres.rs | 726 ++++++++------------------------ src/queue/row.rs | 368 ++++++++++++++++ 5 files changed, 1075 insertions(+), 1241 deletions(-) create mode 100644 src/queue/row.rs diff --git a/src/queue/lifecycle.rs b/src/queue/lifecycle.rs index ca84274..ac7e505 100644 --- a/src/queue/lifecycle.rs +++ b/src/queue/lifecycle.rs @@ -24,7 +24,10 @@ //! [`DatabaseQueue::complete_job`]: super::DatabaseQueue::complete_job //! [`DatabaseQueue::finish_job_run`]: super::DatabaseQueue::finish_job_run +#![cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + use crate::job::{Job, JobId, JobStatus}; +use crate::{Result, workflow::FailurePolicy}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; @@ -196,7 +199,6 @@ impl RecordedOutcome { /// The new state a transition writes. Shared by manual transitions and run outcomes. #[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) enum Target { Completed, Failed(String), @@ -209,7 +211,6 @@ pub(crate) enum Target { }, } -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] impl Target { /// The terminal status this target writes, or `None` for a retry. pub fn terminal_status(&self) -> Option { @@ -273,7 +274,6 @@ impl From for Target { /// Which current states a transition accepts. #[derive(Debug, Clone, Copy)] -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) enum Guard<'a> { /// A manual transition: any of its allowed source statuses. Manual(JobTransition), @@ -281,7 +281,6 @@ pub(crate) enum Guard<'a> { Run(&'a Job), } -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] impl Guard<'_> { /// Whether the job, in its current (locked) state, accepts the transition. pub fn admits(&self, current: &Job) -> bool { @@ -314,7 +313,6 @@ pub(crate) fn is_same_run(current: &Job, run: &Job) -> bool { /// What a backend's transition did. #[derive(Debug)] -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) enum TransitionResult { Applied(RecordedOutcome), /// The guard rejected the job's current status (or run). @@ -322,7 +320,6 @@ pub(crate) enum TransitionResult { NotFound, } -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] impl TransitionResult { /// The result of a manual transition: rejections are errors. pub fn into_manual( @@ -349,7 +346,6 @@ impl TransitionResult { } /// Parse a `status` column value (old rows may hold it JSON-quoted). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn job_status_from_db(value: &str) -> Option { Some(match value.trim_matches('"') { "Pending" => JobStatus::Pending, @@ -366,7 +362,6 @@ pub(crate) fn job_status_from_db(value: &str) -> Option { /// The error for a manual transition whose guarded UPDATE matched no row, given the /// job's current status (`None` when the job does not exist). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn rejection_error( job_id: JobId, transition: JobTransition, @@ -394,29 +389,24 @@ pub(crate) fn rejection_error( } /// Error message for a dependent that can no longer run because `failed` failed. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn dependency_failed_message(failed: JobId) -> String { format!("Dependency failed: job {failed} failed") } /// Error message for a pending job failed by a fail-fast workflow. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn workflow_failed_message(failed: JobId) -> String { format!("Workflow failed: job {failed} failed (fail-fast policy)") } /// Error message for a pending job failed by a fail-fast batch. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn batch_failed_message(failed: JobId) -> String { format!("Batch failed: job {failed} failed (fail-fast mode)") } /// The statuses that count as "not finished yet" for workflow and batch progress. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) const UNFINISHED_STATUS_SQL: &str = "'Pending', 'Running', 'Retrying'"; /// Error message recorded on the unfinished jobs of a cancelled workflow. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) const WORKFLOW_CANCELLED_MESSAGE: &str = "Workflow cancelled"; /// How many missed occurrences [`next_cron_run`] steps through before it gives up @@ -440,7 +430,6 @@ const CRON_CATCH_UP_SCAN_LIMIT: usize = 10_000; /// next run is the first occurrence after it started, not another immediate one. /// /// Returns `None` when the job has no valid cron schedule or no next occurrence. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn next_cron_run(job: &Job, now: DateTime) -> Option> { let schedule = job.get_cron_schedule()?.ok()?; // `next_run_at` is the slot; a retried run has a later `scheduled_at`, and a run @@ -473,7 +462,6 @@ pub(crate) fn next_cron_run(job: &Job, now: DateTime) -> Option Vec { let new: std::collections::HashSet = jobs.iter().map(|job| job.id).collect(); let mut parents: Vec = jobs @@ -542,7 +528,6 @@ pub(crate) fn external_dependencies(jobs: &[Job]) -> Vec { /// - everything else keeps waiting. /// /// Returns the ids of the jobs that were failed. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] pub(crate) fn settle_new_dependents( jobs: &mut [Job], parents: &std::collections::HashMap, @@ -605,6 +590,271 @@ pub(crate) fn settle_new_dependents( } } +/// The locked `hammerwork_workflows` row of a job's workflow. +pub(crate) struct LockedWorkflow { + pub id: crate::workflow::WorkflowId, + pub policy: FailurePolicy, + pub status: crate::workflow::WorkflowStatus, + pub total_jobs: usize, +} + +/// The statements a database backend runs for a job lifecycle transition. +/// +/// The transition itself (lock the job, check the guard, write the target, then apply +/// the side effects of a terminal status) is backend-independent and implemented once, +/// by [`transition_in_tx`] and the functions it calls; each backend implements these +/// statements in its SQL dialect. Every statement runs on the transaction's connection. +pub(crate) trait TransitionStore: Sync { + /// The connection a transition's statements run on. + type Conn: Send; + + /// Apply `target` to a job if `guard` admits its current state, together with the + /// side effects of the new state, in one transaction (retried on conflicts). + fn transition_job( + &self, + job_id: JobId, + guard: Guard<'_>, + target: &Target, + reschedule_recurring: bool, + ) -> impl Future> + Send; + + /// The job `job_id`, locked for update (`None` if it does not exist). + fn lock_job( + conn: &mut Self::Conn, + job_id: JobId, + ) -> impl Future>> + Send; + + /// The current time by the database clock. + fn db_now(conn: &mut Self::Conn) -> impl Future>> + Send; + + /// Write the new status and its timestamps. Clears the lease: the run is over. + fn write_target( + conn: &mut Self::Conn, + job_id: JobId, + target: &Target, + now: DateTime, + ) -> impl Future> + Send; + + /// Whether `next_run_at` can be stored as a recurring job's next run. + fn can_schedule_at(_next_run_at: DateTime) -> bool { + true + } + + /// Put a recurring job back to `Pending` for its next run. A failed run's error and + /// failure time stay visible until the next run; a successful run clears them. + fn reschedule_after_run( + conn: &mut Self::Conn, + job_id: JobId, + next_run_at: DateTime, + run_status: JobStatus, + ) -> impl Future> + Send; + + /// Lock a workflow's row (`None` if it does not exist). + fn lock_workflow( + conn: &mut Self::Conn, + workflow_id: crate::workflow::WorkflowId, + ) -> impl Future>> + Send; + + /// Mark `waiting` dependents of `completed_job_id` whose dependencies have all + /// completed as `satisfied`, so they can be dequeued. Returns them. + fn resolve_dependents( + conn: &mut Self::Conn, + completed_job_id: JobId, + ) -> impl Future>> + Send; + + /// Fail every pending job that (transitively) depends on `failed_job_id`. + fn fail_dependents( + conn: &mut Self::Conn, + failed_job_id: JobId, + now: DateTime, + ) -> impl Future>> + Send; + + /// Fail the pending jobs of a fail-fast workflow after `failed_job_id` failed. + fn fail_workflow_pending( + conn: &mut Self::Conn, + workflow_id: crate::workflow::WorkflowId, + failed_job_id: JobId, + now: DateTime, + ) -> impl Future>> + Send; + + /// Recompute a workflow's counters and status from its jobs. + fn refresh_workflow( + conn: &mut Self::Conn, + workflow: &LockedWorkflow, + now: DateTime, + ) -> impl Future> + Send; + + /// Apply a batch job's terminal `status` to its batch: a `FailFast` batch fails its + /// pending jobs on the first failure, and the batch's counters and status are + /// persisted once the batch has finished (or failed fast). Returns the jobs failed. + fn apply_batch_outcome( + conn: &mut Self::Conn, + batch_id: crate::batch::BatchId, + job_id: JobId, + status: JobStatus, + now: DateTime, + ) -> impl Future>> + Send; +} + +/// Apply a manual transition (see [`JobTransition`]) to `target`. +pub(crate) async fn manual_transition( + store: &S, + job_id: JobId, + transition: JobTransition, + target: Target, +) -> Result<()> { + store + .transition_job(job_id, Guard::Manual(transition), &target, false) + .await? + .into_manual(job_id, transition)?; + Ok(()) +} + +/// Record the outcome of the run `run` ([`DatabaseQueue::finish_job_run`]). +/// +/// [`DatabaseQueue::finish_job_run`]: super::DatabaseQueue::finish_job_run +pub(crate) async fn finish_run( + store: &S, + run: &Job, + outcome: JobOutcome, +) -> Result> { + let target = Target::from(outcome); + Ok(store + .transition_job(run.id, Guard::Run(run), &target, true) + .await? + .into_run()) +} + +/// Apply `target` to a job if `guard` admits its current state, together with the side +/// effects of the new state, inside the caller's transaction. +pub(crate) async fn transition_in_tx( + conn: &mut S::Conn, + job_id: JobId, + guard: Guard<'_>, + target: &Target, + reschedule_recurring: bool, +) -> Result { + let Some(job) = S::lock_job(conn, job_id).await? else { + return Ok(TransitionResult::NotFound); + }; + if !guard.admits(&job) { + return Ok(TransitionResult::Rejected(job.status)); + } + + let now = S::db_now(conn).await?; + let target = target.on_db_clock(&guard, now); + S::write_target(conn, job_id, &target, now).await?; + let recorded = match target.terminal_status() { + Some(status) => after_terminal::(conn, &job, status, now, reschedule_recurring).await?, + None => RecordedOutcome::new(JobStatus::Pending), + }; + Ok(TransitionResult::Applied(recorded)) +} + +/// Side effects of `job` reaching the terminal `status`. +/// +/// A recurring job (when `reschedule_recurring`) is rescheduled for its next run +/// instead. Otherwise dependents are resolved or failed, the workflow policy and +/// counters are applied, and the batch's failure mode and status. +pub(crate) async fn after_terminal( + conn: &mut S::Conn, + job: &Job, + status: JobStatus, + now: DateTime, + reschedule_recurring: bool, +) -> Result { + if reschedule_recurring && job.recurring { + if let Some(next_run_at) = next_cron_run(job, now).filter(|at| S::can_schedule_at(*at)) { + S::reschedule_after_run(conn, job.id, next_run_at, status).await?; + let mut recorded = RecordedOutcome::new(JobStatus::Pending); + recorded.next_run_at = Some(next_run_at); + return Ok(recorded); + } + tracing::warn!( + "Could not calculate the next run time for recurring job {}; it stays {}", + job.id, + status.as_str() + ); + } + + let mut recorded = RecordedOutcome::new(status); + + // Lock the workflow row first: it serializes terminal transitions within a + // workflow, so concurrent completions cannot both miss each other. + let workflow = match job.workflow_id { + Some(id) => S::lock_workflow(conn, id).await?, + None => None, + }; + + if status == JobStatus::Completed { + recorded.unblocked = S::resolve_dependents(conn, job.id).await?; + } else { + recorded.cancelled = + apply_failure_policy::(conn, workflow.as_ref(), job.id, now).await?; + } + + if let Some(workflow) = &workflow { + S::refresh_workflow(conn, workflow, now).await?; + } + if let Some(batch_id) = job.batch_id { + let cancelled = S::apply_batch_outcome(conn, batch_id, job.id, status, now).await?; + recorded.cancelled.extend(cancelled); + } + Ok(recorded) +} + +/// Apply the [`FailurePolicy`] of `workflow` (the failed job's locked workflow, if any) +/// to the failure of `failed_job_id`. Returns the jobs that were failed. +/// +/// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then the jobs +/// that (transitively) depend on the failed one; +/// - `ContinueOnFailure`, and jobs with dependencies outside any workflow, fail only +/// the jobs that (transitively) depend on the failed one; +/// - `Manual` leaves the dependents waiting for an operator. +async fn apply_failure_policy( + conn: &mut S::Conn, + workflow: Option<&LockedWorkflow>, + failed_job_id: JobId, + now: DateTime, +) -> Result> { + match workflow { + Some(w) if w.policy == FailurePolicy::Manual => Ok(Vec::new()), + Some(w) if w.policy == FailurePolicy::FailFast => { + let mut failed = S::fail_workflow_pending(conn, w.id, failed_job_id, now).await?; + for id in S::fail_dependents(conn, failed_job_id, now).await? { + if !failed.contains(&id) { + failed.push(id); + } + } + Ok(failed) + } + _ => S::fail_dependents(conn, failed_job_id, now).await, + } +} + +/// [`DatabaseQueue::fail_job_dependencies`] inside the caller's transaction, once the +/// failed job is locked: lock its workflow (`workflow_id`, in the same order as a +/// terminal transition), apply the workflow's failure policy and update the workflow's +/// counters and status. +/// +/// [`DatabaseQueue::fail_job_dependencies`]: super::DatabaseQueue::fail_job_dependencies +pub(crate) async fn fail_job_dependencies( + conn: &mut S::Conn, + failed_job_id: JobId, + workflow_id: Option, +) -> Result> { + let workflow = match workflow_id { + Some(id) => S::lock_workflow(conn, id).await?, + None => None, + }; + let now = S::db_now(conn).await?; + let failed = apply_failure_policy::(conn, workflow.as_ref(), failed_job_id, now).await?; + if let Some(workflow) = &workflow { + S::refresh_workflow(conn, workflow, now).await?; + } + Ok(failed) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 115b293..f41550f 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -21,6 +21,8 @@ use tokio::sync::RwLock; pub mod lifecycle; pub use lifecycle::{JobOutcome, JobTransition, RecordedOutcome}; +mod row; + #[cfg(feature = "postgres")] pub mod postgres; diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 097025c..599fb84 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -3,7 +3,13 @@ //! This module provides the MySQL-specific implementation of the `DatabaseQueue` trait, //! optimized for MySQL's JSON support and transactional capabilities. -use super::lifecycle::{self, Guard, ParentState, Target, TransitionResult}; +use super::lifecycle::{ + self, Guard, LockedWorkflow, ParentState, Target, TransitionResult, TransitionStore, +}; +use super::row::{ + self, ARCHIVED_JOB_FIELDS, ENCRYPTION_COLUMNS, INSERT_JOB_COLUMNS, JOB_SELECT_FIELDS, + result_storage_str, +}; use super::{ DatabaseQueue, DeadJobSummary, JobOutcome, JobTransition, QueueStats, RecordedOutcome, }; @@ -85,30 +91,6 @@ pub(crate) struct JobRow { pub encrypted_at: Option>, } -/// Standard field list for selecting complete job data from hammerwork_jobs table. -const JOB_SELECT_FIELDS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, retry_strategy, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; - -/// Columns of hammerwork_jobs_archive needed to rebuild a [`Job`]. -const ARCHIVED_JOB_FIELDS: &str = "id, queue_name, payload, payload_compressed, status, priority, attempts, max_attempts, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, result, result_ttl, retry_strategy, timeout_seconds, cron_schedule, next_run_at, recurring, timezone, batch_id, depends_on, dependency_status, result_config, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, pii_fields"; - -/// Encryption columns of hammerwork_jobs and hammerwork_jobs_archive (migration 011). -/// Archiving and restoring copy them between the tables in SQL, so encrypted payloads -/// move without being decrypted, with or without the `encryption` feature. -const ENCRYPTION_COLUMNS: [&str; 12] = [ - "is_encrypted", - "encryption_key_id", - "encryption_algorithm", - "encrypted_payload", - "encryption_nonce", - "encryption_tag", - "encryption_metadata", - "payload_hash", - "pii_fields", - "retention_policy", - "retention_delete_at", - "encrypted_at", -]; - /// Copies the encryption columns of job `id` from table `from` to table `to`. async fn copy_encryption_columns( conn: &mut sqlx::MySqlConnection, @@ -206,40 +188,17 @@ fn archived_job_from_row(row: &sqlx::mysql::MySqlRow) -> Result { } impl JobRow { - pub fn into_job(self) -> Result { - // Extract encryption data before moving self - #[cfg(feature = "encryption")] - let encryption_config = self.build_encryption_config()?; + pub fn into_job(mut self) -> Result { + let pii_fields = json_list(self.pii_fields.take(), "pii_fields")?; #[cfg(feature = "encryption")] - let retention_policy = self.parse_retention_policy()?; - #[cfg(feature = "encryption")] - let encrypted_payload = self.build_encrypted_payload()?; - let pii_fields = json_list(self.pii_fields.clone(), "pii_fields")?; + let (encryption_config, retention_policy, encrypted_payload) = + self.encryption_row(&pii_fields).decode()?; Ok(Job { id: uuid::Uuid::parse_str(&self.id)?, queue_name: self.queue_name, payload: self.payload, - status: { - // Handle both quoted (old format) and unquoted (new format) status values - let cleaned_str = self.status.trim_matches('"'); - match cleaned_str { - "Pending" => JobStatus::Pending, - "Running" => JobStatus::Running, - "Completed" => JobStatus::Completed, - "Failed" => JobStatus::Failed, - "Dead" => JobStatus::Dead, - "TimedOut" => JobStatus::TimedOut, - "Retrying" => JobStatus::Retrying, - "Archived" => JobStatus::Archived, - _ => { - return Err(crate::error::HammerworkError::Processing(format!( - "Unknown job status: {}", - cleaned_str - ))); - } - } - }, + status: row::job_status_from_row(&self.status)?, priority: JobPriority::from_i32(self.priority).unwrap_or(JobPriority::Normal), attempts: self.attempts, max_attempts: self.max_attempts, @@ -263,16 +222,7 @@ impl JobRow { .map(|s| uuid::Uuid::parse_str(&s)) .transpose()?, result_config: crate::job::ResultConfig { - storage: self - .result_storage_type - .as_ref() - .map(|s| match s.as_str() { - "database" => crate::job::ResultStorage::Database, - "memory" => crate::job::ResultStorage::Memory, - "none" => crate::job::ResultStorage::None, - _ => crate::job::ResultStorage::None, - }) - .unwrap_or(crate::job::ResultStorage::None), + storage: row::result_storage_from_db(self.result_storage_type.as_deref()), ttl: self .result_ttl_seconds .map(|s| super::db_seconds(s, "result_ttl_seconds")) @@ -285,15 +235,10 @@ impl JobRow { result_data: self.result_data, result_stored_at: self.result_stored_at, result_expires_at: self.result_expires_at, - retry_strategy: super::retry_strategy_from_json(self.retry_strategy.clone())?, + retry_strategy: super::retry_strategy_from_json(self.retry_strategy)?, depends_on: json_list(self.depends_on, "depends_on")?, dependents: json_list(self.dependents, "dependents")?, - dependency_status: self - .dependency_status - .as_deref() - .map(crate::workflow::DependencyStatus::parse_from_db) - .transpose()? - .unwrap_or(crate::workflow::DependencyStatus::None), + dependency_status: row::dependency_status_from_row(self.dependency_status.as_deref())?, workflow_id: self .workflow_id .map(|s| uuid::Uuid::parse_str(&s)) @@ -314,249 +259,24 @@ impl JobRow { }) } - /// Parses PII fields from JSON value. - #[cfg(feature = "encryption")] - fn parse_pii_fields(&self) -> Vec { - self.pii_fields - .as_ref() - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|v| v.as_str().map(|s| s.to_string())) - .collect() - }) - .unwrap_or_default() - } - - /// Builds an EncryptionConfig from database fields if encryption is enabled. - #[cfg(feature = "encryption")] - fn build_encryption_config(&self) -> Result> { - if !self.is_encrypted { - return Ok(None); - } - - // Parse algorithm - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305, - Some(alg) => { - return Err(crate::HammerworkError::Processing(format!( - "Unknown encryption algorithm: {}", - alg - ))); - } - None => { - return Err(crate::HammerworkError::Processing( - "Missing encryption algorithm for encrypted job".to_string(), - )); - } - }; - - // Parse metadata if available - let (key_id, compression_enabled, version) = - if let Some(metadata) = &self.encryption_metadata { - let key_id = metadata - .get("key_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - let compression_enabled = metadata - .get("compressed") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let version = metadata - .get("config_version") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - (key_id, compression_enabled, version) - } else { - (self.encryption_key_id.clone(), false, 1) - }; - - let config = crate::encryption::EncryptionConfig { - algorithm, - key_source: crate::encryption::KeySource::External( - key_id.unwrap_or_else(|| "unknown".to_string()), - ), - key_rotation_enabled: false, // Not stored in database - key_rotation_interval: None, - default_retention: None, // Will be parsed separately - compression_enabled, - key_id: self.encryption_key_id.clone(), - version, - }; - - Ok(Some(config)) - } - - /// Parses the retention policy from the database string. - #[cfg(feature = "encryption")] - fn parse_retention_policy(&self) -> Result> { - match self.retention_policy.as_deref() { - None => Ok(None), - Some("KeepIndefinitely") => { - Ok(Some(crate::encryption::RetentionPolicy::KeepIndefinitely)) - } - Some("DeleteImmediately") => { - Ok(Some(crate::encryption::RetentionPolicy::DeleteImmediately)) - } - Some("UseDefault") => Ok(Some(crate::encryption::RetentionPolicy::UseDefault)), - Some(policy_str) => { - // Handle DeleteAfter and DeleteAt policies - if let Some(delete_at) = self.retention_delete_at { - if policy_str == "DeleteAt" { - Ok(Some(crate::encryption::RetentionPolicy::DeleteAt( - delete_at, - ))) - } else if policy_str == "DeleteAfter" { - // Calculate duration from creation to deletion time - let duration = delete_at.signed_duration_since(self.created_at); - if let Ok(std_duration) = duration.to_std() { - Ok(Some(crate::encryption::RetentionPolicy::DeleteAfter( - std_duration, - ))) - } else { - Ok(Some(crate::encryption::RetentionPolicy::UseDefault)) - } - } else { - Err(crate::HammerworkError::Processing(format!( - "Unknown retention policy: {}", - policy_str - ))) - } - } else { - Err(crate::HammerworkError::Processing(format!( - "Retention policy '{}' requires retention_delete_at timestamp", - policy_str - ))) - } - } - } - } - - /// Builds an EncryptedPayload from database fields if the job is encrypted. + /// The encryption columns, for [`row::EncryptionRow::decode`]. #[cfg(feature = "encryption")] - fn build_encrypted_payload(&self) -> Result> { - if !self.is_encrypted { - return Ok(None); + fn encryption_row<'a>(&'a self, pii_fields: &'a [String]) -> row::EncryptionRow<'a> { + row::EncryptionRow { + is_encrypted: self.is_encrypted, + created_at: self.created_at, + encryption_key_id: self.encryption_key_id.as_deref(), + encryption_algorithm: self.encryption_algorithm.as_deref(), + encrypted_payload: self.encrypted_payload.as_deref(), + encryption_nonce: self.encryption_nonce.as_deref(), + encryption_tag: self.encryption_tag.as_deref(), + encryption_metadata: self.encryption_metadata.as_ref(), + payload_hash: self.payload_hash.as_deref(), + pii_fields, + retention_policy: self.retention_policy.as_deref(), + retention_delete_at: self.retention_delete_at, + encrypted_at: self.encrypted_at, } - - let encrypted_data = self.encrypted_payload.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encrypted payload for encrypted job".to_string(), - ) - })?; - - let nonce = self.encryption_nonce.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encryption nonce for encrypted job".to_string(), - ) - })?; - - let tag = self.encryption_tag.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encryption tag for encrypted job".to_string(), - ) - })?; - - // Parse metadata - let metadata = if let Some(metadata_json) = &self.encryption_metadata { - // Build metadata from JSON - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => { - crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305 - } - _ => crate::encryption::EncryptionAlgorithm::AES256GCM, // Default fallback - }; - - let key_id = metadata_json - .get("key_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) - .or_else(|| self.encryption_key_id.clone()) - .unwrap_or_else(|| "unknown".to_string()); - - let config_version = metadata_json - .get("config_version") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - - let compressed = metadata_json - .get("compressed") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - let encrypted_fields = metadata_json - .get("encrypted_fields") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|v| v.as_str().map(|s| s.to_string())) - .collect() - }) - .unwrap_or_else(|| self.parse_pii_fields()); - - let retention_policy = self - .parse_retention_policy()? - .unwrap_or(crate::encryption::RetentionPolicy::UseDefault); - - let encrypted_at = self.encrypted_at.unwrap_or(self.created_at); - - crate::encryption::EncryptionMetadata { - algorithm, - key_id, - config_version, - compressed, - encrypted_fields, - retention_policy, - encrypted_at, - delete_at: self.retention_delete_at, - payload_hash: self.payload_hash.clone().unwrap_or_default(), - format_version: crate::encryption::EncryptionMetadata::format_version_from_json( - metadata_json, - ), - } - } else { - // Build basic metadata from available fields - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => { - crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305 - } - _ => crate::encryption::EncryptionAlgorithm::AES256GCM, // Default fallback - }; - - crate::encryption::EncryptionMetadata { - algorithm, - key_id: self - .encryption_key_id - .clone() - .unwrap_or_else(|| "unknown".to_string()), - config_version: 1, - compressed: false, - encrypted_fields: self.parse_pii_fields(), - retention_policy: self - .parse_retention_policy()? - .unwrap_or(crate::encryption::RetentionPolicy::UseDefault), - encrypted_at: self.encrypted_at.unwrap_or(self.created_at), - delete_at: self.retention_delete_at, - payload_hash: self.payload_hash.clone().unwrap_or_default(), - format_version: crate::encryption::EncryptionMetadata::FORMAT_UNBOUND, - } - }; - - // Encode binary data to base64 - use base64::Engine; - let ciphertext = base64::engine::general_purpose::STANDARD.encode(encrypted_data); - let nonce_b64 = base64::engine::general_purpose::STANDARD.encode(nonce); - let tag_b64 = base64::engine::general_purpose::STANDARD.encode(tag); - - Ok(Some(crate::encryption::EncryptedPayload { - ciphertext, - nonce: nonce_b64, - tag: tag_b64, - metadata, - })) } } @@ -972,34 +692,32 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn complete_job(&self, job_id: JobId) -> Result<()> { - let transition = JobTransition::Complete; - self.transition_job(job_id, Guard::Manual(transition), &Target::Completed, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition(self, job_id, JobTransition::Complete, Target::Completed).await } async fn fail_job(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::Fail; - let target = Target::Failed(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::Fail, + Target::Failed(error_message.to_string()), + ) + .await } async fn retry_job(&self, job_id: JobId, retry_at: DateTime) -> Result<()> { check_timestamp(retry_at, "retry time")?; - let transition = JobTransition::Retry; - let target = Target::Retry { - retry_at, - error: None, - timed_out: false, - }; - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::Retry, + Target::Retry { + retry_at, + error: None, + timed_out: false, + }, + ) + .await } async fn finish_job_run( @@ -1007,11 +725,7 @@ impl DatabaseQueue for crate::queue::JobQueue { run: &Job, outcome: JobOutcome, ) -> Result> { - let target = Target::from(outcome); - Ok(self - .transition_job(run.id, Guard::Run(run), &target, true) - .await? - .into_run()) + lifecycle::finish_run(self, run, outcome).await } async fn complete_job_run_with_children( @@ -1026,7 +740,7 @@ impl DatabaseQueue for crate::queue::JobQueue { let mut conn = self.pool.acquire().await?; let mut tx = Self::begin_claim_transaction(&mut conn).await?; let result = async { - let transition = Self::transition_in_tx( + let transition = lifecycle::transition_in_tx::( &mut tx, run.id, Guard::Run(run), @@ -1235,21 +949,23 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn mark_job_dead(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::MarkDead; - let target = Target::Dead(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::MarkDead, + Target::Dead(error_message.to_string()), + ) + .await } async fn mark_job_timed_out(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::MarkTimedOut; - let target = Target::TimedOut(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::MarkTimedOut, + Target::TimedOut(error_message.to_string()), + ) + .await } async fn get_dead_jobs(&self, limit: Option, offset: Option) -> Result> { @@ -2459,7 +2175,8 @@ impl crate::queue::JobQueue { // A reclaimed job that died is a terminal failure like any other: // reschedule it if recurring, otherwise apply it to its dependents, // workflow and batch. - Self::after_terminal(conn, &job, JobStatus::Dead, now, true).await?; + lifecycle::after_terminal::(conn, &job, JobStatus::Dead, now, true) + .await?; recovery.dead.push(job.id); } else { recovery.requeued.push(job.id); @@ -2483,9 +2200,6 @@ impl crate::queue::JobQueue { } } -/// Columns written by [`insert_jobs`], in bind order. -const INSERT_JOB_COLUMNS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_storage_type, result_ttl_seconds, result_max_size_bytes, retry_strategy, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; - /// Rows per multi-row INSERT; 45 placeholders per row stays far below MySQL's 65535 /// and keeps statements well under the default `max_allowed_packet`. const INSERT_CHUNK_ROWS: usize = 200; @@ -2493,14 +2207,6 @@ const INSERT_CHUNK_ROWS: usize = 200; /// Ids per `id IN (...)` statement when locking or failing jobs by id. const ID_CHUNK: usize = 500; -fn result_storage_str(storage: &crate::job::ResultStorage) -> &'static str { - match storage { - crate::job::ResultStorage::Database => "database", - crate::job::ResultStorage::Memory => "memory", - crate::job::ResultStorage::None => "none", - } -} - /// Insert `jobs` with every persisted field. Used by `enqueue`, `enqueue_batch`, /// `enqueue_workflow` and archive restore, so all of them store the same columns. async fn insert_jobs(conn: &mut sqlx::MySqlConnection, jobs: &[Job]) -> Result<()> { @@ -2757,14 +2463,6 @@ async fn insert_dependent_jobs(conn: &mut sqlx::MySqlConnection, jobs: &mut [Job Ok(()) } -/// The locked `hammerwork_workflows` row of a job's workflow. -struct LockedWorkflow { - id: String, - policy: FailurePolicy, - status: WorkflowStatus, - total_jobs: usize, -} - /// Parse the `id` column of a list of rows. fn parse_ids(ids: Vec) -> Result> { ids.iter() @@ -2778,7 +2476,28 @@ fn parse_ids(ids: Vec) -> Result> { /// Transactions run at READ COMMITTED (like the dequeue), so each statement sees the /// latest committed data: a parent completing after another one's transaction /// committed sees that completion when it counts a shared child's dependencies. -impl crate::queue::JobQueue { +impl TransitionStore for crate::queue::JobQueue { + type Conn = sqlx::MySqlConnection; + + async fn lock_job(conn: &mut sqlx::MySqlConnection, job_id: JobId) -> Result> { + let row = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE id = ? FOR UPDATE" + )) + .bind(job_id.to_string()) + .fetch_optional(&mut *conn) + .await?; + row.map(JobRow::into_job).transpose() + } + + async fn db_now(conn: &mut sqlx::MySqlConnection) -> Result> { + db_now(conn).await + } + + /// A next run after the `TIMESTAMP` range cannot be stored. + fn can_schedule_at(next_run_at: DateTime) -> bool { + check_timestamp(next_run_at, "next run time").is_ok() + } + /// Apply `target` to a job if `guard` admits its current state, together with the /// side effects of the new state, in one transaction. async fn transition_job( @@ -2794,53 +2513,6 @@ impl crate::queue::JobQueue { .await } - async fn transition_job_once( - &self, - job_id: JobId, - guard: Guard<'_>, - target: &Target, - reschedule_recurring: bool, - ) -> Result { - let mut conn = self.pool.acquire().await?; - let mut tx = Self::begin_claim_transaction(&mut conn).await?; - let result = - Self::transition_in_tx(&mut tx, job_id, guard, target, reschedule_recurring).await; - super::end_transaction(tx, result).await - } - - async fn transition_in_tx( - conn: &mut sqlx::MySqlConnection, - job_id: JobId, - guard: Guard<'_>, - target: &Target, - reschedule_recurring: bool, - ) -> Result { - let row = sqlx::query_as::<_, JobRow>(&format!( - "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE id = ? FOR UPDATE" - )) - .bind(job_id.to_string()) - .fetch_optional(&mut *conn) - .await?; - let Some(row) = row else { - return Ok(TransitionResult::NotFound); - }; - let job = row.into_job()?; - if !guard.admits(&job) { - return Ok(TransitionResult::Rejected(job.status)); - } - - let now = db_now(conn).await?; - let target = target.on_db_clock(&guard, now); - Self::write_target(conn, job_id, &target, now).await?; - let recorded = match target.terminal_status() { - Some(status) => { - Self::after_terminal(conn, &job, status, now, reschedule_recurring).await? - } - None => RecordedOutcome::new(JobStatus::Pending), - }; - Ok(TransitionResult::Applied(recorded)) - } - /// Write the new status and its timestamps. Clears the lease: the run is over. async fn write_target( conn: &mut sqlx::MySqlConnection, @@ -2892,115 +2564,6 @@ impl crate::queue::JobQueue { Ok(()) } - /// Side effects of `job` reaching the terminal `status`. - /// - /// A recurring job (when `reschedule_recurring`) is rescheduled for its next run - /// instead. Otherwise dependents are resolved or failed, the workflow policy and - /// counters are applied, and the batch's failure mode and status. - async fn after_terminal( - conn: &mut sqlx::MySqlConnection, - job: &Job, - status: JobStatus, - now: DateTime, - reschedule_recurring: bool, - ) -> Result { - if reschedule_recurring && job.recurring { - if let Some(next_run_at) = lifecycle::next_cron_run(job, now) - .filter(|next_run_at| check_timestamp(*next_run_at, "next run time").is_ok()) - { - Self::reschedule_after_run(conn, job.id, next_run_at, status).await?; - let mut recorded = RecordedOutcome::new(JobStatus::Pending); - recorded.next_run_at = Some(next_run_at); - return Ok(recorded); - } - tracing::warn!( - "Could not calculate the next run time for recurring job {}; it stays {}", - job.id, - status.as_str() - ); - } - - let mut recorded = RecordedOutcome::new(status); - - // Lock the workflow row first: it serializes terminal transitions within a - // workflow, so concurrent completions cannot both miss each other. - let workflow = match job.workflow_id { - Some(id) => Self::lock_workflow(conn, id).await?, - None => None, - }; - - if status == JobStatus::Completed { - recorded.unblocked = Self::resolve_dependents(conn, job.id).await?; - } else { - recorded.cancelled = - Self::apply_failure_policy(conn, workflow.as_ref(), job.id, now).await?; - } - - if let Some(workflow) = &workflow { - Self::refresh_workflow(conn, workflow, now).await?; - } - if let Some(batch_id) = job.batch_id { - let cancelled = Self::apply_batch_outcome(conn, batch_id, job.id, status, now).await?; - recorded.cancelled.extend(cancelled); - } - Ok(recorded) - } - - /// Apply the [`FailurePolicy`] of `workflow` (the failed job's locked workflow, if - /// any) to the failure of `failed_job_id`. Returns the jobs that were failed. - /// - /// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then the - /// jobs that (transitively) depend on the failed one; - /// - `ContinueOnFailure`, and jobs with dependencies outside any workflow, fail - /// only the jobs that (transitively) depend on the failed one; - /// - `Manual` leaves the dependents waiting for an operator. - async fn apply_failure_policy( - conn: &mut sqlx::MySqlConnection, - workflow: Option<&LockedWorkflow>, - failed_job_id: JobId, - now: DateTime, - ) -> Result> { - match workflow { - Some(w) if w.policy == FailurePolicy::Manual => Ok(Vec::new()), - Some(w) if w.policy == FailurePolicy::FailFast => { - let mut failed = - Self::fail_workflow_pending(conn, &w.id, failed_job_id, now).await?; - for id in Self::fail_dependents(conn, failed_job_id, now).await? { - if !failed.contains(&id) { - failed.push(id); - } - } - Ok(failed) - } - _ => Self::fail_dependents(conn, failed_job_id, now).await, - } - } - - /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job - /// and its workflow (in the same order as a terminal transition), apply the - /// workflow's failure policy and update the workflow's counters and status. - async fn fail_job_dependencies_in_tx( - conn: &mut sqlx::MySqlConnection, - failed_job_id: JobId, - ) -> Result> { - let workflow_id: Option> = - sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = ? FOR UPDATE") - .bind(failed_job_id.to_string()) - .fetch_optional(&mut *conn) - .await?; - let workflow = match workflow_id.flatten() { - Some(id) => Self::lock_workflow(conn, uuid::Uuid::parse_str(&id)?).await?, - None => None, - }; - let now = db_now(conn).await?; - let failed = - Self::apply_failure_policy(conn, workflow.as_ref(), failed_job_id, now).await?; - if let Some(workflow) = &workflow { - Self::refresh_workflow(conn, workflow, now).await?; - } - Ok(failed) - } - /// Put a recurring job back to `Pending` for its next run. A failed run's error and /// failure time stay visible until the next run; a successful run clears them. async fn reschedule_after_run( @@ -3054,66 +2617,13 @@ impl crate::queue::JobQueue { return Ok(None); }; Ok(Some(LockedWorkflow { - id, + id: workflow_id, policy: FailurePolicy::parse_from_db(&row.try_get::("failure_policy")?)?, status: WorkflowStatus::parse_from_db(&row.try_get::("status")?)?, total_jobs: usize::try_from(row.try_get::("total_jobs")?).unwrap_or(0), })) } - /// Lock the rows among `candidates` that still match `condition`, by primary key - /// and in id order, and return their `columns`. - /// - /// Callers find candidates with a non-locking read first. A locking read that has - /// to scan (e.g. `JSON_CONTAINS`, which no index serves) would lock or wait on - /// every row it scans, including rows that concurrent dequeues and transitions - /// hold; locking by primary key touches only the rows we change. - async fn lock_rows_by_id( - conn: &mut sqlx::MySqlConnection, - candidates: &[String], - columns: &str, - condition: &str, - ) -> Result> { - let mut rows = Vec::new(); - for chunk in candidates.chunks(ID_CHUNK) { - let placeholders = vec!["?"; chunk.len()].join(", "); - let query = format!( - "SELECT {columns} FROM hammerwork_jobs WHERE id IN ({placeholders}) \ - AND {condition} ORDER BY id FOR UPDATE" - ); - let mut select = sqlx::query(&query); - for id in chunk { - select = select.bind(id); - } - rows.extend(select.fetch_all(&mut *conn).await?); - } - Ok(rows) - } - - /// Set `status = 'Failed'` on the (already locked) jobs `ids`, recording `error`. - /// Jobs still waiting on dependencies get `dependency_status = 'failed'`. - async fn fail_jobs_by_id( - conn: &mut sqlx::MySqlConnection, - ids: &[String], - error: &str, - now: DateTime, - ) -> Result<()> { - for chunk in ids.chunks(ID_CHUNK) { - let placeholders = vec!["?"; chunk.len()].join(", "); - let query = format!( - "UPDATE hammerwork_jobs SET status = 'Failed', failed_at = ?, error_message = ?, \ - dependency_status = CASE WHEN dependency_status IN ('waiting', 'satisfied') \ - THEN 'failed' ELSE dependency_status END WHERE id IN ({placeholders})" - ); - let mut update = sqlx::query(&query).bind(now).bind(error); - for id in chunk { - update = update.bind(id); - } - update.execute(&mut *conn).await?; - } - Ok(()) - } - /// Mark `waiting` dependents of `completed_job_id` whose dependencies have all /// completed as `satisfied`, so they can be dequeued. /// @@ -3196,65 +2706,6 @@ impl crate::queue::JobQueue { parse_ids(satisfied) } - /// Cancel a workflow: its unfinished jobs (pending, retrying and **running**) become - /// `Failed` with "Workflow cancelled", and the workflow `cancelled`. - /// - /// A running job keeps running in its worker (a handler cannot be interrupted), but - /// its outcome is discarded: `finish_job_run` only records outcomes for jobs that - /// are still `Running` the same run, and heartbeats stop extending the lease. - async fn cancel_workflow_in_tx( - conn: &mut sqlx::MySqlConnection, - workflow_id: crate::workflow::WorkflowId, - ) -> Result<()> { - // Serializes with the terminal transitions of the workflow's jobs. - Self::lock_workflow(conn, workflow_id).await?; - let now = db_now(conn).await?; - let id = workflow_id.to_string(); - let candidates: Vec = sqlx::query_scalar(&format!( - "SELECT id FROM hammerwork_jobs WHERE workflow_id = ? AND status IN ({})", - lifecycle::UNFINISHED_STATUS_SQL - )) - .bind(&id) - .fetch_all(&mut *conn) - .await?; - let ids: Vec = Self::lock_rows_by_id( - conn, - &candidates, - "id", - &format!("status IN ({})", lifecycle::UNFINISHED_STATUS_SQL), - ) - .await? - .iter() - .map(|row| row.try_get("id")) - .collect::>()?; - for chunk in ids.chunks(ID_CHUNK) { - let placeholders = vec!["?"; chunk.len()].join(", "); - let query = format!( - "UPDATE hammerwork_jobs SET status = 'Failed', failed_at = ?, error_message = ?, \ - dependency_status = CASE WHEN dependency_status = 'waiting' \ - THEN 'failed' ELSE dependency_status END, \ - last_heartbeat_at = NULL, lease_expires_at = NULL WHERE id IN ({placeholders})" - ); - let mut update = sqlx::query(&query) - .bind(now) - .bind(lifecycle::WORKFLOW_CANCELLED_MESSAGE); - for id in chunk { - update = update.bind(id); - } - update.execute(&mut *conn).await?; - } - - sqlx::query( - "UPDATE hammerwork_workflows SET status = 'cancelled', \ - failed_at = COALESCE(failed_at, ?) WHERE id = ?", - ) - .bind(now) - .bind(&id) - .execute(&mut *conn) - .await?; - Ok(()) - } - /// Fail every pending job that (transitively) depends on `failed_job_id`. async fn fail_dependents( conn: &mut sqlx::MySqlConnection, @@ -3298,31 +2749,10 @@ impl crate::queue::JobQueue { Ok(failed) } - /// Fail the jobs among `candidates` that have not started yet (`Pending` or - /// `Retrying`), recording `error`. Returns the jobs failed. - async fn fail_unstarted( - conn: &mut sqlx::MySqlConnection, - candidates: &[String], - error: &str, - now: DateTime, - ) -> Result> { - let ids: Vec = - Self::lock_rows_by_id(conn, candidates, "id", "status IN ('Pending', 'Retrying')") - .await? - .iter() - .map(|row| row.try_get("id")) - .collect::>()?; - if ids.is_empty() { - return Ok(Vec::new()); - } - Self::fail_jobs_by_id(conn, &ids, error, now).await?; - parse_ids(ids) - } - /// Fail the pending jobs of a fail-fast workflow after `failed_job_id` failed. async fn fail_workflow_pending( conn: &mut sqlx::MySqlConnection, - workflow_id: &str, + workflow_id: uuid::Uuid, failed_job_id: JobId, now: DateTime, ) -> Result> { @@ -3330,7 +2760,7 @@ impl crate::queue::JobQueue { "SELECT id FROM hammerwork_jobs WHERE workflow_id = ? AND id <> ? \ AND status IN ('Pending', 'Retrying')", ) - .bind(workflow_id) + .bind(workflow_id.to_string()) .bind(failed_job_id.to_string()) .fetch_all(&mut *conn) .await?; @@ -3352,7 +2782,7 @@ impl crate::queue::JobQueue { let counts: Vec<(String, i64)> = sqlx::query_as( "SELECT status, COUNT(*) FROM hammerwork_jobs WHERE workflow_id = ? GROUP BY status", ) - .bind(&workflow.id) + .bind(workflow.id.to_string()) .fetch_all(&mut *conn) .await?; let progress = WorkflowProgress::from_status_counts(counts); @@ -3374,7 +2804,7 @@ impl crate::queue::JobQueue { .bind(status.as_str()) .bind((status == WorkflowStatus::Completed).then_some(now)) .bind((status == WorkflowStatus::Failed).then_some(now)) - .bind(&workflow.id) + .bind(workflow.id.to_string()) .execute(&mut *conn) .await?; Ok(()) @@ -3486,6 +2916,180 @@ impl crate::queue::JobQueue { .await?; Ok(cancelled) } +} + +impl crate::queue::JobQueue { + async fn transition_job_once( + &self, + job_id: JobId, + guard: Guard<'_>, + target: &Target, + reschedule_recurring: bool, + ) -> Result { + let mut conn = self.pool.acquire().await?; + let mut tx = Self::begin_claim_transaction(&mut conn).await?; + let result = lifecycle::transition_in_tx::( + &mut tx, + job_id, + guard, + target, + reschedule_recurring, + ) + .await; + super::end_transaction(tx, result).await + } + + /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job + /// and its workflow (in the same order as a terminal transition), apply the + /// workflow's failure policy and update the workflow's counters and status. + async fn fail_job_dependencies_in_tx( + conn: &mut sqlx::MySqlConnection, + failed_job_id: JobId, + ) -> Result> { + let workflow_id: Option> = + sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = ? FOR UPDATE") + .bind(failed_job_id.to_string()) + .fetch_optional(&mut *conn) + .await?; + let workflow_id = workflow_id + .flatten() + .map(|id| uuid::Uuid::parse_str(&id)) + .transpose()?; + lifecycle::fail_job_dependencies::(conn, failed_job_id, workflow_id).await + } + + /// Lock the rows among `candidates` that still match `condition`, by primary key + /// and in id order, and return their `columns`. + /// + /// Callers find candidates with a non-locking read first. A locking read that has + /// to scan (e.g. `JSON_CONTAINS`, which no index serves) would lock or wait on + /// every row it scans, including rows that concurrent dequeues and transitions + /// hold; locking by primary key touches only the rows we change. + async fn lock_rows_by_id( + conn: &mut sqlx::MySqlConnection, + candidates: &[String], + columns: &str, + condition: &str, + ) -> Result> { + let mut rows = Vec::new(); + for chunk in candidates.chunks(ID_CHUNK) { + let placeholders = vec!["?"; chunk.len()].join(", "); + let query = format!( + "SELECT {columns} FROM hammerwork_jobs WHERE id IN ({placeholders}) \ + AND {condition} ORDER BY id FOR UPDATE" + ); + let mut select = sqlx::query(&query); + for id in chunk { + select = select.bind(id); + } + rows.extend(select.fetch_all(&mut *conn).await?); + } + Ok(rows) + } + + /// Set `status = 'Failed'` on the (already locked) jobs `ids`, recording `error`. + /// Jobs still waiting on dependencies get `dependency_status = 'failed'`. + async fn fail_jobs_by_id( + conn: &mut sqlx::MySqlConnection, + ids: &[String], + error: &str, + now: DateTime, + ) -> Result<()> { + for chunk in ids.chunks(ID_CHUNK) { + let placeholders = vec!["?"; chunk.len()].join(", "); + let query = format!( + "UPDATE hammerwork_jobs SET status = 'Failed', failed_at = ?, error_message = ?, \ + dependency_status = CASE WHEN dependency_status IN ('waiting', 'satisfied') \ + THEN 'failed' ELSE dependency_status END WHERE id IN ({placeholders})" + ); + let mut update = sqlx::query(&query).bind(now).bind(error); + for id in chunk { + update = update.bind(id); + } + update.execute(&mut *conn).await?; + } + Ok(()) + } + + /// Cancel a workflow: its unfinished jobs (pending, retrying and **running**) become + /// `Failed` with "Workflow cancelled", and the workflow `cancelled`. + /// + /// A running job keeps running in its worker (a handler cannot be interrupted), but + /// its outcome is discarded: `finish_job_run` only records outcomes for jobs that + /// are still `Running` the same run, and heartbeats stop extending the lease. + async fn cancel_workflow_in_tx( + conn: &mut sqlx::MySqlConnection, + workflow_id: crate::workflow::WorkflowId, + ) -> Result<()> { + // Serializes with the terminal transitions of the workflow's jobs. + Self::lock_workflow(conn, workflow_id).await?; + let now = db_now(conn).await?; + let id = workflow_id.to_string(); + let candidates: Vec = sqlx::query_scalar(&format!( + "SELECT id FROM hammerwork_jobs WHERE workflow_id = ? AND status IN ({})", + lifecycle::UNFINISHED_STATUS_SQL + )) + .bind(&id) + .fetch_all(&mut *conn) + .await?; + let ids: Vec = Self::lock_rows_by_id( + conn, + &candidates, + "id", + &format!("status IN ({})", lifecycle::UNFINISHED_STATUS_SQL), + ) + .await? + .iter() + .map(|row| row.try_get("id")) + .collect::>()?; + for chunk in ids.chunks(ID_CHUNK) { + let placeholders = vec!["?"; chunk.len()].join(", "); + let query = format!( + "UPDATE hammerwork_jobs SET status = 'Failed', failed_at = ?, error_message = ?, \ + dependency_status = CASE WHEN dependency_status = 'waiting' \ + THEN 'failed' ELSE dependency_status END, \ + last_heartbeat_at = NULL, lease_expires_at = NULL WHERE id IN ({placeholders})" + ); + let mut update = sqlx::query(&query) + .bind(now) + .bind(lifecycle::WORKFLOW_CANCELLED_MESSAGE); + for id in chunk { + update = update.bind(id); + } + update.execute(&mut *conn).await?; + } + + sqlx::query( + "UPDATE hammerwork_workflows SET status = 'cancelled', \ + failed_at = COALESCE(failed_at, ?) WHERE id = ?", + ) + .bind(now) + .bind(&id) + .execute(&mut *conn) + .await?; + Ok(()) + } + + /// Fail the jobs among `candidates` that have not started yet (`Pending` or + /// `Retrying`), recording `error`. Returns the jobs failed. + async fn fail_unstarted( + conn: &mut sqlx::MySqlConnection, + candidates: &[String], + error: &str, + now: DateTime, + ) -> Result> { + let ids: Vec = + Self::lock_rows_by_id(conn, candidates, "id", "status IN ('Pending', 'Retrying')") + .await? + .iter() + .map(|row| row.try_get("id")) + .collect::>()?; + if ids.is_empty() { + return Ok(Vec::new()); + } + Self::fail_jobs_by_id(conn, &ids, error, now).await?; + parse_ids(ids) + } /// Apply a manual transition that writes no side effects (`retry_dead_job`, /// `reschedule_cron_job`): lock the row, check the guard, then run `update`. diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 3893f1c..389f5f6 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -3,7 +3,13 @@ //! This module provides the PostgreSQL-specific implementation of the `DatabaseQueue` trait, //! optimized for PostgreSQL's JSONB and advanced querying capabilities. -use super::lifecycle::{self, Guard, ParentState, Target, TransitionResult}; +use super::lifecycle::{ + self, Guard, LockedWorkflow, ParentState, Target, TransitionResult, TransitionStore, +}; +use super::row::{ + self, ARCHIVED_JOB_FIELDS, ENCRYPTION_COLUMNS, INSERT_JOB_COLUMNS, JOB_SELECT_FIELDS, + result_storage_str, +}; use super::{ DatabaseQueue, DeadJobSummary, JobOutcome, JobTransition, QueueStats, RecordedOutcome, }; @@ -85,30 +91,6 @@ pub(crate) struct JobRow { pub encrypted_at: Option>, } -/// Standard field list for selecting complete job data from hammerwork_jobs table. -const JOB_SELECT_FIELDS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, retry_strategy, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; - -/// Columns of hammerwork_jobs_archive needed to rebuild a [`Job`]. -const ARCHIVED_JOB_FIELDS: &str = "id, queue_name, payload, payload_compressed, status, priority, attempts, max_attempts, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, result, result_ttl, retry_strategy, timeout_seconds, cron_schedule, next_run_at, recurring, timezone, batch_id, depends_on, dependency_status, result_config, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, pii_fields"; - -/// Encryption columns of hammerwork_jobs and hammerwork_jobs_archive (migration 011). -/// Archiving and restoring copy them between the tables in SQL, so encrypted payloads -/// move without being decrypted, with or without the `encryption` feature. -const ENCRYPTION_COLUMNS: [&str; 12] = [ - "is_encrypted", - "encryption_key_id", - "encryption_algorithm", - "encrypted_payload", - "encryption_nonce", - "encryption_tag", - "encryption_metadata", - "payload_hash", - "pii_fields", - "retention_policy", - "retention_delete_at", - "encrypted_at", -]; - /// Copies the encryption columns of the jobs `ids` from table `from` to table `to`. async fn copy_encryption_columns( conn: &mut sqlx::PgConnection, @@ -211,40 +193,17 @@ fn archived_job_from_row(row: &sqlx::postgres::PgRow) -> Result { } impl JobRow { - pub fn into_job(self) -> Result { - // Extract encryption data before moving self - #[cfg(feature = "encryption")] - let encryption_config = self.build_encryption_config()?; - #[cfg(feature = "encryption")] - let retention_policy = self.parse_retention_policy()?; + pub fn into_job(mut self) -> Result { + let pii_fields = self.pii_fields.take().unwrap_or_default(); #[cfg(feature = "encryption")] - let encrypted_payload = self.build_encrypted_payload()?; - let pii_fields = self.pii_fields.unwrap_or_default(); + let (encryption_config, retention_policy, encrypted_payload) = + self.encryption_row(&pii_fields).decode()?; Ok(Job { id: self.id, queue_name: self.queue_name, payload: self.payload, - status: { - // Handle both quoted (old format) and unquoted (new format) status values - let cleaned_str = self.status.trim_matches('"'); - match cleaned_str { - "Pending" => JobStatus::Pending, - "Running" => JobStatus::Running, - "Completed" => JobStatus::Completed, - "Failed" => JobStatus::Failed, - "Dead" => JobStatus::Dead, - "TimedOut" => JobStatus::TimedOut, - "Retrying" => JobStatus::Retrying, - "Archived" => JobStatus::Archived, - _ => { - return Err(crate::error::HammerworkError::Processing(format!( - "Unknown job status: {}", - cleaned_str - ))); - } - } - }, + status: row::job_status_from_row(&self.status)?, priority: JobPriority::from_i32(self.priority).unwrap_or(JobPriority::Normal), attempts: self.attempts, max_attempts: self.max_attempts, @@ -265,16 +224,7 @@ impl JobRow { timezone: self.timezone, batch_id: self.batch_id, result_config: crate::job::ResultConfig { - storage: self - .result_storage_type - .as_ref() - .map(|s| match s.as_str() { - "database" => crate::job::ResultStorage::Database, - "memory" => crate::job::ResultStorage::Memory, - "none" => crate::job::ResultStorage::None, - _ => crate::job::ResultStorage::None, - }) - .unwrap_or(crate::job::ResultStorage::None), + storage: row::result_storage_from_db(self.result_storage_type.as_deref()), ttl: self .result_ttl_seconds .map(|s| super::db_seconds(s, "result_ttl_seconds")) @@ -290,12 +240,7 @@ impl JobRow { retry_strategy: super::retry_strategy_from_json(self.retry_strategy)?, depends_on: self.depends_on, dependents: self.dependents, - dependency_status: self - .dependency_status - .as_deref() - .map(crate::workflow::DependencyStatus::parse_from_db) - .transpose()? - .unwrap_or(crate::workflow::DependencyStatus::None), + dependency_status: row::dependency_status_from_row(self.dependency_status.as_deref())?, workflow_id: self.workflow_id, workflow_name: self.workflow_name, trace_id: self.trace_id, @@ -313,236 +258,25 @@ impl JobRow { }) } - /// Builds an EncryptionConfig from database fields if encryption is enabled. - #[cfg(feature = "encryption")] - fn build_encryption_config(&self) -> Result> { - if !self.is_encrypted { - return Ok(None); - } - - // Parse algorithm - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305, - Some(alg) => { - return Err(crate::HammerworkError::Processing(format!( - "Unknown encryption algorithm: {}", - alg - ))); - } - None => { - return Err(crate::HammerworkError::Processing( - "Missing encryption algorithm for encrypted job".to_string(), - )); - } - }; - - // Parse metadata if available - let (key_id, compression_enabled, version) = - if let Some(metadata) = &self.encryption_metadata { - let key_id = metadata - .get("key_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); - let compression_enabled = metadata - .get("compressed") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let version = metadata - .get("config_version") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - (key_id, compression_enabled, version) - } else { - (self.encryption_key_id.clone(), false, 1) - }; - - let config = crate::encryption::EncryptionConfig { - algorithm, - key_source: crate::encryption::KeySource::External( - key_id.unwrap_or_else(|| "unknown".to_string()), - ), - key_rotation_enabled: false, // Not stored in database - key_rotation_interval: None, - default_retention: None, // Will be parsed separately - compression_enabled, - key_id: self.encryption_key_id.clone(), - version, - }; - - Ok(Some(config)) - } - - /// Parses the retention policy from the database string. + /// The encryption columns, for [`row::EncryptionRow::decode`]. #[cfg(feature = "encryption")] - fn parse_retention_policy(&self) -> Result> { - match self.retention_policy.as_deref() { - None => Ok(None), - Some("KeepIndefinitely") => { - Ok(Some(crate::encryption::RetentionPolicy::KeepIndefinitely)) - } - Some("DeleteImmediately") => { - Ok(Some(crate::encryption::RetentionPolicy::DeleteImmediately)) - } - Some("UseDefault") => Ok(Some(crate::encryption::RetentionPolicy::UseDefault)), - Some(policy_str) => { - // Handle DeleteAfter and DeleteAt policies - if let Some(delete_at) = self.retention_delete_at { - if policy_str == "DeleteAt" { - Ok(Some(crate::encryption::RetentionPolicy::DeleteAt( - delete_at, - ))) - } else if policy_str == "DeleteAfter" { - // Calculate duration from creation to deletion time - let duration = delete_at.signed_duration_since(self.created_at); - if let Ok(std_duration) = duration.to_std() { - Ok(Some(crate::encryption::RetentionPolicy::DeleteAfter( - std_duration, - ))) - } else { - Ok(Some(crate::encryption::RetentionPolicy::UseDefault)) - } - } else { - Err(crate::HammerworkError::Processing(format!( - "Unknown retention policy: {}", - policy_str - ))) - } - } else { - Err(crate::HammerworkError::Processing(format!( - "Retention policy '{}' requires retention_delete_at timestamp", - policy_str - ))) - } - } + fn encryption_row<'a>(&'a self, pii_fields: &'a [String]) -> row::EncryptionRow<'a> { + row::EncryptionRow { + is_encrypted: self.is_encrypted, + created_at: self.created_at, + encryption_key_id: self.encryption_key_id.as_deref(), + encryption_algorithm: self.encryption_algorithm.as_deref(), + encrypted_payload: self.encrypted_payload.as_deref(), + encryption_nonce: self.encryption_nonce.as_deref(), + encryption_tag: self.encryption_tag.as_deref(), + encryption_metadata: self.encryption_metadata.as_ref(), + payload_hash: self.payload_hash.as_deref(), + pii_fields, + retention_policy: self.retention_policy.as_deref(), + retention_delete_at: self.retention_delete_at, + encrypted_at: self.encrypted_at, } } - - /// Builds an EncryptedPayload from database fields if the job is encrypted. - #[cfg(feature = "encryption")] - fn build_encrypted_payload(&self) -> Result> { - if !self.is_encrypted { - return Ok(None); - } - - let encrypted_data = self.encrypted_payload.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encrypted payload for encrypted job".to_string(), - ) - })?; - - let nonce = self.encryption_nonce.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encryption nonce for encrypted job".to_string(), - ) - })?; - - let tag = self.encryption_tag.as_ref().ok_or_else(|| { - crate::HammerworkError::Processing( - "Missing encryption tag for encrypted job".to_string(), - ) - })?; - - // Parse metadata - let metadata = if let Some(metadata_json) = &self.encryption_metadata { - // Build metadata from JSON - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => { - crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305 - } - _ => crate::encryption::EncryptionAlgorithm::AES256GCM, // Default fallback - }; - - let key_id = metadata_json - .get("key_id") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) - .or_else(|| self.encryption_key_id.clone()) - .unwrap_or_else(|| "unknown".to_string()); - - let config_version = metadata_json - .get("config_version") - .and_then(|v| v.as_u64()) - .unwrap_or(1) as u32; - - let compressed = metadata_json - .get("compressed") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - let encrypted_fields = metadata_json - .get("encrypted_fields") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|v| v.as_str().map(|s| s.to_string())) - .collect() - }) - .unwrap_or_else(|| self.pii_fields.clone().unwrap_or_default()); - - let retention_policy = self - .parse_retention_policy()? - .unwrap_or(crate::encryption::RetentionPolicy::UseDefault); - - let encrypted_at = self.encrypted_at.unwrap_or(self.created_at); - - crate::encryption::EncryptionMetadata { - algorithm, - key_id, - config_version, - compressed, - encrypted_fields, - retention_policy, - encrypted_at, - delete_at: self.retention_delete_at, - payload_hash: self.payload_hash.clone().unwrap_or_default(), - format_version: crate::encryption::EncryptionMetadata::format_version_from_json( - metadata_json, - ), - } - } else { - // Build basic metadata from available fields - let algorithm = match self.encryption_algorithm.as_deref() { - Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, - Some("ChaCha20Poly1305") => { - crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305 - } - _ => crate::encryption::EncryptionAlgorithm::AES256GCM, // Default fallback - }; - - crate::encryption::EncryptionMetadata { - algorithm, - key_id: self - .encryption_key_id - .clone() - .unwrap_or_else(|| "unknown".to_string()), - config_version: 1, - compressed: false, - encrypted_fields: self.pii_fields.clone().unwrap_or_default(), - retention_policy: self - .parse_retention_policy()? - .unwrap_or(crate::encryption::RetentionPolicy::UseDefault), - encrypted_at: self.encrypted_at.unwrap_or(self.created_at), - delete_at: self.retention_delete_at, - payload_hash: self.payload_hash.clone().unwrap_or_default(), - format_version: crate::encryption::EncryptionMetadata::FORMAT_UNBOUND, - } - }; - - // Encode binary data to base64 - use base64::Engine; - let ciphertext = base64::engine::general_purpose::STANDARD.encode(encrypted_data); - let nonce_b64 = base64::engine::general_purpose::STANDARD.encode(nonce); - let tag_b64 = base64::engine::general_purpose::STANDARD.encode(tag); - - Ok(Some(crate::encryption::EncryptedPayload { - ciphertext, - nonce: nonce_b64, - tag: tag_b64, - metadata, - })) - } } impl crate::queue::JobQueue { @@ -740,33 +474,31 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn complete_job(&self, job_id: JobId) -> Result<()> { - let transition = JobTransition::Complete; - self.transition_job(job_id, Guard::Manual(transition), &Target::Completed, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition(self, job_id, JobTransition::Complete, Target::Completed).await } async fn fail_job(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::Fail; - let target = Target::Failed(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::Fail, + Target::Failed(error_message.to_string()), + ) + .await } async fn retry_job(&self, job_id: JobId, retry_at: DateTime) -> Result<()> { - let transition = JobTransition::Retry; - let target = Target::Retry { - retry_at, - error: None, - timed_out: false, - }; - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::Retry, + Target::Retry { + retry_at, + error: None, + timed_out: false, + }, + ) + .await } async fn finish_job_run( @@ -774,11 +506,7 @@ impl DatabaseQueue for crate::queue::JobQueue { run: &Job, outcome: JobOutcome, ) -> Result> { - let target = Target::from(outcome); - Ok(self - .transition_job(run.id, Guard::Run(run), &target, true) - .await? - .into_run()) + lifecycle::finish_run(self, run, outcome).await } async fn complete_job_run_with_children( @@ -792,7 +520,7 @@ impl DatabaseQueue for crate::queue::JobQueue { super::retry_on_conflict(|| async { let mut tx = self.pool.begin().await?; let result = async { - let transition = Self::transition_in_tx( + let transition = lifecycle::transition_in_tx::( &mut tx, run.id, Guard::Run(run), @@ -996,21 +724,23 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn mark_job_dead(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::MarkDead; - let target = Target::Dead(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::MarkDead, + Target::Dead(error_message.to_string()), + ) + .await } async fn mark_job_timed_out(&self, job_id: JobId, error_message: &str) -> Result<()> { - let transition = JobTransition::MarkTimedOut; - let target = Target::TimedOut(error_message.to_string()); - self.transition_job(job_id, Guard::Manual(transition), &target, false) - .await? - .into_manual(job_id, transition)?; - Ok(()) + lifecycle::manual_transition( + self, + job_id, + JobTransition::MarkTimedOut, + Target::TimedOut(error_message.to_string()), + ) + .await } async fn get_dead_jobs(&self, limit: Option, offset: Option) -> Result> { @@ -2215,7 +1945,7 @@ impl crate::queue::JobQueue { continue; } }; - Self::after_terminal(conn, &job, JobStatus::Dead, now, true).await?; + lifecycle::after_terminal::(conn, &job, JobStatus::Dead, now, true).await?; } Ok(recovery) @@ -2234,20 +1964,9 @@ impl crate::queue::JobQueue { } } -/// Columns written by [`insert_jobs`], in bind order. -const INSERT_JOB_COLUMNS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_storage_type, result_ttl_seconds, result_max_size_bytes, retry_strategy, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; - /// Rows per multi-row INSERT; 45 binds per row stays below PostgreSQL's 65535. const INSERT_CHUNK_ROWS: usize = 1000; -fn result_storage_str(storage: &crate::job::ResultStorage) -> &'static str { - match storage { - crate::job::ResultStorage::Database => "database", - crate::job::ResultStorage::Memory => "memory", - crate::job::ResultStorage::None => "none", - } -} - /// Insert `jobs` with every persisted field. Used by `enqueue`, `enqueue_batch`, /// `enqueue_workflow` and archive restore, so all of them store the same columns. async fn insert_jobs(conn: &mut sqlx::PgConnection, jobs: &[Job]) -> Result<()> { @@ -2471,17 +2190,25 @@ async fn insert_dependent_jobs(conn: &mut sqlx::PgConnection, jobs: &mut [Job]) Ok(()) } -/// The locked `hammerwork_workflows` row of a job's workflow. -struct LockedWorkflow { - id: uuid::Uuid, - policy: FailurePolicy, - status: WorkflowStatus, - total_jobs: usize, -} - /// Job lifecycle transitions and their side effects (dependencies, workflows, batches, /// cron). See [`crate::queue::lifecycle`]. -impl crate::queue::JobQueue { +impl TransitionStore for crate::queue::JobQueue { + type Conn = sqlx::PgConnection; + + async fn lock_job(conn: &mut sqlx::PgConnection, job_id: JobId) -> Result> { + let row = sqlx::query_as::<_, JobRow>(&format!( + "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE id = $1 FOR UPDATE" + )) + .bind(job_id) + .fetch_optional(&mut *conn) + .await?; + row.map(JobRow::into_job).transpose() + } + + async fn db_now(conn: &mut sqlx::PgConnection) -> Result> { + db_now(conn).await + } + /// Apply `target` to a job if `guard` admits its current state, together with the /// side effects of the new state, in one transaction. async fn transition_job( @@ -2497,52 +2224,6 @@ impl crate::queue::JobQueue { .await } - async fn transition_job_once( - &self, - job_id: JobId, - guard: Guard<'_>, - target: &Target, - reschedule_recurring: bool, - ) -> Result { - let mut tx = self.pool.begin().await?; - let result = - Self::transition_in_tx(&mut tx, job_id, guard, target, reschedule_recurring).await; - super::end_transaction(tx, result).await - } - - async fn transition_in_tx( - conn: &mut sqlx::PgConnection, - job_id: JobId, - guard: Guard<'_>, - target: &Target, - reschedule_recurring: bool, - ) -> Result { - let row = sqlx::query_as::<_, JobRow>(&format!( - "SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs WHERE id = $1 FOR UPDATE" - )) - .bind(job_id) - .fetch_optional(&mut *conn) - .await?; - let Some(row) = row else { - return Ok(TransitionResult::NotFound); - }; - let job = row.into_job()?; - if !guard.admits(&job) { - return Ok(TransitionResult::Rejected(job.status)); - } - - let now = db_now(conn).await?; - let target = target.on_db_clock(&guard, now); - Self::write_target(conn, job_id, &target, now).await?; - let recorded = match target.terminal_status() { - Some(status) => { - Self::after_terminal(conn, &job, status, now, reschedule_recurring).await? - } - None => RecordedOutcome::new(JobStatus::Pending), - }; - Ok(TransitionResult::Applied(recorded)) - } - /// Write the new status and its timestamps. Clears the lease: the run is over. async fn write_target( conn: &mut sqlx::PgConnection, @@ -2592,113 +2273,6 @@ impl crate::queue::JobQueue { Ok(()) } - /// Side effects of `job` reaching the terminal `status`. - /// - /// A recurring job (when `reschedule_recurring`) is rescheduled for its next run - /// instead. Otherwise dependents are resolved or failed, the workflow policy and - /// counters are applied, and the batch's failure mode and status. - async fn after_terminal( - conn: &mut sqlx::PgConnection, - job: &Job, - status: JobStatus, - now: DateTime, - reschedule_recurring: bool, - ) -> Result { - if reschedule_recurring && job.recurring { - if let Some(next_run_at) = lifecycle::next_cron_run(job, now) { - Self::reschedule_after_run(conn, job.id, next_run_at, status).await?; - let mut recorded = RecordedOutcome::new(JobStatus::Pending); - recorded.next_run_at = Some(next_run_at); - return Ok(recorded); - } - tracing::warn!( - "Could not calculate the next run time for recurring job {}; it stays {}", - job.id, - status.as_str() - ); - } - - let mut recorded = RecordedOutcome::new(status); - - // Lock the workflow row first: it serializes terminal transitions within a - // workflow, so concurrent completions cannot both miss each other. - let workflow = match job.workflow_id { - Some(id) => Self::lock_workflow(conn, id).await?, - None => None, - }; - - if status == JobStatus::Completed { - recorded.unblocked = Self::resolve_dependents(conn, job.id).await?; - } else { - recorded.cancelled = - Self::apply_failure_policy(conn, workflow.as_ref(), job.id, now).await?; - } - - if let Some(workflow) = &workflow { - Self::refresh_workflow(conn, workflow, now).await?; - } - if let Some(batch_id) = job.batch_id { - let cancelled = Self::apply_batch_outcome(conn, batch_id, job.id, status, now).await?; - recorded.cancelled.extend(cancelled); - } - Ok(recorded) - } - - /// Apply the [`FailurePolicy`] of `workflow` (the failed job's locked workflow, if - /// any) to the failure of `failed_job_id`. Returns the jobs that were failed. - /// - /// - `FailFast` fails the workflow's other `Pending` and `Retrying` jobs, then the - /// jobs that (transitively) depend on the failed one; - /// - `ContinueOnFailure`, and jobs with dependencies outside any workflow, fail - /// only the jobs that (transitively) depend on the failed one; - /// - `Manual` leaves the dependents waiting for an operator. - async fn apply_failure_policy( - conn: &mut sqlx::PgConnection, - workflow: Option<&LockedWorkflow>, - failed_job_id: JobId, - now: DateTime, - ) -> Result> { - match workflow { - Some(w) if w.policy == FailurePolicy::Manual => Ok(Vec::new()), - Some(w) if w.policy == FailurePolicy::FailFast => { - let mut failed = - Self::fail_workflow_pending(conn, w.id, failed_job_id, now).await?; - for id in Self::fail_dependents(conn, failed_job_id, now).await? { - if !failed.contains(&id) { - failed.push(id); - } - } - Ok(failed) - } - _ => Self::fail_dependents(conn, failed_job_id, now).await, - } - } - - /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job - /// and its workflow (in the same order as a terminal transition), apply the - /// workflow's failure policy and update the workflow's counters and status. - async fn fail_job_dependencies_in_tx( - conn: &mut sqlx::PgConnection, - failed_job_id: JobId, - ) -> Result> { - let workflow_id: Option> = - sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = $1 FOR UPDATE") - .bind(failed_job_id) - .fetch_optional(&mut *conn) - .await?; - let workflow = match workflow_id.flatten() { - Some(id) => Self::lock_workflow(conn, id).await?, - None => None, - }; - let now = db_now(conn).await?; - let failed = - Self::apply_failure_policy(conn, workflow.as_ref(), failed_job_id, now).await?; - if let Some(workflow) = &workflow { - Self::refresh_workflow(conn, workflow, now).await?; - } - Ok(failed) - } - /// Put a recurring job back to `Pending` for its next run. A failed run's error and /// failure time stay visible until the next run; a successful run clears them. async fn reschedule_after_run( @@ -2807,55 +2381,6 @@ impl crate::queue::JobQueue { .await?) } - /// Cancel a workflow: its unfinished jobs (pending, retrying and **running**) become - /// `Failed` with "Workflow cancelled", and the workflow `cancelled`. - /// - /// A running job keeps running in its worker (a handler cannot be interrupted), but - /// its outcome is discarded: `finish_job_run` only records outcomes for jobs that - /// are still `Running` the same run, and heartbeats stop extending the lease. - async fn cancel_workflow_in_tx( - conn: &mut sqlx::PgConnection, - workflow_id: crate::workflow::WorkflowId, - ) -> Result<()> { - // Serializes with the terminal transitions of the workflow's jobs. - Self::lock_workflow(conn, workflow_id).await?; - let now = db_now(conn).await?; - sqlx::query(&format!( - r#" - UPDATE hammerwork_jobs - SET status = 'Failed', - failed_at = $2, - error_message = $3, - dependency_status = CASE WHEN dependency_status = 'waiting' - THEN 'failed' ELSE dependency_status END, - last_heartbeat_at = NULL, - lease_expires_at = NULL - WHERE workflow_id = $1 - AND status IN ({}) - "#, - lifecycle::UNFINISHED_STATUS_SQL - )) - .bind(workflow_id) - .bind(now) - .bind(lifecycle::WORKFLOW_CANCELLED_MESSAGE) - .execute(&mut *conn) - .await?; - - sqlx::query( - r#" - UPDATE hammerwork_workflows - SET status = 'cancelled', - failed_at = COALESCE(failed_at, $2) - WHERE id = $1 - "#, - ) - .bind(workflow_id) - .bind(now) - .execute(&mut *conn) - .await?; - Ok(()) - } - /// Fail every pending job that (transitively) depends on `failed_job_id`. async fn fail_dependents( conn: &mut sqlx::PgConnection, @@ -3063,6 +2588,91 @@ impl crate::queue::JobQueue { .await?; Ok(cancelled) } +} + +impl crate::queue::JobQueue { + async fn transition_job_once( + &self, + job_id: JobId, + guard: Guard<'_>, + target: &Target, + reschedule_recurring: bool, + ) -> Result { + let mut tx = self.pool.begin().await?; + let result = lifecycle::transition_in_tx::( + &mut tx, + job_id, + guard, + target, + reschedule_recurring, + ) + .await; + super::end_transaction(tx, result).await + } + + /// [`DatabaseQueue::fail_job_dependencies`] in one transaction: lock the failed job + /// and its workflow (in the same order as a terminal transition), apply the + /// workflow's failure policy and update the workflow's counters and status. + async fn fail_job_dependencies_in_tx( + conn: &mut sqlx::PgConnection, + failed_job_id: JobId, + ) -> Result> { + let workflow_id: Option> = + sqlx::query_scalar("SELECT workflow_id FROM hammerwork_jobs WHERE id = $1 FOR UPDATE") + .bind(failed_job_id) + .fetch_optional(&mut *conn) + .await?; + lifecycle::fail_job_dependencies::(conn, failed_job_id, workflow_id.flatten()).await + } + + /// Cancel a workflow: its unfinished jobs (pending, retrying and **running**) become + /// `Failed` with "Workflow cancelled", and the workflow `cancelled`. + /// + /// A running job keeps running in its worker (a handler cannot be interrupted), but + /// its outcome is discarded: `finish_job_run` only records outcomes for jobs that + /// are still `Running` the same run, and heartbeats stop extending the lease. + async fn cancel_workflow_in_tx( + conn: &mut sqlx::PgConnection, + workflow_id: crate::workflow::WorkflowId, + ) -> Result<()> { + // Serializes with the terminal transitions of the workflow's jobs. + Self::lock_workflow(conn, workflow_id).await?; + let now = db_now(conn).await?; + sqlx::query(&format!( + r#" + UPDATE hammerwork_jobs + SET status = 'Failed', + failed_at = $2, + error_message = $3, + dependency_status = CASE WHEN dependency_status = 'waiting' + THEN 'failed' ELSE dependency_status END, + last_heartbeat_at = NULL, + lease_expires_at = NULL + WHERE workflow_id = $1 + AND status IN ({}) + "#, + lifecycle::UNFINISHED_STATUS_SQL + )) + .bind(workflow_id) + .bind(now) + .bind(lifecycle::WORKFLOW_CANCELLED_MESSAGE) + .execute(&mut *conn) + .await?; + + sqlx::query( + r#" + UPDATE hammerwork_workflows + SET status = 'cancelled', + failed_at = COALESCE(failed_at, $2) + WHERE id = $1 + "#, + ) + .bind(workflow_id) + .bind(now) + .execute(&mut *conn) + .await?; + Ok(()) + } /// The error for a manual transition whose guarded UPDATE matched no row. async fn rejected_transition( diff --git a/src/queue/row.rs b/src/queue/row.rs new file mode 100644 index 0000000..2e749f0 --- /dev/null +++ b/src/queue/row.rs @@ -0,0 +1,368 @@ +//! The parts of reading and writing `hammerwork_jobs` rows that do not depend on the SQL +//! dialect, shared by the PostgreSQL and MySQL backends: the column lists, and decoding +//! the status, result configuration and encryption columns of a row into a [`Job`]. +//! +//! Each backend's `JobRow` decodes the columns whose types differ between the databases +//! (ids, arrays) and hands the rest to these helpers. +//! +//! [`Job`]: crate::job::Job +#![cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + +use crate::{ + Result, + job::{JobStatus, ResultStorage}, + workflow::DependencyStatus, +}; +#[cfg(feature = "encryption")] +use chrono::{DateTime, Utc}; + +/// Standard field list for selecting complete job data from hammerwork_jobs table. +pub(crate) const JOB_SELECT_FIELDS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_data, result_stored_at, result_expires_at, result_storage_type, result_ttl_seconds, result_max_size_bytes, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, retry_strategy, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; + +/// Columns of hammerwork_jobs_archive needed to rebuild a [`Job`](crate::job::Job). +pub(crate) const ARCHIVED_JOB_FIELDS: &str = "id, queue_name, payload, payload_compressed, status, priority, attempts, max_attempts, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, result, result_ttl, retry_strategy, timeout_seconds, cron_schedule, next_run_at, recurring, timezone, batch_id, depends_on, dependency_status, result_config, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, pii_fields"; + +/// The columns written by each backend's `insert_jobs`, in bind order. +pub(crate) const INSERT_JOB_COLUMNS: &str = "id, queue_name, payload, status, priority, attempts, max_attempts, timeout_seconds, created_at, scheduled_at, started_at, completed_at, failed_at, timed_out_at, error_message, cron_schedule, next_run_at, recurring, timezone, batch_id, result_storage_type, result_ttl_seconds, result_max_size_bytes, retry_strategy, depends_on, dependents, dependency_status, workflow_id, workflow_name, trace_id, correlation_id, parent_span_id, span_context, is_encrypted, encryption_key_id, encryption_algorithm, encrypted_payload, encryption_nonce, encryption_tag, encryption_metadata, payload_hash, pii_fields, retention_policy, retention_delete_at, encrypted_at"; + +/// Encryption columns of hammerwork_jobs and hammerwork_jobs_archive (migration 011). +/// Archiving and restoring copy them between the tables in SQL, so encrypted payloads +/// move without being decrypted, with or without the `encryption` feature. +pub(crate) const ENCRYPTION_COLUMNS: [&str; 12] = [ + "is_encrypted", + "encryption_key_id", + "encryption_algorithm", + "encrypted_payload", + "encryption_nonce", + "encryption_tag", + "encryption_metadata", + "payload_hash", + "pii_fields", + "retention_policy", + "retention_delete_at", + "encrypted_at", +]; + +/// The `result_storage_type` column value of `storage`. +pub(crate) fn result_storage_str(storage: &ResultStorage) -> &'static str { + match storage { + ResultStorage::Database => "database", + ResultStorage::Memory => "memory", + ResultStorage::None => "none", + } +} + +/// Decode a `result_storage_type` column; unknown values (and `NULL`) are no storage. +pub(crate) fn result_storage_from_db(value: Option<&str>) -> ResultStorage { + match value { + Some("database") => ResultStorage::Database, + Some("memory") => ResultStorage::Memory, + _ => ResultStorage::None, + } +} + +/// Decode a `status` column (old rows may hold it JSON-quoted); an unknown status is an +/// error. +pub(crate) fn job_status_from_row(value: &str) -> Result { + super::lifecycle::job_status_from_db(value).ok_or_else(|| { + crate::error::HammerworkError::Processing(format!( + "Unknown job status: {}", + value.trim_matches('"') + )) + }) +} + +/// Decode a `dependency_status` column; `NULL` is [`DependencyStatus::None`]. +pub(crate) fn dependency_status_from_row(value: Option<&str>) -> Result { + Ok(value + .map(DependencyStatus::parse_from_db) + .transpose()? + .unwrap_or(DependencyStatus::None)) +} + +/// The encryption columns of a `hammerwork_jobs` row, borrowed from a backend's +/// `JobRow` (with `pii_fields` already decoded). +#[cfg(feature = "encryption")] +pub(crate) struct EncryptionRow<'a> { + pub is_encrypted: bool, + pub created_at: DateTime, + pub encryption_key_id: Option<&'a str>, + pub encryption_algorithm: Option<&'a str>, + pub encrypted_payload: Option<&'a [u8]>, + pub encryption_nonce: Option<&'a [u8]>, + pub encryption_tag: Option<&'a [u8]>, + pub encryption_metadata: Option<&'a serde_json::Value>, + pub payload_hash: Option<&'a str>, + pub pii_fields: &'a [String], + pub retention_policy: Option<&'a str>, + pub retention_delete_at: Option>, + pub encrypted_at: Option>, +} + +/// The encryption fields of a [`Job`](crate::job::Job): its encryption configuration, +/// retention policy and encrypted payload. +#[cfg(feature = "encryption")] +pub(crate) type DecodedEncryption = ( + Option, + Option, + Option, +); + +#[cfg(feature = "encryption")] +impl EncryptionRow<'_> { + /// Decode the encryption configuration, retention policy and encrypted payload. + pub(crate) fn decode(&self) -> Result { + Ok(( + self.encryption_config()?, + self.retention_policy()?, + self.encrypted_payload()?, + )) + } + + /// Builds an EncryptionConfig from database fields if encryption is enabled. + fn encryption_config(&self) -> Result> { + if !self.is_encrypted { + return Ok(None); + } + + // Parse algorithm + let algorithm = match self.encryption_algorithm { + Some("AES256GCM") => crate::encryption::EncryptionAlgorithm::AES256GCM, + Some("ChaCha20Poly1305") => crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305, + Some(alg) => { + return Err(crate::HammerworkError::Processing(format!( + "Unknown encryption algorithm: {}", + alg + ))); + } + None => { + return Err(crate::HammerworkError::Processing( + "Missing encryption algorithm for encrypted job".to_string(), + )); + } + }; + + // Parse metadata if available + let (key_id, compression_enabled, version) = + if let Some(metadata) = self.encryption_metadata { + let key_id = metadata + .get("key_id") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()); + let compression_enabled = metadata + .get("compressed") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let version = metadata + .get("config_version") + .and_then(|v| v.as_u64()) + .unwrap_or(1) as u32; + (key_id, compression_enabled, version) + } else { + (self.encryption_key_id.map(str::to_string), false, 1) + }; + + let config = crate::encryption::EncryptionConfig { + algorithm, + key_source: crate::encryption::KeySource::External( + key_id.unwrap_or_else(|| "unknown".to_string()), + ), + key_rotation_enabled: false, // Not stored in database + key_rotation_interval: None, + default_retention: None, // Will be parsed separately + compression_enabled, + key_id: self.encryption_key_id.map(str::to_string), + version, + }; + + Ok(Some(config)) + } + + /// Parses the retention policy from the database string. + fn retention_policy(&self) -> Result> { + match self.retention_policy { + None => Ok(None), + Some("KeepIndefinitely") => { + Ok(Some(crate::encryption::RetentionPolicy::KeepIndefinitely)) + } + Some("DeleteImmediately") => { + Ok(Some(crate::encryption::RetentionPolicy::DeleteImmediately)) + } + Some("UseDefault") => Ok(Some(crate::encryption::RetentionPolicy::UseDefault)), + Some(policy_str) => { + // Handle DeleteAfter and DeleteAt policies + if let Some(delete_at) = self.retention_delete_at { + if policy_str == "DeleteAt" { + Ok(Some(crate::encryption::RetentionPolicy::DeleteAt( + delete_at, + ))) + } else if policy_str == "DeleteAfter" { + // Calculate duration from creation to deletion time + let duration = delete_at.signed_duration_since(self.created_at); + if let Ok(std_duration) = duration.to_std() { + Ok(Some(crate::encryption::RetentionPolicy::DeleteAfter( + std_duration, + ))) + } else { + Ok(Some(crate::encryption::RetentionPolicy::UseDefault)) + } + } else { + Err(crate::HammerworkError::Processing(format!( + "Unknown retention policy: {}", + policy_str + ))) + } + } else { + Err(crate::HammerworkError::Processing(format!( + "Retention policy '{}' requires retention_delete_at timestamp", + policy_str + ))) + } + } + } + } + + /// Builds an EncryptedPayload from database fields if the job is encrypted. + fn encrypted_payload(&self) -> Result> { + if !self.is_encrypted { + return Ok(None); + } + + let encrypted_data = self.encrypted_payload.ok_or_else(|| { + crate::HammerworkError::Processing( + "Missing encrypted payload for encrypted job".to_string(), + ) + })?; + + let nonce = self.encryption_nonce.ok_or_else(|| { + crate::HammerworkError::Processing( + "Missing encryption nonce for encrypted job".to_string(), + ) + })?; + + let tag = self.encryption_tag.ok_or_else(|| { + crate::HammerworkError::Processing( + "Missing encryption tag for encrypted job".to_string(), + ) + })?; + + // An unknown algorithm falls back to AES-256-GCM here. + let algorithm = match self.encryption_algorithm { + Some("ChaCha20Poly1305") => crate::encryption::EncryptionAlgorithm::ChaCha20Poly1305, + _ => crate::encryption::EncryptionAlgorithm::AES256GCM, + }; + let retention_policy = self + .retention_policy()? + .unwrap_or(crate::encryption::RetentionPolicy::UseDefault); + let encrypted_at = self.encrypted_at.unwrap_or(self.created_at); + let payload_hash = self.payload_hash.unwrap_or_default().to_string(); + + let metadata = if let Some(metadata_json) = self.encryption_metadata { + // Build metadata from JSON + let key_id = metadata_json + .get("key_id") + .and_then(|v| v.as_str()) + .or(self.encryption_key_id) + .unwrap_or("unknown") + .to_string(); + + let config_version = metadata_json + .get("config_version") + .and_then(|v| v.as_u64()) + .unwrap_or(1) as u32; + + let compressed = metadata_json + .get("compressed") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + + let encrypted_fields = metadata_json + .get("encrypted_fields") + .and_then(|v| v.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|v| v.as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_else(|| self.pii_fields.to_vec()); + + crate::encryption::EncryptionMetadata { + algorithm, + key_id, + config_version, + compressed, + encrypted_fields, + retention_policy, + encrypted_at, + delete_at: self.retention_delete_at, + payload_hash, + format_version: crate::encryption::EncryptionMetadata::format_version_from_json( + metadata_json, + ), + } + } else { + // Build basic metadata from available fields + crate::encryption::EncryptionMetadata { + algorithm, + key_id: self.encryption_key_id.unwrap_or("unknown").to_string(), + config_version: 1, + compressed: false, + encrypted_fields: self.pii_fields.to_vec(), + retention_policy, + encrypted_at, + delete_at: self.retention_delete_at, + payload_hash, + format_version: crate::encryption::EncryptionMetadata::FORMAT_UNBOUND, + } + }; + + // Encode binary data to base64 + use base64::Engine; + let engine = base64::engine::general_purpose::STANDARD; + Ok(Some(crate::encryption::EncryptedPayload { + ciphertext: engine.encode(encrypted_data), + nonce: engine.encode(nonce), + tag: engine.encode(tag), + metadata, + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn result_storage_round_trips_and_defaults_to_none() { + for storage in [ + ResultStorage::Database, + ResultStorage::Memory, + ResultStorage::None, + ] { + let decoded = result_storage_from_db(Some(result_storage_str(&storage))); + assert_eq!(result_storage_str(&decoded), result_storage_str(&storage)); + } + assert!(matches!( + result_storage_from_db(Some("bogus")), + ResultStorage::None + )); + assert!(matches!(result_storage_from_db(None), ResultStorage::None)); + } + + #[test] + fn job_status_accepts_quoted_values_and_rejects_unknown_ones() { + assert_eq!(job_status_from_row("Running").unwrap(), JobStatus::Running); + assert_eq!(job_status_from_row("\"Dead\"").unwrap(), JobStatus::Dead); + let error = job_status_from_row("\"Bogus\"").unwrap_err().to_string(); + assert!(error.contains("Unknown job status: Bogus"), "{error}"); + } + + #[test] + fn dependency_status_defaults_to_none() { + assert_eq!( + dependency_status_from_row(None).unwrap(), + DependencyStatus::None + ); + assert!(dependency_status_from_row(Some("bogus")).is_err()); + } +} From c520366845f5417891bf8a0e5df11e0d11713af2 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:43:11 -0400 Subject: [PATCH 2/8] refactor(queue): one conflict-retry helper, shared backend helpers module, bind by reference - MySQL's retry_on_deadlock was a copy of retry_on_conflict (same attempts and backoff; its SQLSTATE 40001 check is the MySQL half of is_transaction_conflict). The claim path now uses retry_on_conflict. - The pub(crate) helpers in queue/mod.rs used only by the SQL backends move to queue/backend.rs (re-exported, so call sites are unchanged), with one module-level dead_code allowance replacing 26 per-item cfg_attr lines. - insert_jobs binds the job's fields by reference instead of cloning the payload, strings and encoded columns of every enqueued job. Co-Authored-By: Claude Opus 5.5 --- src/queue/backend.rs | 500 +++++++++++++++++++++++++++++++++++++++ src/queue/mod.rs | 531 +----------------------------------------- src/queue/mysql.rs | 82 ++----- src/queue/postgres.rs | 38 +-- 4 files changed, 547 insertions(+), 604 deletions(-) create mode 100644 src/queue/backend.rs diff --git a/src/queue/backend.rs b/src/queue/backend.rs new file mode 100644 index 0000000..f1ad112 --- /dev/null +++ b/src/queue/backend.rs @@ -0,0 +1,500 @@ +//! Helpers shared by the SQL backends (`postgres` and `mysql`): transactions and +//! conflict retries, column encoding and decoding, cron and dequeue helpers. +#![cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] + +use super::*; + +/// Job statuses after which an encrypted job may be deleted by +/// [`DatabaseQueue::purge_expired_encrypted_jobs`]. Safe to format into a query. +pub(crate) const FINISHED_STATUS_SQL: &str = "'Completed', 'Failed', 'Dead', 'TimedOut'"; + +/// Whether a database error aborted the transaction as a deadlock or serialization +/// victim (SQLSTATE `40001` on both backends, `40P01` on PostgreSQL). The transaction +/// was rolled back, so it is safe to run again. +pub(crate) fn is_transaction_conflict(error: &crate::HammerworkError) -> bool { + matches!( + error, + crate::HammerworkError::Database(sqlx::Error::Database(db_error)) + if matches!(db_error.code().as_deref(), Some("40001") | Some("40P01")) + ) +} + +/// Run a transaction, retrying a few times with a short backoff when the database +/// aborts it as a deadlock or serialization victim. +pub(crate) async fn retry_on_conflict(mut transaction: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + const ATTEMPTS: u32 = 5; + let mut attempt = 1; + loop { + match transaction().await { + Err(error) if attempt < ATTEMPTS && is_transaction_conflict(&error) => { + tokio::time::sleep(std::time::Duration::from_millis(5 * u64::from(attempt))).await; + attempt += 1; + } + result => return result, + } + } +} + +/// End `tx` according to `result`: commit on success, roll back on error. +/// +/// Rolling back explicitly (instead of relying on the rollback a dropped transaction +/// queues on its connection) guarantees the connection never goes back to the pool +/// with an open transaction still holding row locks. +pub(crate) async fn end_transaction( + tx: sqlx::Transaction<'_, DB>, + result: Result, +) -> Result { + match result { + Ok(value) => { + tx.commit().await?; + Ok(value) + } + Err(error) => { + if let Err(rollback_error) = tx.rollback().await { + tracing::warn!("Failed to roll back transaction after error: {rollback_error}"); + } + Err(error) + } + } +} + +/// The JSON stored in the `retry_strategy` column for `job`. +/// +/// Validate a job passed to [`DatabaseQueue::enqueue_cron_job`] and mark it recurring. +/// +/// The job must have a valid cron schedule (in its timezone, if set). When it has no +/// `next_run_at` yet, the next execution is computed and the job is scheduled for it. +pub(crate) fn prepare_cron_job(mut job: Job) -> Result { + let schedule = match job.get_cron_schedule() { + Some(Ok(schedule)) => schedule, + Some(Err(e)) => { + return Err(crate::HammerworkError::Queue { + message: format!("Invalid cron schedule {:?}: {}", job.cron_schedule, e), + }); + } + None => { + return Err(crate::HammerworkError::Queue { + message: "Job must have a cron schedule".to_string(), + }); + } + }; + job.recurring = true; + if job.next_run_at.is_none() { + job.next_run_at = schedule.next_execution_from_now(); + if let Some(next_run_at) = job.next_run_at { + job.scheduled_at = next_run_at; + } + } + Ok(job) +} + +/// When to schedule recurring job `job`, being enabled at `now`: `None` when it is +/// `Running` (its run's outcome reschedules it), otherwise the next occurrence of its +/// schedule after `now`. Fails for a job without a valid cron schedule. +pub(crate) fn enabled_recurring_next_run( + job: &Job, + now: DateTime, +) -> Result>> { + let schedule = match job.get_cron_schedule() { + Some(Ok(schedule)) => schedule, + Some(Err(e)) => { + return Err(crate::HammerworkError::Queue { + message: format!( + "job {} has an invalid cron schedule {:?}: {e}", + job.id, job.cron_schedule + ), + }); + } + None => return Err(not_a_cron_job(job.id)), + }; + if job.status == crate::job::JobStatus::Running { + return Ok(None); + } + schedule + .next_execution(now) + .map(Some) + .ok_or_else(|| crate::HammerworkError::Queue { + message: format!("the cron schedule of job {} has no next occurrence", job.id), + }) +} + +/// Why `disable_recurring_job` changed no row: fine for a job that is already +/// disabled, an error for a missing (or archived) job or one without a cron schedule. +pub(crate) fn disable_recurring_job_not_applied(job: Option, job_id: JobId) -> Result<()> { + match job { + Some(job) if job.status == crate::job::JobStatus::Archived => { + Err(crate::HammerworkError::JobNotFound { + id: job_id.to_string(), + }) + } + Some(job) if job.cron_schedule.is_some() => Ok(()), + Some(_) => Err(not_a_cron_job(job_id)), + None => Err(crate::HammerworkError::JobNotFound { + id: job_id.to_string(), + }), + } +} + +/// The error for a recurring job operation on a job without a cron schedule. +pub(crate) fn not_a_cron_job(job_id: JobId) -> crate::HammerworkError { + crate::HammerworkError::Queue { + message: format!("job {job_id} has no cron schedule, so it is not a recurring job"), + } +} + +/// A [`RetryStrategy::Custom`](crate::retry::RetryStrategy::Custom) holds a closure and +/// cannot be persisted, so enqueueing a job that carries one is rejected; set it as the +/// worker's default with +/// [`Worker::with_default_retry_strategy`](crate::worker::Worker::with_default_retry_strategy) +/// instead. +pub(crate) fn retry_strategy_json(job: &Job) -> Result> { + match &job.retry_strategy { + None => Ok(None), + Some(crate::retry::RetryStrategy::Custom(_)) => { + Err(crate::HammerworkError::InvalidJobPayload { + message: format!( + "job {} has a custom retry strategy, which cannot be stored; use \ + Worker::with_default_retry_strategy for custom strategies", + job.id + ), + }) + } + Some(strategy) => Ok(Some(serde_json::to_value(strategy)?)), + } +} + +/// The encryption columns of a job row (migration 011), as written by the inserts. +#[derive(Debug, Default)] +pub(crate) struct EncryptionColumns { + pub is_encrypted: bool, + pub key_id: Option, + pub algorithm: Option<&'static str>, + pub ciphertext: Option>, + pub nonce: Option>, + pub tag: Option>, + pub metadata: Option, + pub payload_hash: Option, + pub retention_policy: Option<&'static str>, + pub retention_delete_at: Option>, + pub encrypted_at: Option>, +} + +impl EncryptionColumns { + /// The columns for `job`, which must already be sealed ([`JobQueue::seal_jobs`]). + /// + /// Refuses a job that has an encryption config but no ciphertext, so a code path that + /// forgot to seal its jobs fails instead of storing the plaintext. + pub(crate) fn for_job(job: &Job) -> Result { + if !job.is_encrypted { + if job.has_encryption() { + return Err(crate::HammerworkError::Encryption { + message: format!( + "Job {} has an encryption config but its payload was not encrypted", + job.id + ), + }); + } + return Ok(Self::default()); + } + + #[cfg(feature = "encryption")] + { + use crate::encryption::{EncryptionAlgorithm, RetentionPolicy}; + + let encrypted = job.encrypted_payload.as_ref().ok_or_else(|| { + crate::HammerworkError::Encryption { + message: format!( + "Job {} is marked encrypted but has no encrypted payload", + job.id + ), + } + })?; + let metadata = &encrypted.metadata; + Ok(Self { + is_encrypted: true, + key_id: Some(metadata.key_id.clone()), + algorithm: Some(match metadata.algorithm { + EncryptionAlgorithm::AES256GCM => "AES256GCM", + EncryptionAlgorithm::ChaCha20Poly1305 => "ChaCha20Poly1305", + }), + ciphertext: Some(encrypted.decode_ciphertext()?), + nonce: Some(encrypted.decode_nonce()?), + tag: Some(encrypted.decode_tag()?), + metadata: Some(serde_json::to_value(metadata)?), + payload_hash: Some(metadata.payload_hash.clone()), + retention_policy: Some(match metadata.retention_policy { + // A retention too long to represent never expires + RetentionPolicy::DeleteAfter(_) if metadata.delete_at.is_none() => { + "KeepIndefinitely" + } + RetentionPolicy::DeleteAfter(_) => "DeleteAfter", + RetentionPolicy::DeleteAt(_) => "DeleteAt", + RetentionPolicy::KeepIndefinitely => "KeepIndefinitely", + RetentionPolicy::DeleteImmediately => "DeleteImmediately", + RetentionPolicy::UseDefault => "UseDefault", + }), + retention_delete_at: metadata.delete_at, + encrypted_at: Some(metadata.encrypted_at), + }) + } + #[cfg(not(feature = "encryption"))] + Err(crate::HammerworkError::Encryption { + message: format!( + "Job {} is marked encrypted; storing encrypted jobs needs the `encryption` feature", + job.id + ), + }) + } +} + +/// `pii_fields` of a job as stored (`NULL` when there are none). +pub(crate) fn pii_fields_column(job: &Job) -> Option> { + (!job.pii_fields.is_empty()).then(|| job.pii_fields.clone()) +} + +/// Decode the `retry_strategy` column; unknown or invalid values decode as `None`. +pub(crate) fn retry_strategy_from_json( + value: Option, +) -> Result> { + // A stored strategy that no longer decodes is corrupt data: report it instead of + // silently running the job with the worker's default strategy. + Ok(value.map(serde_json::from_value).transpose()?) +} + +/// The stored `timeout_seconds` for a job timeout. The column holds whole seconds, so a +/// sub-second timeout is rounded up (never stored as an immediate zero) and an enormous one +/// saturates at `i32::MAX` instead of wrapping negative. A zero timeout is stored as none. +pub(crate) fn timeout_db_seconds(timeout: Option) -> Option { + let timeout = timeout.filter(|timeout| !timeout.is_zero())?; + let seconds = timeout + .as_secs() + .saturating_add(u64::from(timeout.subsec_nanos() > 0)); + Some(i32::try_from(seconds).unwrap_or(i32::MAX)) +} + +/// The decoded rows of a listing (dead jobs, ready jobs, archived jobs, ...), skipping and +/// logging the rows that cannot be decoded. +/// +/// One corrupt row (say a negative `timeout_seconds` written by an older version) must +/// not make every listing that includes it fail, which would hide all the healthy jobs +/// around it from the dashboard and the CLI. Each item is the row's id (for the log) and +/// its decoding result. Reads of a single job keep returning the error. +pub(crate) fn decodable_rows( + listing: &str, + rows: impl IntoIterator)>, +) -> Vec { + rows.into_iter() + .filter_map(|(id, decoded)| match decoded { + Ok(value) => Some(value), + Err(error) => { + tracing::warn!( + job_id = %id, + error = %error, + "Skipping a row that cannot be decoded while listing {listing}" + ); + None + } + }) + .collect() +} + +/// Log a stale job the reaper reclaimed although its row cannot be decoded, so the side +/// effects of its death (dependents, workflow, batch, recurring schedule) were skipped. +pub(crate) fn warn_undecodable_stale_job(job_id: JobId, error: &crate::HammerworkError) { + tracing::warn!( + job_id = %job_id, + error = %error, + "Reclaimed a stale job whose row cannot be decoded; its dependents, workflow, \ + batch and recurring schedule were not updated" + ); +} + +/// Convert an integer read from the database into the type the API exposes (e.g. a +/// `COUNT(*)` `i64` into `u64`), failing instead of wrapping on out-of-range values. +pub(crate) fn db_int(value: S, column: &str) -> Result +where + T: TryFrom, + S: Copy + std::fmt::Display, +{ + T::try_from(value).map_err(|_| crate::HammerworkError::Queue { + message: format!("{column} read from the database is out of range: {value}"), + }) +} + +/// A duration in whole seconds read from the database (e.g. `timeout_seconds`). +pub(crate) fn db_seconds(value: S, column: &str) -> Result +where + u64: TryFrom, + S: Copy + std::fmt::Display, +{ + Ok(std::time::Duration::from_secs(db_int(value, column)?)) +} + +/// Turn `(key, COUNT(*))` rows into a map, rejecting negative counts. +pub(crate) fn count_map(rows: Vec<(String, i64)>, column: &str) -> Result> { + rows.into_iter() + .map(|(key, count)| Ok((key, db_int(count, column)?))) + .collect() +} + +/// The priorities a weighted dequeue tries. +pub(crate) const ALL_PRIORITIES: [crate::priority::JobPriority; 5] = [ + crate::priority::JobPriority::Critical, + crate::priority::JobPriority::High, + crate::priority::JobPriority::Normal, + crate::priority::JobPriority::Low, + crate::priority::JobPriority::Background, +]; + +/// SQL selecting the priority levels in `priorities` that have a job matching +/// `runnable` (a condition on the alias `j`, ending with the priority check). +pub(crate) fn runnable_priorities_sql(runnable: &str) -> String { + let levels = ALL_PRIORITIES + .iter() + .map(|priority| format!("SELECT {} AS priority", priority.as_i32())) + .collect::>() + .join(" UNION ALL "); + format!( + "SELECT levels.priority FROM ({levels}) levels \ + WHERE EXISTS (SELECT 1 FROM hammerwork_jobs j WHERE {runnable} \ + AND j.priority = levels.priority)" + ) +} + +/// Pick one of `candidates` (the priorities that have runnable jobs) by weight. +/// +/// The probability of a priority is its weight over the candidates' total weight, so +/// every priority with a runnable job and a non-zero weight is chosen regularly, no +/// matter how many jobs of higher priority are queued. Priorities with weight zero +/// are only chosen when no candidate has a weight (then the highest one wins). +/// `seed` drives the choice; callers pass something that varies between calls. +pub(crate) fn pick_weighted_priority( + candidates: &[crate::priority::JobPriority], + weights: &crate::priority::PriorityWeights, + seed: u64, +) -> Option { + let total: u64 = candidates + .iter() + .map(|priority| u64::from(weights.get_weight(*priority))) + .sum(); + if total == 0 { + return candidates.iter().copied().max(); + } + let mut point = seed % total; + for priority in candidates { + let weight = u64::from(weights.get_weight(*priority)); + if point < weight { + return Some(*priority); + } + point -= weight; + } + None +} + +/// Fill a weighted batch claim of up to `max_jobs` jobs of `queue_name` +/// ([`DatabaseQueue::dequeue_batch_leased`] with weights): pick one of `candidates` (the +/// levels with runnable jobs) by weight, claim up to the room left with +/// `claim(level, room)`, and repeat with the remaining levels until the batch is full or +/// no level is left. +/// +/// Each `claim` commits its jobs before the next one runs, so if a later claim fails the +/// jobs already claimed are returned (and the error logged) rather than the error: they +/// are `Running` under this caller's lease, and dropping them would leave them stuck +/// until their leases expire, with an attempt spent (a job on its last attempt would go +/// to `Dead` without having run). The error is returned when nothing was claimed. +pub(crate) async fn fill_weighted_batch( + queue_name: &str, + mut candidates: Vec, + weights: &crate::priority::PriorityWeights, + max_jobs: usize, + mut claim: F, +) -> Result> +where + F: FnMut(crate::priority::JobPriority, usize) -> Fut, + Fut: std::future::Future>>, +{ + let mut jobs = Vec::with_capacity(max_jobs); + let mut attempt = 0; + while jobs.len() < max_jobs + && let Some(priority) = + pick_weighted_priority(&candidates, weights, weighted_seed(queue_name, attempt)) + { + match claim(priority, max_jobs - jobs.len()).await { + Ok(claimed) => jobs.extend(claimed), + Err(error) if jobs.is_empty() => return Err(error), + Err(error) => { + tracing::warn!( + "claiming jobs of queue {} failed after {} were claimed; returning those: {}", + queue_name, + jobs.len(), + error + ); + break; + } + } + candidates.retain(|candidate| *candidate != priority); + attempt += 1; + } + Ok(jobs) +} + +/// A seed for [`pick_weighted_priority`]: a hash of the queue name and the current +/// time (hash-based so the future stays `Send`). +pub(crate) fn weighted_seed(queue_name: &str, attempt: usize) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + queue_name.hash(&mut hasher); + attempt.hash(&mut hasher); + Utc::now() + .timestamp_nanos_opt() + .unwrap_or(0) + .hash(&mut hasher); + std::thread::current().id().hash(&mut hasher); + hasher.finish() +} + +/// Put claimed jobs in claim order: highest priority first, then oldest (`priority +/// DESC, scheduled_at ASC`), as [`DatabaseQueue::dequeue_batch_leased`] returns them. +#[cfg_attr(not(feature = "postgres"), allow(dead_code))] +pub(crate) fn sort_in_claim_order(jobs: &mut [Job]) { + jobs.sort_by(|a, b| { + b.priority + .as_i32() + .cmp(&a.priority.as_i32()) + .then(a.scheduled_at.cmp(&b.scheduled_at)) + }); +} + +/// The lease interval written for `lease`: a zero lease never expires (it is clamped to +/// the longest interval, like any lease longer than that). +pub(crate) fn lease_interval(lease: std::time::Duration) -> chrono::Duration { + if lease.is_zero() { + clamp_interval(std::time::Duration::MAX) + } else { + clamp_interval(lease) + } +} + +/// The range a stored `started_at` must fall in for the row to be the run `run` was +/// dequeued as (see [`lifecycle::is_same_run`]): within 1ms either way, because the +/// backends store microseconds while `Job` carries nanoseconds. `None` when `run` has +/// no start time. +pub(crate) fn run_started_range(run: &Job) -> Option<(DateTime, DateTime)> { + let started = run.started_at?; + let tolerance = chrono::Duration::milliseconds(1); + Some(( + started.checked_sub_signed(tolerance).unwrap_or(started), + started.checked_add_signed(tolerance).unwrap_or(started), + )) +} + +/// The longest lease or staleness window passed to the database as an interval; +/// longer durations are clamped to it (100 years). +pub(crate) fn clamp_interval(duration: std::time::Duration) -> chrono::Duration { + const MAX: std::time::Duration = std::time::Duration::from_secs(100 * 365 * 24 * 3600); + saturating_chrono_duration(duration.min(MAX)) +} diff --git a/src/queue/mod.rs b/src/queue/mod.rs index f41550f..137e78d 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -21,6 +21,9 @@ use tokio::sync::RwLock; pub mod lifecycle; pub use lifecycle::{JobOutcome, JobTransition, RecordedOutcome}; +mod backend; +#[allow(unused_imports)] // unused without a database backend +pub(crate) use backend::*; mod row; #[cfg(feature = "postgres")] @@ -1095,11 +1098,6 @@ pub trait DatabaseQueue: Send + Sync { } } -/// Job statuses after which an encrypted job may be deleted by -/// [`DatabaseQueue::purge_expired_encrypted_jobs`]. Safe to format into a query. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) const FINISHED_STATUS_SQL: &str = "'Completed', 'Failed', 'Dead', 'TimedOut'"; - /// The outcome of [`DatabaseQueue::purge_expired_encrypted_jobs`]. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct EncryptedJobPurge { @@ -1151,535 +1149,12 @@ pub const RELEASED_JOB_MESSAGE: &str = /// MySQL, its list of ids) bounded. pub const MAX_DEQUEUE_BATCH_SIZE: usize = 1000; -/// Whether a database error aborted the transaction as a deadlock or serialization -/// victim (SQLSTATE `40001` on both backends, `40P01` on PostgreSQL). The transaction -/// was rolled back, so it is safe to run again. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn is_transaction_conflict(error: &crate::HammerworkError) -> bool { - matches!( - error, - crate::HammerworkError::Database(sqlx::Error::Database(db_error)) - if matches!(db_error.code().as_deref(), Some("40001") | Some("40P01")) - ) -} - -/// Run a transaction, retrying a few times with a short backoff when the database -/// aborts it as a deadlock or serialization victim. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) async fn retry_on_conflict(mut transaction: F) -> Result -where - F: FnMut() -> Fut, - Fut: std::future::Future>, -{ - const ATTEMPTS: u32 = 5; - let mut attempt = 1; - loop { - match transaction().await { - Err(error) if attempt < ATTEMPTS && is_transaction_conflict(&error) => { - tokio::time::sleep(std::time::Duration::from_millis(5 * u64::from(attempt))).await; - attempt += 1; - } - result => return result, - } - } -} - -/// End `tx` according to `result`: commit on success, roll back on error. -/// -/// Rolling back explicitly (instead of relying on the rollback a dropped transaction -/// queues on its connection) guarantees the connection never goes back to the pool -/// with an open transaction still holding row locks. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) async fn end_transaction( - tx: sqlx::Transaction<'_, DB>, - result: Result, -) -> Result { - match result { - Ok(value) => { - tx.commit().await?; - Ok(value) - } - Err(error) => { - if let Err(rollback_error) = tx.rollback().await { - tracing::warn!("Failed to roll back transaction after error: {rollback_error}"); - } - Err(error) - } - } -} - -/// The JSON stored in the `retry_strategy` column for `job`. -/// -/// Validate a job passed to [`DatabaseQueue::enqueue_cron_job`] and mark it recurring. -/// -/// The job must have a valid cron schedule (in its timezone, if set). When it has no -/// `next_run_at` yet, the next execution is computed and the job is scheduled for it. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn prepare_cron_job(mut job: Job) -> Result { - let schedule = match job.get_cron_schedule() { - Some(Ok(schedule)) => schedule, - Some(Err(e)) => { - return Err(crate::HammerworkError::Queue { - message: format!("Invalid cron schedule {:?}: {}", job.cron_schedule, e), - }); - } - None => { - return Err(crate::HammerworkError::Queue { - message: "Job must have a cron schedule".to_string(), - }); - } - }; - job.recurring = true; - if job.next_run_at.is_none() { - job.next_run_at = schedule.next_execution_from_now(); - if let Some(next_run_at) = job.next_run_at { - job.scheduled_at = next_run_at; - } - } - Ok(job) -} - -/// When to schedule recurring job `job`, being enabled at `now`: `None` when it is -/// `Running` (its run's outcome reschedules it), otherwise the next occurrence of its -/// schedule after `now`. Fails for a job without a valid cron schedule. -#[cfg_attr( - not(any(feature = "postgres", feature = "mysql", feature = "test")), - allow(dead_code) -)] -pub(crate) fn enabled_recurring_next_run( - job: &Job, - now: DateTime, -) -> Result>> { - let schedule = match job.get_cron_schedule() { - Some(Ok(schedule)) => schedule, - Some(Err(e)) => { - return Err(crate::HammerworkError::Queue { - message: format!( - "job {} has an invalid cron schedule {:?}: {e}", - job.id, job.cron_schedule - ), - }); - } - None => return Err(not_a_cron_job(job.id)), - }; - if job.status == crate::job::JobStatus::Running { - return Ok(None); - } - schedule - .next_execution(now) - .map(Some) - .ok_or_else(|| crate::HammerworkError::Queue { - message: format!("the cron schedule of job {} has no next occurrence", job.id), - }) -} - -/// Why `disable_recurring_job` changed no row: fine for a job that is already -/// disabled, an error for a missing (or archived) job or one without a cron schedule. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn disable_recurring_job_not_applied(job: Option, job_id: JobId) -> Result<()> { - match job { - Some(job) if job.status == crate::job::JobStatus::Archived => { - Err(crate::HammerworkError::JobNotFound { - id: job_id.to_string(), - }) - } - Some(job) if job.cron_schedule.is_some() => Ok(()), - Some(_) => Err(not_a_cron_job(job_id)), - None => Err(crate::HammerworkError::JobNotFound { - id: job_id.to_string(), - }), - } -} - -/// The error for a recurring job operation on a job without a cron schedule. -#[cfg_attr( - not(any(feature = "postgres", feature = "mysql", feature = "test")), - allow(dead_code) -)] -pub(crate) fn not_a_cron_job(job_id: JobId) -> crate::HammerworkError { - crate::HammerworkError::Queue { - message: format!("job {job_id} has no cron schedule, so it is not a recurring job"), - } -} - -/// A [`RetryStrategy::Custom`](crate::retry::RetryStrategy::Custom) holds a closure and -/// cannot be persisted, so enqueueing a job that carries one is rejected; set it as the -/// worker's default with -/// [`Worker::with_default_retry_strategy`](crate::worker::Worker::with_default_retry_strategy) -/// instead. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn retry_strategy_json(job: &Job) -> Result> { - match &job.retry_strategy { - None => Ok(None), - Some(crate::retry::RetryStrategy::Custom(_)) => { - Err(crate::HammerworkError::InvalidJobPayload { - message: format!( - "job {} has a custom retry strategy, which cannot be stored; use \ - Worker::with_default_retry_strategy for custom strategies", - job.id - ), - }) - } - Some(strategy) => Ok(Some(serde_json::to_value(strategy)?)), - } -} - -/// The encryption columns of a job row (migration 011), as written by the inserts. -#[derive(Debug, Default)] -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) struct EncryptionColumns { - pub is_encrypted: bool, - pub key_id: Option, - pub algorithm: Option<&'static str>, - pub ciphertext: Option>, - pub nonce: Option>, - pub tag: Option>, - pub metadata: Option, - pub payload_hash: Option, - pub retention_policy: Option<&'static str>, - pub retention_delete_at: Option>, - pub encrypted_at: Option>, -} - -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -impl EncryptionColumns { - /// The columns for `job`, which must already be sealed ([`JobQueue::seal_jobs`]). - /// - /// Refuses a job that has an encryption config but no ciphertext, so a code path that - /// forgot to seal its jobs fails instead of storing the plaintext. - pub(crate) fn for_job(job: &Job) -> Result { - if !job.is_encrypted { - if job.has_encryption() { - return Err(crate::HammerworkError::Encryption { - message: format!( - "Job {} has an encryption config but its payload was not encrypted", - job.id - ), - }); - } - return Ok(Self::default()); - } - - #[cfg(feature = "encryption")] - { - use crate::encryption::{EncryptionAlgorithm, RetentionPolicy}; - - let encrypted = job.encrypted_payload.as_ref().ok_or_else(|| { - crate::HammerworkError::Encryption { - message: format!( - "Job {} is marked encrypted but has no encrypted payload", - job.id - ), - } - })?; - let metadata = &encrypted.metadata; - Ok(Self { - is_encrypted: true, - key_id: Some(metadata.key_id.clone()), - algorithm: Some(match metadata.algorithm { - EncryptionAlgorithm::AES256GCM => "AES256GCM", - EncryptionAlgorithm::ChaCha20Poly1305 => "ChaCha20Poly1305", - }), - ciphertext: Some(encrypted.decode_ciphertext()?), - nonce: Some(encrypted.decode_nonce()?), - tag: Some(encrypted.decode_tag()?), - metadata: Some(serde_json::to_value(metadata)?), - payload_hash: Some(metadata.payload_hash.clone()), - retention_policy: Some(match metadata.retention_policy { - // A retention too long to represent never expires - RetentionPolicy::DeleteAfter(_) if metadata.delete_at.is_none() => { - "KeepIndefinitely" - } - RetentionPolicy::DeleteAfter(_) => "DeleteAfter", - RetentionPolicy::DeleteAt(_) => "DeleteAt", - RetentionPolicy::KeepIndefinitely => "KeepIndefinitely", - RetentionPolicy::DeleteImmediately => "DeleteImmediately", - RetentionPolicy::UseDefault => "UseDefault", - }), - retention_delete_at: metadata.delete_at, - encrypted_at: Some(metadata.encrypted_at), - }) - } - #[cfg(not(feature = "encryption"))] - Err(crate::HammerworkError::Encryption { - message: format!( - "Job {} is marked encrypted; storing encrypted jobs needs the `encryption` feature", - job.id - ), - }) - } -} - -/// `pii_fields` of a job as stored (`NULL` when there are none). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn pii_fields_column(job: &Job) -> Option> { - (!job.pii_fields.is_empty()).then(|| job.pii_fields.clone()) -} - -/// Decode the `retry_strategy` column; unknown or invalid values decode as `None`. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn retry_strategy_from_json( - value: Option, -) -> Result> { - // A stored strategy that no longer decodes is corrupt data: report it instead of - // silently running the job with the worker's default strategy. - Ok(value.map(serde_json::from_value).transpose()?) -} - -/// The stored `timeout_seconds` for a job timeout. The column holds whole seconds, so a -/// sub-second timeout is rounded up (never stored as an immediate zero) and an enormous one -/// saturates at `i32::MAX` instead of wrapping negative. A zero timeout is stored as none. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn timeout_db_seconds(timeout: Option) -> Option { - let timeout = timeout.filter(|timeout| !timeout.is_zero())?; - let seconds = timeout - .as_secs() - .saturating_add(u64::from(timeout.subsec_nanos() > 0)); - Some(i32::try_from(seconds).unwrap_or(i32::MAX)) -} - -/// The decoded rows of a listing (dead jobs, ready jobs, archived jobs, ...), skipping and -/// logging the rows that cannot be decoded. -/// -/// One corrupt row (say a negative `timeout_seconds` written by an older version) must -/// not make every listing that includes it fail, which would hide all the healthy jobs -/// around it from the dashboard and the CLI. Each item is the row's id (for the log) and -/// its decoding result. Reads of a single job keep returning the error. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn decodable_rows( - listing: &str, - rows: impl IntoIterator)>, -) -> Vec { - rows.into_iter() - .filter_map(|(id, decoded)| match decoded { - Ok(value) => Some(value), - Err(error) => { - tracing::warn!( - job_id = %id, - error = %error, - "Skipping a row that cannot be decoded while listing {listing}" - ); - None - } - }) - .collect() -} - -/// Log a stale job the reaper reclaimed although its row cannot be decoded, so the side -/// effects of its death (dependents, workflow, batch, recurring schedule) were skipped. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn warn_undecodable_stale_job(job_id: JobId, error: &crate::HammerworkError) { - tracing::warn!( - job_id = %job_id, - error = %error, - "Reclaimed a stale job whose row cannot be decoded; its dependents, workflow, \ - batch and recurring schedule were not updated" - ); -} - -/// Convert an integer read from the database into the type the API exposes (e.g. a -/// `COUNT(*)` `i64` into `u64`), failing instead of wrapping on out-of-range values. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn db_int(value: S, column: &str) -> Result -where - T: TryFrom, - S: Copy + std::fmt::Display, -{ - T::try_from(value).map_err(|_| crate::HammerworkError::Queue { - message: format!("{column} read from the database is out of range: {value}"), - }) -} - -/// A duration in whole seconds read from the database (e.g. `timeout_seconds`). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn db_seconds(value: S, column: &str) -> Result -where - u64: TryFrom, - S: Copy + std::fmt::Display, -{ - Ok(std::time::Duration::from_secs(db_int(value, column)?)) -} - -/// Turn `(key, COUNT(*))` rows into a map, rejecting negative counts. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn count_map(rows: Vec<(String, i64)>, column: &str) -> Result> { - rows.into_iter() - .map(|(key, count)| Ok((key, db_int(count, column)?))) - .collect() -} - -/// The priorities a weighted dequeue tries. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) const ALL_PRIORITIES: [crate::priority::JobPriority; 5] = [ - crate::priority::JobPriority::Critical, - crate::priority::JobPriority::High, - crate::priority::JobPriority::Normal, - crate::priority::JobPriority::Low, - crate::priority::JobPriority::Background, -]; - -/// SQL selecting the priority levels in `priorities` that have a job matching -/// `runnable` (a condition on the alias `j`, ending with the priority check). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn runnable_priorities_sql(runnable: &str) -> String { - let levels = ALL_PRIORITIES - .iter() - .map(|priority| format!("SELECT {} AS priority", priority.as_i32())) - .collect::>() - .join(" UNION ALL "); - format!( - "SELECT levels.priority FROM ({levels}) levels \ - WHERE EXISTS (SELECT 1 FROM hammerwork_jobs j WHERE {runnable} \ - AND j.priority = levels.priority)" - ) -} - -/// Pick one of `candidates` (the priorities that have runnable jobs) by weight. -/// -/// The probability of a priority is its weight over the candidates' total weight, so -/// every priority with a runnable job and a non-zero weight is chosen regularly, no -/// matter how many jobs of higher priority are queued. Priorities with weight zero -/// are only chosen when no candidate has a weight (then the highest one wins). -/// `seed` drives the choice; callers pass something that varies between calls. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn pick_weighted_priority( - candidates: &[crate::priority::JobPriority], - weights: &crate::priority::PriorityWeights, - seed: u64, -) -> Option { - let total: u64 = candidates - .iter() - .map(|priority| u64::from(weights.get_weight(*priority))) - .sum(); - if total == 0 { - return candidates.iter().copied().max(); - } - let mut point = seed % total; - for priority in candidates { - let weight = u64::from(weights.get_weight(*priority)); - if point < weight { - return Some(*priority); - } - point -= weight; - } - None -} - -/// Fill a weighted batch claim of up to `max_jobs` jobs of `queue_name` -/// ([`DatabaseQueue::dequeue_batch_leased`] with weights): pick one of `candidates` (the -/// levels with runnable jobs) by weight, claim up to the room left with -/// `claim(level, room)`, and repeat with the remaining levels until the batch is full or -/// no level is left. -/// -/// Each `claim` commits its jobs before the next one runs, so if a later claim fails the -/// jobs already claimed are returned (and the error logged) rather than the error: they -/// are `Running` under this caller's lease, and dropping them would leave them stuck -/// until their leases expire, with an attempt spent (a job on its last attempt would go -/// to `Dead` without having run). The error is returned when nothing was claimed. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) async fn fill_weighted_batch( - queue_name: &str, - mut candidates: Vec, - weights: &crate::priority::PriorityWeights, - max_jobs: usize, - mut claim: F, -) -> Result> -where - F: FnMut(crate::priority::JobPriority, usize) -> Fut, - Fut: std::future::Future>>, -{ - let mut jobs = Vec::with_capacity(max_jobs); - let mut attempt = 0; - while jobs.len() < max_jobs - && let Some(priority) = - pick_weighted_priority(&candidates, weights, weighted_seed(queue_name, attempt)) - { - match claim(priority, max_jobs - jobs.len()).await { - Ok(claimed) => jobs.extend(claimed), - Err(error) if jobs.is_empty() => return Err(error), - Err(error) => { - tracing::warn!( - "claiming jobs of queue {} failed after {} were claimed; returning those: {}", - queue_name, - jobs.len(), - error - ); - break; - } - } - candidates.retain(|candidate| *candidate != priority); - attempt += 1; - } - Ok(jobs) -} - -/// A seed for [`pick_weighted_priority`]: a hash of the queue name and the current -/// time (hash-based so the future stays `Send`). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn weighted_seed(queue_name: &str, attempt: usize) -> u64 { - use std::hash::{Hash, Hasher}; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - queue_name.hash(&mut hasher); - attempt.hash(&mut hasher); - Utc::now() - .timestamp_nanos_opt() - .unwrap_or(0) - .hash(&mut hasher); - std::thread::current().id().hash(&mut hasher); - hasher.finish() -} - -/// Put claimed jobs in claim order: highest priority first, then oldest (`priority -/// DESC, scheduled_at ASC`), as [`DatabaseQueue::dequeue_batch_leased`] returns them. -#[cfg_attr(not(feature = "postgres"), allow(dead_code))] -pub(crate) fn sort_in_claim_order(jobs: &mut [Job]) { - jobs.sort_by(|a, b| { - b.priority - .as_i32() - .cmp(&a.priority.as_i32()) - .then(a.scheduled_at.cmp(&b.scheduled_at)) - }); -} - /// The lease a claim holds when the caller does not choose one: /// [`DatabaseQueue::dequeue`] and [`DatabaseQueue::dequeue_with_priority_weights`], and /// workers by default /// ([`Worker::with_lease_duration`](crate::worker::Worker::with_lease_duration)). pub const DEFAULT_LEASE_DURATION: std::time::Duration = std::time::Duration::from_secs(300); -/// The lease interval written for `lease`: a zero lease never expires (it is clamped to -/// the longest interval, like any lease longer than that). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn lease_interval(lease: std::time::Duration) -> chrono::Duration { - if lease.is_zero() { - clamp_interval(std::time::Duration::MAX) - } else { - clamp_interval(lease) - } -} - -/// The range a stored `started_at` must fall in for the row to be the run `run` was -/// dequeued as (see [`lifecycle::is_same_run`]): within 1ms either way, because the -/// backends store microseconds while `Job` carries nanoseconds. `None` when `run` has -/// no start time. -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn run_started_range(run: &Job) -> Option<(DateTime, DateTime)> { - let started = run.started_at?; - let tolerance = chrono::Duration::milliseconds(1); - Some(( - started.checked_sub_signed(tolerance).unwrap_or(started), - started.checked_add_signed(tolerance).unwrap_or(started), - )) -} - -/// The longest lease or staleness window passed to the database as an interval; -/// longer durations are clamped to it (100 years). -#[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] -pub(crate) fn clamp_interval(duration: std::time::Duration) -> chrono::Duration { - const MAX: std::time::Duration = std::time::Duration::from_secs(100 * 365 * 24 * 3600); - saturating_chrono_duration(duration.min(MAX)) -} - /// 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) diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 599fb84..6c10c99 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -280,45 +280,12 @@ impl JobRow { } } -/// Number of attempts for a job claim that keeps hitting InnoDB deadlocks. -const CLAIM_DEADLOCK_ATTEMPTS: u32 = 5; - -/// Whether an error is an InnoDB deadlock (SQLSTATE 40001, error 1213), which is safe to retry. -fn is_deadlock(error: &crate::HammerworkError) -> bool { - matches!( - error, - crate::HammerworkError::Database(sqlx::Error::Database(db_error)) - if db_error.code().as_deref() == Some("40001") - ) -} - /// Whether MySQL refused to change transaction characteristics because the session is /// still inside a transaction (ER_CANT_CHANGE_TX_CHARACTERISTICS, 1568 / SQLSTATE 25001). fn is_open_transaction_error(error: &sqlx::Error) -> bool { matches!(error, sqlx::Error::Database(db_error) if db_error.code().as_deref() == Some("25001")) } -/// Runs a job claim, retrying with a short backoff when InnoDB aborts it as a deadlock -/// victim. Concurrent `SELECT ... FOR UPDATE SKIP LOCKED` + `UPDATE` claims can still -/// deadlock on secondary index locks; the aborted transaction has been rolled back, so -/// retrying is safe. -async fn retry_on_deadlock(mut claim: F) -> Result -where - F: FnMut() -> Fut, - Fut: std::future::Future>, -{ - let mut attempt = 1; - loop { - match claim().await { - Err(error) if attempt < CLAIM_DEADLOCK_ATTEMPTS && is_deadlock(&error) => { - tokio::time::sleep(Duration::from_millis(5 * u64::from(attempt))).await; - attempt += 1; - } - result => return result, - } - } -} - impl crate::queue::JobQueue { /// Starts the transaction used to claim jobs. /// @@ -528,7 +495,8 @@ impl crate::queue::JobQueue { super::weighted_seed(queue_name, attempt), ) { if let Some(job) = - retry_on_deadlock(|| self.claim_attempt(queue_name, Some(priority), lease)).await? + super::retry_on_conflict(|| self.claim_attempt(queue_name, Some(priority), lease)) + .await? { return Ok(Some(job)); } @@ -613,7 +581,7 @@ impl DatabaseQueue for crate::queue::JobQueue { self.dequeue_with_priority_weights_inner(queue_name, weights, lease) .await } - _ => retry_on_deadlock(|| self.claim_attempt(queue_name, None, lease)).await, + _ => super::retry_on_conflict(|| self.claim_attempt(queue_name, None, lease)).await, } } @@ -633,7 +601,7 @@ impl DatabaseQueue for crate::queue::JobQueue { Some(weights) if !weights.is_strict() => weights, // Strict priority: highest priority first, then the oldest jobs. _ => { - return retry_on_deadlock(|| { + return super::retry_on_conflict(|| { self.claim_batch_attempt(queue_name, None, lease, max_jobs) }) .await; @@ -661,7 +629,7 @@ impl DatabaseQueue for crate::queue::JobQueue { weights, max_jobs, |priority, room| { - retry_on_deadlock(move || { + super::retry_on_conflict(move || { self.claim_batch_attempt(queue_name, Some(priority), lease, room) }) }, @@ -2236,8 +2204,8 @@ async fn insert_jobs(conn: &mut sqlx::MySqlConnection, jobs: &[Job]) -> Result<( chunk.iter().zip(encoded), |mut row, (job, (strategy, depends_on, dependents, encryption, pii_fields))| { row.push_bind(job.id.to_string()) - .push_bind(job.queue_name.clone()) - .push_bind(job.payload.clone()) + .push_bind(&job.queue_name) + .push_bind(&job.payload) .push_bind(job.status) .push_bind(job.priority.as_i32()) .push_bind(job.attempts) @@ -2249,34 +2217,34 @@ async fn insert_jobs(conn: &mut sqlx::MySqlConnection, jobs: &[Job]) -> Result<( .push_bind(job.completed_at) .push_bind(job.failed_at) .push_bind(job.timed_out_at) - .push_bind(job.error_message.clone()) - .push_bind(job.cron_schedule.clone()) + .push_bind(&job.error_message) + .push_bind(&job.cron_schedule) .push_bind(job.next_run_at) .push_bind(job.recurring) - .push_bind(job.timezone.clone()) + .push_bind(&job.timezone) .push_bind(job.batch_id.map(|id| id.to_string())) .push_bind(result_storage_str(&job.result_config.storage)) .push_bind(job.result_config.ttl.map(|d| d.as_secs() as i64)) .push_bind(job.result_config.max_size_bytes.map(|s| s as i64)) - .push_bind(strategy.clone()) - .push_bind(depends_on.clone()) - .push_bind(dependents.clone()) + .push_bind(strategy) + .push_bind(depends_on) + .push_bind(dependents) .push_bind(job.dependency_status.as_str()) .push_bind(job.workflow_id.map(|id| id.to_string())) - .push_bind(job.workflow_name.clone()) - .push_bind(job.trace_id.clone()) - .push_bind(job.correlation_id.clone()) - .push_bind(job.parent_span_id.clone()) - .push_bind(job.span_context.clone()) + .push_bind(&job.workflow_name) + .push_bind(&job.trace_id) + .push_bind(&job.correlation_id) + .push_bind(&job.parent_span_id) + .push_bind(&job.span_context) .push_bind(encryption.is_encrypted) - .push_bind(encryption.key_id.clone()) + .push_bind(&encryption.key_id) .push_bind(encryption.algorithm) - .push_bind(encryption.ciphertext.clone()) - .push_bind(encryption.nonce.clone()) - .push_bind(encryption.tag.clone()) - .push_bind(encryption.metadata.clone()) - .push_bind(encryption.payload_hash.clone()) - .push_bind(pii_fields.clone()) + .push_bind(&encryption.ciphertext) + .push_bind(&encryption.nonce) + .push_bind(&encryption.tag) + .push_bind(&encryption.metadata) + .push_bind(&encryption.payload_hash) + .push_bind(pii_fields) .push_bind(encryption.retention_policy) .push_bind(encryption.retention_delete_at) .push_bind(encryption.encrypted_at); diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 389f5f6..79c97e6 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -1991,8 +1991,8 @@ async fn insert_jobs(conn: &mut sqlx::PgConnection, jobs: &[Job]) -> Result<()> let rows = chunk.iter().zip(strategies).zip(encryption); builder.push_values(rows, |mut row, ((job, strategy), encryption)| { row.push_bind(job.id) - .push_bind(job.queue_name.clone()) - .push_bind(job.payload.clone()) + .push_bind(&job.queue_name) + .push_bind(&job.payload) .push_bind(job.status) .push_bind(job.priority.as_i32()) .push_bind(job.attempts) @@ -2004,33 +2004,33 @@ async fn insert_jobs(conn: &mut sqlx::PgConnection, jobs: &[Job]) -> Result<()> .push_bind(job.completed_at) .push_bind(job.failed_at) .push_bind(job.timed_out_at) - .push_bind(job.error_message.clone()) - .push_bind(job.cron_schedule.clone()) + .push_bind(&job.error_message) + .push_bind(&job.cron_schedule) .push_bind(job.next_run_at) .push_bind(job.recurring) - .push_bind(job.timezone.clone()) + .push_bind(&job.timezone) .push_bind(job.batch_id) .push_bind(result_storage_str(&job.result_config.storage)) .push_bind(job.result_config.ttl.map(|d| d.as_secs() as i64)) .push_bind(job.result_config.max_size_bytes.map(|s| s as i64)) - .push_bind(strategy.clone()) - .push_bind(job.depends_on.clone()) - .push_bind(job.dependents.clone()) + .push_bind(strategy) + .push_bind(&job.depends_on) + .push_bind(&job.dependents) .push_bind(job.dependency_status.as_str()) .push_bind(job.workflow_id) - .push_bind(job.workflow_name.clone()) - .push_bind(job.trace_id.clone()) - .push_bind(job.correlation_id.clone()) - .push_bind(job.parent_span_id.clone()) - .push_bind(job.span_context.clone()) + .push_bind(&job.workflow_name) + .push_bind(&job.trace_id) + .push_bind(&job.correlation_id) + .push_bind(&job.parent_span_id) + .push_bind(&job.span_context) .push_bind(encryption.is_encrypted) - .push_bind(encryption.key_id.clone()) + .push_bind(&encryption.key_id) .push_bind(encryption.algorithm) - .push_bind(encryption.ciphertext.clone()) - .push_bind(encryption.nonce.clone()) - .push_bind(encryption.tag.clone()) - .push_bind(encryption.metadata.clone()) - .push_bind(encryption.payload_hash.clone()) + .push_bind(&encryption.ciphertext) + .push_bind(&encryption.nonce) + .push_bind(&encryption.tag) + .push_bind(&encryption.metadata) + .push_bind(&encryption.payload_hash) .push_bind(super::pii_fields_column(job)) .push_bind(encryption.retention_policy) .push_bind(encryption.retention_delete_at) From 42145b96643db8a9801d5249a795dc0ffa9701bf Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:50:56 -0400 Subject: [PATCH 3/8] refactor(cli): share database URL resolution, queue dispatch and row fetching - Config::resolve_database_url replaces fourteen copies of the --database-url / config fallback (same "Database URL is required" error). - with_queue! replaces the Postgres/MySQL matches whose arms made the same JobQueue call (27 sites, including archive.rs building JobQueue::new by hand). - fetch_rows! and IdText replace per-backend row loops whose arms differed only in how the id column decodes (job list, queue stats, monitor dashboard, audit log, backup/export job data). - batch export without payload drops the payload column from csv_fields instead of rebuilding the JobData and re-splitting the CSV row (same output). - status_name delegates to JobStatus::as_str. Co-Authored-By: Claude Opus 5.5 --- cargo-hammerwork/src/commands/archive.rs | 105 ++++-------- cargo-hammerwork/src/commands/backup.rs | 90 +++-------- cargo-hammerwork/src/commands/batch.rs | 78 ++++----- cargo-hammerwork/src/commands/cron.rs | 12 +- cargo-hammerwork/src/commands/encryption.rs | 60 ++----- cargo-hammerwork/src/commands/job.rs | 160 ++++++------------- cargo-hammerwork/src/commands/maintenance.rs | 38 ++--- cargo-hammerwork/src/commands/migration.rs | 12 +- cargo-hammerwork/src/commands/monitor.rs | 67 ++------ cargo-hammerwork/src/commands/queue.rs | 144 +++++------------ cargo-hammerwork/src/commands/spawn.rs | 7 +- cargo-hammerwork/src/commands/worker.rs | 5 +- cargo-hammerwork/src/commands/workflow.rs | 36 ++--- cargo-hammerwork/src/config/mod.rs | 8 + cargo-hammerwork/src/utils/database.rs | 19 ++- cargo-hammerwork/src/utils/job_ops.rs | 22 +-- cargo-hammerwork/src/utils/sql.rs | 64 ++++++++ 17 files changed, 313 insertions(+), 614 deletions(-) diff --git a/cargo-hammerwork/src/commands/archive.rs b/cargo-hammerwork/src/commands/archive.rs index 9f9e1d1..daabd34 100644 --- a/cargo-hammerwork/src/commands/archive.rs +++ b/cargo-hammerwork/src/commands/archive.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::Result; use clap::Subcommand; use tracing::info; @@ -291,20 +292,11 @@ async fn archive_jobs( return Ok(()); } - let stats = match pool { - DatabasePool::Postgres(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue - .archive_jobs(queue_name, &policy, &config, archival_reason, archived_by) - .await? - } - DatabasePool::MySQL(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue - .archive_jobs(queue_name, &policy, &config, archival_reason, archived_by) - .await? - } - }; + let stats = with_queue!(pool.create_job_queue(), |queue| { + queue + .archive_jobs(queue_name, &policy, &config, archival_reason, archived_by) + .await? + }); println!("Archival completed successfully!"); println!(" Jobs archived: {}", stats.jobs_archived); @@ -349,16 +341,9 @@ async fn restore_archived_job(pool: DatabasePool, job_id: &str) -> Result<()> { let job_uuid = Uuid::parse_str(job_id)?; - let job = match pool { - DatabasePool::Postgres(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.restore_archived_job(job_uuid).await? - } - DatabasePool::MySQL(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.restore_archived_job(job_uuid).await? - } - }; + let job = with_queue!(pool.create_job_queue(), |queue| { + queue.restore_archived_job(job_uuid).await? + }); println!("Job restored successfully!"); println!(" Job ID: {}", job.id); @@ -381,20 +366,11 @@ async fn list_archived_jobs( info!("Listing archived jobs..."); let format = check_format(format, &["table", "json", "csv"])?; - let archived_jobs = match pool { - DatabasePool::Postgres(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue - .list_archived_jobs(queue_name, Some(limit), Some(offset)) - .await? - } - DatabasePool::MySQL(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue - .list_archived_jobs(queue_name, Some(limit), Some(offset)) - .await? - } - }; + let archived_jobs = with_queue!(pool.create_job_queue(), |queue| { + queue + .list_archived_jobs(queue_name, Some(limit), Some(offset)) + .await? + }); println!("{}", render_archived_jobs(&archived_jobs, format)?); Ok(()) @@ -469,16 +445,9 @@ async fn show_archival_stats( info!("Getting archival statistics..."); let format = check_format(format, &["table", "json"])?; - let stats = match pool { - DatabasePool::Postgres(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.get_archival_stats(queue_name).await? - } - DatabasePool::MySQL(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.get_archival_stats(queue_name).await? - } - }; + let stats = with_queue!(pool.create_job_queue(), |queue| { + queue.get_archival_stats(queue_name).await? + }); println!("{}", render_archival_stats(&stats, queue_name, format)?); Ok(()) @@ -535,16 +504,9 @@ async fn purge_archived_jobs( return Ok(()); } - let deleted_count = match pool { - DatabasePool::Postgres(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.purge_archived_jobs(cutoff_date).await? - } - DatabasePool::MySQL(pool) => { - let queue = hammerwork::JobQueue::new(pool); - queue.purge_archived_jobs(cutoff_date).await? - } - }; + let deleted_count = with_queue!(pool.create_job_queue(), |queue| { + queue.purge_archived_jobs(cutoff_date).await? + }); println!("Purged {} archived jobs", deleted_count); @@ -554,7 +516,6 @@ async fn purge_archived_jobs( #[cfg(test)] mod tests { use super::*; - use crate::utils::database::JobQueueWrapper; use crate::utils::sql::{IntervalUnit, SqlParams, execute_binds, fetch_i64}; use crate::utils::test_support::*; use clap::Parser; @@ -943,16 +904,11 @@ mod tests { assert!(job_column(pool, &other, "status").await.is_some()); let library = pool.clone().create_job_queue(); - let listed = match &library { - JobQueueWrapper::Postgres(l) => l - .list_archived_jobs(Some(q), Some(10), Some(0)) + let listed = with_queue!(&library, |l| { + l.list_archived_jobs(Some(q), Some(10), Some(0)) .await - .unwrap(), - JobQueueWrapper::MySQL(l) => l - .list_archived_jobs(Some(q), Some(10), Some(0)) - .await - .unwrap(), - }; + .unwrap() + }); assert_eq!(listed.len(), 2); assert!( listed @@ -979,16 +935,11 @@ mod tests { let uncompressed = seed(pool, &more).await; backdate(pool, &uncompressed, "completed_at", 9).await; run(&["run", "-Q", q, "--compress", "false"]).await.unwrap(); - let listed = match &library { - JobQueueWrapper::Postgres(l) => l - .list_archived_jobs(Some(q), Some(10), Some(0)) + let listed = with_queue!(&library, |l| { + l.list_archived_jobs(Some(q), Some(10), Some(0)) .await - .unwrap(), - JobQueueWrapper::MySQL(l) => l - .list_archived_jobs(Some(q), Some(10), Some(0)) - .await - .unwrap(), - }; + .unwrap() + }); let entry = listed .iter() .find(|j| j.id.to_string() == uncompressed) diff --git a/cargo-hammerwork/src/commands/backup.rs b/cargo-hammerwork/src/commands/backup.rs index 4e12aca..c87bb38 100644 --- a/cargo-hammerwork/src/commands/backup.rs +++ b/cargo-hammerwork/src/commands/backup.rs @@ -10,7 +10,7 @@ use crate::commands::job::priority_display; use crate::config::Config; use crate::utils::database::DatabasePool; use crate::utils::job_rows::{self, Column, Param, RowInsert}; -use crate::utils::sql::{Backend, Bind, SqlParams, bind_mysql, bind_pg}; +use crate::utils::sql::{Backend, Bind, IdText, SqlParams, bind_mysql, bind_pg, fetch_rows}; use crate::utils::validation::validate_priority; /// Version of the JSON backup format written by `backup create`. @@ -114,11 +114,7 @@ impl BackupCommand { include_failed, format, } => { - let db_url = database_url - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; + let db_url = &config.resolve_database_url(database_url.as_deref())?; create_backup( db_url, @@ -137,11 +133,7 @@ impl BackupCommand { confirm, skip_existing, } => { - let db_url = database_url - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; + let db_url = &config.resolve_database_url(database_url.as_deref())?; restore_backup( db_url, @@ -255,24 +247,21 @@ pub(crate) async fn fetch_job_data( query: &str, binds: &[Bind], ) -> Result> { - match pool { - DatabasePool::Postgres(pg_pool) => { - let rows = bind_pg(sqlx::query(query), binds) - .fetch_all(pg_pool) - .await?; - rows.into_iter() - .map(|row| extract_job_data_postgres(&row)) - .collect() - } - DatabasePool::MySQL(mysql_pool) => { - let rows = bind_mysql(sqlx::query(query), binds) - .fetch_all(mysql_pool) - .await?; - rows.into_iter() - .map(|row| extract_job_data_mysql(&row)) - .collect() - } - } + Ok(fetch_rows!(pool, query, binds, |row| JobData { + id: row.id_text("id")?, + queue_name: row.try_get("queue_name")?, + payload: row.try_get("payload")?, + status: row.try_get("status")?, + priority: priority_display(row.try_get("priority")?), + attempts: row.try_get("attempts")?, + max_attempts: row.try_get("max_attempts")?, + created_at: row.try_get("created_at")?, + scheduled_at: row.try_get("scheduled_at")?, + started_at: row.try_get("started_at")?, + completed_at: row.try_get("completed_at")?, + failed_at: row.try_get("failed_at")?, + error_message: row.try_get("error_message")?, + })) } pub(crate) const CSV_HEADER: &str = "id,queue_name,payload,status,priority,attempts,max_attempts,created_at,scheduled_at,started_at,completed_at,failed_at,error_message"; @@ -287,6 +276,11 @@ pub(crate) fn csv_field(value: &str) -> String { } pub(crate) fn csv_row(job: &JobData) -> String { + csv_fields(job).join(",") +} + +/// The [`CSV_HEADER`] columns of `job`, each quoted as needed. +pub(crate) fn csv_fields(job: &JobData) -> Vec { let time = |t: Option>| t.map(|t| t.to_rfc3339()).unwrap_or_default(); [ @@ -304,7 +298,7 @@ pub(crate) fn csv_row(job: &JobData) -> String { time(job.failed_at), csv_field(job.error_message.as_deref().unwrap_or("")), ] - .join(",") + .into() } async fn create_backup( @@ -372,42 +366,6 @@ async fn create_backup( Ok(()) } -fn extract_job_data_postgres(row: &sqlx::postgres::PgRow) -> Result { - Ok(JobData { - id: row.try_get::("id")?.to_string(), - queue_name: row.try_get("queue_name")?, - payload: row.try_get("payload")?, - status: row.try_get("status")?, - priority: priority_display(row.try_get("priority")?), - attempts: row.try_get("attempts")?, - max_attempts: row.try_get("max_attempts")?, - created_at: row.try_get("created_at")?, - scheduled_at: row.try_get("scheduled_at")?, - started_at: row.try_get("started_at")?, - completed_at: row.try_get("completed_at")?, - failed_at: row.try_get("failed_at")?, - error_message: row.try_get("error_message")?, - }) -} - -fn extract_job_data_mysql(row: &sqlx::mysql::MySqlRow) -> Result { - Ok(JobData { - id: row.try_get("id")?, - queue_name: row.try_get("queue_name")?, - payload: row.try_get("payload")?, - status: row.try_get("status")?, - priority: priority_display(row.try_get("priority")?), - attempts: row.try_get("attempts")?, - max_attempts: row.try_get("max_attempts")?, - created_at: row.try_get("created_at")?, - scheduled_at: row.try_get("scheduled_at")?, - started_at: row.try_get("started_at")?, - completed_at: row.try_get("completed_at")?, - failed_at: row.try_get("failed_at")?, - error_message: row.try_get("error_message")?, - }) -} - async fn restore_backup( database_url: &str, input: &str, diff --git a/cargo-hammerwork/src/commands/batch.rs b/cargo-hammerwork/src/commands/batch.rs index 0a0913d..b767f74 100644 --- a/cargo-hammerwork/src/commands/batch.rs +++ b/cargo-hammerwork/src/commands/batch.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::{Result, anyhow}; use clap::Subcommand; use hammerwork::queue::DatabaseQueue; @@ -7,7 +8,9 @@ use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Write}; use tracing::info; -use crate::commands::backup::{CSV_HEADER, JOB_DATA_COLUMNS, JobData, csv_row, fetch_job_data}; +use crate::commands::backup::{ + CSV_HEADER, JOB_DATA_COLUMNS, JobData, csv_fields, csv_row, fetch_job_data, +}; use crate::commands::job::status_db_value; use crate::config::Config; use crate::utils::database::{DatabasePool, JobQueueWrapper}; @@ -186,11 +189,7 @@ impl BatchCommand { BatchCommand::Export { database_url, .. } => database_url, }; - url.as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) - .map(|s| s.to_string()) + config.resolve_database_url(url.as_deref()) } } @@ -255,11 +254,8 @@ pub async fn enqueue_lines( let number = line_num + 1; let outcome = match parse_job_line(&line, default_queue, default_priority) { - Ok(job) => match &queue { - JobQueueWrapper::Postgres(q) => q.enqueue(job).await.map(|_| ()), - JobQueueWrapper::MySQL(q) => q.enqueue(job).await.map(|_| ()), - } - .map_err(|e| anyhow!("enqueue failed - {}", e)), + Ok(job) => with_queue!(&queue, |q| q.enqueue(job).await.map(|_| ())) + .map_err(|e| anyhow!("enqueue failed - {}", e)), Err(e) => Err(e), }; match outcome { @@ -413,27 +409,7 @@ pub(crate) fn render_export(jobs: &[JobData], options: &ExportOptions<'_>) -> Re lines.push(drop_payload( CSV_HEADER.split(',').map(String::from).collect(), )); - lines.extend(jobs.iter().map(|job| { - let mut no_payload = JobData { - id: job.id.clone(), - queue_name: job.queue_name.clone(), - payload: Value::Null, - status: job.status.clone(), - priority: job.priority.clone(), - attempts: job.attempts, - max_attempts: job.max_attempts, - created_at: job.created_at, - scheduled_at: job.scheduled_at, - started_at: job.started_at, - completed_at: job.completed_at, - failed_at: job.failed_at, - error_message: job.error_message.clone(), - }; - no_payload.payload = Value::Null; - // Re-split the row on its unquoted commas to drop the payload cell. - let row = csv_row(&no_payload); - drop_payload(split_csv_row(&row)) - })); + lines.extend(jobs.iter().map(|job| drop_payload(csv_fields(job)))); } lines.join("\n") } @@ -446,25 +422,6 @@ pub(crate) fn render_export(jobs: &[JobData], options: &ExportOptions<'_>) -> Re }) } -/// Split one CSV record into fields, keeping quoted fields (with their quotes) intact. -fn split_csv_row(row: &str) -> Vec { - let mut fields = Vec::new(); - let mut current = String::new(); - let mut quoted = false; - for c in row.chars() { - match c { - '"' => { - quoted = !quoted; - current.push(c); - } - ',' if !quoted => fields.push(std::mem::take(&mut current)), - _ => current.push(c), - } - } - fields.push(current); - fields -} - /// Write the matching jobs to `output`; returns how many were exported. pub async fn batch_export( pool: &DatabasePool, @@ -998,6 +955,25 @@ mod tests { assert!(err.contains("Unknown export format 'xml'"), "{err}"); } + /// Split one CSV record into fields, keeping quoted fields (with their quotes) intact. + fn split_csv_row(row: &str) -> Vec { + let mut fields = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + for c in row.chars() { + match c { + '"' => { + quoted = !quoted; + current.push(c); + } + ',' if !quoted => fields.push(std::mem::take(&mut current)), + _ => current.push(c), + } + } + fields.push(current); + fields + } + #[test] fn csv_rows_split_on_unquoted_commas_only() { assert_eq!(split_csv_row("a,\"b,c\",,d"), vec!["a", "\"b,c\"", "", "d"]); diff --git a/cargo-hammerwork/src/commands/cron.rs b/cargo-hammerwork/src/commands/cron.rs index c44f7ce..6774c36 100644 --- a/cargo-hammerwork/src/commands/cron.rs +++ b/cargo-hammerwork/src/commands/cron.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::{Result, anyhow}; use chrono::{DateTime, Duration, Utc}; use clap::Subcommand; @@ -193,11 +194,7 @@ impl CronCommand { CronCommand::Delete { database_url, .. } => database_url, }; - url.as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow!("Database URL is required")) - .map(|s| s.to_string()) + config.resolve_database_url(url.as_deref()) } } @@ -380,10 +377,7 @@ async fn create_cron_job( let timezone = job.timezone.clone().unwrap_or_else(|| "UTC".to_string()); info!("Creating cron job with schedule: {}", schedule); - let job_id = match job_queue { - JobQueueWrapper::Postgres(q) => q.enqueue_cron_job(job).await?, - JobQueueWrapper::MySQL(q) => q.enqueue_cron_job(job).await?, - }; + let job_id = with_queue!(job_queue, |q| q.enqueue_cron_job(job).await?); println!("✅ Cron job created successfully"); println!(" Job ID: {}", job_id); diff --git a/cargo-hammerwork/src/commands/encryption.rs b/cargo-hammerwork/src/commands/encryption.rs index 3eb6f19..587359e 100644 --- a/cargo-hammerwork/src/commands/encryption.rs +++ b/cargo-hammerwork/src/commands/encryption.rs @@ -13,7 +13,7 @@ use sqlx::Row; use crate::config::Config; use crate::utils::database::DatabasePool; -use crate::utils::sql::{Backend, Bind, SqlParams, bind_mysql, bind_pg}; +use crate::utils::sql::{Backend, Bind, SqlParams, fetch_rows}; #[derive(Subcommand)] pub enum EncryptionCommand { @@ -95,11 +95,7 @@ impl EncryptionCommand { fn get_database_url(&self, config: &Config) -> Result { let EncryptionCommand::Audit { database_url, .. } = self; - database_url - .as_deref() - .or(config.get_database_url()) - .map(str::to_string) - .ok_or_else(|| anyhow!("Database URL is required")) + config.resolve_database_url(database_url.as_deref()) } /// The filter described by the `audit` flags. @@ -247,46 +243,18 @@ pub fn build_audit_query(backend: Backend, filter: &AuditFilter) -> (String, Vec /// Read the audit records matching `filter`, newest first. pub async fn read_audit_log(pool: &DatabasePool, filter: &AuditFilter) -> Result> { let (sql, binds) = build_audit_query(pool.backend(), filter); - match pool { - DatabasePool::Postgres(p) => bind_pg(sqlx::query(&sql), &binds) - .fetch_all(p) - .await? - .iter() - .map(|row| { - Ok(AuditRecord { - id: row.try_get("id")?, - key_id: row.try_get("key_id")?, - operation: row.try_get("operation")?, - success: row.try_get("success")?, - error_message: row.try_get("error_message")?, - timestamp: row.try_get("timestamp")?, - user_id: row.try_get("user_id")?, - client_ip: row.try_get("client_ip")?, - user_agent: row.try_get("user_agent")?, - session_id: row.try_get("session_id")?, - }) - }) - .collect(), - DatabasePool::MySQL(p) => bind_mysql(sqlx::query(&sql), &binds) - .fetch_all(p) - .await? - .iter() - .map(|row| { - Ok(AuditRecord { - id: row.try_get("id")?, - key_id: row.try_get("key_id")?, - operation: row.try_get("operation")?, - success: row.try_get("success")?, - error_message: row.try_get("error_message")?, - timestamp: row.try_get("timestamp")?, - user_id: row.try_get("user_id")?, - client_ip: row.try_get("client_ip")?, - user_agent: row.try_get("user_agent")?, - session_id: row.try_get("session_id")?, - }) - }) - .collect(), - } + Ok(fetch_rows!(pool, &sql, &binds, |row| AuditRecord { + id: row.try_get("id")?, + key_id: row.try_get("key_id")?, + operation: row.try_get("operation")?, + success: row.try_get("success")?, + error_message: row.try_get("error_message")?, + timestamp: row.try_get("timestamp")?, + user_id: row.try_get("user_id")?, + client_ip: row.try_get("client_ip")?, + user_agent: row.try_get("user_agent")?, + session_id: row.try_get("session_id")?, + })) } /// The audit records as a table (`table`) or a JSON array (`json`). diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index 2f07c5e..6f54b5b 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::Result; use clap::Subcommand; use hammerwork::queue::DatabaseQueue; @@ -12,7 +13,7 @@ use crate::utils::job_ops::{ JobSelector, cancel_many, cancel_one, retry_many, retry_one, select_job_ids, }; use crate::utils::sql::{ - Backend, Bind, IntervalUnit, SqlParams, bind_mysql, bind_pg, execute_binds, + Backend, Bind, IdText, IntervalUnit, SqlParams, execute_binds, fetch_rows, }; use crate::utils::validation::{validate_json_payload, validate_priority, validate_status}; @@ -295,12 +296,7 @@ impl JobCommand { JobCommand::RequeueStale { database_url, .. } => database_url, }; - url_option - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .map(|s| s.to_string()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + config.resolve_database_url(url_option.as_deref()) } } @@ -422,76 +418,34 @@ async fn list_jobs( let mut job_table = JobTable::new(); - match pool { - DatabasePool::Postgres(pg_pool) => { - let (query, params) = build_list_jobs_query( - true, - queue.as_deref(), - status.as_deref(), - priority, - limit, - failed, - completed, - last_hours, - ); - let rows = bind_pg(sqlx::query(&query), ¶ms) - .fetch_all(&pg_pool) - .await?; - for row in rows { - let id: uuid::Uuid = row.try_get("id")?; - let queue_name: String = row.try_get("queue_name")?; - let status: String = row.try_get("status")?; - let priority: i32 = row.try_get("priority")?; - let attempts: i32 = row.try_get("attempts")?; - let created_at: chrono::DateTime = row.try_get("created_at")?; - let scheduled_at: chrono::DateTime = row.try_get("scheduled_at")?; - - job_table.add_job_row( - &id.to_string(), - &queue_name, - &status, - &priority_display(priority), - attempts, - &created_at.format("%Y-%m-%d %H:%M:%S").to_string(), - &scheduled_at.format("%Y-%m-%d %H:%M:%S").to_string(), - ); - } - } - DatabasePool::MySQL(mysql_pool) => { - let (query, params) = build_list_jobs_query( - false, - queue.as_deref(), - status.as_deref(), - priority, - limit, - failed, - completed, - last_hours, - ); - let rows = bind_mysql(sqlx::query(&query), ¶ms) - .fetch_all(&mysql_pool) - .await?; - for row in rows { - let id: String = row.try_get("id")?; - let queue_name: String = row.try_get("queue_name")?; - let status: String = row.try_get("status")?; - let priority: i32 = row.try_get("priority")?; - let attempts: i32 = row.try_get("attempts")?; - let created_at: chrono::DateTime = row.try_get("created_at")?; - let scheduled_at: chrono::DateTime = row.try_get("scheduled_at")?; - - job_table.add_job_row( - &id, - &queue_name, - &status, - &priority_display(priority), - attempts, - &created_at.format("%Y-%m-%d %H:%M:%S").to_string(), - &scheduled_at.format("%Y-%m-%d %H:%M:%S").to_string(), - ); - } - } - } + let (query, params) = build_list_jobs_query( + pool.backend() == Backend::Postgres, + queue.as_deref(), + status.as_deref(), + priority, + limit, + failed, + completed, + last_hours, + ); + fetch_rows!(&pool, &query, ¶ms, |row| { + let id = row.id_text("id")?; + let queue_name: String = row.try_get("queue_name")?; + let status: String = row.try_get("status")?; + let priority: i32 = row.try_get("priority")?; + let attempts: i32 = row.try_get("attempts")?; + let created_at: chrono::DateTime = row.try_get("created_at")?; + let scheduled_at: chrono::DateTime = row.try_get("scheduled_at")?; + job_table.add_job_row( + &id, + &queue_name, + &status, + &priority_display(priority), + attempts, + &created_at.format("%Y-%m-%d %H:%M:%S").to_string(), + &scheduled_at.format("%Y-%m-%d %H:%M:%S").to_string(), + ) + }); println!("{}", job_table); Ok(()) @@ -725,16 +679,10 @@ async fn enqueue_job( job.scheduled_at = delayed_schedule(chrono::Utc::now(), delay_secs)?; } - match job_queue { - crate::utils::database::JobQueueWrapper::Postgres(queue) => { - let job_id = queue.enqueue(job).await?; - info!("✅ Job enqueued successfully: {}", job_id); - } - crate::utils::database::JobQueueWrapper::MySQL(queue) => { - let job_id = queue.enqueue(job).await?; - info!("✅ Job enqueued successfully: {}", job_id); - } - } + with_queue!(job_queue, |queue| { + let job_id = queue.enqueue(job).await?; + info!("✅ Job enqueued successfully: {}", job_id); + }); Ok(()) } @@ -753,14 +701,9 @@ fn delayed_schedule( 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? - } - }; + let recovery = with_queue!(pool.create_job_queue(), |queue| { + queue.requeue_stale_jobs(older_than).await? + }); for id in &recovery.requeued { info!("↩️ Requeued stale job {}", id); @@ -792,10 +735,7 @@ async fn retry_jobs( // A single job: report the library's verdict (not found / invalid transition). if let Some(id) = job_id { let job_uuid = uuid::Uuid::parse_str(&id)?; - match &wrapper { - JobQueueWrapper::Postgres(q) => retry_one(q, job_uuid).await?, - JobQueueWrapper::MySQL(q) => retry_one(q, job_uuid).await?, - } + with_queue!(&wrapper, |q| retry_one(q, job_uuid).await?); info!("✅ Retried job {}", job_uuid); return Ok(()); } @@ -848,10 +788,7 @@ async fn cancel_jobs( if let Some(id) = job_id { let job_uuid = uuid::Uuid::parse_str(&id)?; - match &wrapper { - JobQueueWrapper::Postgres(q) => cancel_one(q, job_uuid, &allowed).await?, - JobQueueWrapper::MySQL(q) => cancel_one(q, job_uuid, &allowed).await?, - } + with_queue!(&wrapper, |q| cancel_one(q, job_uuid, &allowed).await?); info!("✅ Cancelled job {}", job_uuid); return Ok(()); } @@ -1773,18 +1710,11 @@ mod tests { .await .unwrap(); let job_id = uuid::Uuid::parse_str(&id).unwrap(); - let opened = match app_queue { - JobQueueWrapper::Postgres(q) => { - let q = q.with_encryption(engine); - q.decrypt_job(q.get_job(job_id).await.unwrap().unwrap()) - .await - } - JobQueueWrapper::MySQL(q) => { - let q = q.with_encryption(engine); - q.decrypt_job(q.get_job(job_id).await.unwrap().unwrap()) - .await - } - } + let opened = with_queue!(app_queue, |q| { + let q = q.with_encryption(engine); + q.decrypt_job(q.get_job(job_id).await.unwrap().unwrap()) + .await + }) .unwrap(); assert_eq!(opened.payload["card"], secret.as_str()); diff --git a/cargo-hammerwork/src/commands/maintenance.rs b/cargo-hammerwork/src/commands/maintenance.rs index 84067fb..da5b9ff 100644 --- a/cargo-hammerwork/src/commands/maintenance.rs +++ b/cargo-hammerwork/src/commands/maintenance.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::Result; use clap::Subcommand; use hammerwork::JobStatus; @@ -5,7 +6,7 @@ use hammerwork::queue::DatabaseQueue; use tracing::info; use crate::config::Config; -use crate::utils::database::{DatabasePool, JobQueueWrapper}; +use crate::utils::database::DatabasePool; use crate::utils::job_ops::{JobSelector, retry_many, select_job_ids}; use crate::utils::sql::{Backend, Bind, SqlParams, execute_binds, fetch_i64}; @@ -135,11 +136,7 @@ impl MaintenanceCommand { MaintenanceCommand::PurgeEncrypted { database_url, .. } => database_url, }; - url.as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) - .map(|s| s.to_string()) + config.resolve_database_url(url.as_deref()) } } @@ -207,10 +204,9 @@ async fn purge_expired_encrypted_jobs( return Ok(()); } - let purge = match pool.create_job_queue() { - JobQueueWrapper::Postgres(queue) => queue.purge_expired_encrypted_jobs().await?, - JobQueueWrapper::MySQL(queue) => queue.purge_expired_encrypted_jobs().await?, - }; + let purge = with_queue!(pool.create_job_queue(), |queue| queue + .purge_expired_encrypted_jobs() + .await?); println!( "✅ Deleted {} encrypted jobs past their retention period ({} jobs, {} archived)", purge.total(), @@ -372,24 +368,14 @@ async fn cleanup_dead_jobs( // Mark stale jobs as dead through the library's guarded transition. const REASON: &str = "Job marked as dead due to inactivity"; let mut marked = 0usize; - match pool.clone().create_job_queue() { - JobQueueWrapper::Postgres(queue) => { - for id in &stale_ids { - match queue.mark_job_dead(*id, REASON).await { - Ok(()) => marked += 1, - Err(e) => tracing::warn!("Skipped job {}: {}", id, e), - } - } - } - JobQueueWrapper::MySQL(queue) => { - for id in &stale_ids { - match queue.mark_job_dead(*id, REASON).await { - Ok(()) => marked += 1, - Err(e) => tracing::warn!("Skipped job {}: {}", id, e), - } + with_queue!(pool.clone().create_job_queue(), |queue| { + for id in &stale_ids { + match queue.mark_job_dead(*id, REASON).await { + Ok(()) => marked += 1, + Err(e) => tracing::warn!("Skipped job {}: {}", id, e), } } - } + }); println!("✅ Dead jobs cleanup completed"); println!(" Marked {} jobs as dead", marked); diff --git a/cargo-hammerwork/src/commands/migration.rs b/cargo-hammerwork/src/commands/migration.rs index 5b90718..e58af70 100644 --- a/cargo-hammerwork/src/commands/migration.rs +++ b/cargo-hammerwork/src/commands/migration.rs @@ -28,11 +28,7 @@ impl MigrationCommand { pub async fn execute(&self, config: &Config) -> Result<()> { match self { MigrationCommand::Run { database_url, drop } => { - let db_url = database_url - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; + let db_url = &config.resolve_database_url(database_url.as_deref())?; info!("Running migrations for: {}", redact_url(db_url)); let pool = DatabasePool::connect_with_config(db_url, config).await?; @@ -40,11 +36,7 @@ impl MigrationCommand { info!("Migrations completed successfully"); } MigrationCommand::Status { database_url } => { - let db_url = database_url - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; + let db_url = &config.resolve_database_url(database_url.as_deref())?; info!("Checking migration status for: {}", redact_url(db_url)); check_migration_status(db_url).await?; diff --git a/cargo-hammerwork/src/commands/monitor.rs b/cargo-hammerwork/src/commands/monitor.rs index f7b0e0e..08d7320 100644 --- a/cargo-hammerwork/src/commands/monitor.rs +++ b/cargo-hammerwork/src/commands/monitor.rs @@ -7,7 +7,9 @@ use tokio::time::interval; use crate::commands::job::priority_display; use crate::config::Config; use crate::utils::database::DatabasePool; -use crate::utils::sql::{Backend, Bind, IntervalUnit, SqlParams, bind_mysql, bind_pg, fetch_i64}; +use crate::utils::sql::{ + Backend, Bind, IdText, IntervalUnit, SqlParams, bind_mysql, bind_pg, fetch_i64, fetch_rows, +}; #[derive(Subcommand)] pub enum MonitorCommand { @@ -79,12 +81,7 @@ impl MonitorCommand { MonitorCommand::Metrics { database_url, .. } => database_url, }; - url_option - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .map(|s| s.to_string()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + config.resolve_database_url(url_option.as_deref()) } } @@ -254,51 +251,17 @@ pub async fn fetch_dashboard_data( ) -> Result { let (status_query, status_binds) = build_status_counts_query(pool.backend(), queue); let (recent_query, recent_binds) = build_recent_jobs_query(pool.backend(), queue); - let mut status_counts = Vec::new(); - let mut recent = Vec::new(); - - match pool { - DatabasePool::Postgres(pg_pool) => { - for row in bind_pg(sqlx::query(&status_query), &status_binds) - .fetch_all(pg_pool) - .await? - { - status_counts.push((row.try_get("status")?, row.try_get("count")?)); - } - for row in bind_pg(sqlx::query(&recent_query), &recent_binds) - .fetch_all(pg_pool) - .await? - { - recent.push(RecentJob { - id: row.try_get::("id")?.to_string(), - queue: row.try_get("queue_name")?, - status: row.try_get("status")?, - priority: priority_display(row.try_get("priority")?), - created_at: row.try_get("created_at")?, - }); - } - } - DatabasePool::MySQL(mysql_pool) => { - for row in bind_mysql(sqlx::query(&status_query), &status_binds) - .fetch_all(mysql_pool) - .await? - { - status_counts.push((row.try_get("status")?, row.try_get("count")?)); - } - for row in bind_mysql(sqlx::query(&recent_query), &recent_binds) - .fetch_all(mysql_pool) - .await? - { - recent.push(RecentJob { - id: row.try_get("id")?, - queue: row.try_get("queue_name")?, - status: row.try_get("status")?, - priority: priority_display(row.try_get("priority")?), - created_at: row.try_get("created_at")?, - }); - } - } - } + let status_counts = fetch_rows!(pool, &status_query, &status_binds, |row| ( + row.try_get("status")?, + row.try_get("count")? + )); + let recent = fetch_rows!(pool, &recent_query, &recent_binds, |row| RecentJob { + id: row.id_text("id")?, + queue: row.try_get("queue_name")?, + status: row.try_get("status")?, + priority: priority_display(row.try_get("priority")?), + created_at: row.try_get("created_at")?, + }); Ok(DashboardData { status_counts, recent, diff --git a/cargo-hammerwork/src/commands/queue.rs b/cargo-hammerwork/src/commands/queue.rs index 9c95235..b35b944 100644 --- a/cargo-hammerwork/src/commands/queue.rs +++ b/cargo-hammerwork/src/commands/queue.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::Result; use clap::Subcommand; use hammerwork::JobQueue; @@ -8,10 +9,10 @@ use tracing::info; use crate::commands::job::priority_display; use crate::commands::monitor::build_status_counts_query; use crate::config::Config; -use crate::utils::database::{DatabasePool, JobQueueWrapper}; +use crate::utils::database::DatabasePool; use crate::utils::display::StatsTable; use crate::utils::sql::{ - Backend, Bind, IntervalUnit, SqlParams, bind_mysql, bind_pg, execute_binds, fetch_i64, + Backend, Bind, IntervalUnit, SqlParams, execute_binds, fetch_i64, fetch_rows, }; #[derive(Subcommand)] @@ -118,12 +119,7 @@ impl QueueCommand { QueueCommand::Health { database_url, .. } => database_url, }; - url_option - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .map(|s| s.to_string()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + config.resolve_database_url(url_option.as_deref()) } } @@ -329,56 +325,25 @@ async fn show_basic_stats(pool: DatabasePool, queue: Option) -> Result<( let mut table = comfy_table::Table::new(); table.set_header(vec!["Status", "Count"]); - match &pool { - DatabasePool::Postgres(pg_pool) => { - let rows = bind_pg(sqlx::query(&base_query), &base_binds) - .fetch_all(pg_pool) - .await?; - for row in rows { - let status: String = row.try_get("status")?; - let count: i64 = row.try_get("count")?; - - let status_icon = match status.to_lowercase().as_str() { - "pending" => "🟡", - "running" => "🔵", - "completed" => "🟢", - "failed" => "🔴", - "dead" => "💀", - "retrying" => "🟠", - _ => "❓", - }; - - table.add_row(vec![ - format!("{} {}", status_icon, status), - count.to_string(), - ]); - } - } - DatabasePool::MySQL(mysql_pool) => { - let rows = bind_mysql(sqlx::query(&base_query), &base_binds) - .fetch_all(mysql_pool) - .await?; - for row in rows { - let status: String = row.try_get("status")?; - let count: i64 = row.try_get("count")?; - - let status_icon = match status.to_lowercase().as_str() { - "pending" => "🟡", - "running" => "🔵", - "completed" => "🟢", - "failed" => "🔴", - "dead" => "💀", - "retrying" => "🟠", - _ => "❓", - }; - - table.add_row(vec![ - format!("{} {}", status_icon, status), - count.to_string(), - ]); - } - } - } + fetch_rows!(&pool, &base_query, &base_binds, |row| { + let status: String = row.try_get("status")?; + let count: i64 = row.try_get("count")?; + + let status_icon = match status.to_lowercase().as_str() { + "pending" => "🟡", + "running" => "🔵", + "completed" => "🟢", + "failed" => "🔴", + "dead" => "💀", + "retrying" => "🟠", + _ => "❓", + }; + + table.add_row(vec![ + format!("{} {}", status_icon, status), + count.to_string(), + ]); + }); println!("📊 Queue Statistics"); if let Some(q) = &queue { @@ -399,32 +364,13 @@ async fn show_detailed_stats(pool: DatabasePool, queue: Option) -> Resul let mut stats_table = StatsTable::new(); - match pool { - DatabasePool::Postgres(pg_pool) => { - let rows = bind_pg(sqlx::query(&base_query), &base_binds) - .fetch_all(&pg_pool) - .await?; - for row in rows { - let status: String = row.try_get("status")?; - let priority = priority_display(row.try_get("priority")?); - let count: i64 = row.try_get("count")?; - - stats_table.add_stats_row(&status, &priority, count); - } - } - DatabasePool::MySQL(mysql_pool) => { - let rows = bind_mysql(sqlx::query(&base_query), &base_binds) - .fetch_all(&mysql_pool) - .await?; - for row in rows { - let status: String = row.try_get("status")?; - let priority = priority_display(row.try_get("priority")?); - let count: i64 = row.try_get("count")?; - - stats_table.add_stats_row(&status, &priority, count); - } - } - } + fetch_rows!(&pool, &base_query, &base_binds, |row| { + let status: String = row.try_get("status")?; + let priority = priority_display(row.try_get("priority")?); + let count: i64 = row.try_get("count")?; + + stats_table.add_stats_row(&status, &priority, count); + }); println!("📊 Detailed Queue Statistics"); if let Some(q) = &queue { @@ -468,20 +414,17 @@ async fn clear_queue( } async fn pause_queue(pool: DatabasePool, queue: &str) -> Result<()> { - match pool.create_job_queue() { - JobQueueWrapper::Postgres(q) => q.pause_queue(queue, Some("cli")).await?, - JobQueueWrapper::MySQL(q) => q.pause_queue(queue, Some("cli")).await?, - } + with_queue!(pool.create_job_queue(), |q| q + .pause_queue(queue, Some("cli")) + .await?); println!("⏸️ Queue '{}' has been paused", queue); info!("Queue '{}' has been paused via CLI", queue); Ok(()) } async fn resume_queue(pool: DatabasePool, queue: &str) -> Result<()> { - let was_paused = match pool.create_job_queue() { - JobQueueWrapper::Postgres(q) => resume_if_paused(&q, queue).await?, - JobQueueWrapper::MySQL(q) => resume_if_paused(&q, queue).await?, - }; + let was_paused = with_queue!(pool.create_job_queue(), |q| resume_if_paused(&q, queue) + .await?); if was_paused { println!("▶️ Queue '{}' has been resumed", queue); info!("Queue '{}' has been resumed via CLI", queue); @@ -563,10 +506,7 @@ async fn show_queue_health(pool: DatabasePool, queue: Option) -> Result< } async fn list_paused_queues(pool: DatabasePool) -> Result<()> { - let paused = match pool.create_job_queue() { - JobQueueWrapper::Postgres(q) => q.get_paused_queues().await?, - JobQueueWrapper::MySQL(q) => q.get_paused_queues().await?, - }; + let paused = with_queue!(pool.create_job_queue(), |q| q.get_paused_queues().await?); if paused.is_empty() { println!("✅ No paused queues found - all queues are active"); @@ -869,11 +809,8 @@ mod tests { .await .unwrap(); let library = pool.clone().create_job_queue(); - let info = match &library { - JobQueueWrapper::Postgres(q) => q.get_queue_pause_info(&queue).await.unwrap(), - JobQueueWrapper::MySQL(q) => q.get_queue_pause_info(&queue).await.unwrap(), - } - .expect("queue is paused"); + let info = with_queue!(&library, |q| q.get_queue_pause_info(&queue).await.unwrap()) + .expect("queue is paused"); assert_eq!(info.paused_by.as_deref(), Some("cli")); let summaries = fetch_queue_summaries(&pool).await.unwrap(); assert!(summaries.iter().find(|s| s.name == queue).unwrap().paused); @@ -902,10 +839,7 @@ mod tests { }) .await .unwrap(); // already active - let still_paused = match &library { - JobQueueWrapper::Postgres(q) => q.is_queue_paused(&queue).await.unwrap(), - JobQueueWrapper::MySQL(q) => q.is_queue_paused(&queue).await.unwrap(), - }; + let still_paused = with_queue!(&library, |q| q.is_queue_paused(&queue).await.unwrap()); assert!(!still_paused); run(QueueCommand::Resume { database_url: None, diff --git a/cargo-hammerwork/src/commands/spawn.rs b/cargo-hammerwork/src/commands/spawn.rs index 4ff489d..130b0d8 100644 --- a/cargo-hammerwork/src/commands/spawn.rs +++ b/cargo-hammerwork/src/commands/spawn.rs @@ -333,12 +333,7 @@ impl SpawnCommand { SpawnCommand::Monitor { database_url, .. } => database_url, }; - url_option - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .map(|s| s.to_string()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + config.resolve_database_url(url_option.as_deref()) } } diff --git a/cargo-hammerwork/src/commands/worker.rs b/cargo-hammerwork/src/commands/worker.rs index d223e2b..ead5477 100644 --- a/cargo-hammerwork/src/commands/worker.rs +++ b/cargo-hammerwork/src/commands/worker.rs @@ -44,10 +44,7 @@ impl WorkerCommand { queue, jobs, } => { - let db_url = database_url - .as_deref() - .or(config.get_database_url()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required"))?; + let db_url = &config.resolve_database_url(database_url.as_deref())?; let pool = DatabasePool::connect_with_config(db_url, config).await?; let (now, running) = fetch_running_jobs(&pool, queue.as_deref()).await?; print!("{}", render_status(&running, now, *jobs)); diff --git a/cargo-hammerwork/src/commands/workflow.rs b/cargo-hammerwork/src/commands/workflow.rs index 13cd37d..177b35e 100644 --- a/cargo-hammerwork/src/commands/workflow.rs +++ b/cargo-hammerwork/src/commands/workflow.rs @@ -1,3 +1,4 @@ +use crate::utils::database::with_queue; use anyhow::{Context, Result, anyhow}; use clap::Subcommand; use hammerwork::queue::DatabaseQueue; @@ -9,7 +10,7 @@ use tracing::info; use uuid::Uuid; use crate::config::Config; -use crate::utils::database::{DatabasePool, JobQueueWrapper}; +use crate::utils::database::DatabasePool; use crate::utils::sql::{SqlParams, bind_mysql, bind_pg}; use crate::utils::validation::{validate_json_payload, validate_priority}; @@ -356,12 +357,7 @@ impl WorkflowCommand { WorkflowCommand::Graph { database_url, .. } => database_url, }; - url_option - .as_ref() - .map(|s| s.as_str()) - .or(config.get_database_url()) - .map(|s| s.to_string()) - .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + config.resolve_database_url(url_option.as_deref()) } async fn list_workflows( @@ -396,11 +392,8 @@ impl WorkflowCommand { let id = Uuid::parse_str(workflow_id) .map_err(|e| anyhow!("Invalid workflow ID '{}': {}", workflow_id, e))?; let queue = pool.clone().create_job_queue(); - let workflow = match &queue { - JobQueueWrapper::Postgres(q) => q.get_workflow_status(id).await?, - JobQueueWrapper::MySQL(q) => q.get_workflow_status(id).await?, - } - .ok_or_else(|| anyhow!("Workflow not found: {}", workflow_id))?; + let workflow = with_queue!(&queue, |q| q.get_workflow_status(id).await?) + .ok_or_else(|| anyhow!("Workflow not found: {}", workflow_id))?; let jobs = self.get_workflow_jobs(&pool, workflow_id).await?; println!("{}", render_workflow_details(&workflow, &jobs)); @@ -451,10 +444,9 @@ impl WorkflowCommand { ); // Encrypts like the application, and never writes plaintext to encrypted queues - match pool.create_enqueue_queue(encryption).await? { - JobQueueWrapper::Postgres(q) => q.enqueue_workflow(workflow).await?, - JobQueueWrapper::MySQL(q) => q.enqueue_workflow(workflow).await?, - }; + with_queue!(pool.create_enqueue_queue(encryption).await?, |q| q + .enqueue_workflow(workflow) + .await?); println!("Workflow created:"); println!(" ID: {}", id); @@ -475,11 +467,8 @@ impl WorkflowCommand { let id = Uuid::parse_str(workflow_id) .map_err(|e| anyhow!("Invalid workflow ID '{}': {}", workflow_id, e))?; let queue = pool.clone().create_job_queue(); - let workflow = match &queue { - JobQueueWrapper::Postgres(q) => q.get_workflow_status(id).await?, - JobQueueWrapper::MySQL(q) => q.get_workflow_status(id).await?, - } - .ok_or_else(|| anyhow!("Workflow not found: {}", workflow_id))?; + let workflow = with_queue!(&queue, |q| q.get_workflow_status(id).await?) + .ok_or_else(|| anyhow!("Workflow not found: {}", workflow_id))?; let jobs = self.get_workflow_jobs(&pool, workflow_id).await?; let running = jobs.iter().filter(|j| j.status == "Running").count(); @@ -491,10 +480,7 @@ impl WorkflowCommand { )); } - match &queue { - JobQueueWrapper::Postgres(q) => q.cancel_workflow(id).await?, - JobQueueWrapper::MySQL(q) => q.cancel_workflow(id).await?, - } + with_queue!(&queue, |q| q.cancel_workflow(id).await?); println!("Workflow '{}' ({}) cancelled", workflow.name, workflow_id); Ok(()) } diff --git a/cargo-hammerwork/src/config/mod.rs b/cargo-hammerwork/src/config/mod.rs index 1a59ad7..14bdf75 100644 --- a/cargo-hammerwork/src/config/mod.rs +++ b/cargo-hammerwork/src/config/mod.rs @@ -332,6 +332,14 @@ impl Config { self.database_url.as_deref() } + /// The database URL to use: `flag` (a command's `--database-url`) if given, + /// otherwise the configured one. Errors when neither is set. + pub fn resolve_database_url(&self, flag: Option<&str>) -> Result { + flag.or(self.get_database_url()) + .map(str::to_string) + .ok_or_else(|| anyhow::anyhow!("Database URL is required")) + } + pub fn get_default_queue(&self) -> Option<&str> { self.default_queue.as_deref() } diff --git a/cargo-hammerwork/src/utils/database.rs b/cargo-hammerwork/src/utils/database.rs index 463485b..6478f01 100644 --- a/cargo-hammerwork/src/utils/database.rs +++ b/cargo-hammerwork/src/utils/database.rs @@ -407,13 +407,24 @@ impl JobQueueWrapper { pub fn encryption_engine( &self, ) -> Option<&std::sync::Arc> { - match self { - JobQueueWrapper::Postgres(queue) => queue.encryption_engine(), - JobQueueWrapper::MySQL(queue) => queue.encryption_engine(), - } + with_queue!(self, |queue| queue.encryption_engine()) } } +/// Evaluate `$body` with `$queue` bound to the [`JobQueue`] a [`JobQueueWrapper`] holds, +/// whichever database it is for: `with_queue!(wrapper, |queue| queue.enqueue(job).await?)`. +/// +/// The body is compiled once per backend, so it can call any `DatabaseQueue` method. +macro_rules! with_queue { + ($wrapper:expr, |$queue:ident| $body:expr) => { + match $wrapper { + $crate::utils::database::JobQueueWrapper::Postgres($queue) => $body, + $crate::utils::database::JobQueueWrapper::MySQL($queue) => $body, + } + }; +} +pub(crate) use with_queue; + #[cfg(test)] mod tests { use super::*; diff --git a/cargo-hammerwork/src/utils/job_ops.rs b/cargo-hammerwork/src/utils/job_ops.rs index 4df2036..8338b0e 100644 --- a/cargo-hammerwork/src/utils/job_ops.rs +++ b/cargo-hammerwork/src/utils/job_ops.rs @@ -6,6 +6,7 @@ //! CLI gets the same transition guards and side effects (dependencies, workflows, //! batches) as workers and application code. +use crate::utils::database::with_queue; use anyhow::{Result, anyhow}; use chrono::{DateTime, Utc}; use hammerwork::queue::DatabaseQueue; @@ -81,16 +82,7 @@ impl JobSelector { /// The capitalized status name as stored in the database. pub fn status_name(status: &JobStatus) -> &'static str { - match status { - JobStatus::Pending => "Pending", - JobStatus::Running => "Running", - JobStatus::Completed => "Completed", - JobStatus::Failed => "Failed", - JobStatus::Dead => "Dead", - JobStatus::TimedOut => "TimedOut", - JobStatus::Retrying => "Retrying", - JobStatus::Archived => "Archived", - } + status.as_str() } /// Ids of the jobs matching `selector` (read-only). @@ -162,10 +154,7 @@ pub async fn cancel_one( pub async fn retry_many(queue: &JobQueueWrapper, ids: &[JobId]) -> BulkResult { let mut result = BulkResult::default(); for &id in ids { - let outcome = match queue { - JobQueueWrapper::Postgres(q) => retry_one(q, id).await, - JobQueueWrapper::MySQL(q) => retry_one(q, id).await, - }; + let outcome = with_queue!(queue, |q| retry_one(q, id).await); record(&mut result, id, outcome); } result @@ -179,10 +168,7 @@ pub async fn cancel_many( ) -> BulkResult { let mut result = BulkResult::default(); for &id in ids { - let outcome = match queue { - JobQueueWrapper::Postgres(q) => cancel_one(q, id, allowed).await, - JobQueueWrapper::MySQL(q) => cancel_one(q, id, allowed).await, - }; + let outcome = with_queue!(queue, |q| cancel_one(q, id, allowed).await); record(&mut result, id, outcome); } result diff --git a/cargo-hammerwork/src/utils/sql.rs b/cargo-hammerwork/src/utils/sql.rs index b46d107..6d48f43 100644 --- a/cargo-hammerwork/src/utils/sql.rs +++ b/cargo-hammerwork/src/utils/sql.rs @@ -201,6 +201,70 @@ pub async fn execute_binds(pool: &DatabasePool, sql: &str, binds: &[Bind]) -> Re } } +/// Run `$sql` with `$binds` on whichever database `$pool` (a `&DatabasePool`) is, +/// and collect `$map` evaluated for each row bound to `$row`. +/// +/// `$map` is compiled once per backend, so it can decode columns whose Rust type +/// differs between the databases (see [`IdText`]); `?` in it returns from the +/// enclosing function. `sqlx::Row` must be in scope for `try_get`. +macro_rules! fetch_rows { + ($pool:expr, $sql:expr, $binds:expr, |$row:ident| $map:expr) => { + match $pool { + $crate::utils::database::DatabasePool::Postgres(pool) => { + let rows = $crate::utils::sql::bind_pg(sqlx::query($sql), $binds) + .fetch_all(pool) + .await?; + let mut mapped = Vec::with_capacity(rows.len()); + for $row in rows { + mapped.push($map); + } + mapped + } + $crate::utils::database::DatabasePool::MySQL(pool) => { + let rows = $crate::utils::sql::bind_mysql(sqlx::query($sql), $binds) + .fetch_all(pool) + .await?; + let mut mapped = Vec::with_capacity(rows.len()); + for $row in rows { + mapped.push($map); + } + mapped + } + } + }; +} +pub(crate) use fetch_rows; + +/// Decode an id column as text: PostgreSQL stores ids as `uuid`, MySQL as `CHAR(36)`. +pub trait IdText { + /// The id in column `column`, as text. + fn id_text(&self, column: &str) -> Result; + /// The nullable id in column `column`, as text. + fn opt_id_text(&self, column: &str) -> Result>; +} + +impl IdText for sqlx::postgres::PgRow { + fn id_text(&self, column: &str) -> Result { + Ok(self.try_get::(column)?.to_string()) + } + + fn opt_id_text(&self, column: &str) -> Result> { + Ok(self + .try_get::, _>(column)? + .map(|id| id.to_string())) + } +} + +impl IdText for sqlx::mysql::MySqlRow { + fn id_text(&self, column: &str) -> Result { + Ok(self.try_get(column)?) + } + + fn opt_id_text(&self, column: &str) -> Result> { + Ok(self.try_get(column)?) + } +} + #[cfg(test)] mod tests { use super::*; From c07ca79a6963e58ee59986f95c24dd1f7cd0a3bd Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:50:56 -0400 Subject: [PATCH 4/8] refactor(web): reuse the overview builder, try_api! and JobPriority's Display - overview_handler re-implemented generate_overview_from_stats line for line; it now calls it. - archive handlers spelled out try_api! by hand. - Two handlers matched JobPriority to the names its Display impl already prints. Co-Authored-By: Claude Opus 5.5 --- hammerwork-web/src/api/archive.rs | 25 ++++++------ hammerwork-web/src/api/queues.rs | 11 +---- hammerwork-web/src/api/stats.rs | 68 ++----------------------------- 3 files changed, 18 insertions(+), 86 deletions(-) diff --git a/hammerwork-web/src/api/archive.rs b/hammerwork-web/src/api/archive.rs index 91cffc3..41b2e26 100644 --- a/hammerwork-web/src/api/archive.rs +++ b/hammerwork-web/src/api/archive.rs @@ -368,10 +368,10 @@ where let limit = pagination.get_limit(); let offset = pagination.get_offset(); - let (page, total) = match queue.archived_jobs(&filters, limit, offset).await { - Ok(listing) => listing, - Err(e) => return Ok(internal_error("Failed to list archived jobs", &e)), - }; + let (page, total) = try_api!( + queue.archived_jobs(&filters, limit, offset).await, + "Failed to list archived jobs" + ); let response = PaginatedResponse { items: page.into_iter().map(ArchivedJobInfo::from).collect(), @@ -427,10 +427,11 @@ where archived_before: Some(request.older_than), ..ArchiveFilterParams::default() }; - let count = match queue.archived_jobs(&cutoff, 0, 0).await { - Ok((_, count)) => count, - Err(e) => return Ok(internal_error("Failed to count archived jobs", &e)), - }; + let count = try_api!( + queue.archived_jobs(&cutoff, 0, 0).await, + "Failed to count archived jobs" + ) + .1; let response = PurgeResponse { jobs_purged: count, @@ -468,10 +469,10 @@ where if filters.queue.is_none() { // Get queue list and collect stats for each - let queue_stats = match queue.get_all_queue_stats().await { - Ok(queue_stats) => queue_stats, - Err(e) => return Ok(internal_error("Failed to get queue stats", &e)), - }; + let queue_stats = try_api!( + queue.get_all_queue_stats().await, + "Failed to get queue stats" + ); for queue_stat in queue_stats { match queue.get_archival_stats(Some(&queue_stat.queue_name)).await { Ok(queue_archival_stats) => { diff --git a/hammerwork-web/src/api/queues.rs b/hammerwork-web/src/api/queues.rs index 03d8f0c..b9c7684 100644 --- a/hammerwork-web/src/api/queues.rs +++ b/hammerwork-web/src/api/queues.rs @@ -105,7 +105,7 @@ use super::{ with_filters, with_pagination, with_sort, }; use super::{error_reply, json_reply}; -use hammerwork::{JobPriority, queue::DatabaseQueue}; +use hammerwork::queue::DatabaseQueue; use serde::{Deserialize, Serialize}; use std::sync::Arc; use warp::http::StatusCode; @@ -540,14 +540,7 @@ where let priority_stats = queue.get_priority_stats(queue_name).await?; let mut breakdown = std::collections::HashMap::new(); for (priority, count) in priority_stats.job_counts { - let priority_name = match priority { - JobPriority::Background => "background", - JobPriority::Low => "low", - JobPriority::Normal => "normal", - JobPriority::High => "high", - JobPriority::Critical => "critical", - }; - breakdown.insert(priority_name.to_string(), count); + breakdown.insert(priority.to_string(), count); } Ok(breakdown) } diff --git a/hammerwork-web/src/api/stats.rs b/hammerwork-web/src/api/stats.rs index dca15cc..02a86e5 100644 --- a/hammerwork-web/src/api/stats.rs +++ b/hammerwork-web/src/api/stats.rs @@ -297,61 +297,8 @@ where { match queue.get_all_queue_stats().await { Ok(all_stats) => { - let mut total_pending = 0; - let mut total_running = 0; - let mut total_completed = 0; - let mut total_failed = 0; - let mut total_dead = 0; - let mut total_throughput = 0.0; - let mut total_processing_time = 0.0; - let mut queue_count = 0; - - for stats in &all_stats { - total_pending += stats.pending_count; - total_running += stats.running_count; - total_completed += stats.completed_count; - total_failed += stats.dead_count + stats.timed_out_count; - total_dead += stats.dead_count; - total_throughput += stats.statistics.throughput_per_minute; - total_processing_time += stats.statistics.avg_processing_time_ms; - queue_count += 1; - } - - let avg_processing_time = if queue_count > 0 { - total_processing_time / queue_count as f64 - } else { - 0.0 - }; - - let total_jobs = total_pending + total_running + total_completed + total_failed; - let overall_error_rate = if total_jobs > 0 { - total_failed as f64 / total_jobs as f64 - } else { - 0.0 - }; - - // Generate system health assessment - let health = assess_system_health(&all_stats); - - let overview = SystemOverview { - total_queues: queue_count, - total_jobs, - pending_jobs: total_pending, - running_jobs: total_running, - completed_jobs: total_completed, - failed_jobs: total_failed, - dead_jobs: total_dead, - overall_throughput: total_throughput, - overall_error_rate, - avg_processing_time_ms: avg_processing_time, - system_health: health, - uptime_seconds: { - let state = system_state.read().await; - state.uptime_seconds() as u64 - }, - last_updated: chrono::Utc::now(), - }; - + let uptime_seconds = system_state.read().await.uptime_seconds() as u64; + let overview = generate_overview_from_stats(&all_stats, uptime_seconds); Ok(json_reply(&ApiResponse::success(overview))) } Err(e) => Ok(error_reply( @@ -683,16 +630,7 @@ where Ok(priority_stats .priority_distribution .into_iter() - .map(|(priority, percentage)| { - let priority_name = match priority { - hammerwork::priority::JobPriority::Background => "background", - hammerwork::priority::JobPriority::Low => "low", - hammerwork::priority::JobPriority::Normal => "normal", - hammerwork::priority::JobPriority::High => "high", - hammerwork::priority::JobPriority::Critical => "critical", - }; - (priority_name.to_string(), percentage) - }) + .map(|(priority, percentage)| (priority.to_string(), percentage)) .collect()) } From ed63378a78a322855c52bb6a4fe4cbc13cbc2d3a Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:53:21 -0400 Subject: [PATCH 5/8] test: move duplicated test scaffolding into test_utils - backend_tests! (five copies) and test_queue() (three) move to test_utils; the batch dequeue tests pass their multi-threaded test attribute. - scenario_tests! replaces 118 hand-written one-line wrappers (test__x calls x(setup().await)) in eight files. Test names and module paths are unchanged, so the CI --skip mysql / mysql filters select the same tests (checked against the --list output). - wait_for_job (four copies), eventually (three) and idle_worker (two) are shared. The pool tests' eventually now polls every 25ms and checks once more at the deadline, like the worker config tests' copy. Co-Authored-By: Claude Opus 5.5 --- tests/batch_dequeue_tests.rs | 38 +--- tests/dequeue_concurrency_tests.rs | 46 ++--- tests/job_lifecycle_tests.rs | 209 +++---------------- tests/job_spawning_tests.rs | 39 +--- tests/payload_encryption_tests.rs | 255 ++++------------------- tests/queue_api_tests.rs | 29 +-- tests/queue_followup_tests.rs | 148 +++---------- tests/test_utils.rs | 105 ++++++++++ tests/worker_config_tests.rs | 276 +++++-------------------- tests/worker_pool_archival_tests.rs | 97 +++------ tests/worker_pool_maintenance_tests.rs | 138 +++++-------- tests/worker_robustness_tests.rs | 49 +---- tests/workflow_failure_policy_tests.rs | 29 +-- 13 files changed, 390 insertions(+), 1068 deletions(-) diff --git a/tests/batch_dequeue_tests.rs b/tests/batch_dequeue_tests.rs index f7f4461..233730a 100644 --- a/tests/batch_dequeue_tests.rs +++ b/tests/batch_dequeue_tests.rs @@ -401,24 +401,9 @@ where } } -/// One `#[tokio::test]` per scenario, run against the queue returned by `$setup`. -macro_rules! backend_tests { - ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { - mod $module { - use super::*; - $( - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[$ignore] - async fn $scenario() { - super::$scenario($setup().await).await; - } - )* - } - }; -} - #[cfg(feature = "postgres")] -backend_tests!( +crate::test_utils::backend_tests!( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -433,7 +418,8 @@ backend_tests!( ); #[cfg(feature = "mysql")] -backend_tests!( +crate::test_utils::backend_tests!( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", @@ -448,14 +434,10 @@ backend_tests!( ); #[cfg(feature = "test")] -async fn test_queue() -> Arc { - Arc::new(hammerwork::queue::test::TestQueue::new()) -} - -#[cfg(feature = "test")] -backend_tests!( +crate::test_utils::backend_tests!( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] test_queue_tests, - test_queue, + test_utils::test_queue, allow(unused_attributes), [ batch_claims_in_priority_order, @@ -1013,7 +995,8 @@ mod worker { } #[cfg(feature = "postgres")] - backend_tests!( + crate::test_utils::backend_tests!( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -1029,7 +1012,8 @@ mod worker { ); #[cfg(feature = "mysql")] - backend_tests!( + crate::test_utils::backend_tests!( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", diff --git a/tests/dequeue_concurrency_tests.rs b/tests/dequeue_concurrency_tests.rs index a38ec2b..e557a80 100644 --- a/tests/dequeue_concurrency_tests.rs +++ b/tests/dequeue_concurrency_tests.rs @@ -130,46 +130,24 @@ where mod postgres_tests { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_weighted_dequeue_never_double_claims() { - weighted_dequeue_never_double_claims(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_weighted_dequeue_preserves_job_fields() { - weighted_dequeue_preserves_job_fields(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_dequeue_skips_jobs_waiting_on_dependencies() { - dequeue_skips_jobs_waiting_on_dependencies(test_utils::setup_postgres_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_postgres_queue; + test_postgres_weighted_dequeue_never_double_claims => weighted_dequeue_never_double_claims, + test_postgres_weighted_dequeue_preserves_job_fields => weighted_dequeue_preserves_job_fields, + test_postgres_dequeue_skips_jobs_waiting_on_dependencies => dequeue_skips_jobs_waiting_on_dependencies, + ); } #[cfg(feature = "mysql")] mod mysql_tests { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_weighted_dequeue_never_double_claims() { - weighted_dequeue_never_double_claims(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_weighted_dequeue_preserves_job_fields() { - weighted_dequeue_preserves_job_fields(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_dequeue_skips_jobs_waiting_on_dependencies() { - dequeue_skips_jobs_waiting_on_dependencies(test_utils::setup_mysql_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_mysql_queue; + test_mysql_weighted_dequeue_never_double_claims => weighted_dequeue_never_double_claims, + test_mysql_weighted_dequeue_preserves_job_fields => weighted_dequeue_preserves_job_fields, + test_mysql_dequeue_skips_jobs_waiting_on_dependencies => dequeue_skips_jobs_waiting_on_dependencies, + ); /// A pooled connection returned while still inside a transaction (as happens when a /// future is dropped mid-transaction) must not break later claims on it. diff --git a/tests/job_lifecycle_tests.rs b/tests/job_lifecycle_tests.rs index 07ae21e..6176586 100644 --- a/tests/job_lifecycle_tests.rs +++ b/tests/job_lifecycle_tests.rs @@ -22,32 +22,10 @@ use std::{ Arc, Mutex, atomic::{AtomicUsize, Ordering}, }, - time::{Duration, Instant}, + time::Duration, }; use tokio::{sync::mpsc, task::JoinHandle}; -/// 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; - } -} - /// Wait until no job of `ids` is `Pending` or `Running` (or `timeout` elapses). async fn wait_until_finished(queue: &Arc>, ids: &[JobId], timeout: Duration) where @@ -55,7 +33,7 @@ where JobQueue: DatabaseQueue + Send + Sync + 'static, { for id in ids { - wait_for_job(queue, *id, timeout, |job| { + test_utils::wait_for_job(queue, *id, timeout, |job| { !matches!(job.status, JobStatus::Pending | JobStatus::Running) }) .await; @@ -267,7 +245,7 @@ where w = w.with_max_retries(cap); } let running = RunningWorker::start(w); - let job = wait_for_job(&queue, id, Duration::from_secs(15), |job| { + let job = test_utils::wait_for_job(&queue, id, Duration::from_secs(15), |job| { job.status == JobStatus::Dead }) .await; @@ -389,7 +367,7 @@ where let started = Utc::now(); let running = RunningWorker::start(worker(&queue, &queue_name, handler)); for id in [dies, times_out] { - wait_for_job(&queue, id, Duration::from_secs(15), |job| { + test_utils::wait_for_job(&queue, id, Duration::from_secs(15), |job| { job.status != JobStatus::Running && job.scheduled_at > started }) .await; @@ -886,159 +864,40 @@ where mod postgres_tests { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_manual_transitions_are_guarded() { - manual_transitions_are_guarded(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_zombie_worker_cannot_overwrite_reclaimed_job() { - zombie_worker_cannot_overwrite_reclaimed_job(test_utils::setup_postgres_queue().await) - .await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_job_max_attempts_is_the_retry_limit() { - job_max_attempts_is_the_retry_limit(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_timeouts_retry_until_attempts_are_exhausted() { - timeouts_retry_until_attempts_are_exhausted(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_recurring_jobs_are_rescheduled_after_terminal_failure() { - recurring_jobs_are_rescheduled_after_terminal_failure( - test_utils::setup_postgres_queue().await, - ) - .await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_workflows_complete_end_to_end() { - workflows_complete_end_to_end(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_workflow_failure_policies() { - workflow_failure_policies(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_concurrent_parent_completions_release_child() { - concurrent_parent_completions_release_child(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_concurrent_completions_do_not_block() { - concurrent_completions_do_not_block(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_batch_failure_modes_are_enforced() { - batch_failure_modes_are_enforced(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_retry_strategy_is_persisted() { - retry_strategy_is_persisted(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_enqueue_batch_stores_all_fields() { - enqueue_batch_stores_all_fields(test_utils::setup_postgres_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_postgres_queue; + test_postgres_manual_transitions_are_guarded => manual_transitions_are_guarded, + test_postgres_zombie_worker_cannot_overwrite_reclaimed_job => zombie_worker_cannot_overwrite_reclaimed_job, + test_postgres_job_max_attempts_is_the_retry_limit => job_max_attempts_is_the_retry_limit, + test_postgres_timeouts_retry_until_attempts_are_exhausted => timeouts_retry_until_attempts_are_exhausted, + test_postgres_recurring_jobs_are_rescheduled_after_terminal_failure => recurring_jobs_are_rescheduled_after_terminal_failure, + test_postgres_workflows_complete_end_to_end => workflows_complete_end_to_end, + test_postgres_workflow_failure_policies => workflow_failure_policies, + test_postgres_concurrent_parent_completions_release_child => concurrent_parent_completions_release_child, + test_postgres_concurrent_completions_do_not_block => concurrent_completions_do_not_block, + test_postgres_batch_failure_modes_are_enforced => batch_failure_modes_are_enforced, + test_postgres_retry_strategy_is_persisted => retry_strategy_is_persisted, + test_postgres_enqueue_batch_stores_all_fields => enqueue_batch_stores_all_fields, + ); } #[cfg(feature = "mysql")] mod mysql_tests { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_manual_transitions_are_guarded() { - manual_transitions_are_guarded(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_zombie_worker_cannot_overwrite_reclaimed_job() { - zombie_worker_cannot_overwrite_reclaimed_job(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_job_max_attempts_is_the_retry_limit() { - job_max_attempts_is_the_retry_limit(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_timeouts_retry_until_attempts_are_exhausted() { - timeouts_retry_until_attempts_are_exhausted(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_recurring_jobs_are_rescheduled_after_terminal_failure() { - recurring_jobs_are_rescheduled_after_terminal_failure( - test_utils::setup_mysql_queue().await, - ) - .await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_workflows_complete_end_to_end() { - workflows_complete_end_to_end(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_workflow_failure_policies() { - workflow_failure_policies(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_concurrent_parent_completions_release_child() { - concurrent_parent_completions_release_child(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_concurrent_completions_do_not_block() { - concurrent_completions_do_not_block(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_batch_failure_modes_are_enforced() { - batch_failure_modes_are_enforced(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_retry_strategy_is_persisted() { - retry_strategy_is_persisted(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_enqueue_batch_stores_all_fields() { - enqueue_batch_stores_all_fields(test_utils::setup_mysql_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_mysql_queue; + test_mysql_manual_transitions_are_guarded => manual_transitions_are_guarded, + test_mysql_zombie_worker_cannot_overwrite_reclaimed_job => zombie_worker_cannot_overwrite_reclaimed_job, + test_mysql_job_max_attempts_is_the_retry_limit => job_max_attempts_is_the_retry_limit, + test_mysql_timeouts_retry_until_attempts_are_exhausted => timeouts_retry_until_attempts_are_exhausted, + test_mysql_recurring_jobs_are_rescheduled_after_terminal_failure => recurring_jobs_are_rescheduled_after_terminal_failure, + test_mysql_workflows_complete_end_to_end => workflows_complete_end_to_end, + test_mysql_workflow_failure_policies => workflow_failure_policies, + test_mysql_concurrent_parent_completions_release_child => concurrent_parent_completions_release_child, + test_mysql_concurrent_completions_do_not_block => concurrent_completions_do_not_block, + test_mysql_batch_failure_modes_are_enforced => batch_failure_modes_are_enforced, + test_mysql_retry_strategy_is_persisted => retry_strategy_is_persisted, + test_mysql_enqueue_batch_stores_all_fields => enqueue_batch_stores_all_fields, + ); } diff --git a/tests/job_spawning_tests.rs b/tests/job_spawning_tests.rs index 2270a7e..af07319 100644 --- a/tests/job_spawning_tests.rs +++ b/tests/job_spawning_tests.rs @@ -20,26 +20,10 @@ use std::{ Arc, atomic::{AtomicUsize, Ordering}, }, - time::{Duration, Instant}, + time::Duration, }; use tokio::sync::mpsc; -/// Poll `get_job` until `predicate` holds or 15 seconds pass; returns the last job. -async fn wait_for_job(queue: &Arc, id: JobId, predicate: F) -> Job -where - Q: DatabaseQueue + ?Sized, - F: Fn(&Job) -> bool, -{ - let deadline = Instant::now() + Duration::from_secs(15); - 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; - } -} - /// Every job of `queue_name`, by claiming them all. async fn drain(queue: &Arc, queue_name: &str) -> Vec { let mut jobs = Vec::new(); @@ -69,7 +53,7 @@ where .with_spawn_manager(Arc::new(manager)); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); - let job = wait_for_job(queue, id, done).await; + let job = test_utils::wait_for_job(queue, id, Duration::from_secs(15), done).await; shutdown_tx.send(()).await.unwrap(); task.await.unwrap().unwrap(); job @@ -308,23 +292,8 @@ where queue.delete_job(id).await.unwrap(); } -macro_rules! backend_tests { - ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { - mod $module { - use super::*; - $( - #[tokio::test] - #[$ignore] - async fn $scenario() { - super::$scenario($setup().await).await; - } - )* - } - }; -} - #[cfg(feature = "postgres")] -backend_tests!( +crate::test_utils::backend_tests!( postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -337,7 +306,7 @@ backend_tests!( ); #[cfg(feature = "mysql")] -backend_tests!( +crate::test_utils::backend_tests!( mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", diff --git a/tests/payload_encryption_tests.rs b/tests/payload_encryption_tests.rs index 7770200..e4ef9c6 100644 --- a/tests/payload_encryption_tests.rs +++ b/tests/payload_encryption_tests.rs @@ -267,23 +267,6 @@ fn long_retention() -> RetentionPolicy { RetentionPolicy::DeleteAfter(Duration::from_secs(30 * 24 * 60 * 60)) } -/// Poll `get_job` until `predicate` holds or 15 seconds elapse; returns the last job. -async fn wait_for_job(queue: &Arc>, id: JobId, predicate: F) -> Job -where - DB: sqlx::Database, - JobQueue: DatabaseQueue + Send + Sync + 'static, - F: Fn(&Job) -> bool, -{ - let deadline = Instant::now() + Duration::from_secs(15); - 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; - } -} - /// Runs a worker on `queue_name` until job `id` is no longer pending or running. /// Returns the job and the payloads the handler saw. async fn run_worker_until_done( @@ -309,7 +292,7 @@ where let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); - let job = wait_for_job(queue, id, |job| { + let job = test_utils::wait_for_job(queue, id, Duration::from_secs(15), |job| { !matches!(job.status, JobStatus::Pending | JobStatus::Running) }) .await; @@ -1320,7 +1303,7 @@ where .with_spawn_manager(Arc::new(manager)); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); - let job = wait_for_job(&queue, id, |job| { + let job = test_utils::wait_for_job(&queue, id, Duration::from_secs(15), |job| { !matches!(job.status, JobStatus::Pending | JobStatus::Running) }) .await; @@ -1415,104 +1398,25 @@ where mod postgres { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_whole_payload_round_trip() { - whole_payload_round_trip(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_batch_claims_round_trip() { - batch_claims_round_trip(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_pii_fields_round_trip() { - pii_fields_round_trip(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_every_read_path_keeps_the_ciphertext() { - every_read_path_keeps_the_ciphertext(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_plaintext_guard_refuses_plaintext_on_encrypted_queues() { - plaintext_guard_refuses_plaintext_on_encrypted_queues( - test_utils::setup_postgres_queue().await, - ) - .await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_batch_and_workflow_are_encrypted() { - batch_and_workflow_are_encrypted(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_encrypted_job_spawns_children() { - encrypted_job_spawns_children(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_missing_engine_fails_closed() { - missing_engine_fails_closed(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_wrong_and_rotated_keys() { - wrong_and_rotated_keys(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_retention_purge() { - retention_purge(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_archive_and_restore_keep_ciphertext() { - archive_and_restore_keep_ciphertext(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_plain_jobs_unchanged() { - plain_jobs_unchanged(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_swapped_ciphertexts_do_not_decrypt() { - swapped_ciphertexts_do_not_decrypt(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_moved_job_does_not_decrypt() { - moved_job_does_not_decrypt(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_legacy_unbound_payload_decrypts() { - legacy_unbound_payload_decrypts(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_pool_purges_expired_jobs() { - worker_pool_purges_expired_jobs(test_utils::setup_postgres_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_postgres_queue; + test_postgres_whole_payload_round_trip => whole_payload_round_trip, + test_postgres_batch_claims_round_trip => batch_claims_round_trip, + test_postgres_pii_fields_round_trip => pii_fields_round_trip, + test_postgres_every_read_path_keeps_the_ciphertext => every_read_path_keeps_the_ciphertext, + test_postgres_plaintext_guard_refuses_plaintext_on_encrypted_queues => plaintext_guard_refuses_plaintext_on_encrypted_queues, + test_postgres_batch_and_workflow_are_encrypted => batch_and_workflow_are_encrypted, + test_postgres_encrypted_job_spawns_children => encrypted_job_spawns_children, + test_postgres_missing_engine_fails_closed => missing_engine_fails_closed, + test_postgres_wrong_and_rotated_keys => wrong_and_rotated_keys, + test_postgres_retention_purge => retention_purge, + test_postgres_archive_and_restore_keep_ciphertext => archive_and_restore_keep_ciphertext, + test_postgres_plain_jobs_unchanged => plain_jobs_unchanged, + test_postgres_swapped_ciphertexts_do_not_decrypt => swapped_ciphertexts_do_not_decrypt, + test_postgres_moved_job_does_not_decrypt => moved_job_does_not_decrypt, + test_postgres_legacy_unbound_payload_decrypts => legacy_unbound_payload_decrypts, + test_postgres_worker_pool_purges_expired_jobs => worker_pool_purges_expired_jobs, + ); #[tokio::test] #[ignore] // Requires database connection @@ -1532,104 +1436,25 @@ mod postgres { mod mysql { use super::*; - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_whole_payload_round_trip() { - whole_payload_round_trip(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_batch_claims_round_trip() { - batch_claims_round_trip(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_pii_fields_round_trip() { - pii_fields_round_trip(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_every_read_path_keeps_the_ciphertext() { - every_read_path_keeps_the_ciphertext(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_plaintext_guard_refuses_plaintext_on_encrypted_queues() { - plaintext_guard_refuses_plaintext_on_encrypted_queues( - test_utils::setup_mysql_queue().await, - ) - .await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_batch_and_workflow_are_encrypted() { - batch_and_workflow_are_encrypted(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_encrypted_job_spawns_children() { - encrypted_job_spawns_children(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_missing_engine_fails_closed() { - missing_engine_fails_closed(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_wrong_and_rotated_keys() { - wrong_and_rotated_keys(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_retention_purge() { - retention_purge(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_archive_and_restore_keep_ciphertext() { - archive_and_restore_keep_ciphertext(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_plain_jobs_unchanged() { - plain_jobs_unchanged(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_swapped_ciphertexts_do_not_decrypt() { - swapped_ciphertexts_do_not_decrypt(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_moved_job_does_not_decrypt() { - moved_job_does_not_decrypt(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_legacy_unbound_payload_decrypts() { - legacy_unbound_payload_decrypts(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_pool_purges_expired_jobs() { - worker_pool_purges_expired_jobs(test_utils::setup_mysql_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_mysql_queue; + test_mysql_whole_payload_round_trip => whole_payload_round_trip, + test_mysql_batch_claims_round_trip => batch_claims_round_trip, + test_mysql_pii_fields_round_trip => pii_fields_round_trip, + test_mysql_every_read_path_keeps_the_ciphertext => every_read_path_keeps_the_ciphertext, + test_mysql_plaintext_guard_refuses_plaintext_on_encrypted_queues => plaintext_guard_refuses_plaintext_on_encrypted_queues, + test_mysql_batch_and_workflow_are_encrypted => batch_and_workflow_are_encrypted, + test_mysql_encrypted_job_spawns_children => encrypted_job_spawns_children, + test_mysql_missing_engine_fails_closed => missing_engine_fails_closed, + test_mysql_wrong_and_rotated_keys => wrong_and_rotated_keys, + test_mysql_retention_purge => retention_purge, + test_mysql_archive_and_restore_keep_ciphertext => archive_and_restore_keep_ciphertext, + test_mysql_plain_jobs_unchanged => plain_jobs_unchanged, + test_mysql_swapped_ciphertexts_do_not_decrypt => swapped_ciphertexts_do_not_decrypt, + test_mysql_moved_job_does_not_decrypt => moved_job_does_not_decrypt, + test_mysql_legacy_unbound_payload_decrypts => legacy_unbound_payload_decrypts, + test_mysql_worker_pool_purges_expired_jobs => worker_pool_purges_expired_jobs, + ); #[tokio::test] #[ignore] // Requires database connection diff --git a/tests/queue_api_tests.rs b/tests/queue_api_tests.rs index 70f21f9..59ced33 100644 --- a/tests/queue_api_tests.rs +++ b/tests/queue_api_tests.rs @@ -617,24 +617,8 @@ where } } -/// One `#[tokio::test]` per scenario, run against the queue returned by `$setup`. -macro_rules! backend_tests { - ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { - mod $module { - use super::*; - $( - #[tokio::test] - #[$ignore] - async fn $scenario() { - super::$scenario($setup().await).await; - } - )* - } - }; -} - #[cfg(feature = "postgres")] -backend_tests!( +crate::test_utils::backend_tests!( postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -652,7 +636,7 @@ backend_tests!( ); #[cfg(feature = "mysql")] -backend_tests!( +crate::test_utils::backend_tests!( mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", @@ -670,14 +654,9 @@ backend_tests!( ); #[cfg(feature = "test")] -async fn test_queue() -> Arc { - Arc::new(hammerwork::queue::test::TestQueue::new()) -} - -#[cfg(feature = "test")] -backend_tests!( +crate::test_utils::backend_tests!( test_queue_tests, - test_queue, + test_utils::test_queue, allow(unused_attributes), [ dead_job_management, diff --git a/tests/queue_followup_tests.rs b/tests/queue_followup_tests.rs index 33674dd..3953c01 100644 --- a/tests/queue_followup_tests.rs +++ b/tests/queue_followup_tests.rs @@ -551,65 +551,23 @@ mod postgres_tests { Arc::new(JobQueue::new(pool)) } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_late_dependents_are_settled_at_enqueue() { - late_dependents_are_settled_at_enqueue(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_late_dependents_respect_manual_policy() { - late_dependents_respect_manual_policy(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_late_dependents_race_with_completion() { - late_dependents_race_with_completion(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_paused_queue_is_not_dequeued() { - paused_queue_is_not_dequeued(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_weighted_dequeue_reaches_every_priority() { - weighted_dequeue_reaches_every_priority(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_due_times_use_the_database_clock() { - due_times_use_the_database_clock(queue_with_clock_ahead().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_cancel_workflow_discards_running_jobs() { - cancel_workflow_discards_running_jobs(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_cron_catches_up_missed_slots_once() { - cron_catches_up_missed_slots_once(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_processing_time_statistics() { - processing_time_statistics(test_utils::setup_postgres_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_postgres_queue; + test_postgres_late_dependents_are_settled_at_enqueue => late_dependents_are_settled_at_enqueue, + test_postgres_late_dependents_respect_manual_policy => late_dependents_respect_manual_policy, + test_postgres_late_dependents_race_with_completion => late_dependents_race_with_completion, + test_postgres_paused_queue_is_not_dequeued => paused_queue_is_not_dequeued, + test_postgres_weighted_dequeue_reaches_every_priority => weighted_dequeue_reaches_every_priority, + test_postgres_cancel_workflow_discards_running_jobs => cancel_workflow_discards_running_jobs, + test_postgres_cron_catches_up_missed_slots_once => cron_catches_up_missed_slots_once, + test_postgres_processing_time_statistics => processing_time_statistics, + test_postgres_fan_out_dependents_are_released_together => fan_out_dependents_are_released_together, + ); - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_fan_out_dependents_are_released_together() { - fan_out_dependents_are_released_together(test_utils::setup_postgres_queue().await).await; - } + crate::test_utils::scenario_tests!( + queue_with_clock_ahead; + test_postgres_due_times_use_the_database_clock => due_times_use_the_database_clock, + ); /// #17 M13: corrupt column values are reported instead of being replaced with /// defaults or wrapped into huge numbers. @@ -675,65 +633,23 @@ mod mysql_tests { Arc::new(JobQueue::new(pool)) } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_late_dependents_are_settled_at_enqueue() { - late_dependents_are_settled_at_enqueue(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_late_dependents_respect_manual_policy() { - late_dependents_respect_manual_policy(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_late_dependents_race_with_completion() { - late_dependents_race_with_completion(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_paused_queue_is_not_dequeued() { - paused_queue_is_not_dequeued(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_weighted_dequeue_reaches_every_priority() { - weighted_dequeue_reaches_every_priority(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_due_times_use_the_database_clock() { - due_times_use_the_database_clock(mysql_queue_with_clock_ahead().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_cancel_workflow_discards_running_jobs() { - cancel_workflow_discards_running_jobs(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_cron_catches_up_missed_slots_once() { - cron_catches_up_missed_slots_once(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_processing_time_statistics() { - processing_time_statistics(test_utils::setup_mysql_queue().await).await; - } + crate::test_utils::scenario_tests!( + test_utils::setup_mysql_queue; + test_mysql_late_dependents_are_settled_at_enqueue => late_dependents_are_settled_at_enqueue, + test_mysql_late_dependents_respect_manual_policy => late_dependents_respect_manual_policy, + test_mysql_late_dependents_race_with_completion => late_dependents_race_with_completion, + test_mysql_paused_queue_is_not_dequeued => paused_queue_is_not_dequeued, + test_mysql_weighted_dequeue_reaches_every_priority => weighted_dequeue_reaches_every_priority, + test_mysql_cancel_workflow_discards_running_jobs => cancel_workflow_discards_running_jobs, + test_mysql_cron_catches_up_missed_slots_once => cron_catches_up_missed_slots_once, + test_mysql_processing_time_statistics => processing_time_statistics, + test_mysql_fan_out_dependents_are_released_together => fan_out_dependents_are_released_together, + ); - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_fan_out_dependents_are_released_together() { - fan_out_dependents_are_released_together(test_utils::setup_mysql_queue().await).await; - } + crate::test_utils::scenario_tests!( + mysql_queue_with_clock_ahead; + test_mysql_due_times_use_the_database_clock => due_times_use_the_database_clock, + ); /// #17 M13: corrupt column values are reported instead of being replaced with /// defaults or wrapped into huge numbers. diff --git a/tests/test_utils.rs b/tests/test_utils.rs index 492e0b7..766cc08 100644 --- a/tests/test_utils.rs +++ b/tests/test_utils.rs @@ -111,3 +111,108 @@ pub fn skip_known_bug() -> bool { eprintln!("skipping known-bug test; set HAMMERWORK_TEST_KNOWN_BUGS=1 to run it"); true } + +/// A fresh in-memory [`TestQueue`](hammerwork::queue::test::TestQueue). +#[cfg(feature = "test")] +pub async fn test_queue() -> std::sync::Arc { + std::sync::Arc::new(hammerwork::queue::test::TestQueue::new()) +} + +/// One test per scenario in module `$module`, each running `scenario($setup().await)`. +/// +/// The test attribute defaults to `#[tokio::test]`; pass another one first, e.g. +/// `backend_tests!(#[tokio::test(flavor = "multi_thread")] module, ...)`. +#[allow(unused_macros)] +macro_rules! backend_tests { + (#[$test:meta] $module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { + mod $module { + use super::*; + $( + #[$test] + #[$ignore] + async fn $scenario() { + super::$scenario($setup().await).await; + } + )* + } + }; + ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { + $crate::test_utils::backend_tests!( + #[tokio::test] $module, $setup, $ignore, [$($scenario),*] + ); + }; +} +#[allow(unused_imports)] +pub(crate) use backend_tests; + +/// Poll `get_job` until `predicate` holds or `timeout` elapses; returns the last job. +pub async fn wait_for_job( + queue: &std::sync::Arc, + id: hammerwork::JobId, + timeout: std::time::Duration, + predicate: F, +) -> hammerwork::Job +where + Q: hammerwork::queue::DatabaseQueue + ?Sized, + F: Fn(&hammerwork::Job) -> bool, +{ + let deadline = std::time::Instant::now() + timeout; + loop { + let job = queue.get_job(id).await.unwrap().expect("job exists"); + if predicate(&job) || std::time::Instant::now() >= deadline { + return job; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } +} + +/// Poll `condition` until it holds or `timeout` elapses; returns whether it held. +pub async fn eventually(timeout: std::time::Duration, mut condition: F) -> bool +where + F: FnMut() -> Fut, + Fut: std::future::Future, +{ + let deadline = std::time::Instant::now() + timeout; + loop { + if condition().await { + return true; + } + if std::time::Instant::now() >= deadline { + return false; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } +} + +/// A worker on a queue of its own (named after `prefix`), so it never touches the jobs +/// under test. +#[cfg(any(feature = "postgres", feature = "mysql"))] +pub fn idle_worker(queue: &Arc>, prefix: &str) -> hammerwork::Worker +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: hammerwork::queue::DatabaseQueue + Send + Sync + 'static, +{ + let handler: hammerwork::worker::JobHandler = + Arc::new(|_job: hammerwork::Job| Box::pin(async { Ok(()) })); + hammerwork::Worker::new(Arc::clone(queue), unique_queue(prefix), handler) + .with_poll_interval(std::time::Duration::from_millis(50)) +} + +/// One ignored (it needs a database) `#[tokio::test]` per `name => scenario`, each +/// running `scenario($setup().await)`. Attributes before a name (e.g. `#[cfg(...)]`) +/// apply to that test. +#[allow(unused_macros)] +macro_rules! scenario_tests { + ($setup:path; $($(#[$attr:meta])* $name:ident => $scenario:path),* $(,)?) => { + $( + $(#[$attr])* + #[tokio::test] + #[ignore] // Requires database connection + async fn $name() { + $scenario($setup().await).await; + } + )* + }; +} +#[allow(unused_imports)] +pub(crate) use scenario_tests; diff --git a/tests/worker_config_tests.rs b/tests/worker_config_tests.rs index e4a2029..7ec59a1 100644 --- a/tests/worker_config_tests.rs +++ b/tests/worker_config_tests.rs @@ -30,24 +30,6 @@ use std::{ }; use tokio::sync::mpsc; -/// Poll `condition` until it holds or `timeout` elapses; returns whether it held. -async fn eventually(timeout: Duration, mut condition: F) -> bool -where - F: FnMut() -> Fut, - Fut: Future, -{ - let deadline = Instant::now() + timeout; - loop { - if condition().await { - return true; - } - if Instant::now() >= deadline { - return false; - } - tokio::time::sleep(Duration::from_millis(25)).await; - } -} - /// Wait until every job in `ids` matches `predicate`. async fn wait_for_jobs( queue: &Arc>, @@ -60,7 +42,7 @@ where JobQueue: DatabaseQueue + Send + Sync + 'static, P: Fn(&Job) -> bool, { - eventually(timeout, || async { + test_utils::eventually(timeout, || async { for id in ids { match queue.get_job(*id).await.unwrap() { Some(job) if predicate(&job) => {} @@ -516,7 +498,7 @@ where ); // With the queue empty it scales back down to min_workers. - let scaled_down = eventually(Duration::from_secs(10), || async { + let scaled_down = test_utils::eventually(Duration::from_secs(10), || async { pool.get_autoscale_metrics().active_workers == 1 }) .await; @@ -953,7 +935,7 @@ where let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); // Let alerts fire (and hang) while the queue is idle, then give it work. - let fired = eventually(Duration::from_secs(5), || async { + let fired = test_utils::eventually(Duration::from_secs(5), || async { accepted.load(Ordering::SeqCst) > 0 }) .await; @@ -1164,106 +1146,34 @@ mod postgres_tests { Arc::new(JobQueue::new(pool)) } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_pool_runs_pool_size_workers() { - pool_runs_pool_size_workers(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_config_timeout_and_retry_strategy_apply() { - config_timeout_and_retry_strategy_apply(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_config_strict_priority_orders_jobs() { - config_strict_priority_orders_jobs(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_throttle_max_concurrent_caps_the_pool() { - throttle_max_concurrent_caps_the_pool(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_throttle_rate_limits_the_pool() { - throttle_rate_limits_the_pool(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_autoscaling_adds_and_retires_workers() { - autoscaling_adds_and_retires_workers(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_autoscaling_only_scales_the_template_queue() { - autoscaling_only_scales_the_template_queue(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_rate_limit_is_not_spent_on_empty_polls() { - rate_limit_is_not_spent_on_empty_polls(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_waits_while_queue_is_paused() { - worker_waits_while_queue_is_paused(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_job_hooks_fire_for_each_outcome() { - job_hooks_fire_for_each_outcome(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_backs_off_on_errors_and_stops_promptly() { - worker_backs_off_on_errors_and_stops_promptly(broken_queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_sends_queue_depth_and_starvation_alerts() { - worker_sends_queue_depth_and_starvation_alerts(queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_sends_error_rate_alerts() { - worker_sends_error_rate_alerts(queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_hanging_alert_target_does_not_block_jobs() { - hanging_alert_target_does_not_block_jobs(queue().await).await; - } - - #[cfg(feature = "metrics")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_records_prometheus_metrics() { - worker_records_prometheus_metrics(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_postgres_pool_runs_pool_size_workers => pool_runs_pool_size_workers, + test_postgres_config_timeout_and_retry_strategy_apply => config_timeout_and_retry_strategy_apply, + test_postgres_config_strict_priority_orders_jobs => config_strict_priority_orders_jobs, + test_postgres_throttle_max_concurrent_caps_the_pool => throttle_max_concurrent_caps_the_pool, + test_postgres_throttle_rate_limits_the_pool => throttle_rate_limits_the_pool, + test_postgres_autoscaling_adds_and_retires_workers => autoscaling_adds_and_retires_workers, + test_postgres_autoscaling_only_scales_the_template_queue => autoscaling_only_scales_the_template_queue, + test_postgres_rate_limit_is_not_spent_on_empty_polls => rate_limit_is_not_spent_on_empty_polls, + test_postgres_worker_waits_while_queue_is_paused => worker_waits_while_queue_is_paused, + test_postgres_job_hooks_fire_for_each_outcome => job_hooks_fire_for_each_outcome, + #[cfg(feature = "alerting")] + test_postgres_worker_sends_queue_depth_and_starvation_alerts => worker_sends_queue_depth_and_starvation_alerts, + #[cfg(feature = "alerting")] + test_postgres_worker_sends_error_rate_alerts => worker_sends_error_rate_alerts, + #[cfg(feature = "alerting")] + test_postgres_hanging_alert_target_does_not_block_jobs => hanging_alert_target_does_not_block_jobs, + #[cfg(feature = "metrics")] + test_postgres_worker_records_prometheus_metrics => worker_records_prometheus_metrics, + #[cfg(feature = "webhooks")] + test_postgres_worker_publishes_lifecycle_events => worker_publishes_lifecycle_events, + ); - #[cfg(feature = "webhooks")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_publishes_lifecycle_events() { - worker_publishes_lifecycle_events(queue().await).await; - } + crate::test_utils::scenario_tests!( + broken_queue; + test_postgres_worker_backs_off_on_errors_and_stops_promptly => worker_backs_off_on_errors_and_stops_promptly, + ); } #[cfg(feature = "mysql")] @@ -1283,104 +1193,32 @@ mod mysql_tests { Arc::new(JobQueue::new(pool)) } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_pool_runs_pool_size_workers() { - pool_runs_pool_size_workers(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_config_timeout_and_retry_strategy_apply() { - config_timeout_and_retry_strategy_apply(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_config_strict_priority_orders_jobs() { - config_strict_priority_orders_jobs(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_throttle_max_concurrent_caps_the_pool() { - throttle_max_concurrent_caps_the_pool(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_throttle_rate_limits_the_pool() { - throttle_rate_limits_the_pool(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_autoscaling_adds_and_retires_workers() { - autoscaling_adds_and_retires_workers(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_autoscaling_only_scales_the_template_queue() { - autoscaling_only_scales_the_template_queue(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_rate_limit_is_not_spent_on_empty_polls() { - rate_limit_is_not_spent_on_empty_polls(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_waits_while_queue_is_paused() { - worker_waits_while_queue_is_paused(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_job_hooks_fire_for_each_outcome() { - job_hooks_fire_for_each_outcome(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_backs_off_on_errors_and_stops_promptly() { - worker_backs_off_on_errors_and_stops_promptly(broken_queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_sends_queue_depth_and_starvation_alerts() { - worker_sends_queue_depth_and_starvation_alerts(queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_sends_error_rate_alerts() { - worker_sends_error_rate_alerts(queue().await).await; - } - - #[cfg(feature = "alerting")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_hanging_alert_target_does_not_block_jobs() { - hanging_alert_target_does_not_block_jobs(queue().await).await; - } - - #[cfg(feature = "metrics")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_records_prometheus_metrics() { - worker_records_prometheus_metrics(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_mysql_pool_runs_pool_size_workers => pool_runs_pool_size_workers, + test_mysql_config_timeout_and_retry_strategy_apply => config_timeout_and_retry_strategy_apply, + test_mysql_config_strict_priority_orders_jobs => config_strict_priority_orders_jobs, + test_mysql_throttle_max_concurrent_caps_the_pool => throttle_max_concurrent_caps_the_pool, + test_mysql_throttle_rate_limits_the_pool => throttle_rate_limits_the_pool, + test_mysql_autoscaling_adds_and_retires_workers => autoscaling_adds_and_retires_workers, + test_mysql_autoscaling_only_scales_the_template_queue => autoscaling_only_scales_the_template_queue, + test_mysql_rate_limit_is_not_spent_on_empty_polls => rate_limit_is_not_spent_on_empty_polls, + test_mysql_worker_waits_while_queue_is_paused => worker_waits_while_queue_is_paused, + test_mysql_job_hooks_fire_for_each_outcome => job_hooks_fire_for_each_outcome, + #[cfg(feature = "alerting")] + test_mysql_worker_sends_queue_depth_and_starvation_alerts => worker_sends_queue_depth_and_starvation_alerts, + #[cfg(feature = "alerting")] + test_mysql_worker_sends_error_rate_alerts => worker_sends_error_rate_alerts, + #[cfg(feature = "alerting")] + test_mysql_hanging_alert_target_does_not_block_jobs => hanging_alert_target_does_not_block_jobs, + #[cfg(feature = "metrics")] + test_mysql_worker_records_prometheus_metrics => worker_records_prometheus_metrics, + #[cfg(feature = "webhooks")] + test_mysql_worker_publishes_lifecycle_events => worker_publishes_lifecycle_events, + ); - #[cfg(feature = "webhooks")] - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_publishes_lifecycle_events() { - worker_publishes_lifecycle_events(queue().await).await; - } + crate::test_utils::scenario_tests!( + broken_queue; + test_mysql_worker_backs_off_on_errors_and_stops_promptly => worker_backs_off_on_errors_and_stops_promptly, + ); } diff --git a/tests/worker_pool_archival_tests.rs b/tests/worker_pool_archival_tests.rs index 77a2e0d..59dcc8f 100644 --- a/tests/worker_pool_archival_tests.rs +++ b/tests/worker_pool_archival_tests.rs @@ -11,18 +11,12 @@ mod test_utils; use chrono::Utc; use hammerwork::{ - HammerworkConfig, Job, JobId, JobQueue, JobStatus, Worker, WorkerPool, + HammerworkConfig, Job, JobId, JobQueue, JobStatus, WorkerPool, archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason, JobArchiver}, queue::DatabaseQueue, - worker::JobHandler, }; use serde_json::json; -use std::{ - collections::HashSet, - future::Future, - sync::Arc, - time::{Duration, Instant}, -}; +use std::{collections::HashSet, sync::Arc, time::Duration}; /// Archive completed jobs at once; keep archived jobs for an hour. fn policy() -> ArchivalPolicy { @@ -68,37 +62,6 @@ where .collect() } -/// Polls `condition` every 50ms until it holds or 20 seconds pass. -async fn eventually(condition: F) -> bool -where - F: Fn() -> Fut, - Fut: Future, -{ - let deadline = Instant::now() + Duration::from_secs(20); - while Instant::now() < deadline { - if condition().await { - return true; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - false -} - -/// A worker on a queue of its own, so it never touches the jobs under test. -fn idle_worker(queue: &Arc>) -> Worker -where - DB: sqlx::Database + Send + Sync + 'static, - JobQueue: DatabaseQueue + Send + Sync + 'static, -{ - let handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); - Worker::new( - Arc::clone(queue), - test_utils::unique_queue("archival_idle"), - handler, - ) - .with_poll_interval(Duration::from_millis(50)) -} - /// The pool archives eligible jobs (in several batches), leaves pending jobs alone, /// purges archived jobs older than `purge_archived_after` and keeps newer ones, and /// stops archiving once it is shut down. @@ -146,11 +109,11 @@ where .without_autoscaling() .without_stale_job_reaper() .with_archival(policy(), ArchivalConfig::new(), Duration::from_millis(100)); - pool.add_worker(idle_worker(&queue)); + pool.add_worker(test_utils::idle_worker(&queue, "archival_idle")); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), - done = eventually(|| async { + done = test_utils::eventually(Duration::from_secs(20), || async { let archived = archived_ids(&queue, &queue_name).await; eligible.iter().all(|id| archived.contains(id)) && !archived.contains(&old) }) => assert!(done, "the pool archived the eligible jobs and purged the old one"), @@ -210,9 +173,12 @@ where config.archive.check_interval = Duration::from_millis(100); let job = completed_job(&queue, &queue_name).await; - let mut pool = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); + let mut pool = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "archival_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), () = tokio::time::sleep(Duration::from_millis(500)) => {} @@ -224,12 +190,15 @@ where ); config.archive.enabled = true; - let mut pool = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); + let mut pool = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "archival_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), - done = eventually(|| async { archived_ids(&queue, &queue_name).await.contains(&job) }) => { + done = test_utils::eventually(Duration::from_secs(20), || async { archived_ids(&queue, &queue_name).await.contains(&job) }) => { assert!(done, "the configured pool archived the job"); } } @@ -332,17 +301,11 @@ mod postgres_tests { pool_archives_and_purges(queue().await, backdate).await; } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_configured_pool_archives() { - configured_pool_archives(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_concurrent_passes_archive_each_job_once() { - concurrent_passes_archive_each_job_once(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_postgres_configured_pool_archives => configured_pool_archives, + test_postgres_concurrent_passes_archive_each_job_once => concurrent_passes_archive_each_job_once, + ); } #[cfg(feature = "mysql")] @@ -368,15 +331,9 @@ mod mysql_tests { pool_archives_and_purges(queue().await, backdate).await; } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_configured_pool_archives() { - configured_pool_archives(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_concurrent_passes_archive_each_job_once() { - concurrent_passes_archive_each_job_once(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_mysql_configured_pool_archives => configured_pool_archives, + test_mysql_concurrent_passes_archive_each_job_once => concurrent_passes_archive_each_job_once, + ); } diff --git a/tests/worker_pool_maintenance_tests.rs b/tests/worker_pool_maintenance_tests.rs index 8baa1b5..786e065 100644 --- a/tests/worker_pool_maintenance_tests.rs +++ b/tests/worker_pool_maintenance_tests.rs @@ -10,47 +10,9 @@ mod test_utils; use chrono::Utc; -use hammerwork::{ - HammerworkConfig, Job, JobId, JobQueue, Worker, WorkerPool, queue::DatabaseQueue, - worker::JobHandler, -}; +use hammerwork::{HammerworkConfig, Job, JobId, JobQueue, WorkerPool, queue::DatabaseQueue}; use serde_json::json; -use std::{ - future::Future, - sync::Arc, - time::{Duration, Instant}, -}; - -/// Polls `condition` every 50ms until it holds or 20 seconds pass. -async fn eventually(condition: F) -> bool -where - F: Fn() -> Fut, - Fut: Future, -{ - let deadline = Instant::now() + Duration::from_secs(20); - while Instant::now() < deadline { - if condition().await { - return true; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - false -} - -/// A worker on a queue of its own, so it never touches the jobs under test. -fn idle_worker(queue: &Arc>) -> Worker -where - DB: sqlx::Database + Send + Sync + 'static, - JobQueue: DatabaseQueue + Send + Sync + 'static, -{ - let handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); - Worker::new( - Arc::clone(queue), - test_utils::unique_queue("maintenance_idle"), - handler, - ) - .with_poll_interval(Duration::from_millis(50)) -} +use std::{sync::Arc, time::Duration}; /// A completed job with a stored result expiring at `expires_at`. async fn job_with_result( @@ -109,7 +71,7 @@ where .without_autoscaling() .without_stale_job_reaper() .with_result_cleanup(Duration::from_millis(100)); - pool.add_worker(idle_worker(&queue)); + pool.add_worker(test_utils::idle_worker(&queue, "maintenance_idle")); // The first cleanup runs at start; a result that expires later is cleared by a // later one. @@ -121,7 +83,7 @@ where .await; tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), - done = eventually(|| async { + done = test_utils::eventually(Duration::from_secs(20), || async { !has_result(&queue, expired).await && !has_result(&queue, later).await }) => assert!(done, "the pool cleared the expired results"), } @@ -171,9 +133,12 @@ where config.worker.result_cleanup_interval = Duration::from_millis(100); let id = job_with_result(&queue, &queue_name, past).await; - let mut pool = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); + let mut pool = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "maintenance_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), () = tokio::time::sleep(Duration::from_millis(500)) => {} @@ -182,12 +147,15 @@ where assert!(has_result(&queue, id).await, "cleanup is off when disabled"); config.worker.result_cleanup_enabled = true; - let mut pool = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); + let mut pool = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "maintenance_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), - done = eventually(|| async { !has_result(&queue, id).await }) => { + done = test_utils::eventually(Duration::from_secs(20), || async { !has_result(&queue, id).await }) => { assert!(done, "the configured pool cleared the expired result"); } } @@ -282,9 +250,12 @@ mod key_rotation { let key_id = due_key(&mut manager).await; let mut off = rotation_config(); off.encryption.key_rotation.enabled = false; - let mut pool = WorkerPool::from_hammerwork_config(idle_worker(&queue), &off) - .unwrap() - .without_stale_job_reaper(); + let mut pool = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "maintenance_idle"), + &off, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), () = tokio::time::sleep(Duration::from_millis(500)) => {} @@ -294,17 +265,23 @@ mod key_rotation { // Two configured pools at once: the key gets exactly one new version. let config = rotation_config(); - let mut first = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); - let mut second = WorkerPool::from_hammerwork_config(idle_worker(&queue), &config) - .unwrap() - .without_stale_job_reaper(); + let mut first = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "maintenance_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); + let mut second = WorkerPool::from_hammerwork_config( + test_utils::idle_worker(&queue, "maintenance_idle"), + &config, + ) + .unwrap() + .without_stale_job_reaper(); tokio::select! { result = first.start() => panic!("pool stopped early: {result:?}"), result = second.start() => panic!("pool stopped early: {result:?}"), done = async { - let rotated = eventually(|| async { versions(key_id.clone()).await.0 >= 2 }).await; + let rotated = test_utils::eventually(Duration::from_secs(20), || async { versions(key_id.clone()).await.0 >= 2 }).await; // Both pools run several passes meanwhile. tokio::time::sleep(Duration::from_millis(2500)).await; rotated @@ -319,7 +296,12 @@ mod key_rotation { // Another due key while both pools keep running (dropping `start` does not // stop them): rotated once too. let second_key = due_key(&mut manager).await; - assert!(eventually(|| async { versions(second_key.clone()).await.0 >= 2 }).await); + assert!( + test_utils::eventually(Duration::from_secs(20), || async { + versions(second_key.clone()).await.0 >= 2 + }) + .await + ); tokio::time::sleep(Duration::from_millis(1500)).await; assert_eq!(versions(second_key.clone()).await, (2, 1)); first.shutdown().await.unwrap(); @@ -364,10 +346,10 @@ mod key_rotation { .without_stale_job_reaper() .without_result_cleanup() .with_key_rotation(manager.clone(), Duration::from_millis(100)); - pool.add_worker(idle_worker(&queue)); + pool.add_worker(test_utils::idle_worker(&queue, "maintenance_idle")); tokio::select! { result = pool.start() => panic!("pool stopped early: {result:?}"), - done = eventually(|| async { versions(key_id.clone()).await.0 >= 2 }) => { + done = test_utils::eventually(Duration::from_secs(20), || async { versions(key_id.clone()).await.0 >= 2 }) => { assert!(done, "the pool rotated the due key"); } } @@ -384,17 +366,11 @@ mod postgres_tests { test_utils::setup_postgres_queue().await } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_pool_cleans_expired_results() { - pool_cleans_expired_results(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_configured_pool_cleans_results() { - configured_pool_cleans_results(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_postgres_pool_cleans_expired_results => pool_cleans_expired_results, + test_postgres_configured_pool_cleans_results => configured_pool_cleans_results, + ); #[cfg(feature = "encryption")] async fn versions(pool: sqlx::PgPool, key_id: String) -> (i64, i64) { @@ -439,17 +415,11 @@ mod mysql_tests { test_utils::setup_mysql_queue().await } - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_pool_cleans_expired_results() { - pool_cleans_expired_results(queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_configured_pool_cleans_results() { - configured_pool_cleans_results(queue().await).await; - } + crate::test_utils::scenario_tests!( + queue; + test_mysql_pool_cleans_expired_results => pool_cleans_expired_results, + test_mysql_configured_pool_cleans_results => configured_pool_cleans_results, + ); #[cfg(feature = "encryption")] async fn versions(pool: sqlx::MySqlPool, key_id: String) -> (i64, i64) { diff --git a/tests/worker_robustness_tests.rs b/tests/worker_robustness_tests.rs index bfa8d94..c3eb4fb 100644 --- a/tests/worker_robustness_tests.rs +++ b/tests/worker_robustness_tests.rs @@ -23,28 +23,6 @@ use std::{ }; 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>) @@ -75,7 +53,7 @@ where 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| { + let job = test_utils::wait_for_job(&queue, panicking, Duration::from_secs(10), |job| { job.status != JobStatus::Running && job.status != JobStatus::Pending }) .await; @@ -91,7 +69,7 @@ where .enqueue(Job::new(queue_name.clone(), json!({ "panic": false }))) .await .unwrap(); - let job = wait_for_job(&queue, healthy, Duration::from_secs(10), |job| { + let job = test_utils::wait_for_job(&queue, healthy, Duration::from_secs(10), |job| { job.status == JobStatus::Completed }) .await; @@ -132,7 +110,7 @@ where 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| { + let job = test_utils::wait_for_job(&queue, id, Duration::from_secs(10), |job| { job.attempts >= 1 && job.status == JobStatus::Pending }) .await; @@ -569,7 +547,7 @@ where result = async { tokio::join!(service_a.start(), service_b.start()) } => { panic!("pools stopped early: {result:?}") } - _ = wait_for_job(&queue, id, Duration::from_secs(10), |job| { + _ = test_utils::wait_for_job(&queue, id, Duration::from_secs(10), |job| { job.status == JobStatus::Completed }) => {} } @@ -691,23 +669,8 @@ where queue.delete_job(id).await.unwrap(); } -macro_rules! backend_tests { - ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { - mod $module { - use super::*; - $( - #[tokio::test] - #[$ignore] - async fn $scenario() { - super::$scenario($setup().await).await; - } - )* - } - }; -} - #[cfg(feature = "postgres")] -backend_tests!( +crate::test_utils::backend_tests!( postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -726,7 +689,7 @@ backend_tests!( ); #[cfg(feature = "mysql")] -backend_tests!( +crate::test_utils::backend_tests!( mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", diff --git a/tests/workflow_failure_policy_tests.rs b/tests/workflow_failure_policy_tests.rs index a6f5c52..5aedb30 100644 --- a/tests/workflow_failure_policy_tests.rs +++ b/tests/workflow_failure_policy_tests.rs @@ -376,24 +376,8 @@ where } } -/// One `#[tokio::test]` per scenario, run against the queue returned by `$setup`. -macro_rules! backend_tests { - ($module:ident, $setup:path, $ignore:meta, [$($scenario:ident),* $(,)?]) => { - mod $module { - use super::*; - $( - #[tokio::test] - #[$ignore] - async fn $scenario() { - super::$scenario($setup().await).await; - } - )* - } - }; -} - #[cfg(feature = "postgres")] -backend_tests!( +crate::test_utils::backend_tests!( postgres_tests, test_utils::setup_postgres_queue, ignore = "requires PostgreSQL: DATABASE_URL", @@ -407,7 +391,7 @@ backend_tests!( ); #[cfg(feature = "mysql")] -backend_tests!( +crate::test_utils::backend_tests!( mysql_tests, test_utils::setup_mysql_queue, ignore = "requires MySQL: MYSQL_DATABASE_URL", @@ -421,14 +405,9 @@ backend_tests!( ); #[cfg(feature = "test")] -async fn test_queue() -> Arc { - Arc::new(hammerwork::queue::test::TestQueue::new()) -} - -#[cfg(feature = "test")] -backend_tests!( +crate::test_utils::backend_tests!( test_queue_tests, - test_queue, + test_utils::test_queue, allow(unused_attributes), [ fail_job_is_terminal, From c65b9239f95681575184ae750dc61fab4315728e Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 00:59:14 -0400 Subject: [PATCH 6/8] refactor(worker): share the heartbeat loop, event construction and pool task spawning - maintain_lease and maintain_held_leases share every_heartbeat (the interval, the zero-lease case and the never-completing tail); maintain_lease recomputed the interval held_renewal_interval already gives. - Acquired serves the single-job and batch paths (AcquiredBatch and idle_wait_batch removed). - job_event builds the six JobEvents, and announce_retry is the retry hook and event shared by failed and timed-out runs. - The stale job reaper, encrypted job purge and result cleanup spawn through spawn_queue_task (spawn_periodic on the first worker's queue). - Lock reads use map/unwrap_or_default instead of if-let/else. Co-Authored-By: Claude Opus 5.5 --- src/worker.rs | 340 ++++++++++++++++++++++++++------------------------ 1 file changed, 175 insertions(+), 165 deletions(-) diff --git a/src/worker.rs b/src/worker.rs index cd48c87..b107f40 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -161,17 +161,10 @@ impl Drop for AbortOnDrop { } } -/// Result of one attempt to acquire a job in the worker loop. -enum Acquired { - // Boxed: a `Job` is much larger than the other variants. - Job(Box), - Idle, - Shutdown, -} - -/// What a batch-mode worker got from one poll. -enum AcquiredBatch { - Jobs(Vec), +/// Result of one attempt to acquire work in the worker loop: a job (boxed, as a `Job` +/// is much larger than the other variants) or, in batch mode, the claimed jobs. +enum Acquired { + Work(T), Idle, Shutdown, } @@ -225,6 +218,25 @@ enum HeldStart { RenewThenRun, } +/// A [`JobEvent`] of `event_type` for `job`. +fn job_event( + job: &Job, + event_type: JobEventType, + processing_time_ms: Option, + error_message: Option, + timestamp: DateTime, +) -> JobEvent { + JobEvent { + job_id: job.id, + queue_name: job.queue_name.clone(), + event_type, + priority: job.priority, + processing_time_ms, + error_message, + timestamp, + } +} + /// Whether shutdown was requested (or the shutdown sender was dropped), without waiting. fn shutdown_requested(shutdown_rx: &mut mpsc::Receiver<()>) -> bool { !matches!( @@ -1923,14 +1935,14 @@ where let (outcome, shutting_down) = if self.batch_processing_enabled { // Each claimed job holds its own throttle permit (see `acquire_batch`). match self.acquire_batch(&mut shutdown_rx).await { - Ok(AcquiredBatch::Shutdown) => { + Ok(Acquired::Shutdown) => { info!("Worker shutting down for queue: {}", self.queue_name); break; } - Ok(AcquiredBatch::Jobs(batch)) => { + Ok(Acquired::Work(batch)) => { self.run_batch_until_done(batch, &mut shutdown_rx).await } - Ok(AcquiredBatch::Idle) => (Ok(()), false), + Ok(Acquired::Idle) => (Ok(()), false), Err(e) => { error!("Error dequeuing jobs from queue {}: {}", self.queue_name, e); (Err(e), false) @@ -1958,7 +1970,9 @@ where info!("Worker shutting down for queue: {}", self.queue_name); break; } - Ok(Acquired::Job(job)) => self.run_job_until_done(*job, &mut shutdown_rx).await, + Ok(Acquired::Work(job)) => { + self.run_job_until_done(*job, &mut shutdown_rx).await + } Ok(Acquired::Idle) => (Ok(()), false), Err(e) => { error!("Error dequeuing job from queue {}: {}", self.queue_name, e); @@ -2061,7 +2075,10 @@ where /// Returns `Idle` after waiting for the poll interval when the queue is empty or /// paused, `Shutdown` when shutdown is requested during a wait, and `Err` when the /// dequeue itself fails. Database calls are never interrupted by shutdown. - async fn acquire_job(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> Result { + async fn acquire_job( + &self, + shutdown_rx: &mut mpsc::Receiver<()>, + ) -> Result>> { // Alert checks and queue depth metrics run in the monitoring task // (`start_monitoring_task`), never here: a slow alert endpoint or a COUNT(*) must // not hold up dequeuing. @@ -2096,7 +2113,7 @@ where "Processing job: {} with priority: {:?}", job.id, job.priority ); - Ok(Acquired::Job(Box::new(job))) + Ok(Acquired::Work(Box::new(job))) } // No job available (or the queue is paused): wait before polling again. None => Ok(self.idle_wait(shutdown_rx).await), @@ -2144,14 +2161,17 @@ where /// more as are free right now, up to the batch size, and claims no more jobs than /// that. Tokens for jobs it did not get are handed back; permits it did not need are /// dropped. - async fn acquire_batch(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> Result { + async fn acquire_batch( + &self, + shutdown_rx: &mut mpsc::Receiver<()>, + ) -> Result>> { let mut capacity = self.batch_size.max(1); let mut permits = Vec::new(); if let Some(limit) = &self.concurrency_limit { let first = tokio::select! { biased; - _ = shutdown_rx.recv() => return Ok(AcquiredBatch::Shutdown), + _ = shutdown_rx.recv() => return Ok(Acquired::Shutdown), // The semaphore is never closed, so this is always a permit. permit = Arc::clone(limit).acquire_owned() => permit.ok(), }; @@ -2164,7 +2184,7 @@ where } capacity = permits.len(); if capacity == 0 { - return Ok(self.idle_wait_batch(shutdown_rx).await); + return Ok(self.idle_wait(shutdown_rx).await); } } @@ -2172,12 +2192,12 @@ where if let Some(rate_limiter) = &self.rate_limiter { let permit = tokio::select! { biased; - _ = shutdown_rx.recv() => return Ok(AcquiredBatch::Shutdown), + _ = shutdown_rx.recv() => return Ok(Acquired::Shutdown), permit = rate_limiter.acquire() => permit, }; if let Err(e) = permit { warn!("Rate limiter error: {}", e); - return Ok(self.idle_wait_batch(shutdown_rx).await); + return Ok(self.idle_wait(shutdown_rx).await); } tokens = 1; while tokens < capacity && rate_limiter.try_acquire() { @@ -2208,7 +2228,7 @@ where let jobs = claimed?; if jobs.is_empty() { // No job available (or the queue is paused): wait before polling again. - return Ok(self.idle_wait_batch(shutdown_rx).await); + return Ok(self.idle_wait(shutdown_rx).await); } debug!( "Claimed {} job(s) from queue {}", @@ -2216,7 +2236,7 @@ where self.queue_name ); let mut permits = permits.into_iter(); - Ok(AcquiredBatch::Jobs( + Ok(Acquired::Work( jobs.into_iter() .map(|job| ClaimedJob { job, @@ -2226,14 +2246,6 @@ where )) } - /// [`idle_wait`](Self::idle_wait) for batch mode. - async fn idle_wait_batch(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> AcquiredBatch { - match self.idle_wait(shutdown_rx).await { - Acquired::Shutdown => AcquiredBatch::Shutdown, - _ => AcquiredBatch::Idle, - } - } - /// Process the jobs of a claimed batch, up to `batch_concurrency` at a time, while /// renewing the leases of the ones still waiting for their turn. /// @@ -2422,12 +2434,7 @@ where /// job, which takes over once a job starts). A job whose lease is found lost is /// marked so it is not run. Never completes. async fn maintain_held_leases(&self, held: &std::sync::Mutex) { - if self.lease_duration.is_zero() { - return std::future::pending().await; - } - let interval = self.held_renewal_interval(); - loop { - sleep(interval).await; + self.every_heartbeat(|| async move { let waiting = held .lock() .map(|held| held.waiting.clone()) @@ -2454,7 +2461,29 @@ where Err(e) => warn!("Failed to renew the lease on waiting job {}: {}", run.id, e), } } + true + }) + .await + } + + /// Run `beat` every [heartbeat interval](Self::held_renewal_interval) (the first + /// one after an interval) until it returns `false`. Never completes. With a zero + /// lease, which never expires, `beat` never runs. + async fn every_heartbeat(&self, mut beat: F) + where + F: FnMut() -> Fut, + Fut: Future, + { + if !self.lease_duration.is_zero() { + let interval = self.held_renewal_interval(); + loop { + sleep(interval).await; + if !beat().await { + break; + } + } } + std::future::pending().await } /// Hand claimed jobs that never started back to the queue @@ -2491,7 +2520,7 @@ where /// Sleep for the poll interval (at least [`MIN_POLL_INTERVAL`]), returning early /// with `Shutdown` if shutdown is requested meanwhile. - async fn idle_wait(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> Acquired { + async fn idle_wait(&self, shutdown_rx: &mut mpsc::Receiver<()>) -> Acquired { tokio::select! { biased; _ = shutdown_rx.recv() => Acquired::Shutdown, @@ -2602,7 +2631,6 @@ where } async fn process_job(&self, job: Job) -> Result<()> { - let job_id = job.id; let batch_id = job.batch_id; let start_time = Utc::now(); @@ -2622,15 +2650,13 @@ where self.event_hooks.fire_job_start(job.clone()); // Record job started event - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::Started, - priority: job.priority, - processing_time_ms: None, - error_message: None, - timestamp: start_time, - }) + self.record_event(job_event( + &job, + JobEventType::Started, + None, + None, + start_time, + )) .await; // The job's own max_attempts decides whether a failed run is retried. @@ -2834,15 +2860,13 @@ where .fire_job_complete(job.clone(), processing_duration); // Record job completed event - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::Completed, - priority: job.priority, - processing_time_ms: Some(processing_time_ms), - error_message: None, - timestamp: Utc::now(), - }) + self.record_event(job_event( + job, + JobEventType::Completed, + Some(processing_time_ms), + None, + Utc::now(), + )) .await; Ok(()) @@ -2899,31 +2923,18 @@ where job.attempts + 1, self.attempt_limit(job) ); - self.event_hooks - .fire_job_retry(job.clone(), error_message.clone()); - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::Retried, - priority: job.priority, - processing_time_ms: None, - error_message: Some(error_message), - timestamp: Utc::now(), - }) - .await; + self.announce_retry(job, error_message).await; } else { debug!("Job {} run ended with status {:?}", job_id, recorded.status); self.event_hooks .fire_job_fail(job.clone(), error_message.clone()); - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::Dead, - priority: job.priority, - processing_time_ms: None, - error_message: Some(error_message), - timestamp: Utc::now(), - }) + self.record_event(job_event( + job, + JobEventType::Dead, + None, + Some(error_message), + Utc::now(), + )) .await; } @@ -2974,15 +2985,13 @@ where self.event_hooks.fire_job_timeout(job.clone(), timeout); // Record timeout event - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::TimedOut, - priority: job.priority, - processing_time_ms: Some(timeout.as_millis() as u64), - error_message: Some(error_message.clone()), - timestamp: Utc::now(), - }) + self.record_event(job_event( + job, + JobEventType::TimedOut, + Some(timeout.as_millis() as u64), + Some(error_message.clone()), + Utc::now(), + )) .await; if attempts_left { @@ -2992,23 +3001,26 @@ where job.attempts + 1, self.attempt_limit(job) ); - self.event_hooks - .fire_job_retry(job.clone(), error_message.clone()); - self.record_event(JobEvent { - job_id, - queue_name: job.queue_name.clone(), - event_type: JobEventType::Retried, - priority: job.priority, - processing_time_ms: None, - error_message: Some(error_message), - timestamp: Utc::now(), - }) - .await; + self.announce_retry(job, error_message).await; } Ok(()) } + /// Fire the retry hook and record the `Retried` event of a failed or timed-out run. + async fn announce_retry(&self, job: &Job, error_message: String) { + self.event_hooks + .fire_job_retry(job.clone(), error_message.clone()); + self.record_event(job_event( + job, + JobEventType::Retried, + None, + Some(error_message), + Utc::now(), + )) + .await; + } + /// Batch statistics after a failed (or timed-out) run. async fn after_failed_run(&self, job: &Job, error_message: &str, attempts_left: bool) { if !self.batch_processing_enabled { @@ -3097,12 +3109,7 @@ where /// interval, so short jobs never pay for a heartbeat write. Never completes. async fn maintain_lease(&self, run: &Job) { let job_id = run.id; - 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; + self.every_heartbeat(|| async move { match self.queue.heartbeat_job(run, self.lease_duration).await { Ok(true) => debug!("Renewed lease on job {}", job_id), Ok(false) => { @@ -3111,11 +3118,13 @@ where have been reclaimed as stale); the handler keeps running", job_id ); - return std::future::pending().await; + return false; } Err(e) => warn!("Failed to renew the lease on job {}: {}", job_id, e), } - } + true + }) + .await } /// Update batch processing statistics @@ -3238,11 +3247,10 @@ where /// Get current batch processing statistics pub fn get_batch_stats(&self) -> BatchProcessingStats { - if let Ok(stats) = self.batch_stats.read() { - stats.clone() - } else { - BatchProcessingStats::default() - } + self.batch_stats + .read() + .map(|stats| stats.clone()) + .unwrap_or_default() } async fn record_event(&self, event: JobEvent) { @@ -3360,13 +3368,7 @@ where // Check worker starvation #[cfg(feature = "alerting")] if let Some(alert_manager) = &alert_manager { - let last_time_value = { - if let Ok(last_time) = last_job_time.read() { - Some(*last_time) - } else { - None - } - }; + let last_time_value = last_job_time.read().ok().map(|last_time| *last_time); if let Some(last_time_value) = last_time_value && let Err(e) = alert_manager .check_worker_starvation(&queue_name, last_time_value) @@ -4036,7 +4038,6 @@ where 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() @@ -4046,20 +4047,17 @@ where .unwrap_or(DEFAULT_LEASE_DURATION) }); - Some(spawn_periodic(interval, signal_rx, move || { - let queue = Arc::clone(&queue); - async move { - 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), - } + spawn_queue_task(workers, interval, signal_rx, move |queue| async move { + 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), } - })) + }) } /// Spawn the periodic encrypted job retention purge, if enabled. @@ -4069,20 +4067,16 @@ where signal_rx: watch::Receiver, ) -> Option> { let interval = self.encrypted_job_purge_interval?; - let queue = Arc::clone(&workers.first()?.queue); - Some(spawn_periodic(interval, signal_rx, move || { - let queue = Arc::clone(&queue); - async move { - match queue.purge_expired_encrypted_jobs().await { - Ok(purge) if purge.total() > 0 => info!( - "Encrypted job purge deleted {} jobs and {} archived jobs", - purge.jobs, purge.archived_jobs - ), - Ok(_) => {} - Err(e) => warn!("Encrypted job purge failed: {}", e), - } + spawn_queue_task(workers, interval, signal_rx, |queue| async move { + match queue.purge_expired_encrypted_jobs().await { + Ok(purge) if purge.total() > 0 => info!( + "Encrypted job purge deleted {} jobs and {} archived jobs", + purge.jobs, purge.archived_jobs + ), + Ok(_) => {} + Err(e) => warn!("Encrypted job purge failed: {}", e), } - })) + }) } /// Spawn the periodic archival pass, if enabled. @@ -4135,20 +4129,18 @@ where signal_rx: watch::Receiver, ) -> Option> { let interval = self.result_cleanup_interval?; - let queue = Arc::clone(&workers.first()?.queue); - debug!("Clearing expired job results every {:?}", interval); - Some(spawn_periodic(interval, signal_rx, move || { - let queue = Arc::clone(&queue); - async move { - match queue.cleanup_expired_results().await { - Ok(cleared) if cleared > 0 => { - info!("Result cleanup cleared {} expired job results", cleared) - } - Ok(_) => debug!("Result cleanup found no expired job results"), - Err(e) => warn!("Result cleanup failed: {}", e), + if !workers.is_empty() { + debug!("Clearing expired job results every {:?}", interval); + } + spawn_queue_task(workers, interval, signal_rx, |queue| async move { + match queue.cleanup_expired_results().await { + Ok(cleared) if cleared > 0 => { + info!("Result cleanup cleared {} expired job results", cleared) } + Ok(_) => debug!("Result cleanup found no expired job results"), + Err(e) => warn!("Result cleanup failed: {}", e), } - })) + }) } /// Start the autoscaling background task. @@ -4248,11 +4240,10 @@ where /// Get current autoscaling metrics pub fn get_autoscale_metrics(&self) -> AutoscaleMetrics { - if let Ok(metrics) = self.autoscale_metrics.read() { - metrics.clone() - } else { - AutoscaleMetrics::default() - } + self.autoscale_metrics + .read() + .map(|metrics| metrics.clone()) + .unwrap_or_default() } /// Shut the pool down gracefully. @@ -4505,6 +4496,25 @@ where }) } +/// [`spawn_periodic`] for a maintenance pass on the queue of the pool's first worker +/// (`None` when the pool has no workers). +fn spawn_queue_task( + workers: &[Worker], + interval: Duration, + signal_rx: watch::Receiver, + pass: F, +) -> Option> +where + DB: Database + Send + Sync + 'static, + F: Fn(Arc>) -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + let queue = Arc::clone(&workers.first()?.queue); + Some(spawn_periodic(interval, signal_rx, move || { + pass(Arc::clone(&queue)) + })) +} + impl Drop for WorkerPool { fn drop(&mut self) { // Stop autoscaling task when dropping the pool @@ -5753,7 +5763,7 @@ mod tests { let started = std::time::Instant::now(); for _ in 0..5 { assert!(matches!( - worker.idle_wait(&mut shutdown_rx).await, + worker.idle_wait::>(&mut shutdown_rx).await, Acquired::Idle )); } From ec270708a0b728f9e5c46d585b9b0ad851353fb6 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 01:01:51 -0400 Subject: [PATCH 7/8] refactor(worker): split hooks, autoscaling and WorkerPool into submodules worker.rs (5.8k lines) keeps Worker; worker/hooks.rs holds the job event hooks, worker/autoscale.rs the autoscaling configuration, metrics and decision, and worker/pool.rs WorkerPool with its supervisor and maintenance tasks. Each module carries its own unit tests. The public paths (hammerwork::worker:: WorkerPool, AutoscaleConfig, JobEventHooks, ...) are re-exported unchanged. Code is moved, not changed. Co-Authored-By: Claude Opus 5.5 --- src/worker.rs | 2285 ++------------------------------------- src/worker/autoscale.rs | 451 ++++++++ src/worker/hooks.rs | 391 +++++++ src/worker/pool.rs | 1348 +++++++++++++++++++++++ 4 files changed, 2256 insertions(+), 2219 deletions(-) create mode 100644 src/worker/autoscale.rs create mode 100644 src/worker/hooks.rs create mode 100644 src/worker/pool.rs diff --git a/src/worker.rs b/src/worker.rs index b107f40..0517a89 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -43,6 +43,14 @@ use tokio::{ }; use tracing::{debug, error, info, warn}; +mod autoscale; +mod hooks; +mod pool; + +pub use autoscale::{AutoscaleConfig, AutoscaleMetrics}; +pub use hooks::{JobEventHooks, JobHookEvent, JobHookHandler}; +pub use pool::{DEFAULT_RESULT_CLEANUP_INTERVAL, WorkerPool}; + /// 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); @@ -254,340 +262,6 @@ fn error_backoff(base: Duration, consecutive_errors: u32) -> Duration { .min(MAX_ERROR_BACKOFF.max(base)) } -/// Event data for job lifecycle event hooks. -#[derive(Debug, Clone)] -pub struct JobHookEvent { - /// The job that triggered the event - pub job: Job, - /// When the event occurred - pub timestamp: DateTime, - /// Processing duration (for completion events) - pub duration: Option, - /// Error message (for failure events) - pub error: Option, -} - -/// Type alias for job event hook handler functions. -pub type JobHookHandler = Arc; - -/// Job lifecycle event hooks that can be registered with workers. -#[derive(Clone, Default)] -pub struct JobEventHooks { - /// Called when a job starts processing - pub on_job_start: Option, - /// Called when a job completes successfully - pub on_job_complete: Option, - /// Called when a job fails (before retry logic) - pub on_job_fail: Option, - /// Called when a job times out - pub on_job_timeout: Option, - /// Called when a job is retried - pub on_job_retry: Option, -} - -impl JobEventHooks { - /// Create a new set of empty job event hooks. - pub fn new() -> Self { - Self::default() - } - - /// Set the job start event handler. - pub fn on_start(mut self, handler: F) -> Self - where - F: Fn(JobHookEvent) + Send + Sync + 'static, - { - self.on_job_start = Some(Arc::new(handler)); - self - } - - /// Set the job completion event handler. - pub fn on_complete(mut self, handler: F) -> Self - where - F: Fn(JobHookEvent) + Send + Sync + 'static, - { - self.on_job_complete = Some(Arc::new(handler)); - self - } - - /// Set the job failure event handler. - pub fn on_fail(mut self, handler: F) -> Self - where - F: Fn(JobHookEvent) + Send + Sync + 'static, - { - self.on_job_fail = Some(Arc::new(handler)); - self - } - - /// Set the job timeout event handler. - pub fn on_timeout(mut self, handler: F) -> Self - where - F: Fn(JobHookEvent) + Send + Sync + 'static, - { - self.on_job_timeout = Some(Arc::new(handler)); - self - } - - /// Set the job retry event handler. - pub fn on_retry(mut self, handler: F) -> Self - where - F: Fn(JobHookEvent) + Send + Sync + 'static, - { - self.on_job_retry = Some(Arc::new(handler)); - self - } - - /// Fire the job start event if a handler is registered. - pub(crate) fn fire_job_start(&self, job: Job) { - if let Some(handler) = &self.on_job_start { - let event = JobHookEvent { - job, - timestamp: Utc::now(), - duration: None, - error: None, - }; - handler(event); - } - } - - /// Fire the job completion event if a handler is registered. - pub(crate) fn fire_job_complete(&self, job: Job, duration: Duration) { - if let Some(handler) = &self.on_job_complete { - let event = JobHookEvent { - job, - timestamp: Utc::now(), - duration: Some(duration), - error: None, - }; - handler(event); - } - } - - /// Fire the job failure event if a handler is registered. - pub(crate) fn fire_job_fail(&self, job: Job, error: String) { - if let Some(handler) = &self.on_job_fail { - let event = JobHookEvent { - job, - timestamp: Utc::now(), - duration: None, - error: Some(error), - }; - handler(event); - } - } - - /// Fire the job timeout event if a handler is registered. - pub(crate) fn fire_job_timeout(&self, job: Job, duration: Duration) { - if let Some(handler) = &self.on_job_timeout { - let event = JobHookEvent { - job, - timestamp: Utc::now(), - duration: Some(duration), - error: Some("Job timed out".to_string()), - }; - handler(event); - } - } - - /// Fire the job retry event if a handler is registered. - pub(crate) fn fire_job_retry(&self, job: Job, error: String) { - if let Some(handler) = &self.on_job_retry { - let event = JobHookEvent { - job, - timestamp: Utc::now(), - duration: None, - error: Some(error), - }; - handler(event); - } - } -} - -/// Configuration for worker autoscaling behavior. -/// -/// A [`WorkerPool`] does not autoscale until it is given a configuration with -/// [`WorkerPool::with_autoscaling`]. [`AutoscaleConfig::default`] (and the presets) are -/// enabled, so `with_autoscaling(AutoscaleConfig::default())` turns autoscaling on; see -/// [`WorkerPool::with_autoscaling`] for which workers it starts and retires. -#[derive(Debug, Clone)] -pub struct AutoscaleConfig { - /// Whether autoscaling is enabled - pub enabled: bool, - /// Minimum number of workers to maintain - pub min_workers: usize, - /// Maximum number of workers to allow - pub max_workers: usize, - /// Queue depth per worker threshold to trigger scale-up - pub scale_up_threshold: usize, - /// Queue depth per worker threshold to trigger scale-down - pub scale_down_threshold: usize, - /// Minimum time between scaling decisions - pub cooldown_period: Duration, - /// Number of workers to add/remove during scaling events - pub scale_step: usize, - /// Time window for queue depth averaging - pub evaluation_window: Duration, -} - -impl Default for AutoscaleConfig { - fn default() -> Self { - Self { - enabled: true, - min_workers: 1, - max_workers: 10, - scale_up_threshold: 5, - scale_down_threshold: 2, - cooldown_period: Duration::from_secs(60), - scale_step: 1, - evaluation_window: Duration::from_secs(30), - } - } -} - -impl AutoscaleConfig { - /// Create a new autoscale configuration with default values - pub fn new() -> Self { - Self::default() - } - - /// Enable or disable autoscaling - pub fn with_enabled(mut self, enabled: bool) -> Self { - self.enabled = enabled; - self - } - - /// Set the minimum number of workers - pub fn with_min_workers(mut self, min_workers: usize) -> Self { - self.min_workers = min_workers.max(1); // Ensure at least 1 worker - self - } - - /// Set the maximum number of workers - pub fn with_max_workers(mut self, max_workers: usize) -> Self { - self.max_workers = max_workers.max(self.min_workers); - self - } - - /// Set the queue depth threshold for scaling up - pub fn with_scale_up_threshold(mut self, threshold: usize) -> Self { - self.scale_up_threshold = threshold.max(1); - self - } - - /// Set the queue depth threshold for scaling down - pub fn with_scale_down_threshold(mut self, threshold: usize) -> Self { - self.scale_down_threshold = threshold; - self - } - - /// Set the cooldown period between scaling decisions - pub fn with_cooldown_period(mut self, period: Duration) -> Self { - self.cooldown_period = period; - self - } - - /// Set the number of workers to add/remove per scaling event - pub fn with_scale_step(mut self, step: usize) -> Self { - self.scale_step = step.max(1); - self - } - - /// Set the evaluation window for queue depth averaging - pub fn with_evaluation_window(mut self, window: Duration) -> Self { - self.evaluation_window = window; - self - } - - /// Create a conservative autoscaling configuration - pub fn conservative() -> Self { - Self { - enabled: true, - min_workers: 2, - max_workers: 5, - scale_up_threshold: 10, - scale_down_threshold: 1, - cooldown_period: Duration::from_secs(300), // 5 mins - scale_step: 1, - evaluation_window: Duration::from_secs(60), - } - } - - /// Create an aggressive autoscaling configuration - pub fn aggressive() -> Self { - Self { - enabled: true, - min_workers: 1, - max_workers: 20, - scale_up_threshold: 3, - scale_down_threshold: 1, - cooldown_period: Duration::from_secs(30), - scale_step: 2, - evaluation_window: Duration::from_secs(15), - } - } - - /// Disable autoscaling - pub fn disabled() -> Self { - Self { - enabled: false, - ..Self::default() - } - } -} - -/// Metrics for autoscaling decisions -#[derive(Debug, Clone, Default)] -pub struct AutoscaleMetrics { - /// Current number of active workers: those of the autoscaled queue when - /// autoscaling is enabled, otherwise all of the pool's workers - pub active_workers: usize, - /// Average queue depth over evaluation window - pub avg_queue_depth: f64, - /// Current queue depth - pub current_queue_depth: u64, - /// Jobs processed per second (recent average) - pub jobs_per_second: f64, - /// Average worker utilization (0.0 to 1.0) - pub worker_utilization: f64, - /// Time since last scaling action - pub time_since_last_scale: Duration, - /// Timestamp of last scaling decision - pub last_scale_time: Option>, -} - -/// Scaling decision enum -#[derive(Debug, Clone, Copy)] -enum ScalingDecision { - ScaleUp, - ScaleDown, -} - -/// Type alias for queue depth history storage -type QueueDepthHistory = Arc, u64)>>>; - -/// What a [`WorkerPool`] supervisor needs to apply autoscaling decisions. -struct Scaling { - /// Cloned for every worker started by a scale-up. Only workers of its queue are - /// started or retired. - template: Worker, - /// Desired number of workers on the template's queue, published by the - /// autoscaling task - desired: watch::Receiver, - /// Workers on the template's queue when the pool started - initial: usize, -} - -/// Wait for the next value on `rx`. Returns `None` once the sender is gone, and never -/// completes when there is no receiver. -async fn wait_for_change(rx: &mut Option>) -> Option { - match rx { - Some(rx) => match rx.changed().await { - Ok(()) => Some(*rx.borrow_and_update()), - Err(_) => None, - }, - None => std::future::pending().await, - } -} - /// Statistics for batch job processing by a worker. #[derive(Debug, Clone, Default)] pub struct BatchProcessingStats { @@ -3404,1202 +3078,82 @@ 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`]. -/// -/// It also clears expired job results every 5 minutes by calling -/// [`DatabaseQueue::cleanup_expired_results`] ([`WorkerPool::with_result_cleanup`], -/// disable it with [`WorkerPool::without_result_cleanup`]). -/// -/// Optionally, the pool also enforces the retention of encrypted jobs by calling -/// [`DatabaseQueue::purge_expired_encrypted_jobs`] periodically -/// ([`WorkerPool::with_encrypted_job_purge`]), archives finished jobs -/// ([`WorkerPool::with_archival`]) and, with the `encryption` feature, rotates -/// encryption keys as they fall due (`WorkerPool::with_key_rotation`). -/// -/// These maintenance tasks run each pass in its own task, so workers never wait for -/// them and shutting the pool down never cancels a pass part-way through its database -/// transaction. They stop when the pool shuts down. -pub struct WorkerPool { - workers: 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, - /// How often encrypted jobs whose retention ended are purged (`None`: never) - encrypted_job_purge_interval: Option, - /// Automatic archival and purge of archived jobs (`None`: off) - archival: Option, - /// How often expired job results are cleared (`None`: never) - result_cleanup_interval: Option, - /// Automatic rotation of encryption keys (`None`: off) - #[cfg(feature = "encryption")] - key_rotation: Option, - stats_collector: Option>, - /// Worker template for creating new workers during autoscaling - worker_template: Option>, - /// Autoscaling configuration - autoscale_config: AutoscaleConfig, - /// Autoscaling metrics and state - autoscale_metrics: Arc>, - /// Queue depth history for averaging - queue_depth_history: QueueDepthHistory, - /// Autoscaling task handle - autoscale_task: Option>, -} - -impl WorkerPool -where - JobQueue: DatabaseQueue + Send + Sync, -{ - /// Create an empty pool. Autoscaling is off; enable it with - /// [`with_autoscaling`](Self::with_autoscaling). The stale job reaper and the - /// expired result cleanup are on. - pub fn new() -> Self { - Self { - workers: Vec::new(), - shutdown_signal: None, - supervisor_done: None, - reaper_interval: Some(DEFAULT_STALE_JOB_REAPER_INTERVAL), - reaper_older_than: None, - encrypted_job_purge_interval: None, - archival: None, - result_cleanup_interval: Some(DEFAULT_RESULT_CLEANUP_INTERVAL), - #[cfg(feature = "encryption")] - key_rotation: None, - stats_collector: None, - worker_template: None, - autoscale_config: AutoscaleConfig::disabled(), - autoscale_metrics: Arc::new(std::sync::RwLock::new(AutoscaleMetrics::default())), - queue_depth_history: Arc::new(std::sync::RwLock::new(Vec::new())), - autoscale_task: None, - } - } - - /// Build a pool from a [`WorkerConfig`](crate::config::WorkerConfig). - /// - /// Adds `pool_size` copies of `worker` (at least one), uses it as the autoscaling - /// template, configures autoscaling from `autoscaling_enabled`, `min_workers` - /// and `max_workers`, and the expired result cleanup from `result_cleanup_enabled` - /// and `result_cleanup_interval`. Apply the per-worker settings to `worker` first - /// with [`Worker::with_config`] or [`Worker::with_hammerwork_config`]. - pub fn from_config(worker: Worker, config: &crate::config::WorkerConfig) -> Self { - let mut pool = Self::new() - .with_autoscaling(config.autoscale_config()) - .with_worker_template(worker.clone()); - pool.result_cleanup_interval = config - .result_cleanup_enabled - .then_some(config.result_cleanup_interval); - for _ in 1..config.pool_size { - pool.add_worker(worker.clone()); - } - pool.add_worker(worker); - pool - } +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; - /// Build a pool from a [`HammerworkConfig`](crate::config::HammerworkConfig). - /// - /// Like [`WorkerPool::from_config`] with `config.worker` (including the expired - /// result cleanup every `worker.result_cleanup_interval`, on by default), and also - /// schedules the encrypted job retention purge every - /// `encryption.purge_interval_secs`, when set - /// ([`WorkerPool::with_encrypted_job_purge`]), automatic archival every - /// `archive.check_interval` when `archive.enabled` ([`WorkerPool::with_archival`] - /// with [`ArchiveConfig::archival_policy`](crate::config::ArchiveConfig::archival_policy) - /// and [`ArchiveConfig::archival_config`](crate::config::ArchiveConfig::archival_config)), - /// and key rotation every `encryption.key_rotation.check_interval_secs` when - /// `encryption.key_rotation.enabled` (see `WorkerPool::with_key_rotation`; the - /// `KeyManager` is created on the worker's database, with - /// [`KeyRotationConfig::key_manager_config`](crate::config::KeyRotationConfig::key_manager_config), - /// when the pool starts, and [`WorkerPool::start`] fails if its master key cannot be - /// loaded). Validates the `encryption`, `worker` and `archive` sections; enabling - /// key rotation without the `encryption` feature is an error. - pub fn from_hammerwork_config( - worker: Worker, - config: &crate::config::HammerworkConfig, - ) -> Result { - config.encryption.validate()?; - config.worker.validate()?; - config.archive.validate()?; - let rotation = &config.encryption.key_rotation; - #[cfg(feature = "encryption")] - let key_rotation = if rotation.enabled { - Some(PoolKeyRotation { - interval: rotation.check_interval(), - start: key_rotation_from_config(&worker.queue.pool, rotation.key_manager_config())?, - }) - } else { - None + #[test] + fn test_error_handling() { + let error = HammerworkError::Worker { + message: "Test error".to_string(), }; - #[cfg(not(feature = "encryption"))] - if rotation.enabled { - return Err(HammerworkError::Config( - "encryption.key_rotation.enabled is set but hammerwork was built without the \ - `encryption` feature" - .to_string(), - )); - } - let mut pool = Self::from_config(worker, &config.worker); - #[cfg(feature = "encryption")] - { - pool.key_rotation = key_rotation; - } - pool.encrypted_job_purge_interval = config.encryption.purge_interval(); - if config.archive.enabled { - pool = pool.with_archival( - config.archive.archival_policy(), - config.archive.archival_config(), - config.archive.check_interval, - ); - } - Ok(pool) - } - - pub fn with_stats_collector(mut self, stats_collector: Arc) -> Self { - self.stats_collector = Some(stats_collector); - self - } - /// Configure autoscaling for the worker pool. - /// - /// Autoscaling is off unless enabled here (or by - /// [`from_config`](Self::from_config) with `autoscaling_enabled`). It scales one - /// queue: that of the [worker template](Self::with_worker_template), or of the first - /// worker added when no template is set. It measures that queue's depth, starts - /// clones of the template while it is deep and retires workers of that queue (never - /// below `min_workers`) once it drains. Workers of other queues are never started - /// or retired. A retired worker stops like on shutdown: it finishes its in-flight - /// job within its [shutdown grace period](Worker::with_shutdown_grace_period). - pub fn with_autoscaling(mut self, config: AutoscaleConfig) -> Self { - self.autoscale_config = config; - self + assert_eq!(error.to_string(), "Worker error: Test error"); } - /// Disable autoscaling for the worker pool - pub fn without_autoscaling(mut self) -> Self { - self.autoscale_config = AutoscaleConfig::disabled(); - self - } + #[test] + fn test_job_timeout_detection_logic() { + use crate::job::{Job, JobStatus}; + use serde_json::json; + use std::time::Duration; - /// 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). Workers take their lease when they claim a job, so a job whose worker is - /// alive is never reclaimed, whatever this pool's settings or those of other pools. - /// `older_than` only applies to running jobs without a lease of their own (claimed - /// by an older Hammerwork version); 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, with different settings, 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 - } + // Test job timeout detection scenarios + let mut job = Job::new("timeout_test".to_string(), json!({"data": "test"})) + .with_timeout(Duration::from_millis(100)); - /// 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 - } + // Job not started - should not timeout + assert!(!job.should_timeout()); - /// Purge encrypted jobs whose retention period ended every `interval`. - /// - /// The pool calls [`DatabaseQueue::purge_expired_encrypted_jobs`], which deletes - /// finished encrypted jobs (and archived ones) past their `retention_delete_at`; it - /// needs no encryption key. Off by default: without it, run - /// `cargo hammerwork maintenance purge-encrypted` on a schedule. Running purges in - /// several pools or processes at once is safe. - /// - /// The first purge runs when the pool starts. Each purge runs in its own task, so - /// shutting the pool down never cancels one part-way through its transaction. - pub fn with_encrypted_job_purge(mut self, interval: Duration) -> Self { - self.encrypted_job_purge_interval = Some(interval); - self - } + // Job started recently - should not timeout + job.started_at = Some(chrono::Utc::now() - chrono::Duration::milliseconds(50)); + job.status = JobStatus::Running; + assert!(!job.should_timeout()); - /// Disable the encrypted job retention purge (the default). - pub fn without_encrypted_job_purge(mut self) -> Self { - self.encrypted_job_purge_interval = None; - self - } + // Job started long ago - should timeout + job.started_at = Some(chrono::Utc::now() - chrono::Duration::milliseconds(200)); + assert!(job.should_timeout()); - /// Archive finished jobs, and purge old archived jobs, every `interval`. - /// - /// Each pass runs [`JobArchiver::run_scheduled_pass`](crate::archive::JobArchiver::run_scheduled_pass) - /// with `policy` as the policy for every queue and `config` for compression: it - /// moves completed, failed, dead and timed out jobs older than the policy's - /// thresholds to `hammerwork_jobs_archive` (reason `Automatic`, archived by - /// `"worker_pool"`), then deletes archived jobs older than `purge_archived_after`, - /// when set. Results are logged. Off by default; a disabled `policy` does nothing. - /// - /// The first pass runs when the pool starts. Passes run in their own task, so - /// workers are never blocked by them. On shutdown no new pass starts, and a running - /// pass stops before its next batch; a batch that has started commits or rolls back - /// as a whole. Running archival in several pools or processes at once is safe: rows - /// are claimed with `FOR UPDATE SKIP LOCKED`, so each job is archived once. - pub fn with_archival( - mut self, - policy: crate::archive::ArchivalPolicy, - config: crate::archive::ArchivalConfig, - interval: Duration, - ) -> Self { - self.archival = Some(PoolArchival { - policy, - config, - interval, - }); - self + // Job without timeout - should never timeout + let mut job_no_timeout = Job::new("no_timeout".to_string(), json!({"data": "test"})); + job_no_timeout.started_at = Some(chrono::Utc::now() - chrono::Duration::hours(1)); + assert!(!job_no_timeout.should_timeout()); } - /// Disable automatic archival (the default). - pub fn without_archival(mut self) -> Self { - self.archival = None; - self - } + #[tokio::test] + async fn test_timeout_statistics_integration() { + use crate::stats::{InMemoryStatsCollector, JobEvent, JobEventType}; + use std::sync::Arc; - /// Clear expired job results every `interval`. - /// - /// The pool calls [`DatabaseQueue::cleanup_expired_results`], which removes the - /// stored results (`result_data`) of jobs whose result TTL has passed. Expired - /// results are never returned by - /// [`DatabaseQueue::get_job_result`], so this only frees the space they take (and - /// stops [`DatabaseQueue::get_job`] from still showing them in `Job::result_data`). - /// On by default every 5 minutes ([`DEFAULT_RESULT_CLEANUP_INTERVAL`]); a pool - /// built from configuration uses `worker.result_cleanup_enabled` and - /// `worker.result_cleanup_interval`. Running it in several pools or processes at - /// once is safe. - /// - /// The first cleanup runs when the pool starts. Each cleanup runs in its own task, - /// so workers never wait for it, and shutting the pool down stops the schedule - /// without cancelling a cleanup part-way. Each cleanup that clears results logs how - /// many at `info` level (failures at `warn`). - pub fn with_result_cleanup(mut self, interval: Duration) -> Self { - self.result_cleanup_interval = Some(interval); - self - } + let stats_collector = Arc::new(InMemoryStatsCollector::new_default()); - /// Disable the expired result cleanup (for example when it runs elsewhere). - pub fn without_result_cleanup(mut self) -> Self { - self.result_cleanup_interval = None; - self - } + // Simulate timeout event recording + let timeout_event = JobEvent { + job_id: uuid::Uuid::new_v4(), + queue_name: "timeout_queue".to_string(), + event_type: JobEventType::TimedOut, + priority: crate::priority::JobPriority::Normal, + processing_time_ms: Some(5000), // 5 seconds before timeout + error_message: Some("Job timed out after 5s".to_string()), + timestamp: chrono::Utc::now(), + }; - /// Rotate the encryption keys of `key_manager` as they fall due, checking every - /// `check_interval`. - /// - /// Each pass runs [`KeyManager::perform_automatic_rotation`](crate::encryption::KeyManager::perform_automatic_rotation), - /// which rotates the keys whose `next_rotation_at` has passed, and logs the rotated - /// keys (`info`) or the failure (`error`). The key manager must have automatic - /// rotation enabled ([`KeyManagerConfig::with_auto_rotation_enabled`](crate::encryption::KeyManagerConfig::with_auto_rotation_enabled)); - /// otherwise the pool logs a warning and does not rotate. Off by default; a pool - /// built with [`WorkerPool::from_hammerwork_config`] turns it on from - /// `[encryption.key_rotation]`. - /// - /// The first pass runs when the pool starts. Passes run in their own task, so - /// workers never wait for them, and shutting the pool down stops the schedule - /// without interrupting a rotation part-way. Several pools or processes can rotate - /// at once: each due key gets exactly one new version (see - /// [`KeyManager::perform_automatic_rotation`](crate::encryption::KeyManager::perform_automatic_rotation)). - /// - /// ```rust,no_run - /// # #[cfg(all(feature = "encryption", feature = "postgres"))] - /// # { - /// use hammerwork::encryption::{KeyManager, KeyManagerConfig}; - /// use hammerwork::{JobQueue, Worker, WorkerPool, worker::JobHandler}; - /// use std::{sync::Arc, time::Duration}; - /// - /// # async fn example(pool: sqlx::PgPool, handler: JobHandler) -> Result<(), Box> { - /// let key_manager = KeyManager::new( - /// KeyManagerConfig::new() - /// .with_master_key_env("HAMMERWORK_MASTER_KEY") - /// .with_auto_rotation_enabled(true), - /// pool.clone(), - /// ) - /// .await?; - /// let queue = Arc::new(JobQueue::new(pool)); - /// let mut worker_pool = WorkerPool::new() - /// .with_key_rotation(key_manager, Duration::from_secs(3600)); - /// worker_pool.add_worker(Worker::new(queue, "default".to_string(), handler)); - /// worker_pool.start().await?; - /// # Ok(()) - /// # } - /// # } - /// ``` - #[cfg(feature = "encryption")] - pub fn with_key_rotation( - mut self, - key_manager: crate::encryption::KeyManager, - check_interval: Duration, - ) -> Self { - let pass = rotation_pass(key_manager); - self.key_rotation = Some(PoolKeyRotation { - interval: check_interval, - start: Arc::new(move || { - let pass = pass.clone(); - Box::pin(async move { Ok(pass) }) - }), - }); - self - } + stats_collector.record_event(timeout_event).await.unwrap(); - /// Disable automatic key rotation (the default). - #[cfg(feature = "encryption")] - pub fn without_key_rotation(mut self) -> Self { - self.key_rotation = None; - self - } + // Verify timeout event is tracked in statistics + let stats = stats_collector + .get_queue_statistics("timeout_queue", Duration::from_secs(60)) + .await + .unwrap(); - /// 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 { - self.worker_template = Some(worker); - self + assert_eq!(stats.total_processed, 1); + assert_eq!(stats.timed_out, 1); + assert_eq!(stats.error_rate, 1.0); // 1 timeout / 1 total = 100% error rate } - pub fn add_worker(&mut self, mut worker: Worker) { - // Apply the pool's stats collector to the worker if available - if let Some(stats_collector) = &self.stats_collector { - worker.stats_collector = Some(Arc::clone(stats_collector)); - } - - // If no worker template is set and autoscaling is enabled, use the first worker - // as template (`start` also falls back to the first worker). - if self.worker_template.is_none() - && self.autoscale_config.enabled - && self.workers.is_empty() - { - self.worker_template = Some(worker.clone()); - } - - 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()); - - // Created first, so a key manager that cannot start fails the pool before any - // worker runs. - #[cfg(feature = "encryption")] - let key_rotation = match &self.key_rotation { - Some(rotation) => (rotation.start)() - .await? - .map(|pass| (pass, rotation.interval)), - None => None, - }; - - 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 workers = std::mem::take(&mut self.workers); - #[cfg_attr(not(feature = "encryption"), allow(unused_mut))] - let mut maintenance: Vec> = [ - self.start_stale_job_reaper(&workers, signal_rx.clone()), - self.start_encrypted_job_purge(&workers, signal_rx.clone()), - self.start_archival(&workers, signal_rx.clone()), - self.start_result_cleanup(&workers, signal_rx.clone()), - ] - .into_iter() - .flatten() - .collect(); - #[cfg(feature = "encryption")] - if let Some((pass, interval)) = key_rotation { - info!("Rotating due encryption keys every {:?}", interval); - maintenance.push(spawn_periodic(interval, signal_rx.clone(), move || pass())); - } - - // Start autoscaling task if enabled. It publishes the desired number of workers - // on the template's queue, which the supervisor applies by starting workers from - // the template or retiring workers of that queue. - let scaling = if self.autoscale_config.enabled { - self.start_autoscaling_task(&workers) - } else { - None - }; - if let Ok(mut metrics) = self.autoscale_metrics.write() { - metrics.active_workers = match &scaling { - Some(scaling) => scaling.initial, - None => workers.len(), - }; - } - - let supervisor = tokio::spawn(Self::supervise( - workers, - signal_rx, - done_tx, - maintenance, - scaling, - )); - - // 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, - maintenance: Vec>, - scaling: Option>, - ) -> Result<()> { - let mut 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(); - // Workers stopped by a scale-down: not restarted, and their slot is reused by - // the next scale-up once their task has finished. - let mut retired: Vec = vec![false; senders.len()]; - let mut finished: Vec = vec![false; senders.len()]; - let (template, mut desired_rx) = match scaling { - Some(scaling) => (Some(scaling.template), Some(scaling.desired)), - None => (None, None), - }; - - 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(()); - } - } - changed = wait_for_change(&mut desired_rx), if !shutting_down => { - let (Some(desired), Some(template)) = (changed, template.as_ref()) else { - // The autoscaler stopped: keep the current workers. - desired_rx = None; - continue; - }; - // Only the template's queue is scaled: workers of other queues are - // never retired, and new workers are clones of the template. - let active: Vec = (0..senders.len()) - .filter(|i| !retired[*i] && templates[*i].queue_name == template.queue_name) - .collect(); - if desired > active.len() { - for _ in active.len()..desired { - let worker = template.clone(); - let reusable = (0..senders.len()).find(|i| retired[*i] && finished[*i]); - let index = reusable.unwrap_or(senders.len()); - let tx = Self::spawn_worker(&mut set, index, worker.clone(), None); - if index == senders.len() { - templates.push(worker); - senders.push(tx); - retired.push(false); - finished.push(false); - } else { - templates[index] = worker; - senders[index] = tx; - retired[index] = false; - finished[index] = false; - } - } - info!( - "Autoscaling: started workers for queue {}, now {}", - template.queue_name, desired - ); - } else { - for index in active.iter().rev().take(active.len() - desired) { - retired[*index] = true; - let _ = senders[*index].try_send(()); - } - if desired < active.len() { - info!( - "Autoscaling: retiring workers of queue {}, now {}", - template.queue_name, desired - ); - } - } - } - joined = set.join_next() => { - let Some(joined) = joined else { break }; - let index = match joined { - Ok((index, Ok(Ok(())))) => { - if shutting_down { - continue; - } - if retired[index] { - finished[index] = true; - 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 retired[index] { - finished[index] = true; - } else 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), - ); - } - } - } - } - - // Stops the maintenance loops; a pass already running finishes in its own task - for task in maintenance { - task.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], - signal_rx: watch::Receiver, - ) -> Option> { - let interval = self.reaper_interval?; - 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) - }); - - spawn_queue_task(workers, interval, signal_rx, move |queue| async move { - 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), - } - }) - } - - /// Spawn the periodic encrypted job retention purge, if enabled. - fn start_encrypted_job_purge( - &self, - workers: &[Worker], - signal_rx: watch::Receiver, - ) -> Option> { - let interval = self.encrypted_job_purge_interval?; - spawn_queue_task(workers, interval, signal_rx, |queue| async move { - match queue.purge_expired_encrypted_jobs().await { - Ok(purge) if purge.total() > 0 => info!( - "Encrypted job purge deleted {} jobs and {} archived jobs", - purge.jobs, purge.archived_jobs - ), - Ok(_) => {} - Err(e) => warn!("Encrypted job purge failed: {}", e), - } - }) - } - - /// Spawn the periodic archival pass, if enabled. - fn start_archival( - &self, - workers: &[Worker], - signal_rx: watch::Receiver, - ) -> Option> { - let archival = self.archival.clone()?; - let queue = Arc::clone(&workers.first()?.queue); - if !archival.policy.enabled { - info!("Automatic archival is configured with a disabled policy; not starting it"); - return None; - } - let archiver = Arc::new( - crate::archive::JobArchiver::new(queue.pool.clone()) - .with_default_policy(archival.policy) - .with_config(archival.config), - ); - let stop_rx = signal_rx.clone(); - Some(spawn_periodic(archival.interval, signal_rx, move || { - let (queue, archiver, stop_rx) = - (Arc::clone(&queue), Arc::clone(&archiver), stop_rx.clone()); - async move { - let pass = archiver - .run_scheduled_pass(queue.as_ref(), Some("worker_pool"), || *stop_rx.borrow()) - .await; - match pass { - Ok(pass) if pass.jobs_archived > 0 || pass.jobs_purged > 0 => info!( - "Archival archived {} jobs and purged {} archived jobs{}", - pass.jobs_archived, - pass.jobs_purged, - if pass.stopped_early { - " (stopped early for shutdown)" - } else { - "" - } - ), - Ok(_) => debug!("Archival found nothing to archive or purge"), - Err(e) => warn!("Archival failed: {}", e), - } - } - })) - } - - /// Spawn the periodic expired result cleanup, if enabled. - fn start_result_cleanup( - &self, - workers: &[Worker], - signal_rx: watch::Receiver, - ) -> Option> { - let interval = self.result_cleanup_interval?; - if !workers.is_empty() { - debug!("Clearing expired job results every {:?}", interval); - } - spawn_queue_task(workers, interval, signal_rx, |queue| async move { - match queue.cleanup_expired_results().await { - Ok(cleared) if cleared > 0 => { - info!("Result cleanup cleared {} expired job results", cleared) - } - Ok(_) => debug!("Result cleanup found no expired job results"), - Err(e) => warn!("Result cleanup failed: {}", e), - } - }) - } - - /// Start the autoscaling background task. - /// - /// Returns the worker template and a channel carrying the desired worker count, - /// which the supervisor applies, or `None` when there is no worker template. - fn start_autoscaling_task(&mut self, workers: &[Worker]) -> Option> { - // Without an explicit template, scale the first worker's queue. - let Some(worker_template) = self.worker_template.as_ref().or(workers.first()) else { - warn!("Cannot start autoscaling: no worker template available"); - return None; - }; - let mut template = worker_template.clone(); - let initial_workers = workers - .iter() - .filter(|worker| worker.queue_name == template.queue_name) - .count(); - if let Some(stats_collector) = &self.stats_collector { - template.stats_collector = Some(Arc::clone(stats_collector)); - } - let queue = Arc::clone(&template.queue); - let queue_name = template.queue_name.clone(); - let config = self.autoscale_config.clone(); - let metrics = Arc::clone(&self.autoscale_metrics); - let history = Arc::clone(&self.queue_depth_history); - let (desired_tx, desired_rx) = watch::channel(initial_workers); - - let task = tokio::spawn(async move { - Self::autoscaling_loop(queue, queue_name, config, metrics, history, desired_tx).await; - }); - - if let Some(previous) = self.autoscale_task.replace(task) { - previous.abort(); - } - info!( - "Autoscaling task started for queue: {}", - template.queue_name - ); - Some(Scaling { - template, - desired: desired_rx, - initial: initial_workers, - }) - } - - /// Main autoscaling evaluation loop - async fn autoscaling_loop( - queue: Arc>, - queue_name: String, - config: AutoscaleConfig, - metrics: Arc>, - history: QueueDepthHistory, - desired: watch::Sender, - ) { - // `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; - - match Self::evaluate_scaling_decision(&queue, &queue_name, &config, &metrics, &history) - .await - { - Ok(Some(count)) => { - // An error means the supervisor stopped: nothing left to scale. - if desired.send(count).is_err() { - return; - } - } - Ok(None) => {} - Err(e) => warn!("Autoscaling evaluation error: {}", e), - } - } - } - - /// Evaluate whether scaling up or down is needed. - /// - /// Returns the new worker count when the pool should scale. - async fn evaluate_scaling_decision( - queue: &Arc>, - queue_name: &str, - config: &AutoscaleConfig, - metrics: &Arc>, - history: &QueueDepthHistory, - ) -> Result> { - // Get current queue depth - let current_depth = queue.get_queue_depth(queue_name).await?; - Ok(apply_queue_depth( - current_depth, - Utc::now(), - config, - metrics, - history, - )) - } - - /// Get current autoscaling metrics - pub fn get_autoscale_metrics(&self) -> AutoscaleMetrics { - self.autoscale_metrics - .read() - .map(|metrics| metrics.clone()) - .unwrap_or_default() - } - - /// 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"); - - // Stop autoscaling task - if let Some(task) = &self.autoscale_task { - task.abort(); - info!("Autoscaling task stopped"); - } - - 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(()) - } - - /// Get the statistics collector for the worker pool - pub fn stats_collector(&self) -> Option> { - self.stats_collector.clone() - } -} - -impl Default for WorkerPool -where - JobQueue: DatabaseQueue + Send + Sync, -{ - fn default() -> Self { - Self::new() - } -} - -/// Record a queue depth sample and decide whether to scale. -/// -/// Returns the new worker count (within `min_workers..=max_workers`) when the -/// average depth per worker crossed a threshold outside the cooldown period. -fn apply_queue_depth( - current_depth: u64, - now: DateTime, - config: &AutoscaleConfig, - metrics: &Arc>, - history: &QueueDepthHistory, -) -> Option { - // Update queue depth history, dropping entries outside the evaluation window - let avg_depth = match history.write() { - Ok(mut hist) => { - hist.push((now, current_depth)); - let cutoff = now - - chrono::Duration::from_std(config.evaluation_window) - .unwrap_or(chrono::Duration::seconds(30)); - hist.retain(|(timestamp, _)| *timestamp > cutoff); - if hist.is_empty() { - current_depth as f64 - } else { - hist.iter().map(|(_, depth)| *depth as f64).sum::() / hist.len() as f64 - } - } - Err(_) => current_depth as f64, - }; - - let mut m = metrics.write().ok()?; - m.current_queue_depth = current_depth; - m.avg_queue_depth = avg_depth; - - // Check cooldown period - let time_since_last = m - .last_scale_time - .map(|t| now - t) - .and_then(|d| d.to_std().ok()) - .unwrap_or(config.cooldown_period); - m.time_since_last_scale = time_since_last; - if time_since_last < config.cooldown_period { - return None; - } - - // Calculate queue depth per worker - let depth_per_worker = if m.active_workers > 0 { - avg_depth / m.active_workers as f64 - } else { - avg_depth - }; - - let decision = if depth_per_worker > config.scale_up_threshold as f64 - && m.active_workers < config.max_workers - { - ScalingDecision::ScaleUp - } else if depth_per_worker < config.scale_down_threshold as f64 - && m.active_workers > config.min_workers - { - ScalingDecision::ScaleDown - } else { - return None; - }; - - let new_count = match decision { - ScalingDecision::ScaleUp => (m.active_workers + config.scale_step).min(config.max_workers), - ScalingDecision::ScaleDown => { - (m.active_workers.saturating_sub(config.scale_step)).max(config.min_workers) - } - }; - info!( - "Autoscaling: {:?} from {} to {} workers (avg queue depth: {:.1})", - decision, m.active_workers, new_count, m.avg_queue_depth - ); - m.active_workers = new_count; - m.last_scale_time = Some(now); - Some(new_count) -} - -/// Automatic archival settings of a [`WorkerPool`] ([`WorkerPool::with_archival`]). -#[derive(Debug, Clone)] -struct PoolArchival { - policy: crate::archive::ArchivalPolicy, - config: crate::archive::ArchivalConfig, - interval: Duration, -} - -/// Default interval of the expired result cleanup of a [`WorkerPool`] -/// ([`WorkerPool::with_result_cleanup`]): five minutes. -pub const DEFAULT_RESULT_CLEANUP_INTERVAL: Duration = - crate::config::DEFAULT_RESULT_CLEANUP_INTERVAL; - -/// One key rotation pass, whatever the key manager's database. -#[cfg(feature = "encryption")] -type RotationPass = Arc Pin + Send>> + Send + Sync>; - -/// Creates the key manager when the pool starts and returns its rotation pass (`None` -/// when its automatic rotation is disabled). -#[cfg(feature = "encryption")] -type RotationStarter = Arc< - dyn Fn() -> Pin< - Box< - dyn Future< - Output = std::result::Result< - Option, - crate::encryption::EncryptionError, - >, - > + Send, - >, - > + Send - + Sync, ->; - -/// Key rotation settings of a [`WorkerPool`] (`WorkerPool::with_key_rotation`). -#[cfg(feature = "encryption")] -#[derive(Clone)] -struct PoolKeyRotation { - interval: Duration, - start: RotationStarter, -} - -/// The rotation pass of `manager`, or `None` (logged) when its automatic rotation is -/// disabled. -#[cfg(feature = "encryption")] -fn rotation_pass( - manager: crate::encryption::KeyManager, -) -> Option { - if !manager.auto_rotation_enabled() { - warn!( - "Key rotation is configured with a KeyManager whose automatic rotation is \ - disabled; not starting it" - ); - return None; - } - Some(Arc::new(move || Box::pin(manager.clone().rotation_pass()))) -} - -/// A starter that creates a `KeyManager` with `config` on `pool`. -#[cfg(feature = "encryption")] -#[allow(dead_code)] // unused without a database backend -fn key_manager_starter( - pool: sqlx::Pool, - config: crate::encryption::KeyManagerConfig, -) -> RotationStarter { - Arc::new(move || { - let (pool, config) = (pool.clone(), config.clone()); - Box::pin(async move { - let manager = crate::encryption::KeyManager::new(config, pool).await?; - Ok(rotation_pass(manager)) - }) - }) -} - -/// The starter for `[encryption.key_rotation]`: a `KeyManager` on the pool's own -/// database, which must be PostgreSQL or MySQL. -#[cfg(feature = "encryption")] -#[allow(unused_variables)] // without a database backend nothing matches -fn key_rotation_from_config( - pool: &sqlx::Pool, - config: crate::encryption::KeyManagerConfig, -) -> Result { - let pool: &dyn std::any::Any = pool; - #[cfg(feature = "postgres")] - if let Some(pool) = pool.downcast_ref::() { - return Ok(key_manager_starter(pool.clone(), config)); - } - #[cfg(feature = "mysql")] - if let Some(pool) = pool.downcast_ref::() { - return Ok(key_manager_starter(pool.clone(), config)); - } - Err(HammerworkError::Config( - "encryption.key_rotation needs a PostgreSQL or MySQL database".to_string(), - )) -} - -/// Spawn a task that calls `run` every `interval` (first right away) until shutdown is -/// signalled on `signal_rx` (or its sender is dropped). -/// -/// Each run is spawned as its own task and awaited, so neither the shutdown signal nor -/// aborting the returned handle cancels a run part-way: database work always reaches -/// commit or rollback instead of leaving a pooled connection inside a transaction. -fn spawn_periodic( - interval: Duration, - mut signal_rx: watch::Receiver, - run: F, -) -> tokio::task::JoinHandle<()> -where - F: Fn() -> Fut + Send + 'static, - Fut: std::future::Future + Send + 'static, -{ - 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() => {} - } - if *signal_rx.borrow() { - break; - } - if let Err(e) = tokio::spawn(run()).await - && e.is_panic() - { - error!("Periodic maintenance task panicked: {}", e); - } - } - }) -} - -/// [`spawn_periodic`] for a maintenance pass on the queue of the pool's first worker -/// (`None` when the pool has no workers). -fn spawn_queue_task( - workers: &[Worker], - interval: Duration, - signal_rx: watch::Receiver, - pass: F, -) -> Option> -where - DB: Database + Send + Sync + 'static, - F: Fn(Arc>) -> Fut + Send + 'static, - Fut: std::future::Future + Send + 'static, -{ - let queue = Arc::clone(&workers.first()?.queue); - Some(spawn_periodic(interval, signal_rx, move || { - pass(Arc::clone(&queue)) - })) -} - -impl Drop for WorkerPool { - fn drop(&mut self) { - // Stop autoscaling task when dropping the pool - if let Some(task) = &self.autoscale_task { - task.abort(); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::time::Duration; - - #[test] - fn test_error_handling() { - let error = HammerworkError::Worker { - message: "Test error".to_string(), - }; - - assert_eq!(error.to_string(), "Worker error: Test error"); - } - - #[test] - fn test_job_timeout_detection_logic() { - use crate::job::{Job, JobStatus}; - use serde_json::json; - use std::time::Duration; - - // Test job timeout detection scenarios - let mut job = Job::new("timeout_test".to_string(), json!({"data": "test"})) - .with_timeout(Duration::from_millis(100)); - - // Job not started - should not timeout - assert!(!job.should_timeout()); - - // Job started recently - should not timeout - job.started_at = Some(chrono::Utc::now() - chrono::Duration::milliseconds(50)); - job.status = JobStatus::Running; - assert!(!job.should_timeout()); - - // Job started long ago - should timeout - job.started_at = Some(chrono::Utc::now() - chrono::Duration::milliseconds(200)); - assert!(job.should_timeout()); - - // Job without timeout - should never timeout - let mut job_no_timeout = Job::new("no_timeout".to_string(), json!({"data": "test"})); - job_no_timeout.started_at = Some(chrono::Utc::now() - chrono::Duration::hours(1)); - assert!(!job_no_timeout.should_timeout()); - } - - #[tokio::test] - async fn test_timeout_statistics_integration() { - use crate::stats::{InMemoryStatsCollector, JobEvent, JobEventType}; - use std::sync::Arc; - - let stats_collector = Arc::new(InMemoryStatsCollector::new_default()); - - // Simulate timeout event recording - let timeout_event = JobEvent { - job_id: uuid::Uuid::new_v4(), - queue_name: "timeout_queue".to_string(), - event_type: JobEventType::TimedOut, - priority: crate::priority::JobPriority::Normal, - processing_time_ms: Some(5000), // 5 seconds before timeout - error_message: Some("Job timed out after 5s".to_string()), - timestamp: chrono::Utc::now(), - }; - - stats_collector.record_event(timeout_event).await.unwrap(); - - // Verify timeout event is tracked in statistics - let stats = stats_collector - .get_queue_statistics("timeout_queue", Duration::from_secs(60)) - .await - .unwrap(); - - assert_eq!(stats.total_processed, 1); - assert_eq!(stats.timed_out, 1); - assert_eq!(stats.error_rate, 1.0); // 1 timeout / 1 total = 100% error rate - } - - #[test] - fn test_worker_rate_limit_configuration() { - use crate::rate_limit::RateLimit; + #[test] + fn test_worker_rate_limit_configuration() { + use crate::rate_limit::RateLimit; // Test rate limit configuration let rate_limit = RateLimit::per_second(10).with_burst_limit(20); @@ -4745,327 +3299,6 @@ mod tests { assert_eq!(new_config.max_concurrent, default_config.max_concurrent); } - #[test] - fn test_autoscale_config_defaults() { - let config = AutoscaleConfig::default(); - - assert!(config.enabled); - assert_eq!(config.min_workers, 1); - assert_eq!(config.max_workers, 10); - assert_eq!(config.scale_up_threshold, 5); - assert_eq!(config.scale_down_threshold, 2); - assert_eq!(config.cooldown_period, Duration::from_secs(60)); - assert_eq!(config.scale_step, 1); - assert_eq!(config.evaluation_window, Duration::from_secs(30)); - } - - #[test] - fn test_autoscale_config_builder() { - let config = AutoscaleConfig::new() - .with_min_workers(2) - .with_max_workers(20) - .with_scale_up_threshold(8) - .with_scale_down_threshold(1) - .with_cooldown_period(Duration::from_secs(120)) - .with_scale_step(2) - .with_evaluation_window(Duration::from_secs(45)); - - assert_eq!(config.min_workers, 2); - assert_eq!(config.max_workers, 20); - assert_eq!(config.scale_up_threshold, 8); - assert_eq!(config.scale_down_threshold, 1); - assert_eq!(config.cooldown_period, Duration::from_secs(120)); - assert_eq!(config.scale_step, 2); - assert_eq!(config.evaluation_window, Duration::from_secs(45)); - } - - #[test] - fn test_autoscale_config_presets() { - let conservative = AutoscaleConfig::conservative(); - assert_eq!(conservative.min_workers, 2); - assert_eq!(conservative.max_workers, 5); - assert_eq!(conservative.scale_up_threshold, 10); - assert_eq!(conservative.cooldown_period, Duration::from_secs(300)); - - let aggressive = AutoscaleConfig::aggressive(); - assert_eq!(aggressive.min_workers, 1); - assert_eq!(aggressive.max_workers, 20); - assert_eq!(aggressive.scale_up_threshold, 3); - assert_eq!(aggressive.cooldown_period, Duration::from_secs(30)); - - let disabled = AutoscaleConfig::disabled(); - assert!(!disabled.enabled); - } - - #[test] - fn test_autoscale_config_validation() { - // Test that min_workers is at least 1 - let config = AutoscaleConfig::new().with_min_workers(0); - assert_eq!(config.min_workers, 1); - - // Test that max_workers is at least min_workers - let config = AutoscaleConfig::new() - .with_min_workers(5) - .with_max_workers(3); - assert_eq!(config.max_workers, 5); - - // Test that scale_up_threshold is at least 1 - let config = AutoscaleConfig::new().with_scale_up_threshold(0); - assert_eq!(config.scale_up_threshold, 1); - - // Test that scale_step is at least 1 - let config = AutoscaleConfig::new().with_scale_step(0); - assert_eq!(config.scale_step, 1); - } - - #[test] - fn test_autoscale_metrics_default() { - let metrics = AutoscaleMetrics::default(); - - assert_eq!(metrics.active_workers, 0); - assert_eq!(metrics.avg_queue_depth, 0.0); - assert_eq!(metrics.current_queue_depth, 0); - assert_eq!(metrics.jobs_per_second, 0.0); - assert_eq!(metrics.worker_utilization, 0.0); - assert_eq!(metrics.time_since_last_scale, Duration::from_secs(0)); - assert!(metrics.last_scale_time.is_none()); - } - - #[test] - fn test_job_event_hooks_default() { - let hooks = JobEventHooks::default(); - assert!(hooks.on_job_start.is_none()); - assert!(hooks.on_job_complete.is_none()); - assert!(hooks.on_job_fail.is_none()); - assert!(hooks.on_job_timeout.is_none()); - assert!(hooks.on_job_retry.is_none()); - } - - #[test] - fn test_job_event_hooks_new() { - let hooks = JobEventHooks::new(); - assert!(hooks.on_job_start.is_none()); - assert!(hooks.on_job_complete.is_none()); - assert!(hooks.on_job_fail.is_none()); - assert!(hooks.on_job_timeout.is_none()); - assert!(hooks.on_job_retry.is_none()); - } - - #[test] - fn test_job_event_hooks_builder() { - use std::sync::{Arc, Mutex}; - - let events = Arc::new(Mutex::new(Vec::new())); - - let events_start = Arc::clone(&events); - let events_complete = Arc::clone(&events); - let events_fail = Arc::clone(&events); - let events_timeout = Arc::clone(&events); - let events_retry = Arc::clone(&events); - - let hooks = JobEventHooks::new() - .on_start(move |event: JobHookEvent| { - events_start - .lock() - .unwrap() - .push(format!("start:{}", event.job.id)); - }) - .on_complete(move |event: JobHookEvent| { - events_complete - .lock() - .unwrap() - .push(format!("complete:{}", event.job.id)); - }) - .on_fail(move |event: JobHookEvent| { - events_fail - .lock() - .unwrap() - .push(format!("fail:{}", event.job.id)); - }) - .on_timeout(move |event: JobHookEvent| { - events_timeout - .lock() - .unwrap() - .push(format!("timeout:{}", event.job.id)); - }) - .on_retry(move |event: JobHookEvent| { - events_retry - .lock() - .unwrap() - .push(format!("retry:{}", event.job.id)); - }); - - // Verify all hooks are set - assert!(hooks.on_job_start.is_some()); - assert!(hooks.on_job_complete.is_some()); - assert!(hooks.on_job_fail.is_some()); - assert!(hooks.on_job_timeout.is_some()); - assert!(hooks.on_job_retry.is_some()); - } - - #[test] - fn test_job_hook_event_creation() { - use crate::Job; - use serde_json::json; - use std::time::Duration; - - let job = Job::new("test_queue".to_string(), json!({"test": "data"})) - .with_trace_id("trace-123") - .with_correlation_id("corr-456"); - - let event = JobHookEvent { - job: job.clone(), - timestamp: Utc::now(), - duration: Some(Duration::from_millis(500)), - error: Some("Test error".to_string()), - }; - - assert_eq!(event.job.id, job.id); - assert_eq!(event.job.queue_name, "test_queue"); - assert_eq!(event.job.trace_id, Some("trace-123".to_string())); - assert_eq!(event.job.correlation_id, Some("corr-456".to_string())); - assert_eq!(event.duration, Some(Duration::from_millis(500))); - assert_eq!(event.error, Some("Test error".to_string())); - } - - #[test] - fn test_job_event_hooks_fire_methods() { - use crate::Job; - use serde_json::json; - use std::sync::{Arc, Mutex}; - use std::time::Duration; - - let events = Arc::new(Mutex::new(Vec::new())); - let job = Job::new("test_queue".to_string(), json!({"test": "data"})); - - // Test fire_job_start - { - let events_clone = Arc::clone(&events); - let hooks = JobEventHooks::new().on_start(move |event: JobHookEvent| { - events_clone - .lock() - .unwrap() - .push(format!("start:{}", event.job.queue_name)); - }); - - hooks.fire_job_start(job.clone()); - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 1); - assert_eq!(captured_events[0], "start:test_queue"); - } - - // Clear events for next test - events.lock().unwrap().clear(); - - // Test fire_job_complete - { - let events_clone = Arc::clone(&events); - let hooks = JobEventHooks::new().on_complete(move |event: JobHookEvent| { - events_clone.lock().unwrap().push(format!( - "complete:{}:{}ms", - event.job.queue_name, - event.duration.unwrap_or_default().as_millis() - )); - }); - - hooks.fire_job_complete(job.clone(), Duration::from_millis(150)); - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 1); - assert_eq!(captured_events[0], "complete:test_queue:150ms"); - } - - // Clear events for next test - events.lock().unwrap().clear(); - - // Test fire_job_fail - { - let events_clone = Arc::clone(&events); - let hooks = JobEventHooks::new().on_fail(move |event: JobHookEvent| { - events_clone.lock().unwrap().push(format!( - "fail:{}:{}", - event.job.queue_name, - event.error.unwrap_or_default() - )); - }); - - hooks.fire_job_fail(job.clone(), "Connection timeout".to_string()); - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 1); - assert_eq!(captured_events[0], "fail:test_queue:Connection timeout"); - } - - // Clear events for next test - events.lock().unwrap().clear(); - - // Test fire_job_timeout - { - let events_clone = Arc::clone(&events); - let hooks = JobEventHooks::new().on_timeout(move |event: JobHookEvent| { - events_clone.lock().unwrap().push(format!( - "timeout:{}:{}ms", - event.job.queue_name, - event.duration.unwrap_or_default().as_millis() - )); - }); - - hooks.fire_job_timeout(job.clone(), Duration::from_secs(30)); - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 1); - assert_eq!(captured_events[0], "timeout:test_queue:30000ms"); - } - - // Clear events for next test - events.lock().unwrap().clear(); - - // Test fire_job_retry - { - let events_clone = Arc::clone(&events); - let hooks = JobEventHooks::new().on_retry(move |event: JobHookEvent| { - events_clone.lock().unwrap().push(format!( - "retry:{}:{}", - event.job.queue_name, - event.error.unwrap_or_default() - )); - }); - - hooks.fire_job_retry(job.clone(), "API rate limit exceeded".to_string()); - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 1); - assert_eq!( - captured_events[0], - "retry:test_queue:API rate limit exceeded" - ); - } - } - - #[test] - fn test_job_event_hooks_clone() { - use std::sync::{Arc, Mutex}; - - let events = Arc::new(Mutex::new(Vec::new())); - let events_clone = Arc::clone(&events); - - let hooks = JobEventHooks::new().on_start(move |event: JobHookEvent| { - events_clone - .lock() - .unwrap() - .push(format!("cloned:{}", event.job.id)); - }); - - // Clone the hooks - let hooks_clone = hooks.clone(); - - // Both original and clone should work - let job = crate::Job::new("test".to_string(), serde_json::json!({})); - hooks.fire_job_start(job.clone()); - hooks_clone.fire_job_start(job); - - let captured_events = events.lock().unwrap(); - assert_eq!(captured_events.len(), 2); - 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(); @@ -5125,197 +3358,6 @@ mod tests { assert_eq!(panic_message(payload.as_ref()), "code 42"); } - #[tokio::test] - async fn spawn_periodic_runs_until_shutdown() { - let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let (signal_tx, signal_rx) = watch::channel(false); - let counter = Arc::clone(&runs); - let task = spawn_periodic(Duration::from_millis(10), signal_rx, move || { - let counter = Arc::clone(&counter); - async move { - counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } - }); - tokio::time::sleep(Duration::from_millis(100)).await; - signal_tx.send_replace(true); - tokio::time::timeout(Duration::from_secs(5), task) - .await - .expect("the loop stops on shutdown") - .unwrap(); - let seen = runs.load(std::sync::atomic::Ordering::SeqCst); - assert!(seen >= 2, "ran {seen} times"); - tokio::time::sleep(Duration::from_millis(50)).await; - assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), seen); - } - - /// Shutting down (or aborting the loop, as the pool's supervisor does) while a run is - /// in flight must not cancel the run: it would drop a database transaction mid-way. - #[tokio::test] - async fn spawn_periodic_never_cancels_a_run() { - use std::sync::atomic::{AtomicBool, Ordering}; - - let started = Arc::new(tokio::sync::Notify::new()); - let finished = Arc::new(AtomicBool::new(false)); - let (signal_tx, signal_rx) = watch::channel(false); - let (run_started, run_finished) = (Arc::clone(&started), Arc::clone(&finished)); - let task = spawn_periodic(Duration::from_secs(3600), signal_rx, move || { - let (started, finished) = (Arc::clone(&run_started), Arc::clone(&run_finished)); - async move { - started.notify_one(); - tokio::time::sleep(Duration::from_millis(200)).await; - finished.store(true, Ordering::SeqCst); - } - }); - started.notified().await; - signal_tx.send_replace(true); - task.abort(); - assert!(!finished.load(Ordering::SeqCst)); - tokio::time::sleep(Duration::from_millis(400)).await; - assert!( - finished.load(Ordering::SeqCst), - "the in-flight run completed after the loop was stopped" - ); - } - - #[cfg(any(feature = "postgres", feature = "mysql"))] - #[test] - fn encrypted_job_purge_is_opt_in_and_configurable() { - #[cfg(feature = "postgres")] - type Db = sqlx::Postgres; - #[cfg(all(feature = "mysql", not(feature = "postgres")))] - type Db = sqlx::MySql; - - let pool = WorkerPool::::new(); - assert_eq!(pool.encrypted_job_purge_interval, None); - let pool = pool.with_encrypted_job_purge(Duration::from_secs(30)); - assert_eq!( - pool.encrypted_job_purge_interval, - Some(Duration::from_secs(30)) - ); - assert_eq!( - pool.without_encrypted_job_purge() - .encrypted_job_purge_interval, - None - ); - } - - #[cfg(any(feature = "postgres", feature = "mysql"))] - #[test] - fn result_cleanup_is_on_by_default_and_configurable() { - #[cfg(feature = "postgres")] - type Db = sqlx::Postgres; - #[cfg(all(feature = "mysql", not(feature = "postgres")))] - type Db = sqlx::MySql; - - let pool = WorkerPool::::new(); - assert_eq!( - pool.result_cleanup_interval, - Some(DEFAULT_RESULT_CLEANUP_INTERVAL) - ); - assert_eq!(DEFAULT_RESULT_CLEANUP_INTERVAL, Duration::from_secs(300)); - let pool = pool.with_result_cleanup(Duration::from_secs(42)); - assert_eq!(pool.result_cleanup_interval, Some(Duration::from_secs(42))); - assert_eq!(pool.without_result_cleanup().result_cleanup_interval, None); - } - - #[cfg(feature = "postgres")] - #[tokio::test] - async fn pool_from_config_applies_the_result_cleanup_settings() { - let mut config = crate::HammerworkConfig::new(); - let pool = WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).unwrap(); - assert_eq!( - pool.result_cleanup_interval, - Some(DEFAULT_RESULT_CLEANUP_INTERVAL), - "on by default" - ); - - config.worker.result_cleanup_interval = Duration::from_secs(60); - let pool = WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).unwrap(); - assert_eq!(pool.result_cleanup_interval, Some(Duration::from_secs(60))); - - config.worker.result_cleanup_enabled = false; - let pool = WorkerPool::from_config(lazy_worker("r"), &config.worker); - assert_eq!(pool.result_cleanup_interval, None); - - config.worker.result_cleanup_enabled = true; - config.worker.result_cleanup_interval = Duration::ZERO; - assert!( - WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).is_err(), - "a zero interval is rejected" - ); - } - - #[cfg(all(feature = "postgres", feature = "encryption"))] - #[tokio::test] - async fn pool_from_config_schedules_key_rotation_when_enabled() { - let mut config = crate::HammerworkConfig::new(); - let pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); - assert!(pool.key_rotation.is_none(), "off by default"); - - config.encryption.key_rotation.enabled = true; - config.encryption.key_rotation.check_interval_secs = 90; - let pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); - let rotation = pool.key_rotation.as_ref().expect("rotation scheduled"); - assert_eq!(rotation.interval, Duration::from_secs(90)); - assert!(pool.without_key_rotation().key_rotation.is_none()); - - config.encryption.key_rotation.check_interval_secs = 0; - assert!(WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).is_err()); - } - - /// A pool whose key manager cannot load its master key fails to start, before any - /// worker runs. - #[cfg(all(feature = "postgres", feature = "encryption"))] - #[tokio::test] - async fn pool_with_unloadable_master_key_fails_to_start() { - let mut config = crate::HammerworkConfig::new(); - config.encryption.key_rotation.enabled = true; - config.encryption.key_rotation.master_key_source = - crate::config::KeySourceRef::parse("env://HAMMERWORK_TEST_UNSET_MASTER_KEY_7F3A") - .unwrap(); - let mut pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); - let err = pool.start().await.unwrap_err(); - assert!( - matches!(err, HammerworkError::Encryption { .. }), - "unexpected error: {err}" - ); - assert!(pool.shutdown_signal.is_none(), "no worker was started"); - } - - #[cfg(all(feature = "postgres", not(feature = "encryption")))] - #[tokio::test] - async fn key_rotation_without_the_encryption_feature_is_rejected() { - let mut config = crate::HammerworkConfig::new(); - config.encryption.key_rotation.enabled = true; - let err = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config) - .err() - .expect("rejected"); - assert!(err.to_string().contains("`encryption` feature"), "{err}"); - } - - #[cfg(any(feature = "postgres", feature = "mysql"))] - #[test] - fn archival_is_opt_in() { - #[cfg(feature = "postgres")] - type Db = sqlx::Postgres; - #[cfg(all(feature = "mysql", not(feature = "postgres")))] - type Db = sqlx::MySql; - - let pool = WorkerPool::::new(); - assert!(pool.archival.is_none()); - let policy = crate::archive::ArchivalPolicy::new().with_batch_size(7); - let pool = pool.with_archival( - policy, - crate::archive::ArchivalConfig::new().with_compression_level(2), - Duration::from_secs(90), - ); - let archival = pool.archival.as_ref().unwrap(); - assert_eq!(archival.interval, Duration::from_secs(90)); - assert_eq!(archival.policy.batch_size, 7); - assert_eq!(archival.config.compression_level, 2); - assert!(pool.without_archival().archival.is_none()); - } - #[test] fn panic_message_describes_every_payload_kind() { assert_eq!(panic_message(&"static str"), "static str"); @@ -5340,127 +3382,10 @@ mod tests { ); } - fn autoscale_state( - active_workers: usize, - ) -> (Arc>, QueueDepthHistory) { - ( - Arc::new(std::sync::RwLock::new(AutoscaleMetrics { - active_workers, - ..Default::default() - })), - Arc::new(std::sync::RwLock::new(Vec::new())), - ) - } - - fn fast_autoscale() -> AutoscaleConfig { - AutoscaleConfig::new() - .with_min_workers(1) - .with_max_workers(3) - .with_scale_up_threshold(4) - .with_scale_down_threshold(1) - .with_cooldown_period(Duration::ZERO) - .with_evaluation_window(Duration::from_secs(30)) - } - - #[test] - fn autoscaling_scales_up_within_max_workers() { - let config = fast_autoscale().with_scale_step(5); - let (metrics, history) = autoscale_state(1); - // 10 jobs for 1 worker is above the threshold of 4 per worker; the step of 5 - // is capped at max_workers. - let decision = apply_queue_depth(10, Utc::now(), &config, &metrics, &history); - assert_eq!(decision, Some(3)); - let m = metrics.read().unwrap().clone(); - assert_eq!(m.active_workers, 3); - assert_eq!(m.current_queue_depth, 10); - assert_eq!(m.avg_queue_depth, 10.0); - assert!(m.last_scale_time.is_some()); - - // At max_workers it never goes higher, however deep the queue. - let decision = apply_queue_depth(1000, Utc::now(), &config, &metrics, &history); - assert_eq!(decision, None); - assert_eq!(metrics.read().unwrap().active_workers, 3); - } - - #[test] - fn autoscaling_scales_down_to_min_workers() { - let config = fast_autoscale().with_scale_step(2); - let (metrics, history) = autoscale_state(3); - let decision = apply_queue_depth(0, Utc::now(), &config, &metrics, &history); - assert_eq!(decision, Some(1)); - let decision = apply_queue_depth(0, Utc::now(), &config, &metrics, &history); - assert_eq!(decision, None, "never below min_workers"); - assert_eq!(metrics.read().unwrap().active_workers, 1); - } - - #[test] - fn autoscaling_holds_between_thresholds_and_during_cooldown() { - let (metrics, history) = autoscale_state(2); - // 6 jobs / 2 workers = 3 per worker: between the thresholds (1 and 4). - let decision = apply_queue_depth(6, Utc::now(), &fast_autoscale(), &metrics, &history); - assert_eq!(decision, None); - - let config = fast_autoscale().with_cooldown_period(Duration::from_secs(3600)); - let (metrics, history) = autoscale_state(1); - let now = Utc::now(); - assert_eq!( - apply_queue_depth(100, now, &config, &metrics, &history), - Some(2), - "the first decision is not in a cooldown" - ); - assert_eq!( - apply_queue_depth( - 100, - now + chrono::Duration::seconds(1), - &config, - &metrics, - &history - ), - None, - "a second decision within the cooldown period is suppressed" - ); - let m = metrics.read().unwrap().clone(); - assert_eq!(m.active_workers, 2); - assert_eq!(m.time_since_last_scale, Duration::from_secs(1)); - } - - #[test] - fn autoscaling_averages_depth_over_the_evaluation_window() { - let config = fast_autoscale() - .with_scale_up_threshold(100) - .with_scale_down_threshold(0) - .with_evaluation_window(Duration::from_secs(10)); - let (metrics, history) = autoscale_state(1); - let start = Utc::now(); - for (offset, depth) in [(0, 30), (4, 10), (8, 20)] { - apply_queue_depth( - depth, - start + chrono::Duration::seconds(offset), - &config, - &metrics, - &history, - ); - } - assert_eq!(metrics.read().unwrap().avg_queue_depth, 20.0); - - // 12 seconds later the first sample (at 0s) is outside the 10s window. - apply_queue_depth( - 40, - start + chrono::Duration::seconds(12), - &config, - &metrics, - &history, - ); - assert_eq!(history.read().unwrap().len(), 3); - let m = metrics.read().unwrap().clone(); - assert_eq!(m.avg_queue_depth, (10.0 + 20.0 + 40.0) / 3.0); - assert_eq!(m.current_queue_depth, 40); - } - /// A worker on a pool that never connects (no database is needed to inspect how a /// worker is configured). #[cfg(feature = "postgres")] - fn lazy_worker(queue_name: &str) -> Worker { + pub(super) fn lazy_worker(queue_name: &str) -> Worker { let pool = sqlx::PgPool::connect_lazy("postgres://localhost/hammerwork_unused").unwrap(); let handler: JobHandler = Arc::new(|_job| Box::pin(async { Ok(()) })); Worker::new( @@ -5590,84 +3515,6 @@ mod tests { )); } - #[cfg(feature = "postgres")] - #[tokio::test] - async fn pool_from_config_uses_pool_size_and_autoscaling() { - let config = crate::config::WorkerConfig { - pool_size: 3, - autoscaling_enabled: true, - min_workers: 2, - max_workers: 6, - ..Default::default() - }; - let pool = WorkerPool::from_config(lazy_worker("p").with_config(&config), &config); - assert_eq!(pool.workers.len(), 3); - assert!(pool.worker_template.is_some()); - assert!(pool.autoscale_config.enabled); - assert_eq!(pool.autoscale_config.min_workers, 2); - assert_eq!(pool.autoscale_config.max_workers, 6); - - let config = crate::config::WorkerConfig { - pool_size: 0, - ..Default::default() - }; - let pool = WorkerPool::from_config(lazy_worker("p"), &config); - assert_eq!(pool.workers.len(), 1, "a pool always has a worker"); - assert!(!pool.autoscale_config.enabled); - } - - #[cfg(feature = "postgres")] - #[tokio::test] - async fn pool_from_hammerwork_config_schedules_purge_and_validates_encryption() { - let mut config = crate::HammerworkConfig::new(); - config.worker.pool_size = 2; - config.encryption.purge_interval_secs = Some(90); - let pool = WorkerPool::from_hammerwork_config(lazy_worker("p"), &config).unwrap(); - assert_eq!(pool.workers.len(), 2); - assert_eq!( - pool.encrypted_job_purge_interval, - Some(Duration::from_secs(90)) - ); - - config.encryption.purge_interval_secs = Some(0); - assert!( - WorkerPool::from_hammerwork_config(lazy_worker("p"), &config).is_err(), - "an invalid encryption section is rejected" - ); - } - - #[cfg(feature = "postgres")] - #[tokio::test] - async fn pool_stats_collector_is_applied_to_workers() { - use crate::stats::InMemoryStatsCollector; - let stats: Arc = Arc::new(InMemoryStatsCollector::new_default()); - let mut pool = WorkerPool::new().with_stats_collector(Arc::clone(&stats)); - pool.add_worker(lazy_worker("s")); - assert!(Arc::ptr_eq( - pool.workers[0].stats_collector.as_ref().unwrap(), - &stats - )); - assert!(Arc::ptr_eq( - pool.stats_collector().as_ref().unwrap(), - &stats - )); - - // With autoscaling on, the first worker becomes the template. - let mut pool = WorkerPool::new().with_autoscaling(AutoscaleConfig::new()); - assert!(pool.worker_template.is_none()); - pool.add_worker(lazy_worker("s")); - assert!(pool.worker_template.is_some()); - let mut pool = WorkerPool::new().without_autoscaling(); - pool.add_worker(lazy_worker("s")); - assert!(pool.worker_template.is_none()); - - // #64 H9: a plain pool does not autoscale. - let mut pool = WorkerPool::new(); - assert!(!pool.autoscale_config.enabled); - pool.add_worker(lazy_worker("s")); - assert!(pool.worker_template.is_none()); - } - #[cfg(all(feature = "postgres", feature = "webhooks"))] #[tokio::test] async fn lifecycle_events_carry_the_job_event_details() { diff --git a/src/worker/autoscale.rs b/src/worker/autoscale.rs new file mode 100644 index 0000000..c51a7ad --- /dev/null +++ b/src/worker/autoscale.rs @@ -0,0 +1,451 @@ +//! Worker pool autoscaling: its configuration ([`AutoscaleConfig`]), metrics and +//! scaling decision. + +use super::*; + +/// Configuration for worker autoscaling behavior. +/// +/// A [`WorkerPool`] does not autoscale until it is given a configuration with +/// [`WorkerPool::with_autoscaling`]. [`AutoscaleConfig::default`] (and the presets) are +/// enabled, so `with_autoscaling(AutoscaleConfig::default())` turns autoscaling on; see +/// [`WorkerPool::with_autoscaling`] for which workers it starts and retires. +#[derive(Debug, Clone)] +pub struct AutoscaleConfig { + /// Whether autoscaling is enabled + pub enabled: bool, + /// Minimum number of workers to maintain + pub min_workers: usize, + /// Maximum number of workers to allow + pub max_workers: usize, + /// Queue depth per worker threshold to trigger scale-up + pub scale_up_threshold: usize, + /// Queue depth per worker threshold to trigger scale-down + pub scale_down_threshold: usize, + /// Minimum time between scaling decisions + pub cooldown_period: Duration, + /// Number of workers to add/remove during scaling events + pub scale_step: usize, + /// Time window for queue depth averaging + pub evaluation_window: Duration, +} + +impl Default for AutoscaleConfig { + fn default() -> Self { + Self { + enabled: true, + min_workers: 1, + max_workers: 10, + scale_up_threshold: 5, + scale_down_threshold: 2, + cooldown_period: Duration::from_secs(60), + scale_step: 1, + evaluation_window: Duration::from_secs(30), + } + } +} + +impl AutoscaleConfig { + /// Create a new autoscale configuration with default values + pub fn new() -> Self { + Self::default() + } + + /// Enable or disable autoscaling + pub fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Set the minimum number of workers + pub fn with_min_workers(mut self, min_workers: usize) -> Self { + self.min_workers = min_workers.max(1); // Ensure at least 1 worker + self + } + + /// Set the maximum number of workers + pub fn with_max_workers(mut self, max_workers: usize) -> Self { + self.max_workers = max_workers.max(self.min_workers); + self + } + + /// Set the queue depth threshold for scaling up + pub fn with_scale_up_threshold(mut self, threshold: usize) -> Self { + self.scale_up_threshold = threshold.max(1); + self + } + + /// Set the queue depth threshold for scaling down + pub fn with_scale_down_threshold(mut self, threshold: usize) -> Self { + self.scale_down_threshold = threshold; + self + } + + /// Set the cooldown period between scaling decisions + pub fn with_cooldown_period(mut self, period: Duration) -> Self { + self.cooldown_period = period; + self + } + + /// Set the number of workers to add/remove per scaling event + pub fn with_scale_step(mut self, step: usize) -> Self { + self.scale_step = step.max(1); + self + } + + /// Set the evaluation window for queue depth averaging + pub fn with_evaluation_window(mut self, window: Duration) -> Self { + self.evaluation_window = window; + self + } + + /// Create a conservative autoscaling configuration + pub fn conservative() -> Self { + Self { + enabled: true, + min_workers: 2, + max_workers: 5, + scale_up_threshold: 10, + scale_down_threshold: 1, + cooldown_period: Duration::from_secs(300), // 5 mins + scale_step: 1, + evaluation_window: Duration::from_secs(60), + } + } + + /// Create an aggressive autoscaling configuration + pub fn aggressive() -> Self { + Self { + enabled: true, + min_workers: 1, + max_workers: 20, + scale_up_threshold: 3, + scale_down_threshold: 1, + cooldown_period: Duration::from_secs(30), + scale_step: 2, + evaluation_window: Duration::from_secs(15), + } + } + + /// Disable autoscaling + pub fn disabled() -> Self { + Self { + enabled: false, + ..Self::default() + } + } +} + +/// Metrics for autoscaling decisions +#[derive(Debug, Clone, Default)] +pub struct AutoscaleMetrics { + /// Current number of active workers: those of the autoscaled queue when + /// autoscaling is enabled, otherwise all of the pool's workers + pub active_workers: usize, + /// Average queue depth over evaluation window + pub avg_queue_depth: f64, + /// Current queue depth + pub current_queue_depth: u64, + /// Jobs processed per second (recent average) + pub jobs_per_second: f64, + /// Average worker utilization (0.0 to 1.0) + pub worker_utilization: f64, + /// Time since last scaling action + pub time_since_last_scale: Duration, + /// Timestamp of last scaling decision + pub last_scale_time: Option>, +} + +/// Scaling decision enum +#[derive(Debug, Clone, Copy)] +enum ScalingDecision { + ScaleUp, + ScaleDown, +} + +/// Type alias for queue depth history storage +pub(super) type QueueDepthHistory = Arc, u64)>>>; + +/// Record a queue depth sample and decide whether to scale. +/// +/// Returns the new worker count (within `min_workers..=max_workers`) when the +/// average depth per worker crossed a threshold outside the cooldown period. +pub(super) fn apply_queue_depth( + current_depth: u64, + now: DateTime, + config: &AutoscaleConfig, + metrics: &Arc>, + history: &QueueDepthHistory, +) -> Option { + // Update queue depth history, dropping entries outside the evaluation window + let avg_depth = match history.write() { + Ok(mut hist) => { + hist.push((now, current_depth)); + let cutoff = now + - chrono::Duration::from_std(config.evaluation_window) + .unwrap_or(chrono::Duration::seconds(30)); + hist.retain(|(timestamp, _)| *timestamp > cutoff); + if hist.is_empty() { + current_depth as f64 + } else { + hist.iter().map(|(_, depth)| *depth as f64).sum::() / hist.len() as f64 + } + } + Err(_) => current_depth as f64, + }; + + let mut m = metrics.write().ok()?; + m.current_queue_depth = current_depth; + m.avg_queue_depth = avg_depth; + + // Check cooldown period + let time_since_last = m + .last_scale_time + .map(|t| now - t) + .and_then(|d| d.to_std().ok()) + .unwrap_or(config.cooldown_period); + m.time_since_last_scale = time_since_last; + if time_since_last < config.cooldown_period { + return None; + } + + // Calculate queue depth per worker + let depth_per_worker = if m.active_workers > 0 { + avg_depth / m.active_workers as f64 + } else { + avg_depth + }; + + let decision = if depth_per_worker > config.scale_up_threshold as f64 + && m.active_workers < config.max_workers + { + ScalingDecision::ScaleUp + } else if depth_per_worker < config.scale_down_threshold as f64 + && m.active_workers > config.min_workers + { + ScalingDecision::ScaleDown + } else { + return None; + }; + + let new_count = match decision { + ScalingDecision::ScaleUp => (m.active_workers + config.scale_step).min(config.max_workers), + ScalingDecision::ScaleDown => { + (m.active_workers.saturating_sub(config.scale_step)).max(config.min_workers) + } + }; + info!( + "Autoscaling: {:?} from {} to {} workers (avg queue depth: {:.1})", + decision, m.active_workers, new_count, m.avg_queue_depth + ); + m.active_workers = new_count; + m.last_scale_time = Some(now); + Some(new_count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_autoscale_config_defaults() { + let config = AutoscaleConfig::default(); + + assert!(config.enabled); + assert_eq!(config.min_workers, 1); + assert_eq!(config.max_workers, 10); + assert_eq!(config.scale_up_threshold, 5); + assert_eq!(config.scale_down_threshold, 2); + assert_eq!(config.cooldown_period, Duration::from_secs(60)); + assert_eq!(config.scale_step, 1); + assert_eq!(config.evaluation_window, Duration::from_secs(30)); + } + + #[test] + fn test_autoscale_config_builder() { + let config = AutoscaleConfig::new() + .with_min_workers(2) + .with_max_workers(20) + .with_scale_up_threshold(8) + .with_scale_down_threshold(1) + .with_cooldown_period(Duration::from_secs(120)) + .with_scale_step(2) + .with_evaluation_window(Duration::from_secs(45)); + + assert_eq!(config.min_workers, 2); + assert_eq!(config.max_workers, 20); + assert_eq!(config.scale_up_threshold, 8); + assert_eq!(config.scale_down_threshold, 1); + assert_eq!(config.cooldown_period, Duration::from_secs(120)); + assert_eq!(config.scale_step, 2); + assert_eq!(config.evaluation_window, Duration::from_secs(45)); + } + + #[test] + fn test_autoscale_config_presets() { + let conservative = AutoscaleConfig::conservative(); + assert_eq!(conservative.min_workers, 2); + assert_eq!(conservative.max_workers, 5); + assert_eq!(conservative.scale_up_threshold, 10); + assert_eq!(conservative.cooldown_period, Duration::from_secs(300)); + + let aggressive = AutoscaleConfig::aggressive(); + assert_eq!(aggressive.min_workers, 1); + assert_eq!(aggressive.max_workers, 20); + assert_eq!(aggressive.scale_up_threshold, 3); + assert_eq!(aggressive.cooldown_period, Duration::from_secs(30)); + + let disabled = AutoscaleConfig::disabled(); + assert!(!disabled.enabled); + } + + #[test] + fn test_autoscale_config_validation() { + // Test that min_workers is at least 1 + let config = AutoscaleConfig::new().with_min_workers(0); + assert_eq!(config.min_workers, 1); + + // Test that max_workers is at least min_workers + let config = AutoscaleConfig::new() + .with_min_workers(5) + .with_max_workers(3); + assert_eq!(config.max_workers, 5); + + // Test that scale_up_threshold is at least 1 + let config = AutoscaleConfig::new().with_scale_up_threshold(0); + assert_eq!(config.scale_up_threshold, 1); + + // Test that scale_step is at least 1 + let config = AutoscaleConfig::new().with_scale_step(0); + assert_eq!(config.scale_step, 1); + } + + #[test] + fn test_autoscale_metrics_default() { + let metrics = AutoscaleMetrics::default(); + + assert_eq!(metrics.active_workers, 0); + assert_eq!(metrics.avg_queue_depth, 0.0); + assert_eq!(metrics.current_queue_depth, 0); + assert_eq!(metrics.jobs_per_second, 0.0); + assert_eq!(metrics.worker_utilization, 0.0); + assert_eq!(metrics.time_since_last_scale, Duration::from_secs(0)); + assert!(metrics.last_scale_time.is_none()); + } + + fn autoscale_state( + active_workers: usize, + ) -> (Arc>, QueueDepthHistory) { + ( + Arc::new(std::sync::RwLock::new(AutoscaleMetrics { + active_workers, + ..Default::default() + })), + Arc::new(std::sync::RwLock::new(Vec::new())), + ) + } + + fn fast_autoscale() -> AutoscaleConfig { + AutoscaleConfig::new() + .with_min_workers(1) + .with_max_workers(3) + .with_scale_up_threshold(4) + .with_scale_down_threshold(1) + .with_cooldown_period(Duration::ZERO) + .with_evaluation_window(Duration::from_secs(30)) + } + + #[test] + fn autoscaling_scales_up_within_max_workers() { + let config = fast_autoscale().with_scale_step(5); + let (metrics, history) = autoscale_state(1); + // 10 jobs for 1 worker is above the threshold of 4 per worker; the step of 5 + // is capped at max_workers. + let decision = apply_queue_depth(10, Utc::now(), &config, &metrics, &history); + assert_eq!(decision, Some(3)); + let m = metrics.read().unwrap().clone(); + assert_eq!(m.active_workers, 3); + assert_eq!(m.current_queue_depth, 10); + assert_eq!(m.avg_queue_depth, 10.0); + assert!(m.last_scale_time.is_some()); + + // At max_workers it never goes higher, however deep the queue. + let decision = apply_queue_depth(1000, Utc::now(), &config, &metrics, &history); + assert_eq!(decision, None); + assert_eq!(metrics.read().unwrap().active_workers, 3); + } + + #[test] + fn autoscaling_scales_down_to_min_workers() { + let config = fast_autoscale().with_scale_step(2); + let (metrics, history) = autoscale_state(3); + let decision = apply_queue_depth(0, Utc::now(), &config, &metrics, &history); + assert_eq!(decision, Some(1)); + let decision = apply_queue_depth(0, Utc::now(), &config, &metrics, &history); + assert_eq!(decision, None, "never below min_workers"); + assert_eq!(metrics.read().unwrap().active_workers, 1); + } + + #[test] + fn autoscaling_holds_between_thresholds_and_during_cooldown() { + let (metrics, history) = autoscale_state(2); + // 6 jobs / 2 workers = 3 per worker: between the thresholds (1 and 4). + let decision = apply_queue_depth(6, Utc::now(), &fast_autoscale(), &metrics, &history); + assert_eq!(decision, None); + + let config = fast_autoscale().with_cooldown_period(Duration::from_secs(3600)); + let (metrics, history) = autoscale_state(1); + let now = Utc::now(); + assert_eq!( + apply_queue_depth(100, now, &config, &metrics, &history), + Some(2), + "the first decision is not in a cooldown" + ); + assert_eq!( + apply_queue_depth( + 100, + now + chrono::Duration::seconds(1), + &config, + &metrics, + &history + ), + None, + "a second decision within the cooldown period is suppressed" + ); + let m = metrics.read().unwrap().clone(); + assert_eq!(m.active_workers, 2); + assert_eq!(m.time_since_last_scale, Duration::from_secs(1)); + } + + #[test] + fn autoscaling_averages_depth_over_the_evaluation_window() { + let config = fast_autoscale() + .with_scale_up_threshold(100) + .with_scale_down_threshold(0) + .with_evaluation_window(Duration::from_secs(10)); + let (metrics, history) = autoscale_state(1); + let start = Utc::now(); + for (offset, depth) in [(0, 30), (4, 10), (8, 20)] { + apply_queue_depth( + depth, + start + chrono::Duration::seconds(offset), + &config, + &metrics, + &history, + ); + } + assert_eq!(metrics.read().unwrap().avg_queue_depth, 20.0); + + // 12 seconds later the first sample (at 0s) is outside the 10s window. + apply_queue_depth( + 40, + start + chrono::Duration::seconds(12), + &config, + &metrics, + &history, + ); + assert_eq!(history.read().unwrap().len(), 3); + let m = metrics.read().unwrap().clone(); + assert_eq!(m.avg_queue_depth, (10.0 + 20.0 + 40.0) / 3.0); + assert_eq!(m.current_queue_depth, 40); + } +} diff --git a/src/worker/hooks.rs b/src/worker/hooks.rs new file mode 100644 index 0000000..6bf30b9 --- /dev/null +++ b/src/worker/hooks.rs @@ -0,0 +1,391 @@ +//! Job lifecycle event hooks ([`JobEventHooks`]). + +use super::*; + +/// Event data for job lifecycle event hooks. +#[derive(Debug, Clone)] +pub struct JobHookEvent { + /// The job that triggered the event + pub job: Job, + /// When the event occurred + pub timestamp: DateTime, + /// Processing duration (for completion events) + pub duration: Option, + /// Error message (for failure events) + pub error: Option, +} + +/// Type alias for job event hook handler functions. +pub type JobHookHandler = Arc; + +/// Job lifecycle event hooks that can be registered with workers. +#[derive(Clone, Default)] +pub struct JobEventHooks { + /// Called when a job starts processing + pub on_job_start: Option, + /// Called when a job completes successfully + pub on_job_complete: Option, + /// Called when a job fails (before retry logic) + pub on_job_fail: Option, + /// Called when a job times out + pub on_job_timeout: Option, + /// Called when a job is retried + pub on_job_retry: Option, +} + +impl JobEventHooks { + /// Create a new set of empty job event hooks. + pub fn new() -> Self { + Self::default() + } + + /// Set the job start event handler. + pub fn on_start(mut self, handler: F) -> Self + where + F: Fn(JobHookEvent) + Send + Sync + 'static, + { + self.on_job_start = Some(Arc::new(handler)); + self + } + + /// Set the job completion event handler. + pub fn on_complete(mut self, handler: F) -> Self + where + F: Fn(JobHookEvent) + Send + Sync + 'static, + { + self.on_job_complete = Some(Arc::new(handler)); + self + } + + /// Set the job failure event handler. + pub fn on_fail(mut self, handler: F) -> Self + where + F: Fn(JobHookEvent) + Send + Sync + 'static, + { + self.on_job_fail = Some(Arc::new(handler)); + self + } + + /// Set the job timeout event handler. + pub fn on_timeout(mut self, handler: F) -> Self + where + F: Fn(JobHookEvent) + Send + Sync + 'static, + { + self.on_job_timeout = Some(Arc::new(handler)); + self + } + + /// Set the job retry event handler. + pub fn on_retry(mut self, handler: F) -> Self + where + F: Fn(JobHookEvent) + Send + Sync + 'static, + { + self.on_job_retry = Some(Arc::new(handler)); + self + } + + /// Fire the job start event if a handler is registered. + pub(crate) fn fire_job_start(&self, job: Job) { + if let Some(handler) = &self.on_job_start { + let event = JobHookEvent { + job, + timestamp: Utc::now(), + duration: None, + error: None, + }; + handler(event); + } + } + + /// Fire the job completion event if a handler is registered. + pub(crate) fn fire_job_complete(&self, job: Job, duration: Duration) { + if let Some(handler) = &self.on_job_complete { + let event = JobHookEvent { + job, + timestamp: Utc::now(), + duration: Some(duration), + error: None, + }; + handler(event); + } + } + + /// Fire the job failure event if a handler is registered. + pub(crate) fn fire_job_fail(&self, job: Job, error: String) { + if let Some(handler) = &self.on_job_fail { + let event = JobHookEvent { + job, + timestamp: Utc::now(), + duration: None, + error: Some(error), + }; + handler(event); + } + } + + /// Fire the job timeout event if a handler is registered. + pub(crate) fn fire_job_timeout(&self, job: Job, duration: Duration) { + if let Some(handler) = &self.on_job_timeout { + let event = JobHookEvent { + job, + timestamp: Utc::now(), + duration: Some(duration), + error: Some("Job timed out".to_string()), + }; + handler(event); + } + } + + /// Fire the job retry event if a handler is registered. + pub(crate) fn fire_job_retry(&self, job: Job, error: String) { + if let Some(handler) = &self.on_job_retry { + let event = JobHookEvent { + job, + timestamp: Utc::now(), + duration: None, + error: Some(error), + }; + handler(event); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_job_event_hooks_default() { + let hooks = JobEventHooks::default(); + assert!(hooks.on_job_start.is_none()); + assert!(hooks.on_job_complete.is_none()); + assert!(hooks.on_job_fail.is_none()); + assert!(hooks.on_job_timeout.is_none()); + assert!(hooks.on_job_retry.is_none()); + } + + #[test] + fn test_job_event_hooks_new() { + let hooks = JobEventHooks::new(); + assert!(hooks.on_job_start.is_none()); + assert!(hooks.on_job_complete.is_none()); + assert!(hooks.on_job_fail.is_none()); + assert!(hooks.on_job_timeout.is_none()); + assert!(hooks.on_job_retry.is_none()); + } + + #[test] + fn test_job_event_hooks_builder() { + use std::sync::{Arc, Mutex}; + + let events = Arc::new(Mutex::new(Vec::new())); + + let events_start = Arc::clone(&events); + let events_complete = Arc::clone(&events); + let events_fail = Arc::clone(&events); + let events_timeout = Arc::clone(&events); + let events_retry = Arc::clone(&events); + + let hooks = JobEventHooks::new() + .on_start(move |event: JobHookEvent| { + events_start + .lock() + .unwrap() + .push(format!("start:{}", event.job.id)); + }) + .on_complete(move |event: JobHookEvent| { + events_complete + .lock() + .unwrap() + .push(format!("complete:{}", event.job.id)); + }) + .on_fail(move |event: JobHookEvent| { + events_fail + .lock() + .unwrap() + .push(format!("fail:{}", event.job.id)); + }) + .on_timeout(move |event: JobHookEvent| { + events_timeout + .lock() + .unwrap() + .push(format!("timeout:{}", event.job.id)); + }) + .on_retry(move |event: JobHookEvent| { + events_retry + .lock() + .unwrap() + .push(format!("retry:{}", event.job.id)); + }); + + // Verify all hooks are set + assert!(hooks.on_job_start.is_some()); + assert!(hooks.on_job_complete.is_some()); + assert!(hooks.on_job_fail.is_some()); + assert!(hooks.on_job_timeout.is_some()); + assert!(hooks.on_job_retry.is_some()); + } + + #[test] + fn test_job_hook_event_creation() { + use crate::Job; + use serde_json::json; + use std::time::Duration; + + let job = Job::new("test_queue".to_string(), json!({"test": "data"})) + .with_trace_id("trace-123") + .with_correlation_id("corr-456"); + + let event = JobHookEvent { + job: job.clone(), + timestamp: Utc::now(), + duration: Some(Duration::from_millis(500)), + error: Some("Test error".to_string()), + }; + + assert_eq!(event.job.id, job.id); + assert_eq!(event.job.queue_name, "test_queue"); + assert_eq!(event.job.trace_id, Some("trace-123".to_string())); + assert_eq!(event.job.correlation_id, Some("corr-456".to_string())); + assert_eq!(event.duration, Some(Duration::from_millis(500))); + assert_eq!(event.error, Some("Test error".to_string())); + } + + #[test] + fn test_job_event_hooks_fire_methods() { + use crate::Job; + use serde_json::json; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + let events = Arc::new(Mutex::new(Vec::new())); + let job = Job::new("test_queue".to_string(), json!({"test": "data"})); + + // Test fire_job_start + { + let events_clone = Arc::clone(&events); + let hooks = JobEventHooks::new().on_start(move |event: JobHookEvent| { + events_clone + .lock() + .unwrap() + .push(format!("start:{}", event.job.queue_name)); + }); + + hooks.fire_job_start(job.clone()); + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 1); + assert_eq!(captured_events[0], "start:test_queue"); + } + + // Clear events for next test + events.lock().unwrap().clear(); + + // Test fire_job_complete + { + let events_clone = Arc::clone(&events); + let hooks = JobEventHooks::new().on_complete(move |event: JobHookEvent| { + events_clone.lock().unwrap().push(format!( + "complete:{}:{}ms", + event.job.queue_name, + event.duration.unwrap_or_default().as_millis() + )); + }); + + hooks.fire_job_complete(job.clone(), Duration::from_millis(150)); + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 1); + assert_eq!(captured_events[0], "complete:test_queue:150ms"); + } + + // Clear events for next test + events.lock().unwrap().clear(); + + // Test fire_job_fail + { + let events_clone = Arc::clone(&events); + let hooks = JobEventHooks::new().on_fail(move |event: JobHookEvent| { + events_clone.lock().unwrap().push(format!( + "fail:{}:{}", + event.job.queue_name, + event.error.unwrap_or_default() + )); + }); + + hooks.fire_job_fail(job.clone(), "Connection timeout".to_string()); + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 1); + assert_eq!(captured_events[0], "fail:test_queue:Connection timeout"); + } + + // Clear events for next test + events.lock().unwrap().clear(); + + // Test fire_job_timeout + { + let events_clone = Arc::clone(&events); + let hooks = JobEventHooks::new().on_timeout(move |event: JobHookEvent| { + events_clone.lock().unwrap().push(format!( + "timeout:{}:{}ms", + event.job.queue_name, + event.duration.unwrap_or_default().as_millis() + )); + }); + + hooks.fire_job_timeout(job.clone(), Duration::from_secs(30)); + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 1); + assert_eq!(captured_events[0], "timeout:test_queue:30000ms"); + } + + // Clear events for next test + events.lock().unwrap().clear(); + + // Test fire_job_retry + { + let events_clone = Arc::clone(&events); + let hooks = JobEventHooks::new().on_retry(move |event: JobHookEvent| { + events_clone.lock().unwrap().push(format!( + "retry:{}:{}", + event.job.queue_name, + event.error.unwrap_or_default() + )); + }); + + hooks.fire_job_retry(job.clone(), "API rate limit exceeded".to_string()); + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 1); + assert_eq!( + captured_events[0], + "retry:test_queue:API rate limit exceeded" + ); + } + } + + #[test] + fn test_job_event_hooks_clone() { + use std::sync::{Arc, Mutex}; + + let events = Arc::new(Mutex::new(Vec::new())); + let events_clone = Arc::clone(&events); + + let hooks = JobEventHooks::new().on_start(move |event: JobHookEvent| { + events_clone + .lock() + .unwrap() + .push(format!("cloned:{}", event.job.id)); + }); + + // Clone the hooks + let hooks_clone = hooks.clone(); + + // Both original and clone should work + let job = crate::Job::new("test".to_string(), serde_json::json!({})); + hooks.fire_job_start(job.clone()); + hooks_clone.fire_job_start(job); + + let captured_events = events.lock().unwrap(); + assert_eq!(captured_events.len(), 2); + assert!(captured_events[0].starts_with("cloned:")); + assert!(captured_events[1].starts_with("cloned:")); + } +} diff --git a/src/worker/pool.rs b/src/worker/pool.rs new file mode 100644 index 0000000..fbc938f --- /dev/null +++ b/src/worker/pool.rs @@ -0,0 +1,1348 @@ +//! [`WorkerPool`]: running, supervising and autoscaling workers, and the pool's +//! periodic maintenance tasks. + +use super::autoscale::{QueueDepthHistory, apply_queue_depth}; +use super::*; + +/// What a [`WorkerPool`] supervisor needs to apply autoscaling decisions. +struct Scaling { + /// Cloned for every worker started by a scale-up. Only workers of its queue are + /// started or retired. + template: Worker, + /// Desired number of workers on the template's queue, published by the + /// autoscaling task + desired: watch::Receiver, + /// Workers on the template's queue when the pool started + initial: usize, +} + +/// Wait for the next value on `rx`. Returns `None` once the sender is gone, and never +/// completes when there is no receiver. +async fn wait_for_change(rx: &mut Option>) -> Option { + match rx { + Some(rx) => match rx.changed().await { + Ok(()) => Some(*rx.borrow_and_update()), + Err(_) => None, + }, + None => std::future::pending().await, + } +} + +/// 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`]. +/// +/// It also clears expired job results every 5 minutes by calling +/// [`DatabaseQueue::cleanup_expired_results`] ([`WorkerPool::with_result_cleanup`], +/// disable it with [`WorkerPool::without_result_cleanup`]). +/// +/// Optionally, the pool also enforces the retention of encrypted jobs by calling +/// [`DatabaseQueue::purge_expired_encrypted_jobs`] periodically +/// ([`WorkerPool::with_encrypted_job_purge`]), archives finished jobs +/// ([`WorkerPool::with_archival`]) and, with the `encryption` feature, rotates +/// encryption keys as they fall due (`WorkerPool::with_key_rotation`). +/// +/// These maintenance tasks run each pass in its own task, so workers never wait for +/// them and shutting the pool down never cancels a pass part-way through its database +/// transaction. They stop when the pool shuts down. +pub struct WorkerPool { + workers: 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, + /// How often encrypted jobs whose retention ended are purged (`None`: never) + encrypted_job_purge_interval: Option, + /// Automatic archival and purge of archived jobs (`None`: off) + archival: Option, + /// How often expired job results are cleared (`None`: never) + result_cleanup_interval: Option, + /// Automatic rotation of encryption keys (`None`: off) + #[cfg(feature = "encryption")] + key_rotation: Option, + stats_collector: Option>, + /// Worker template for creating new workers during autoscaling + worker_template: Option>, + /// Autoscaling configuration + autoscale_config: AutoscaleConfig, + /// Autoscaling metrics and state + autoscale_metrics: Arc>, + /// Queue depth history for averaging + queue_depth_history: QueueDepthHistory, + /// Autoscaling task handle + autoscale_task: Option>, +} + +impl WorkerPool +where + JobQueue: DatabaseQueue + Send + Sync, +{ + /// Create an empty pool. Autoscaling is off; enable it with + /// [`with_autoscaling`](Self::with_autoscaling). The stale job reaper and the + /// expired result cleanup are on. + pub fn new() -> Self { + Self { + workers: Vec::new(), + shutdown_signal: None, + supervisor_done: None, + reaper_interval: Some(DEFAULT_STALE_JOB_REAPER_INTERVAL), + reaper_older_than: None, + encrypted_job_purge_interval: None, + archival: None, + result_cleanup_interval: Some(DEFAULT_RESULT_CLEANUP_INTERVAL), + #[cfg(feature = "encryption")] + key_rotation: None, + stats_collector: None, + worker_template: None, + autoscale_config: AutoscaleConfig::disabled(), + autoscale_metrics: Arc::new(std::sync::RwLock::new(AutoscaleMetrics::default())), + queue_depth_history: Arc::new(std::sync::RwLock::new(Vec::new())), + autoscale_task: None, + } + } + + /// Build a pool from a [`WorkerConfig`](crate::config::WorkerConfig). + /// + /// Adds `pool_size` copies of `worker` (at least one), uses it as the autoscaling + /// template, configures autoscaling from `autoscaling_enabled`, `min_workers` + /// and `max_workers`, and the expired result cleanup from `result_cleanup_enabled` + /// and `result_cleanup_interval`. Apply the per-worker settings to `worker` first + /// with [`Worker::with_config`] or [`Worker::with_hammerwork_config`]. + pub fn from_config(worker: Worker, config: &crate::config::WorkerConfig) -> Self { + let mut pool = Self::new() + .with_autoscaling(config.autoscale_config()) + .with_worker_template(worker.clone()); + pool.result_cleanup_interval = config + .result_cleanup_enabled + .then_some(config.result_cleanup_interval); + for _ in 1..config.pool_size { + pool.add_worker(worker.clone()); + } + pool.add_worker(worker); + pool + } + + /// Build a pool from a [`HammerworkConfig`](crate::config::HammerworkConfig). + /// + /// Like [`WorkerPool::from_config`] with `config.worker` (including the expired + /// result cleanup every `worker.result_cleanup_interval`, on by default), and also + /// schedules the encrypted job retention purge every + /// `encryption.purge_interval_secs`, when set + /// ([`WorkerPool::with_encrypted_job_purge`]), automatic archival every + /// `archive.check_interval` when `archive.enabled` ([`WorkerPool::with_archival`] + /// with [`ArchiveConfig::archival_policy`](crate::config::ArchiveConfig::archival_policy) + /// and [`ArchiveConfig::archival_config`](crate::config::ArchiveConfig::archival_config)), + /// and key rotation every `encryption.key_rotation.check_interval_secs` when + /// `encryption.key_rotation.enabled` (see `WorkerPool::with_key_rotation`; the + /// `KeyManager` is created on the worker's database, with + /// [`KeyRotationConfig::key_manager_config`](crate::config::KeyRotationConfig::key_manager_config), + /// when the pool starts, and [`WorkerPool::start`] fails if its master key cannot be + /// loaded). Validates the `encryption`, `worker` and `archive` sections; enabling + /// key rotation without the `encryption` feature is an error. + pub fn from_hammerwork_config( + worker: Worker, + config: &crate::config::HammerworkConfig, + ) -> Result { + config.encryption.validate()?; + config.worker.validate()?; + config.archive.validate()?; + let rotation = &config.encryption.key_rotation; + #[cfg(feature = "encryption")] + let key_rotation = if rotation.enabled { + Some(PoolKeyRotation { + interval: rotation.check_interval(), + start: key_rotation_from_config(&worker.queue.pool, rotation.key_manager_config())?, + }) + } else { + None + }; + #[cfg(not(feature = "encryption"))] + if rotation.enabled { + return Err(HammerworkError::Config( + "encryption.key_rotation.enabled is set but hammerwork was built without the \ + `encryption` feature" + .to_string(), + )); + } + let mut pool = Self::from_config(worker, &config.worker); + #[cfg(feature = "encryption")] + { + pool.key_rotation = key_rotation; + } + pool.encrypted_job_purge_interval = config.encryption.purge_interval(); + if config.archive.enabled { + pool = pool.with_archival( + config.archive.archival_policy(), + config.archive.archival_config(), + config.archive.check_interval, + ); + } + Ok(pool) + } + + pub fn with_stats_collector(mut self, stats_collector: Arc) -> Self { + self.stats_collector = Some(stats_collector); + self + } + + /// Configure autoscaling for the worker pool. + /// + /// Autoscaling is off unless enabled here (or by + /// [`from_config`](Self::from_config) with `autoscaling_enabled`). It scales one + /// queue: that of the [worker template](Self::with_worker_template), or of the first + /// worker added when no template is set. It measures that queue's depth, starts + /// clones of the template while it is deep and retires workers of that queue (never + /// below `min_workers`) once it drains. Workers of other queues are never started + /// or retired. A retired worker stops like on shutdown: it finishes its in-flight + /// job within its [shutdown grace period](Worker::with_shutdown_grace_period). + pub fn with_autoscaling(mut self, config: AutoscaleConfig) -> Self { + self.autoscale_config = config; + self + } + + /// Disable autoscaling for the worker pool + pub fn without_autoscaling(mut self) -> Self { + self.autoscale_config = AutoscaleConfig::disabled(); + 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). Workers take their lease when they claim a job, so a job whose worker is + /// alive is never reclaimed, whatever this pool's settings or those of other pools. + /// `older_than` only applies to running jobs without a lease of their own (claimed + /// by an older Hammerwork version); 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, with different settings, 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 + } + + /// Purge encrypted jobs whose retention period ended every `interval`. + /// + /// The pool calls [`DatabaseQueue::purge_expired_encrypted_jobs`], which deletes + /// finished encrypted jobs (and archived ones) past their `retention_delete_at`; it + /// needs no encryption key. Off by default: without it, run + /// `cargo hammerwork maintenance purge-encrypted` on a schedule. Running purges in + /// several pools or processes at once is safe. + /// + /// The first purge runs when the pool starts. Each purge runs in its own task, so + /// shutting the pool down never cancels one part-way through its transaction. + pub fn with_encrypted_job_purge(mut self, interval: Duration) -> Self { + self.encrypted_job_purge_interval = Some(interval); + self + } + + /// Disable the encrypted job retention purge (the default). + pub fn without_encrypted_job_purge(mut self) -> Self { + self.encrypted_job_purge_interval = None; + self + } + + /// Archive finished jobs, and purge old archived jobs, every `interval`. + /// + /// Each pass runs [`JobArchiver::run_scheduled_pass`](crate::archive::JobArchiver::run_scheduled_pass) + /// with `policy` as the policy for every queue and `config` for compression: it + /// moves completed, failed, dead and timed out jobs older than the policy's + /// thresholds to `hammerwork_jobs_archive` (reason `Automatic`, archived by + /// `"worker_pool"`), then deletes archived jobs older than `purge_archived_after`, + /// when set. Results are logged. Off by default; a disabled `policy` does nothing. + /// + /// The first pass runs when the pool starts. Passes run in their own task, so + /// workers are never blocked by them. On shutdown no new pass starts, and a running + /// pass stops before its next batch; a batch that has started commits or rolls back + /// as a whole. Running archival in several pools or processes at once is safe: rows + /// are claimed with `FOR UPDATE SKIP LOCKED`, so each job is archived once. + pub fn with_archival( + mut self, + policy: crate::archive::ArchivalPolicy, + config: crate::archive::ArchivalConfig, + interval: Duration, + ) -> Self { + self.archival = Some(PoolArchival { + policy, + config, + interval, + }); + self + } + + /// Disable automatic archival (the default). + pub fn without_archival(mut self) -> Self { + self.archival = None; + self + } + + /// Clear expired job results every `interval`. + /// + /// The pool calls [`DatabaseQueue::cleanup_expired_results`], which removes the + /// stored results (`result_data`) of jobs whose result TTL has passed. Expired + /// results are never returned by + /// [`DatabaseQueue::get_job_result`], so this only frees the space they take (and + /// stops [`DatabaseQueue::get_job`] from still showing them in `Job::result_data`). + /// On by default every 5 minutes ([`DEFAULT_RESULT_CLEANUP_INTERVAL`]); a pool + /// built from configuration uses `worker.result_cleanup_enabled` and + /// `worker.result_cleanup_interval`. Running it in several pools or processes at + /// once is safe. + /// + /// The first cleanup runs when the pool starts. Each cleanup runs in its own task, + /// so workers never wait for it, and shutting the pool down stops the schedule + /// without cancelling a cleanup part-way. Each cleanup that clears results logs how + /// many at `info` level (failures at `warn`). + pub fn with_result_cleanup(mut self, interval: Duration) -> Self { + self.result_cleanup_interval = Some(interval); + self + } + + /// Disable the expired result cleanup (for example when it runs elsewhere). + pub fn without_result_cleanup(mut self) -> Self { + self.result_cleanup_interval = None; + self + } + + /// Rotate the encryption keys of `key_manager` as they fall due, checking every + /// `check_interval`. + /// + /// Each pass runs [`KeyManager::perform_automatic_rotation`](crate::encryption::KeyManager::perform_automatic_rotation), + /// which rotates the keys whose `next_rotation_at` has passed, and logs the rotated + /// keys (`info`) or the failure (`error`). The key manager must have automatic + /// rotation enabled ([`KeyManagerConfig::with_auto_rotation_enabled`](crate::encryption::KeyManagerConfig::with_auto_rotation_enabled)); + /// otherwise the pool logs a warning and does not rotate. Off by default; a pool + /// built with [`WorkerPool::from_hammerwork_config`] turns it on from + /// `[encryption.key_rotation]`. + /// + /// The first pass runs when the pool starts. Passes run in their own task, so + /// workers never wait for them, and shutting the pool down stops the schedule + /// without interrupting a rotation part-way. Several pools or processes can rotate + /// at once: each due key gets exactly one new version (see + /// [`KeyManager::perform_automatic_rotation`](crate::encryption::KeyManager::perform_automatic_rotation)). + /// + /// ```rust,no_run + /// # #[cfg(all(feature = "encryption", feature = "postgres"))] + /// # { + /// use hammerwork::encryption::{KeyManager, KeyManagerConfig}; + /// use hammerwork::{JobQueue, Worker, WorkerPool, worker::JobHandler}; + /// use std::{sync::Arc, time::Duration}; + /// + /// # async fn example(pool: sqlx::PgPool, handler: JobHandler) -> Result<(), Box> { + /// let key_manager = KeyManager::new( + /// KeyManagerConfig::new() + /// .with_master_key_env("HAMMERWORK_MASTER_KEY") + /// .with_auto_rotation_enabled(true), + /// pool.clone(), + /// ) + /// .await?; + /// let queue = Arc::new(JobQueue::new(pool)); + /// let mut worker_pool = WorkerPool::new() + /// .with_key_rotation(key_manager, Duration::from_secs(3600)); + /// worker_pool.add_worker(Worker::new(queue, "default".to_string(), handler)); + /// worker_pool.start().await?; + /// # Ok(()) + /// # } + /// # } + /// ``` + #[cfg(feature = "encryption")] + pub fn with_key_rotation( + mut self, + key_manager: crate::encryption::KeyManager, + check_interval: Duration, + ) -> Self { + let pass = rotation_pass(key_manager); + self.key_rotation = Some(PoolKeyRotation { + interval: check_interval, + start: Arc::new(move || { + let pass = pass.clone(); + Box::pin(async move { Ok(pass) }) + }), + }); + self + } + + /// Disable automatic key rotation (the default). + #[cfg(feature = "encryption")] + pub fn without_key_rotation(mut self) -> Self { + self.key_rotation = 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 { + self.worker_template = Some(worker); + self + } + + pub fn add_worker(&mut self, mut worker: Worker) { + // Apply the pool's stats collector to the worker if available + if let Some(stats_collector) = &self.stats_collector { + worker.stats_collector = Some(Arc::clone(stats_collector)); + } + + // If no worker template is set and autoscaling is enabled, use the first worker + // as template (`start` also falls back to the first worker). + if self.worker_template.is_none() + && self.autoscale_config.enabled + && self.workers.is_empty() + { + self.worker_template = Some(worker.clone()); + } + + 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()); + + // Created first, so a key manager that cannot start fails the pool before any + // worker runs. + #[cfg(feature = "encryption")] + let key_rotation = match &self.key_rotation { + Some(rotation) => (rotation.start)() + .await? + .map(|pass| (pass, rotation.interval)), + None => None, + }; + + 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 workers = std::mem::take(&mut self.workers); + #[cfg_attr(not(feature = "encryption"), allow(unused_mut))] + let mut maintenance: Vec> = [ + self.start_stale_job_reaper(&workers, signal_rx.clone()), + self.start_encrypted_job_purge(&workers, signal_rx.clone()), + self.start_archival(&workers, signal_rx.clone()), + self.start_result_cleanup(&workers, signal_rx.clone()), + ] + .into_iter() + .flatten() + .collect(); + #[cfg(feature = "encryption")] + if let Some((pass, interval)) = key_rotation { + info!("Rotating due encryption keys every {:?}", interval); + maintenance.push(spawn_periodic(interval, signal_rx.clone(), move || pass())); + } + + // Start autoscaling task if enabled. It publishes the desired number of workers + // on the template's queue, which the supervisor applies by starting workers from + // the template or retiring workers of that queue. + let scaling = if self.autoscale_config.enabled { + self.start_autoscaling_task(&workers) + } else { + None + }; + if let Ok(mut metrics) = self.autoscale_metrics.write() { + metrics.active_workers = match &scaling { + Some(scaling) => scaling.initial, + None => workers.len(), + }; + } + + let supervisor = tokio::spawn(Self::supervise( + workers, + signal_rx, + done_tx, + maintenance, + scaling, + )); + + // 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, + maintenance: Vec>, + scaling: Option>, + ) -> Result<()> { + let mut 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(); + // Workers stopped by a scale-down: not restarted, and their slot is reused by + // the next scale-up once their task has finished. + let mut retired: Vec = vec![false; senders.len()]; + let mut finished: Vec = vec![false; senders.len()]; + let (template, mut desired_rx) = match scaling { + Some(scaling) => (Some(scaling.template), Some(scaling.desired)), + None => (None, None), + }; + + 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(()); + } + } + changed = wait_for_change(&mut desired_rx), if !shutting_down => { + let (Some(desired), Some(template)) = (changed, template.as_ref()) else { + // The autoscaler stopped: keep the current workers. + desired_rx = None; + continue; + }; + // Only the template's queue is scaled: workers of other queues are + // never retired, and new workers are clones of the template. + let active: Vec = (0..senders.len()) + .filter(|i| !retired[*i] && templates[*i].queue_name == template.queue_name) + .collect(); + if desired > active.len() { + for _ in active.len()..desired { + let worker = template.clone(); + let reusable = (0..senders.len()).find(|i| retired[*i] && finished[*i]); + let index = reusable.unwrap_or(senders.len()); + let tx = Self::spawn_worker(&mut set, index, worker.clone(), None); + if index == senders.len() { + templates.push(worker); + senders.push(tx); + retired.push(false); + finished.push(false); + } else { + templates[index] = worker; + senders[index] = tx; + retired[index] = false; + finished[index] = false; + } + } + info!( + "Autoscaling: started workers for queue {}, now {}", + template.queue_name, desired + ); + } else { + for index in active.iter().rev().take(active.len() - desired) { + retired[*index] = true; + let _ = senders[*index].try_send(()); + } + if desired < active.len() { + info!( + "Autoscaling: retiring workers of queue {}, now {}", + template.queue_name, desired + ); + } + } + } + joined = set.join_next() => { + let Some(joined) = joined else { break }; + let index = match joined { + Ok((index, Ok(Ok(())))) => { + if shutting_down { + continue; + } + if retired[index] { + finished[index] = true; + 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 retired[index] { + finished[index] = true; + } else 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), + ); + } + } + } + } + + // Stops the maintenance loops; a pass already running finishes in its own task + for task in maintenance { + task.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], + signal_rx: watch::Receiver, + ) -> Option> { + let interval = self.reaper_interval?; + 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) + }); + + spawn_queue_task(workers, interval, signal_rx, move |queue| async move { + 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), + } + }) + } + + /// Spawn the periodic encrypted job retention purge, if enabled. + fn start_encrypted_job_purge( + &self, + workers: &[Worker], + signal_rx: watch::Receiver, + ) -> Option> { + let interval = self.encrypted_job_purge_interval?; + spawn_queue_task(workers, interval, signal_rx, |queue| async move { + match queue.purge_expired_encrypted_jobs().await { + Ok(purge) if purge.total() > 0 => info!( + "Encrypted job purge deleted {} jobs and {} archived jobs", + purge.jobs, purge.archived_jobs + ), + Ok(_) => {} + Err(e) => warn!("Encrypted job purge failed: {}", e), + } + }) + } + + /// Spawn the periodic archival pass, if enabled. + fn start_archival( + &self, + workers: &[Worker], + signal_rx: watch::Receiver, + ) -> Option> { + let archival = self.archival.clone()?; + let queue = Arc::clone(&workers.first()?.queue); + if !archival.policy.enabled { + info!("Automatic archival is configured with a disabled policy; not starting it"); + return None; + } + let archiver = Arc::new( + crate::archive::JobArchiver::new(queue.pool.clone()) + .with_default_policy(archival.policy) + .with_config(archival.config), + ); + let stop_rx = signal_rx.clone(); + Some(spawn_periodic(archival.interval, signal_rx, move || { + let (queue, archiver, stop_rx) = + (Arc::clone(&queue), Arc::clone(&archiver), stop_rx.clone()); + async move { + let pass = archiver + .run_scheduled_pass(queue.as_ref(), Some("worker_pool"), || *stop_rx.borrow()) + .await; + match pass { + Ok(pass) if pass.jobs_archived > 0 || pass.jobs_purged > 0 => info!( + "Archival archived {} jobs and purged {} archived jobs{}", + pass.jobs_archived, + pass.jobs_purged, + if pass.stopped_early { + " (stopped early for shutdown)" + } else { + "" + } + ), + Ok(_) => debug!("Archival found nothing to archive or purge"), + Err(e) => warn!("Archival failed: {}", e), + } + } + })) + } + + /// Spawn the periodic expired result cleanup, if enabled. + fn start_result_cleanup( + &self, + workers: &[Worker], + signal_rx: watch::Receiver, + ) -> Option> { + let interval = self.result_cleanup_interval?; + if !workers.is_empty() { + debug!("Clearing expired job results every {:?}", interval); + } + spawn_queue_task(workers, interval, signal_rx, |queue| async move { + match queue.cleanup_expired_results().await { + Ok(cleared) if cleared > 0 => { + info!("Result cleanup cleared {} expired job results", cleared) + } + Ok(_) => debug!("Result cleanup found no expired job results"), + Err(e) => warn!("Result cleanup failed: {}", e), + } + }) + } + + /// Start the autoscaling background task. + /// + /// Returns the worker template and a channel carrying the desired worker count, + /// which the supervisor applies, or `None` when there is no worker template. + fn start_autoscaling_task(&mut self, workers: &[Worker]) -> Option> { + // Without an explicit template, scale the first worker's queue. + let Some(worker_template) = self.worker_template.as_ref().or(workers.first()) else { + warn!("Cannot start autoscaling: no worker template available"); + return None; + }; + let mut template = worker_template.clone(); + let initial_workers = workers + .iter() + .filter(|worker| worker.queue_name == template.queue_name) + .count(); + if let Some(stats_collector) = &self.stats_collector { + template.stats_collector = Some(Arc::clone(stats_collector)); + } + let queue = Arc::clone(&template.queue); + let queue_name = template.queue_name.clone(); + let config = self.autoscale_config.clone(); + let metrics = Arc::clone(&self.autoscale_metrics); + let history = Arc::clone(&self.queue_depth_history); + let (desired_tx, desired_rx) = watch::channel(initial_workers); + + let task = tokio::spawn(async move { + Self::autoscaling_loop(queue, queue_name, config, metrics, history, desired_tx).await; + }); + + if let Some(previous) = self.autoscale_task.replace(task) { + previous.abort(); + } + info!( + "Autoscaling task started for queue: {}", + template.queue_name + ); + Some(Scaling { + template, + desired: desired_rx, + initial: initial_workers, + }) + } + + /// Main autoscaling evaluation loop + async fn autoscaling_loop( + queue: Arc>, + queue_name: String, + config: AutoscaleConfig, + metrics: Arc>, + history: QueueDepthHistory, + desired: watch::Sender, + ) { + // `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; + + match Self::evaluate_scaling_decision(&queue, &queue_name, &config, &metrics, &history) + .await + { + Ok(Some(count)) => { + // An error means the supervisor stopped: nothing left to scale. + if desired.send(count).is_err() { + return; + } + } + Ok(None) => {} + Err(e) => warn!("Autoscaling evaluation error: {}", e), + } + } + } + + /// Evaluate whether scaling up or down is needed. + /// + /// Returns the new worker count when the pool should scale. + async fn evaluate_scaling_decision( + queue: &Arc>, + queue_name: &str, + config: &AutoscaleConfig, + metrics: &Arc>, + history: &QueueDepthHistory, + ) -> Result> { + // Get current queue depth + let current_depth = queue.get_queue_depth(queue_name).await?; + Ok(apply_queue_depth( + current_depth, + Utc::now(), + config, + metrics, + history, + )) + } + + /// Get current autoscaling metrics + pub fn get_autoscale_metrics(&self) -> AutoscaleMetrics { + self.autoscale_metrics + .read() + .map(|metrics| metrics.clone()) + .unwrap_or_default() + } + + /// 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"); + + // Stop autoscaling task + if let Some(task) = &self.autoscale_task { + task.abort(); + info!("Autoscaling task stopped"); + } + + 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(()) + } + + /// Get the statistics collector for the worker pool + pub fn stats_collector(&self) -> Option> { + self.stats_collector.clone() + } +} + +impl Default for WorkerPool +where + JobQueue: DatabaseQueue + Send + Sync, +{ + fn default() -> Self { + Self::new() + } +} + +/// Automatic archival settings of a [`WorkerPool`] ([`WorkerPool::with_archival`]). +#[derive(Debug, Clone)] +struct PoolArchival { + policy: crate::archive::ArchivalPolicy, + config: crate::archive::ArchivalConfig, + interval: Duration, +} + +/// Default interval of the expired result cleanup of a [`WorkerPool`] +/// ([`WorkerPool::with_result_cleanup`]): five minutes. +pub const DEFAULT_RESULT_CLEANUP_INTERVAL: Duration = + crate::config::DEFAULT_RESULT_CLEANUP_INTERVAL; + +/// One key rotation pass, whatever the key manager's database. +#[cfg(feature = "encryption")] +type RotationPass = Arc Pin + Send>> + Send + Sync>; + +/// Creates the key manager when the pool starts and returns its rotation pass (`None` +/// when its automatic rotation is disabled). +#[cfg(feature = "encryption")] +type RotationStarter = Arc< + dyn Fn() -> Pin< + Box< + dyn Future< + Output = std::result::Result< + Option, + crate::encryption::EncryptionError, + >, + > + Send, + >, + > + Send + + Sync, +>; + +/// Key rotation settings of a [`WorkerPool`] (`WorkerPool::with_key_rotation`). +#[cfg(feature = "encryption")] +#[derive(Clone)] +struct PoolKeyRotation { + interval: Duration, + start: RotationStarter, +} + +/// The rotation pass of `manager`, or `None` (logged) when its automatic rotation is +/// disabled. +#[cfg(feature = "encryption")] +fn rotation_pass( + manager: crate::encryption::KeyManager, +) -> Option { + if !manager.auto_rotation_enabled() { + warn!( + "Key rotation is configured with a KeyManager whose automatic rotation is \ + disabled; not starting it" + ); + return None; + } + Some(Arc::new(move || Box::pin(manager.clone().rotation_pass()))) +} + +/// A starter that creates a `KeyManager` with `config` on `pool`. +#[cfg(feature = "encryption")] +#[allow(dead_code)] // unused without a database backend +fn key_manager_starter( + pool: sqlx::Pool, + config: crate::encryption::KeyManagerConfig, +) -> RotationStarter { + Arc::new(move || { + let (pool, config) = (pool.clone(), config.clone()); + Box::pin(async move { + let manager = crate::encryption::KeyManager::new(config, pool).await?; + Ok(rotation_pass(manager)) + }) + }) +} + +/// The starter for `[encryption.key_rotation]`: a `KeyManager` on the pool's own +/// database, which must be PostgreSQL or MySQL. +#[cfg(feature = "encryption")] +#[allow(unused_variables)] // without a database backend nothing matches +fn key_rotation_from_config( + pool: &sqlx::Pool, + config: crate::encryption::KeyManagerConfig, +) -> Result { + let pool: &dyn std::any::Any = pool; + #[cfg(feature = "postgres")] + if let Some(pool) = pool.downcast_ref::() { + return Ok(key_manager_starter(pool.clone(), config)); + } + #[cfg(feature = "mysql")] + if let Some(pool) = pool.downcast_ref::() { + return Ok(key_manager_starter(pool.clone(), config)); + } + Err(HammerworkError::Config( + "encryption.key_rotation needs a PostgreSQL or MySQL database".to_string(), + )) +} + +/// Spawn a task that calls `run` every `interval` (first right away) until shutdown is +/// signalled on `signal_rx` (or its sender is dropped). +/// +/// Each run is spawned as its own task and awaited, so neither the shutdown signal nor +/// aborting the returned handle cancels a run part-way: database work always reaches +/// commit or rollback instead of leaving a pooled connection inside a transaction. +fn spawn_periodic( + interval: Duration, + mut signal_rx: watch::Receiver, + run: F, +) -> tokio::task::JoinHandle<()> +where + F: Fn() -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + 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() => {} + } + if *signal_rx.borrow() { + break; + } + if let Err(e) = tokio::spawn(run()).await + && e.is_panic() + { + error!("Periodic maintenance task panicked: {}", e); + } + } + }) +} + +/// [`spawn_periodic`] for a maintenance pass on the queue of the pool's first worker +/// (`None` when the pool has no workers). +fn spawn_queue_task( + workers: &[Worker], + interval: Duration, + signal_rx: watch::Receiver, + pass: F, +) -> Option> +where + DB: Database + Send + Sync + 'static, + F: Fn(Arc>) -> Fut + Send + 'static, + Fut: std::future::Future + Send + 'static, +{ + let queue = Arc::clone(&workers.first()?.queue); + Some(spawn_periodic(interval, signal_rx, move || { + pass(Arc::clone(&queue)) + })) +} + +impl Drop for WorkerPool { + fn drop(&mut self) { + // Stop autoscaling task when dropping the pool + if let Some(task) = &self.autoscale_task { + task.abort(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[cfg(feature = "postgres")] + use crate::worker::tests::lazy_worker; + + #[tokio::test] + async fn spawn_periodic_runs_until_shutdown() { + let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (signal_tx, signal_rx) = watch::channel(false); + let counter = Arc::clone(&runs); + let task = spawn_periodic(Duration::from_millis(10), signal_rx, move || { + let counter = Arc::clone(&counter); + async move { + counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + }); + tokio::time::sleep(Duration::from_millis(100)).await; + signal_tx.send_replace(true); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("the loop stops on shutdown") + .unwrap(); + let seen = runs.load(std::sync::atomic::Ordering::SeqCst); + assert!(seen >= 2, "ran {seen} times"); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), seen); + } + + /// Shutting down (or aborting the loop, as the pool's supervisor does) while a run is + /// in flight must not cancel the run: it would drop a database transaction mid-way. + #[tokio::test] + async fn spawn_periodic_never_cancels_a_run() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let started = Arc::new(tokio::sync::Notify::new()); + let finished = Arc::new(AtomicBool::new(false)); + let (signal_tx, signal_rx) = watch::channel(false); + let (run_started, run_finished) = (Arc::clone(&started), Arc::clone(&finished)); + let task = spawn_periodic(Duration::from_secs(3600), signal_rx, move || { + let (started, finished) = (Arc::clone(&run_started), Arc::clone(&run_finished)); + async move { + started.notify_one(); + tokio::time::sleep(Duration::from_millis(200)).await; + finished.store(true, Ordering::SeqCst); + } + }); + started.notified().await; + signal_tx.send_replace(true); + task.abort(); + assert!(!finished.load(Ordering::SeqCst)); + tokio::time::sleep(Duration::from_millis(400)).await; + assert!( + finished.load(Ordering::SeqCst), + "the in-flight run completed after the loop was stopped" + ); + } + + #[cfg(any(feature = "postgres", feature = "mysql"))] + #[test] + fn encrypted_job_purge_is_opt_in_and_configurable() { + #[cfg(feature = "postgres")] + type Db = sqlx::Postgres; + #[cfg(all(feature = "mysql", not(feature = "postgres")))] + type Db = sqlx::MySql; + + let pool = WorkerPool::::new(); + assert_eq!(pool.encrypted_job_purge_interval, None); + let pool = pool.with_encrypted_job_purge(Duration::from_secs(30)); + assert_eq!( + pool.encrypted_job_purge_interval, + Some(Duration::from_secs(30)) + ); + assert_eq!( + pool.without_encrypted_job_purge() + .encrypted_job_purge_interval, + None + ); + } + + #[cfg(any(feature = "postgres", feature = "mysql"))] + #[test] + fn result_cleanup_is_on_by_default_and_configurable() { + #[cfg(feature = "postgres")] + type Db = sqlx::Postgres; + #[cfg(all(feature = "mysql", not(feature = "postgres")))] + type Db = sqlx::MySql; + + let pool = WorkerPool::::new(); + assert_eq!( + pool.result_cleanup_interval, + Some(DEFAULT_RESULT_CLEANUP_INTERVAL) + ); + assert_eq!(DEFAULT_RESULT_CLEANUP_INTERVAL, Duration::from_secs(300)); + let pool = pool.with_result_cleanup(Duration::from_secs(42)); + assert_eq!(pool.result_cleanup_interval, Some(Duration::from_secs(42))); + assert_eq!(pool.without_result_cleanup().result_cleanup_interval, None); + } + + #[cfg(feature = "postgres")] + #[tokio::test] + async fn pool_from_config_applies_the_result_cleanup_settings() { + let mut config = crate::HammerworkConfig::new(); + let pool = WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).unwrap(); + assert_eq!( + pool.result_cleanup_interval, + Some(DEFAULT_RESULT_CLEANUP_INTERVAL), + "on by default" + ); + + config.worker.result_cleanup_interval = Duration::from_secs(60); + let pool = WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).unwrap(); + assert_eq!(pool.result_cleanup_interval, Some(Duration::from_secs(60))); + + config.worker.result_cleanup_enabled = false; + let pool = WorkerPool::from_config(lazy_worker("r"), &config.worker); + assert_eq!(pool.result_cleanup_interval, None); + + config.worker.result_cleanup_enabled = true; + config.worker.result_cleanup_interval = Duration::ZERO; + assert!( + WorkerPool::from_hammerwork_config(lazy_worker("r"), &config).is_err(), + "a zero interval is rejected" + ); + } + + #[cfg(all(feature = "postgres", feature = "encryption"))] + #[tokio::test] + async fn pool_from_config_schedules_key_rotation_when_enabled() { + let mut config = crate::HammerworkConfig::new(); + let pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); + assert!(pool.key_rotation.is_none(), "off by default"); + + config.encryption.key_rotation.enabled = true; + config.encryption.key_rotation.check_interval_secs = 90; + let pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); + let rotation = pool.key_rotation.as_ref().expect("rotation scheduled"); + assert_eq!(rotation.interval, Duration::from_secs(90)); + assert!(pool.without_key_rotation().key_rotation.is_none()); + + config.encryption.key_rotation.check_interval_secs = 0; + assert!(WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).is_err()); + } + + /// A pool whose key manager cannot load its master key fails to start, before any + /// worker runs. + #[cfg(all(feature = "postgres", feature = "encryption"))] + #[tokio::test] + async fn pool_with_unloadable_master_key_fails_to_start() { + let mut config = crate::HammerworkConfig::new(); + config.encryption.key_rotation.enabled = true; + config.encryption.key_rotation.master_key_source = + crate::config::KeySourceRef::parse("env://HAMMERWORK_TEST_UNSET_MASTER_KEY_7F3A") + .unwrap(); + let mut pool = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config).unwrap(); + let err = pool.start().await.unwrap_err(); + assert!( + matches!(err, HammerworkError::Encryption { .. }), + "unexpected error: {err}" + ); + assert!(pool.shutdown_signal.is_none(), "no worker was started"); + } + + #[cfg(all(feature = "postgres", not(feature = "encryption")))] + #[tokio::test] + async fn key_rotation_without_the_encryption_feature_is_rejected() { + let mut config = crate::HammerworkConfig::new(); + config.encryption.key_rotation.enabled = true; + let err = WorkerPool::from_hammerwork_config(lazy_worker("k"), &config) + .err() + .expect("rejected"); + assert!(err.to_string().contains("`encryption` feature"), "{err}"); + } + + #[cfg(any(feature = "postgres", feature = "mysql"))] + #[test] + fn archival_is_opt_in() { + #[cfg(feature = "postgres")] + type Db = sqlx::Postgres; + #[cfg(all(feature = "mysql", not(feature = "postgres")))] + type Db = sqlx::MySql; + + let pool = WorkerPool::::new(); + assert!(pool.archival.is_none()); + let policy = crate::archive::ArchivalPolicy::new().with_batch_size(7); + let pool = pool.with_archival( + policy, + crate::archive::ArchivalConfig::new().with_compression_level(2), + Duration::from_secs(90), + ); + let archival = pool.archival.as_ref().unwrap(); + assert_eq!(archival.interval, Duration::from_secs(90)); + assert_eq!(archival.policy.batch_size, 7); + assert_eq!(archival.config.compression_level, 2); + assert!(pool.without_archival().archival.is_none()); + } + + #[cfg(feature = "postgres")] + #[tokio::test] + async fn pool_from_config_uses_pool_size_and_autoscaling() { + let config = crate::config::WorkerConfig { + pool_size: 3, + autoscaling_enabled: true, + min_workers: 2, + max_workers: 6, + ..Default::default() + }; + let pool = WorkerPool::from_config(lazy_worker("p").with_config(&config), &config); + assert_eq!(pool.workers.len(), 3); + assert!(pool.worker_template.is_some()); + assert!(pool.autoscale_config.enabled); + assert_eq!(pool.autoscale_config.min_workers, 2); + assert_eq!(pool.autoscale_config.max_workers, 6); + + let config = crate::config::WorkerConfig { + pool_size: 0, + ..Default::default() + }; + let pool = WorkerPool::from_config(lazy_worker("p"), &config); + assert_eq!(pool.workers.len(), 1, "a pool always has a worker"); + assert!(!pool.autoscale_config.enabled); + } + + #[cfg(feature = "postgres")] + #[tokio::test] + async fn pool_from_hammerwork_config_schedules_purge_and_validates_encryption() { + let mut config = crate::HammerworkConfig::new(); + config.worker.pool_size = 2; + config.encryption.purge_interval_secs = Some(90); + let pool = WorkerPool::from_hammerwork_config(lazy_worker("p"), &config).unwrap(); + assert_eq!(pool.workers.len(), 2); + assert_eq!( + pool.encrypted_job_purge_interval, + Some(Duration::from_secs(90)) + ); + + config.encryption.purge_interval_secs = Some(0); + assert!( + WorkerPool::from_hammerwork_config(lazy_worker("p"), &config).is_err(), + "an invalid encryption section is rejected" + ); + } + + #[cfg(feature = "postgres")] + #[tokio::test] + async fn pool_stats_collector_is_applied_to_workers() { + use crate::stats::InMemoryStatsCollector; + let stats: Arc = Arc::new(InMemoryStatsCollector::new_default()); + let mut pool = WorkerPool::new().with_stats_collector(Arc::clone(&stats)); + pool.add_worker(lazy_worker("s")); + assert!(Arc::ptr_eq( + pool.workers[0].stats_collector.as_ref().unwrap(), + &stats + )); + assert!(Arc::ptr_eq( + pool.stats_collector().as_ref().unwrap(), + &stats + )); + + // With autoscaling on, the first worker becomes the template. + let mut pool = WorkerPool::new().with_autoscaling(AutoscaleConfig::new()); + assert!(pool.worker_template.is_none()); + pool.add_worker(lazy_worker("s")); + assert!(pool.worker_template.is_some()); + let mut pool = WorkerPool::new().without_autoscaling(); + pool.add_worker(lazy_worker("s")); + assert!(pool.worker_template.is_none()); + + // #64 H9: a plain pool does not autoscale. + let mut pool = WorkerPool::new(); + assert!(!pool.autoscale_config.enabled); + pool.add_worker(lazy_worker("s")); + assert!(pool.worker_template.is_none()); + } +} From bfdd555d340f04c0678b3d5db7ae4344c1219864 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 01:02:53 -0400 Subject: [PATCH 8/8] chore: remove dead code and stale comments - calculate_job_level threaded an unused _current_level through its recursion. - JobQueue::pool is public, so its allow(dead_code) did nothing. - test_utils::skip_known_bug had no callers. - A comment in the web queue API called get_priority_stats "new". Co-Authored-By: Claude Opus 5.5 --- cargo-hammerwork/src/commands/workflow.rs | 11 ++--------- hammerwork-web/src/api/queues.rs | 1 - src/queue/mod.rs | 1 - tests/test_utils.rs | 13 ------------- 4 files changed, 2 insertions(+), 24 deletions(-) diff --git a/cargo-hammerwork/src/commands/workflow.rs b/cargo-hammerwork/src/commands/workflow.rs index 177b35e..67cc7af 100644 --- a/cargo-hammerwork/src/commands/workflow.rs +++ b/cargo-hammerwork/src/commands/workflow.rs @@ -607,7 +607,7 @@ impl WorkflowCommand { for job in jobs { if !visited.contains(&job.id) { - Self::calculate_job_level(job, &job_map, &mut levels, &mut visited, 0); + Self::calculate_job_level(job, &job_map, &mut levels, &mut visited); } } @@ -632,7 +632,6 @@ impl WorkflowCommand { job_map: &HashMap, levels: &mut HashMap, visited: &mut HashSet, - _current_level: usize, ) { if visited.contains(&job.id) { return; @@ -647,13 +646,7 @@ impl WorkflowCommand { .filter_map(|dep_id| { if let Some(dep_job) = job_map.get(dep_id) { if !visited.contains(dep_id) { - Self::calculate_job_level( - dep_job, - job_map, - levels, - visited, - _current_level, - ); + Self::calculate_job_level(dep_job, job_map, levels, visited); } levels.get(dep_id).copied() } else { diff --git a/hammerwork-web/src/api/queues.rs b/hammerwork-web/src/api/queues.rs index b9c7684..73463c2 100644 --- a/hammerwork-web/src/api/queues.rs +++ b/hammerwork-web/src/api/queues.rs @@ -536,7 +536,6 @@ async fn get_priority_breakdown( where T: DatabaseQueue + Send + Sync, { - // Use the new get_priority_stats method let priority_stats = queue.get_priority_stats(queue_name).await?; let mut breakdown = std::collections::HashMap::new(); for (priority, count) in priority_stats.job_counts { diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 137e78d..e36de50 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -1211,7 +1211,6 @@ pub(crate) fn saturating_add_to( /// # } /// ``` pub struct JobQueue { - #[allow(dead_code)] // Used in database-specific implementations pub pool: Pool, pub(crate) _phantom: PhantomData, pub(crate) throttle_configs: Arc>>, diff --git a/tests/test_utils.rs b/tests/test_utils.rs index 766cc08..b931425 100644 --- a/tests/test_utils.rs +++ b/tests/test_utils.rs @@ -99,19 +99,6 @@ pub async fn serial() -> tokio::sync::MutexGuard<'static, ()> { SERIAL.lock().await } -/// Whether to skip a test that is `#[ignore]`d because it exposes a known library bug. -/// -/// CI runs the suite with `--include-ignored`, which would also run these tests. -/// They return early unless `HAMMERWORK_TEST_KNOWN_BUGS` is set, so the bug can be -/// reproduced with `HAMMERWORK_TEST_KNOWN_BUGS=1 cargo test ... -- --include-ignored`. -pub fn skip_known_bug() -> bool { - if std::env::var_os("HAMMERWORK_TEST_KNOWN_BUGS").is_some() { - return false; - } - eprintln!("skipping known-bug test; set HAMMERWORK_TEST_KNOWN_BUGS=1 to run it"); - true -} - /// A fresh in-memory [`TestQueue`](hammerwork::queue::test::TestQueue). #[cfg(feature = "test")] pub async fn test_queue() -> std::sync::Arc {