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
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `cargo hammerwork backup create` writes format `2.0`: every column, with `priority` as its numeric level. `backup restore` still reads `1.0` files.
- `cargo hammerwork job enqueue`, `batch enqueue`, `cron create` and `workflow create` fail with an error when they would store a plaintext job on a queue that holds encrypted jobs, or when the configured encryption key cannot be loaded; `hammerwork-web` does not start in the latter case.
- `ExternalKmsConfig`, `WebhookConfig`, `WebhookAuth`, `AlertTarget`, `StreamBackend`, `DatabaseConfig`, `cargo_hammerwork::config::Config`, `hammerwork_web::DashboardConfig` and `AuthConfig` implement `Debug` by hand (secrets redacted) instead of deriving it. `cargo_hammerwork::config::Config` has a new `encryption_config` field.
- **`WorkerPool::new()` no longer autoscales** ([#64](https://github.com/CodingAnarchy/hammerwork/issues/64) H9). Autoscaling is enabled only by `with_autoscaling(...)` or `WorkerPool::from_config` with `worker.autoscaling_enabled`. `AutoscaleConfig::default()` and the presets are still enabled, so `with_autoscaling(AutoscaleConfig::default())` keeps working.
- **Alerts are checked by the worker's monitoring task, not its polling loop** ([#64](https://github.com/CodingAnarchy/hammerwork/issues/64) H10): queue depth, worker starvation, error rate and processing time alerts are evaluated every `Worker::with_monitoring_interval` (new, default 30 seconds) instead of on every poll.
- **The rate limiter only spends a token when a job is claimed** ([#64](https://github.com/CodingAnarchy/hammerwork/issues/64) M6). New `RateLimiter::refund` and `TokenBucket::refund`.
- **Zero durations** ([#64](https://github.com/CodingAnarchy/hammerwork/issues/64) M5): `HammerworkConfig::from_file` / `from_env` and `WorkerPool::from_hammerwork_config` reject `worker.polling_interval = 0` and `worker.job_timeout = 0` (new `WorkerConfig::validate`). `Worker::with_poll_interval` waits at least `MIN_POLL_INTERVAL` (10ms) between idle polls, and `with_default_timeout(Duration::ZERO)` means no default timeout.
- `DatabaseQueue::heartbeat_job` takes the run (`&Job` as dequeued) instead of a job id, and `RecordedOutcome` has a new `spawned` field.
- CLI `cron enable` / `cron disable` use the library's `enable_recurring_job` / `disable_recurring_job` (see Fixed).
- **CLI flag consistency** ([#61](https://github.com/CodingAnarchy/hammerwork/issues/61)); old spellings keep working as aliases:
- `queue` commands take `-u/--database-url` like every other group (`-d` remains as a hidden alias).
- The queue filter is `-n/--queue` everywhere (`job purge`, `spawn list/stats/pending/monitor`, `archive run/list/stats`); `-Q` and `archive --queue-name` still work.
Expand Down Expand Up @@ -147,6 +153,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `tracing`: `shutdown_tracing()` now flushes and shuts down the provider installed by `init_tracing()` (OpenTelemetry 0.33 removed the global shutdown hook). Code that uses the `opentelemetry` crates directly alongside Hammerwork must move to 0.33.

### Fixed
- **Job lifecycle hardening** ([#64](https://github.com/CodingAnarchy/hammerwork/issues/64) C1, C2, H3, H9, H10, M1, M2, M5, M6, M8, M10):
- **C1: the stale job reaper no longer reclaims jobs that are still running.** A claim wrote no lease, so until the worker's first heartbeat (a third of its lease in) any reaper with a shorter staleness window, such as another pool's or `cargo hammerwork job requeue-stale --older-than-secs N`, moved the running job back to `Pending` and it ran twice. The claim now writes `lease_expires_at` (and `last_heartbeat_at`) in the same statement on PostgreSQL, MySQL and `TestQueue`, and the reaper reclaims a job only once its lease expired; `older_than` only applies to jobs claimed by older versions without a lease. New `DatabaseQueue::dequeue_leased(queue, weights, lease)` (workers pass their lease; `dequeue` takes `queue::DEFAULT_LEASE_DURATION`, 5 minutes). A zero lease never expires (the reaper leaves the job alone; it used to be reclaimed after the pool's fallback window). `heartbeat_job` only extends the run it belongs to (same `attempts` and `started_at`), so a worker whose job was reclaimed and re-run elsewhere gets `false` and no longer keeps the new run's lease alive. No migration: the columns come from `015_add_job_leases`.
- **C2: spawned children are no longer lost.** The worker completed the parent and only then enqueued its children one at a time, so a database error, a spawn handler error, `SpawnLimitExceeded`, a crash or a shutdown left a `Completed` parent with some or none of its children. The children are now built before the completion (`SpawnManager::prepare_spawn`) and enqueued in the same transaction that completes the parent (new `DatabaseQueue::complete_job_run_with_children`); any spawn failure fails the parent's run, so it is retried. `on_spawn_complete` runs after the commit. The completion hook no longer fires twice for spawning jobs.
- **H3: concurrent migrations no longer fail.** `MigrationManager::run_migrations` holds a migration lock for the whole run (`pg_advisory_lock` on PostgreSQL, `GET_LOCK` on MySQL, on a dedicated connection that runs every statement), re-reads the applied migrations after acquiring it, and releases it on every path. Several replicas with `auto_migrate`, or the CLI and an application, can migrate at once. Recording a migration ignores an existing row. New `MigrationRunner::acquire_migration_lock` / `release_migration_lock` (default: no lock). The PostgreSQL runner checks for the tracking table in `current_schema()` instead of `public`.
- **H9: autoscaling only starts or retires workers of the queue it scales** (the template's, or the first worker's). It used to retire the highest-index workers whatever their queue, so other queues stopped being processed.
- **H10: a slow or failing alert target no longer stalls job processing.** Alert HTTP requests time out after `alerting::ALERT_HTTP_TIMEOUT` (10 seconds), and an alert that reached no target is retried after `FAILED_ALERT_RETRY_DELAY` (60 seconds, or the cooldown if shorter) instead of on every check.
- **M1: `disable_recurring_job` stops the next run, and `enable_recurring_job` revives a finished job.** Disabling used to leave the pending occurrence runnable; it is now held (a job with a cron schedule is only dequeued while it is recurring) and `next_run_at` is cleared. Enabling reschedules the job for the next occurrence after now (`Pending`, attempts reset) unless it is running, so a job whose last run finished while disabled runs again. Both report `JobNotFound` for missing jobs and an error for jobs without a cron schedule, on every backend.
- **M2:** the `Worker::with_max_retries` example claimed it raises the attempt limit; it can only lower it. `Worker::new` no longer documents a 3-attempt cap.
- **M5:** the 500ms default `polling_interval` was saved to TOML as `"0s"` and loaded back as zero; durations with sub-second precision are now written in milliseconds (`"500ms"`), and `ms` is accepted when parsing.
- **M6:** the token bucket dropped the sub-millisecond part of the elapsed time on every refill, so frequent checks refilled slower than the configured rate.
- **M8:** a worker with a metrics collector no longer runs `COUNT(*)` for the queue depth on every poll; the monitoring task already updates it.
- **M10:** a worker's monitoring task is aborted however `run` ends (an error, a panic, or the future being dropped), so supervisor restarts no longer leak monitoring loops.
- `TestQueue::mark_job_dead` and `mark_job_timed_out` apply the workflow failure policy and a fail-fast batch's failure like the database backends, `TestQueue::finish_job_run` reports the jobs failed with a run in `RecordedOutcome::cancelled`, and a stale job the `TestQueue` reaper marks `Dead` applies the policy too.
- The CLI no longer hangs when the database is unreachable: connecting gives up after 10 seconds with a clear error. Configure with `connect_timeout_secs` in `config.toml`, `cargo hammerwork config set connect_timeout_secs N`, or `HAMMERWORK_CONNECT_TIMEOUT`.
- **Queue failure semantics are the same on every backend** ([#59](https://github.com/CodingAnarchy/hammerwork/issues/59)):
- PostgreSQL/MySQL `fail_job_dependencies` now applies the workflow's `FailurePolicy`, as documented. It used to fail the failed job's dependents under every policy: under `Manual` it failed jobs that should keep waiting, and under `FailFast` it left the workflow's other pending jobs and its status alone. It now locks the job and its workflow like a terminal transition, applies `FailFast` (the workflow's `Pending`/`Retrying` jobs and all dependents fail, workflow `failed`), `ContinueOnFailure` (only the transitive dependents fail) or `Manual` (nothing changes), and updates the workflow's counters and status.
Expand Down
10 changes: 7 additions & 3 deletions cargo-hammerwork/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,10 @@ cargo hammerwork job requeue-stale --older-than-secs 3600
- `job purge` needs at least one of `--completed`, `--dead`, `--failed`, optionally
narrowed with `--queue` and `--older-than-days`, plus `--confirm`.
- `job requeue-stale` moves `Running` jobs whose lease has expired (their worker crashed
or was killed) back to `Pending`, or to `Dead` when they have no attempts left. Jobs
that never recorded a lease are reclaimed once they started more than
or was killed) back to `Pending`, or to `Dead` when they have no attempts left. Workers
take the lease when they claim a job, so a job whose worker is alive is never
reclaimed, whatever `--older-than-secs` is. Only jobs without a lease (claimed by an
older Hammerwork version) are reclaimed by age, once they started more than
`--older-than-secs` ago (default 3600). It is safe to run alongside workers, and needs
migration `015_add_job_leases`.
- `job show` prints the redacted payload of an encrypted job (the CLI never decrypts)
Expand Down Expand Up @@ -299,7 +301,9 @@ cargo hammerwork cron delete <job-id> --confirm
`cron create` requires `--queue`, `--payload` and `--schedule`. Cron expressions have a
leading seconds field (six fields, e.g. `0 0 9 * * MON-FRI`). `cron next` shows 10
executions unless `--count` is given. There is no `cron add` or `cron remove`; use
`create` and `delete`.
`create` and `delete`. `cron disable` holds the job's pending run until `cron enable`,
which resumes it at the next occurrence of its schedule (also when its last run finished
while it was disabled).

### Maintenance Commands

Expand Down
47 changes: 35 additions & 12 deletions cargo-hammerwork/src/commands/cron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,23 @@ pub enum CronCommand {
#[arg(short = 'r', long, help = "Job priority")]
priority: Option<String>,
},
#[command(about = "Enable cron job execution")]
#[command(
about = "Enable a cron job",
long_about = "Enable a cron job. It resumes at the next occurrence of its schedule \
(occurrences missed while it was disabled are not run), also when its last run \
finished while it was disabled. A run in progress is rescheduled when it ends."
)]
Enable {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
#[arg(help = "Job ID")]
job_id: String,
},
#[command(about = "Disable cron job execution")]
#[command(
about = "Disable a cron job",
long_about = "Disable a cron job. Its pending run is held (not executed) until the \
job is enabled again; a run in progress finishes and is not rescheduled."
)]
Disable {
#[arg(short = 'u', long, help = "Database connection URL")]
database_url: Option<String>,
Expand Down Expand Up @@ -388,19 +397,33 @@ async fn create_cron_job(
Ok(())
}

/// Enable or disable a cron job through the library (`enable_recurring_job` /
/// `disable_recurring_job`), so the CLI has the same semantics as applications: a
/// disabled job's pending run is held, and enabling resumes it at the next occurrence,
/// also after its last run finished while it was disabled.
async fn toggle_cron_job(pool: &DatabasePool, job_id: &str, enable: bool) -> Result<()> {
let id = parse_job_id(job_id)?.to_string();
let id = parse_job_id(job_id)?;
let status = if enable { "enabled" } else { "disabled" };

let mut params = SqlParams::new(pool.backend());
let id_expr = params.uuid(&id);
let flag = if enable { "true" } else { "false" };
let sql = format!(
"UPDATE hammerwork_jobs SET recurring = {flag} WHERE id = {id_expr} AND cron_schedule IS NOT NULL"
);
let updated = execute_binds(pool, &sql, params.binds()).await?;
if updated == 0 {
return Err(anyhow!("Cron job not found: {}", job_id));
let result = match (pool.clone().create_job_queue(), enable) {
(JobQueueWrapper::Postgres(q), true) => q.enable_recurring_job(id).await,
(JobQueueWrapper::Postgres(q), false) => q.disable_recurring_job(id).await,
(JobQueueWrapper::MySQL(q), true) => q.enable_recurring_job(id).await,
(JobQueueWrapper::MySQL(q), false) => q.disable_recurring_job(id).await,
};
match result {
Ok(()) => {}
Err(hammerwork::HammerworkError::JobNotFound { .. }) => {
return Err(anyhow!("Cron job not found: {}", job_id));
}
Err(e) => {
return Err(anyhow!(
"Cannot {} job {}: {}",
&status[..status.len() - 1],
job_id,
e
));
}
}

println!("✅ Cron job {} successfully", status);
Expand Down
11 changes: 7 additions & 4 deletions cargo-hammerwork/src/commands/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,12 @@ pub enum JobCommand {
#[command(
about = "Reclaim jobs stuck in Running after a worker crashed",
long_about = "Reclaim jobs left in Running by workers that crashed or were killed.\n\n\
A Running job is stale when its lease (renewed by worker heartbeats) has \
expired, or, if it never recorded a lease, when it started more than \
--older-than-secs ago. Stale jobs with attempts left go back to Pending; \
A Running job is stale when its lease has expired. Workers take the lease \
when they claim a job and renew it with heartbeats, so a job whose worker \
is alive is never reclaimed, whatever --older-than-secs is. Only a job \
without a lease (claimed by an older Hammerwork version) is reclaimed by \
age, when it started more than --older-than-secs ago. Stale jobs with \
attempts left go back to Pending; \
the rest are marked Dead. Safe to run while workers and other reapers are \
running. Requires migration 015_add_job_leases.\n\n\
Example: cargo hammerwork job requeue-stale --older-than-secs 3600"
Expand All @@ -166,7 +169,7 @@ pub enum JobCommand {
#[arg(
long,
default_value_t = 3600,
help = "For jobs without a lease: reclaim if started more than N seconds ago"
help = "For jobs without a lease (claimed by older versions): reclaim if started more than N seconds ago"
)]
older_than_secs: u64,
},
Expand Down
18 changes: 16 additions & 2 deletions docs/cron-scheduling.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,10 +323,10 @@ for job in &recurring_jobs {
println!("Recurring job: {} - Next run: {:?}", job.id, job.next_run_at);
}

// Stop future executions
// Stop future executions: a pending run is held, a running one is not rescheduled
queue.disable_recurring_job(job_id).await?;

// Resume
// Resume at the next occurrence (also revives a job whose last run finished meanwhile)
queue.enable_recurring_job(job_id).await?;

// Move a job back to Pending at an explicit time
Expand All @@ -336,6 +336,20 @@ queue.reschedule_cron_job(job_id, next).await?;
# }
```

Disabling and enabling:

- `disable_recurring_job` clears `recurring` and `next_run_at`. If the job's next run is
pending, it stays `Pending` but is held: a job with a cron schedule is only dequeued
while it is recurring. A run already in progress finishes and is then not
rescheduled (it ends `Completed`, `Dead` or `TimedOut`). Disabling a disabled job does
nothing.
- `enable_recurring_job` sets `recurring` again and, unless the job is `Running` (that
run's outcome reschedules it), schedules it for the next occurrence of its schedule
after now: `Pending`, attempts reset. This also revives a job whose last run finished
while it was disabled. Occurrences missed while it was disabled are not run.
- Both fail with `JobNotFound` for a missing job and with an error for a job without a
cron schedule. `cargo hammerwork cron disable|enable <JOB_ID>` call them.

### Job Lifecycle

To run a cron-timed job only once, do not give it a schedule: compute the time from the
Expand Down
11 changes: 7 additions & 4 deletions docs/job-spawning.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ The spawning system provides:
3. The worker looks up the spawn handler registered for the job's **queue name**. If there is none, nothing is spawned.
4. The handler's `validate_spawn` is called, then `spawn_jobs` returns the child jobs.
5. If the number of children exceeds `max_spawn_count`, the operation fails with `SpawnError::SpawnLimitExceeded` and nothing is enqueued.
6. The manager applies the inheritance settings, sets each child's `depends_on` to the parent, copies the parent's workflow, enqueues the children and calls `on_spawn_complete`.
6. The manager applies the inheritance settings, sets each child's `depends_on` to the parent and copies the parent's workflow (`SpawnManager::prepare_spawn`).
7. The worker completes the parent and enqueues the children **in one transaction** (`DatabaseQueue::complete_job_run_with_children`), then calls `on_spawn_complete`.

A failure to spawn is logged by the worker; it does not fail the parent job, which has already completed.
Spawning is part of the parent's run. If the spawn handler fails, the spawn limit is exceeded, the `_spawn_config` is malformed or a child cannot be enqueued, nothing is written: the parent is not completed and none of its children exist, and the run fails like a handler error, so the parent is retried (or ends `Dead` once it is out of attempts). A crash between the two steps cannot leave a completed parent without its children either. Spawn handlers should therefore be deterministic and free of side effects: a retried parent calls them again. An error from `on_spawn_complete`, which runs after the commit, is only logged.

`SpawnManager::execute_spawn` remains for code that spawns outside a worker; it enqueues the children one at a time and does not complete the parent.

## Key Concepts

Expand Down Expand Up @@ -463,12 +466,12 @@ The web dashboard has no spawn endpoints; spawn trees are available from the CLI
2. **Set operation IDs** so spawn operations can be traced in `SpawnResult`.
3. **Size `max_spawn_count`** to the largest fan-out you expect.
4. **Bound recursion yourself**: children that carry their own `_spawn_config` can spawn further, so track depth in the payload if you need a limit.
5. **Handle spawn failures**: they are logged, not retried, and do not fail the parent.
5. **Keep spawn handlers retry-safe**: a spawn failure fails the parent's run, so the parent (and its spawn handler) runs again.
6. **Test with both databases** if you run both.

## Error Handling

Return a `HammerworkError` (for example a `SpawnError` wrapped in `HammerworkError::SpawnError`) to abort a spawn:
Return a `HammerworkError` (for example a `SpawnError` wrapped in `HammerworkError::SpawnError`) to abort a spawn. Nothing is enqueued and the parent's run fails, so it is retried like any failed run:

```rust,no_run
# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue;
Expand Down
Loading
Loading