Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions CHANGELOG.md

Large diffs are not rendered by default.

33 changes: 19 additions & 14 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ Hammerwork is a high-performance, database-driven job queue library for Rust wit

## Development Notes

- SQLx compile-time query checking requires database connections
- Queries are built at run time with `sqlx::query` and bound parameters (no compile-time `query!` macros, so building needs no database)
- PostgreSQL uses `FOR UPDATE SKIP LOCKED` for efficient job polling
- MySQL implementation uses transaction-based locking (less optimal)
- MySQL (8.0+) also claims jobs with `FOR UPDATE SKIP LOCKED`, inside a transaction
- Priority-aware queries use `ORDER BY priority DESC, scheduled_at ASC`
- Weighted selection uses hash-based algorithms for Send compatibility
- Tracing is integrated for observability
Expand Down Expand Up @@ -67,10 +67,15 @@ cargo clippy -- -D warnings
```

### Feature Flags
The project uses feature flags for database support:
- `postgres`: Enable PostgreSQL support
- `mysql`: Enable MySQL support
- `default`: No database features enabled by default
`default` is empty: a plain `hammerwork` dependency has only the queue, worker and job APIs. Opt in to:
- `postgres`, `mysql`: the database backends (at least one is needed for a `JobQueue`)
- `metrics`, `alerting`, `webhooks`, `streaming`, `tracing`, `encryption`: subsystems; `full` enables all six (not the backends, KMS sources, event sinks or `test-queue`)
- `aws-kms`, `gcp-kms`, `vault-kms`, `azure-kms`: encryption key sources
- `kafka`, `google-pubsub`, `kinesis`: event stream sinks
- `test-queue`: the in-memory `TestQueue`

A configuration file section for a feature that is not enabled is rejected by `HammerworkConfig::from_file`.
`cargo-hammerwork` and `hammerwork-web` enable the features they need; `hammerwork-web` has a `postgres` (default), `mysql` and `auth` (default) feature.

## Architecture

Expand All @@ -80,18 +85,18 @@ The codebase follows a modular architecture with clear separation of concerns:

1. **Job (`src/job.rs`)**
- Defines the `Job` struct with UUID, payload, status, priority, retry logic
- Job statuses: Pending, Running, Completed, Failed, Retrying, Dead, TimedOut
- Job statuses: Pending, Running, Completed, Failed, Dead, TimedOut, Archived (`Retrying` is only read from rows older versions wrote; a retry goes back to `Pending`)
- Job priorities: Background, Low, Normal, High, Critical
- Supports delayed execution, configurable retry attempts, and priority levels

2. **Queue (`src/queue/`)**
- `mod.rs`: the `DatabaseQueue` trait (the interface for database operations) and the generic `JobQueue<DB>` wrapping a connection pool
- `mod.rs`: the sealed `DatabaseQueue` trait (the interface for database operations; only Hammerwork implements it) and the generic `JobQueue<DB>` wrapping a connection pool. Jobs are claimed with `dequeue(queue, &DequeueOptions)` (batch size, priority weights, lease) or the one-job shortcut `dequeue_one(queue)`; a `Running` job holds a lease that heartbeats renew, and `requeue_stale_jobs(queue_name: Option<&str>)` reclaims jobs whose lease expired (one queue or all)
- `postgres.rs` / `mysql.rs`: the dialect-specific implementations (SQL, row types, locking)
- `backend.rs`: helpers shared by both backends (transactions and conflict retries, column encoding, cron and dequeue helpers)
- `row.rs`: dialect-independent row decoding (column lists, status, result config and encryption columns)
- `lifecycle.rs`: the job lifecycle state machine (manual transitions and worker run outcomes)
- `payload_encryption.rs`, `memory_results.rs`: payload sealing and in-memory result storage
- `test.rs`: the in-memory `TestQueue` (feature `test`)
- `test.rs`: the in-memory `TestQueue` (feature `test-queue`)
- Priority-aware job selection with weighted algorithms; atomic transitions in transactions

3. **Worker (`src/worker.rs` and `src/worker/`)**
Expand Down Expand Up @@ -146,13 +151,13 @@ Both PostgreSQL and MySQL implementations use a single table `hammerwork_jobs` w

```bash
# 1. Format code according to Rust standards
cargo fmt
cargo fmt --all

# 2. Run all linting checks with strict warnings
cargo clippy --all-features -- -D warnings
# 2. Run all linting checks with strict warnings (as CI does)
cargo clippy --workspace --all-features --all-targets -- -D warnings

# 3. Run complete test suite with all features
cargo test --all-features
# 3. Run the complete test suite with all features (the whole workspace)
cargo test --workspace --all-features

# 4. Test CLI crate specifically
cargo test -p cargo-hammerwork
Expand Down
13 changes: 11 additions & 2 deletions cargo-hammerwork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ The `cargo-hammerwork` crate provides a modular CLI for managing Hammerwork-base
# Run migrations to set up the database schema
cargo hammerwork migration run --database-url postgres://localhost/mydb

# Check migration status
# Show applied and pending migrations (from the hammerwork_migrations table)
cargo hammerwork migration status --database-url postgres://localhost/mydb
```

Expand Down Expand Up @@ -183,6 +183,8 @@ cargo hammerwork job purge --completed --older-than-days 30 --confirm
cargo hammerwork job purge --queue emails --dead --failed --confirm

cargo hammerwork job requeue-stale
cargo hammerwork job requeue-stale --dry-run # count only, change nothing
cargo hammerwork job requeue-stale --queue emails # one queue only
```

- `job enqueue` requires `--queue` and `--payload`; `--payload` must be valid JSON,
Expand All @@ -198,7 +200,9 @@ cargo hammerwork job requeue-stale
reclaimed, however long it runs. A `Running` job without a lease (left by a
Hammerwork 1.x worker) is never reclaimed; `maintenance check --fix` gives such jobs an
expired lease once every 1.x worker has stopped (see the 3.0 upgrade guide). It is
safe to run alongside workers. (3.0 removed `--older-than-secs`.)
safe to run alongside workers. `--dry-run` counts what would be reclaimed without
changing anything, and `--queue` limits the reclaim to one queue. (3.0 removed
`--older-than-secs`.)
- `job show` prints the redacted payload of an encrypted job (the CLI never decrypts)
together with its key id, algorithm and retention.

Expand Down Expand Up @@ -255,6 +259,11 @@ cargo hammerwork monitor metrics --period 24h --queue emails
`--refresh` is in seconds (default 5). `--format` is `table` or `json`; `--period` is
`1h`, `24h` or `7d`.

`monitor health` and `queue health` call a `Running` job stuck only when its lease has
expired, the rule `job requeue-stale` uses; a long-running job that keeps heartbeating is
healthy. `Running` jobs without a lease (left by a Hammerwork 1.x worker) get their own
`Lease-less Running Jobs` row.

### Batch Operation Commands

Operate on many jobs at once.
Expand Down
144 changes: 131 additions & 13 deletions cargo-hammerwork/src/commands/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::config::Config;
use crate::utils::database::{DatabasePool, JobQueueWrapper};
use crate::utils::display::JobTable;
use crate::utils::job_ops::{
JobSelector, cancel_many, cancel_one, retry_many, retry_one, select_job_ids,
JobSelector, StaleRunning, cancel_many, cancel_one, retry_many, retry_one, select_job_ids,
};
use crate::utils::sql::{
Backend, Bind, FAILURE_STATUSES, FAILURE_STATUSES_SQL, IdText, IntervalUnit, SqlParams,
Expand Down Expand Up @@ -167,11 +167,26 @@ pub enum JobCommand {
upgrade guide for the one-off fix. Stale jobs with attempts left go back to \
Pending; the rest are marked Dead. Safe to run while workers and other \
reapers are running.\n\n\
Example: cargo hammerwork job requeue-stale"
Use --dry-run to count what would be reclaimed without changing anything, \
and --queue to reclaim (or count) one queue only.\n\n\
Examples:\n cargo hammerwork job requeue-stale --dry-run\n \
cargo hammerwork job requeue-stale --queue emails"
)]
RequeueStale {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[arg(
short = 'n',
short_alias = 'Q',
long,
help = "Only reclaim jobs in this queue"
)]
queue: Option<String>,
#[arg(
long,
help = "Count the jobs that would be reclaimed without changing them"
)]
dry_run: bool,
},
}

Expand Down Expand Up @@ -276,8 +291,8 @@ impl JobCommand {
)
.await?;
}
JobCommand::RequeueStale { .. } => {
requeue_stale_jobs(pool).await?;
JobCommand::RequeueStale { queue, dry_run, .. } => {
requeue_stale_jobs(pool, queue.as_deref(), *dry_run).await?;
}
}
Ok(())
Expand Down Expand Up @@ -717,9 +732,38 @@ fn delayed_schedule(
.ok_or_else(|| anyhow::anyhow!("--delay {} seconds is out of range", delay_secs))
}

async fn requeue_stale_jobs(pool: DatabasePool) -> Result<()> {
let recovery = with_queue!(pool.create_job_queue(), |queue| {
queue.requeue_stale_jobs().await?
/// The `Running` jobs `requeue_stale_jobs` would reclaim (their lease expired), optionally
/// in one queue. The same lease-only rule the library applies.
fn stale_selector(queue: Option<&str>) -> JobSelector {
JobSelector {
statuses: vec![JobStatus::Running],
queue: queue.map(str::to_string),
stale_running: Some(StaleRunning::new(chrono::Utc::now())),
..Default::default()
}
}

async fn requeue_stale_jobs(pool: DatabasePool, queue: Option<&str>, dry_run: bool) -> Result<()> {
let scope = queue.map_or_else(|| "all queues".to_string(), |q| format!("queue '{q}'"));

if dry_run {
let ids = select_job_ids(&pool, &stale_selector(queue)).await?;
for id in &ids {
info!("Would reclaim stale job {}", id);
}
info!(
"🔍 Dry run: {} stale job(s) in {} would be reclaimed (lease expired). Nothing was changed.",
ids.len(),
scope
);
return Ok(());
}

// One atomic reclaim in the library, scoped to the queue when given: the queue filter
// sits in the same statement as the lease check, so a job whose worker renews its
// lease meanwhile is never touched.
let recovery = with_queue!(pool.create_job_queue(), |q| {
q.requeue_stale_jobs(queue).await?
});

for id in &recovery.requeued {
Expand All @@ -729,8 +773,9 @@ async fn requeue_stale_jobs(pool: DatabasePool) -> Result<()> {
info!("💀 Marked stale job {} dead (no attempts left)", id);
}
info!(
"✅ Reclaimed {} stale jobs ({} requeued, {} dead)",
"✅ Reclaimed {} stale jobs in {} ({} requeued, {} dead)",
recovery.total(),
scope,
recovery.requeued.len(),
recovery.dead.len()
);
Expand Down Expand Up @@ -923,26 +968,63 @@ mod tests {
fn test_requeue_stale_parses() {
let cli = TestCli::try_parse_from(["test", "requeue-stale"]).unwrap();
match cli.command {
JobCommand::RequeueStale { database_url } => assert!(database_url.is_none()),
JobCommand::RequeueStale {
database_url,
queue,
dry_run,
} => {
assert!(database_url.is_none() && queue.is_none());
assert!(!dry_run);
}
_ => panic!("expected RequeueStale"),
}

let cli =
TestCli::try_parse_from(["test", "requeue-stale", "-u", "postgres://localhost/db"])
.unwrap();
let cli = TestCli::try_parse_from([
"test",
"requeue-stale",
"-u",
"postgres://localhost/db",
"--queue",
"emails",
"--dry-run",
])
.unwrap();
match cli.command {
JobCommand::RequeueStale { database_url } => {
JobCommand::RequeueStale {
database_url,
queue,
dry_run,
} => {
assert_eq!(database_url.as_deref(), Some("postgres://localhost/db"));
assert_eq!(queue.as_deref(), Some("emails"));
assert!(dry_run);
}
_ => panic!("expected RequeueStale"),
}
assert!(TestCli::try_parse_from(["test", "requeue-stale", "-n", "q"]).is_ok());

// The 2.x age threshold for lease-less jobs is gone.
assert!(
TestCli::try_parse_from(["test", "requeue-stale", "--older-than-secs", "60"]).is_err()
);
}

#[test]
fn test_stale_selector_is_lease_only_and_scoped_by_bound_queue() {
let (sql, binds) = stale_selector(Some(HOSTILE_QUEUE)).sql(Backend::Postgres);
assert_eq!(
sql,
"SELECT id FROM hammerwork_jobs WHERE status IN ($1) AND queue_name = $2 AND (last_heartbeat_at >= started_at AND lease_expires_at < $3) ORDER BY created_at"
);
assert_eq!(binds.len(), 3);
assert_eq!(binds[1], Bind::Text(HOSTILE_QUEUE.into()));
assert!(!sql.contains("DROP"));

let (sql, binds) = stale_selector(None).sql(Backend::MySql);
assert!(!sql.contains("queue_name"));
assert_eq!(binds.len(), 2);
}

#[test]
fn test_list_jobs_query_postgres_binds_typed_params() {
let (query, params) = build_list_jobs_query(
Expand Down Expand Up @@ -1611,9 +1693,45 @@ mod tests {
let leaseless = seed(pool, &stale).await;
let fresh = seed(pool, &SeedJob::new(&q, "Running")).await;
backdate(pool, &fresh, "started_at", 0).await;
// another queue's stale job, to prove --queue scopes the reclaim
let other_queue = format!("{q}_other");
let mut other_stale = SeedJob::new(&other_queue, "Running");
other_stale.started_long_ago = true;
let other = seed(pool, &other_stale).await;
set_time(pool, &other, "last_heartbeat_at", -60).await;
set_time(pool, &other, "lease_expires_at", -10).await;
let stale_count = |queue: Option<&str>| {
let selector = stale_selector(queue);
async move { select_job_ids(pool, &selector).await.unwrap().len() }
};
assert_eq!(stale_count(Some(&q)).await, 2);
assert_eq!(stale_count(Some(&other_queue)).await, 1);

// --dry-run counts the same jobs and changes nothing
run(&["requeue-stale", "--dry-run"]).await.unwrap();
run(&["requeue-stale", "--dry-run", "--queue", &q])
.await
.unwrap();
assert_eq!(job_status(pool, &retryable).await, "Running");
assert_eq!(job_status(pool, &other).await, "Running");
assert_eq!(stale_count(Some(&q)).await, 2);

// --queue reclaims that queue only: retryable goes back to Pending, exhausted dies
run(&["requeue-stale", "--queue", &q]).await.unwrap();
assert_eq!(job_status(pool, &other).await, "Running");
assert_eq!(job_status(pool, &leaseless).await, "Running");
assert_eq!(job_status(pool, &fresh).await, "Running");
assert_eq!(job_status(pool, &retryable).await, "Pending");
assert_eq!(job_status(pool, &exhausted).await, "Dead");
assert_eq!(stale_count(Some(&q)).await, 0);
assert_eq!(stale_count(Some(&other_queue)).await, 1);

// without --queue every queue is reclaimed
run(&["requeue-stale"]).await.unwrap();
assert_eq!(job_status(pool, &other).await, "Pending");
assert_eq!(job_status(pool, &retryable).await, "Pending");
assert_eq!(job_status(pool, &exhausted).await, "Dead");
assert_eq!(job_status(pool, &exhausted).await, "Dead");
assert_eq!(job_status(pool, &leaseless).await, "Running");
assert_eq!(job_status(pool, &fresh).await, "Running");
run(&["requeue-stale"]).await.unwrap();
Expand Down
Loading
Loading