diff --git a/CHANGELOG.md b/CHANGELOG.md index cc03b82..c86bb7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. @@ -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. diff --git a/cargo-hammerwork/README.md b/cargo-hammerwork/README.md index 9847ade..30f0b5b 100644 --- a/cargo-hammerwork/README.md +++ b/cargo-hammerwork/README.md @@ -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) @@ -299,7 +301,9 @@ cargo hammerwork cron delete --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 diff --git a/cargo-hammerwork/src/commands/cron.rs b/cargo-hammerwork/src/commands/cron.rs index a5466f7..c44f7ce 100644 --- a/cargo-hammerwork/src/commands/cron.rs +++ b/cargo-hammerwork/src/commands/cron.rs @@ -45,14 +45,23 @@ pub enum CronCommand { #[arg(short = 'r', long, help = "Job priority")] priority: Option, }, - #[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, #[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, @@ -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); diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index 084dd41..2f07c5e 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -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" @@ -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, }, diff --git a/docs/cron-scheduling.md b/docs/cron-scheduling.md index aa4ea93..e3d77e8 100644 --- a/docs/cron-scheduling.md +++ b/docs/cron-scheduling.md @@ -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 @@ -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 ` call them. + ### Job Lifecycle To run a cron-timed job only once, do not give it a schedule: compute the time from the diff --git a/docs/job-spawning.md b/docs/job-spawning.md index 4068bed..9c357ac 100644 --- a/docs/job-spawning.md +++ b/docs/job-spawning.md @@ -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 @@ -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; diff --git a/docs/migrations.md b/docs/migrations.md index 0cdfc00..9740653 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -102,6 +102,29 @@ All migrations are designed to be idempotent - you can run them multiple times s - Uses `ADD COLUMN IF NOT EXISTS` for PostgreSQL column additions - Checks for existing columns before adding them in MySQL +### Concurrent Runs + +Several processes may migrate the same database at once: every replica of a service +starting with `auto_migrate`, or `cargo hammerwork migration run` while the application +starts. `MigrationManager::run_migrations` serializes them with a database lock held +for the whole run: + +- PostgreSQL: a session-level `pg_advisory_lock` (key `0x686d72776b6d6967`, per + database); +- MySQL: `GET_LOCK` on `hammerwork_migrations:` followed by the SHA-1 of the database + name (lock names are server-wide), waiting up to 10 minutes. + +The lock is taken on a dedicated connection that also runs every statement of the +run, and the list of applied migrations is read only after it is acquired, so a run +that waited sees what the previous one applied and runs nothing twice. The lock is +released when the run ends, also after an error; if the run is abandoned the +connection is closed, which releases it too. Recording a migration also ignores a row +that already exists (`ON CONFLICT DO NOTHING` / `INSERT IGNORE`), for runs by older +Hammerwork versions that take no lock. + +A custom `MigrationRunner` can take part by implementing `acquire_migration_lock` and +`release_migration_lock`; the default implementations take no lock. + ### Tracking The migration system creates a `hammerwork_migrations` table to track which migrations have been executed: diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index f71c55c..3da4255 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -21,6 +21,11 @@ let worker = Worker::new(queue, "email_queue".to_string(), handler) `handler` is a `JobHandler`: an `Arc` of a function from `Job` to a boxed future returning `hammerwork::Result<()>`. +An idle worker waits the poll interval between polls, and never less than 10ms +(`worker::MIN_POLL_INTERVAL`), so a zero interval cannot make it poll in a tight loop. +`HammerworkConfig` rejects `worker.polling_interval = 0` (and `worker.job_timeout = 0`) +when it is loaded. + ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; # #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] @@ -64,6 +69,11 @@ let worker = Worker::new(queue, "processing_queue".to_string(), handler) 2. **Worker default timeout** 3. **No timeout** (job runs until completion) +`with_default_timeout(Duration::ZERO)` means no default timeout. A worker built with +`Worker::with_config` or `with_hammerwork_config` uses `worker.job_timeout` (5 minutes +by default) as its default timeout, so every job without its own timeout is limited to +it. + ## Priority Configuration ### Weighted Priority Scheduling @@ -125,6 +135,10 @@ let worker = Worker::new(queue, "api_queue".to_string(), handler) # } ``` +A worker takes a token before it polls and hands it back when the poll claims no job +(the queue is empty or paused), so only claimed jobs spend the rate limit and the +full burst is available when jobs arrive after an idle period. + ### Advanced Throttling `ThrottleConfig` combines a concurrency cap, a rate limit and a pause after errors: @@ -212,11 +226,21 @@ let alerting_config = AlertingConfig::new() .with_cooldown(Duration::from_secs(300)); let worker = Worker::new(queue, "production_queue".to_string(), handler) - .with_alerting_config(alerting_config); + .with_alerting_config(alerting_config) + // How often thresholds are checked (default 30 seconds) + .with_monitoring_interval(Duration::from_secs(30)); # Ok(()) # } ``` +Alert thresholds (and the queue depth metric) are checked by a background monitoring +task every `with_monitoring_interval` (30 seconds by default), never in the loop that +dequeues jobs, so a slow or unreachable alert target cannot hold up job processing. +Webhook and Slack alerts time out after 10 seconds. An alert that reached no target is +retried after 60 seconds (or the cooldown, if shorter) instead of on every check; one +that was delivered starts the cooldown. The monitoring task stops with the worker, +however the worker stops. + ## Worker Pools ### Basic Pool Management @@ -268,6 +292,39 @@ tokio::select! { Dropping the pool also shuts its workers down gracefully. +### Autoscaling + +A `WorkerPool` does not autoscale unless you enable it with `with_autoscaling` (or +`WorkerPool::from_config` with `worker.autoscaling_enabled = true`). Autoscaling scales +a single queue: that of the worker template (`with_worker_template`), or of the first +worker added. It measures that queue's depth, starts clones of the template while the +queue is deep (up to `max_workers`), and retires workers of that queue (down to +`min_workers`) once it drains. Workers of other queues in the same pool are never +started or retired. A retired worker stops like on shutdown: it finishes its in-flight +job within its shutdown grace period. + +```rust,no_run +# #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; +# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)] +# async fn doc(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler, payload: serde_json::Value, job: hammerwork::Job) -> std::result::Result<(), Box> { +use hammerwork::{Worker, WorkerPool, worker::AutoscaleConfig}; + +let mut pool = WorkerPool::new().with_autoscaling( + AutoscaleConfig::new() + .with_min_workers(1) + .with_max_workers(8) + .with_scale_up_threshold(10), // queued jobs per worker before scaling up +); +// The first worker is the template: only "email" is scaled. +pool.add_worker(Worker::new(queue.clone(), "email".to_string(), handler.clone())); +// Always exactly one "reports" worker. +pool.add_worker(Worker::new(queue.clone(), "reports".to_string(), handler.clone())); +# Ok(()) +# } +``` + +To scale several queues, run one pool per queue. + ### Supervision If a worker task stops unexpectedly (a bug that panics outside a job handler, for @@ -306,17 +363,27 @@ let worker = Worker::new(queue.clone(), "reports".to_string(), handler) A worker that crashes, is OOM-killed or loses its pod leaves its job in `Running`. Hammerwork recovers these jobs with leases (requires migration `015_add_job_leases`): -- While a handler runs, the worker records a heartbeat and extends the job's lease - every third of its lease duration (5 minutes by default). Jobs that finish sooner - never write a heartbeat. -- `DatabaseQueue::requeue_stale_jobs(older_than)` reclaims `Running` jobs whose - lease has expired. Jobs that never recorded a lease (they had not reached their - first heartbeat, or were started by an older Hammerwork version) count as stale - once they started more than `older_than` ago. +- A worker takes the lease in the same statement that claims the job + (`DatabaseQueue::dequeue_leased`; plain `dequeue` takes the default 5 minute lease). + While the handler runs, the worker records a heartbeat and extends the lease every + third of its lease duration (5 minutes by default). Jobs that finish sooner never + write a heartbeat. +- A heartbeat only extends the run it belongs to (same attempt and start time): a + worker whose job was reclaimed and picked up by another worker cannot keep the new + run's lease alive. +- `DatabaseQueue::requeue_stale_jobs(older_than)` reclaims `Running` jobs whose lease + has expired. A job whose lease is valid is never reclaimed, whatever `older_than` is, + so pools with different lease durations (or `cargo hammerwork job requeue-stale + --older-than-secs 1`) can share a database safely. `older_than` only applies to jobs + claimed by an older Hammerwork version that did not take a lease at claim time: + they count as stale once they started more than `older_than` ago. - A reclaimed job goes back to `Pending` and runs again immediately. The interrupted run already counted as an attempt; a job with no attempts left is moved to `Dead`. - Every `WorkerPool` runs this reaper every 60 seconds, with `older_than` set to the longest lease of its workers. Several pools or processes can reap at once safely. +- `with_lease_duration(Duration::ZERO)` takes a lease that never expires and sends no + heartbeats: the reaper never reclaims that worker's jobs, so if it dies an operator + has to re-run them (`cargo hammerwork job retry`). ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; diff --git a/docs/workflows.md b/docs/workflows.md index ec1961e..aa58a9d 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -310,11 +310,11 @@ on the failed job, directly or transitively, are marked `Failed` with `Job::depends_on` outside a workflow behave like `ContinueOnFailure`. `queue.fail_job_dependencies(job_id)` applies the same policy explicitly (and updates the -workflow's counters and status), and returns the jobs it failed. On PostgreSQL and -MySQL every terminal transition already applies it, so after one it finds nothing left -to do. `TestQueue` applies the policies the same way, from `fail_job`, from a worker's -`finish_job_run` and from `fail_job_dependencies`; its `mark_job_dead` and -`mark_job_timed_out` only change the job's status. +workflow's counters and status), and returns the jobs it failed. Every terminal +transition (`fail_job`, `mark_job_dead`, `mark_job_timed_out`, a worker's +`finish_job_run` and a stale job the reaper marks `Dead`) already applies it, so after +one it finds nothing left to do. `TestQueue` applies the policies the same way as +PostgreSQL and MySQL. ## Workflow Management diff --git a/src/alerting.rs b/src/alerting.rs index f2cc9de..63eb261 100644 --- a/src/alerting.rs +++ b/src/alerting.rs @@ -4,6 +4,14 @@ use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc, time::Duration}; use tokio::sync::RwLock; +/// Timeout of a whole webhook or Slack alert request (connect, send and response). +pub const ALERT_HTTP_TIMEOUT: Duration = Duration::from_secs(10); + +/// How long an alert that could not be delivered to any target waits before it is +/// tried again (at most the cooldown period), so a failing endpoint is not retried on +/// every check. +pub const FAILED_ALERT_RETRY_DELAY: Duration = Duration::from_secs(60); + /// Configuration for alerting thresholds and targets #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AlertingConfig { @@ -453,10 +461,31 @@ pub struct Alert { /// Type alias for last alerts storage type LastAlertsStorage = Arc>>>; +/// The HTTP client for webhook and Slack alerts: every request is bounded by +/// [`ALERT_HTTP_TIMEOUT`], so a hanging endpoint cannot stall the caller. +#[cfg(feature = "alerting")] +fn alert_http_client() -> reqwest::Client { + alert_http_client_with_timeout(ALERT_HTTP_TIMEOUT) +} + +#[cfg(feature = "alerting")] +fn alert_http_client_with_timeout(timeout: Duration) -> reqwest::Client { + reqwest::Client::builder() + .timeout(timeout) + .connect_timeout(timeout) + .build() + .unwrap_or_else(|e| { + tracing::error!("Failed to build the alert HTTP client with a timeout: {e}"); + reqwest::Client::new() + }) +} + /// Alert manager for monitoring thresholds and sending notifications pub struct AlertManager { config: AlertingConfig, last_alerts: LastAlertsStorage, + /// When each alert last failed to reach any target + failed_alerts: LastAlertsStorage, #[cfg(feature = "alerting")] http_client: reqwest::Client, } @@ -474,8 +503,9 @@ impl AlertManager { Self { config, last_alerts: Arc::new(RwLock::new(HashMap::new())), + failed_alerts: Arc::new(RwLock::new(HashMap::new())), #[cfg(feature = "alerting")] - http_client: reqwest::Client::new(), + http_client: alert_http_client(), } } @@ -664,6 +694,19 @@ impl AlertManager { } } } + // An alert that reached no target is retried after a shorter delay. + { + let failed_alerts = self.failed_alerts.read().await; + if let Some(failed_at) = failed_alerts.get(&alert_key) { + let retry_delay = chrono::Duration::from_std( + FAILED_ALERT_RETRY_DELAY.min(self.config.cooldown_period), + ) + .unwrap_or(chrono::Duration::MAX); + if Utc::now() - *failed_at < retry_delay { + return Ok(()); + } + } + } // Send alert to all targets let mut failures = Vec::new(); @@ -674,11 +717,18 @@ impl AlertManager { } } - // Start the cooldown only once some target was reached, so an alert that - // could not be delivered anywhere is tried again on the next check. + // Start the cooldown only once some target was reached. An alert that could not + // be delivered anywhere is tried again after FAILED_ALERT_RETRY_DELAY (or the + // cooldown, if shorter), not on every check. if failures.len() < self.config.targets.len() || self.config.targets.is_empty() { + self.failed_alerts.write().await.remove(&alert_key); let mut last_alerts = self.last_alerts.write().await; last_alerts.insert(alert_key, alert.timestamp); + } else { + self.failed_alerts + .write() + .await + .insert(alert_key, Utc::now()); } if failures.is_empty() { @@ -1660,11 +1710,52 @@ mod tests { let err = manager.check_queue_depth("q", 5).await.unwrap_err(); assert!(err.to_string().contains("500"), "{err}"); next_request(&mut requests).await; - // Not delivered anywhere, so the next check tries again. + assert!(manager.last_alerts.read().await.is_empty()); + // Not delivered anywhere: the next check within the retry delay does not hit the + // failing endpoint again. + manager.check_queue_depth("q", 5).await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(200), requests.recv()) + .await + .is_err(), + "a failed alert was retried on the next check" + ); + + // With a cooldown shorter than the retry delay, the cooldown applies. + let manager = AlertManager::new( + AlertingConfig::new() + .alert_on_queue_depth(1) + .webhook(&url) + .with_cooldown(Duration::ZERO), + ); + assert!(manager.check_queue_depth("q", 5).await.is_err()); + next_request(&mut requests).await; assert!(manager.check_queue_depth("q", 5).await.is_err()); next_request(&mut requests).await; } + #[tokio::test] + async fn test_hanging_webhook_times_out() { + // Accepts connections and never answers. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/alert", listener.local_addr().unwrap()); + tokio::spawn(async move { + let mut open = Vec::new(); + while let Ok((socket, _)) = listener.accept().await { + open.push(socket); + } + }); + let mut manager = + AlertManager::new(AlertingConfig::new().alert_on_queue_depth(1).webhook(&url)); + // The same client as ALERT_HTTP_TIMEOUT, with a timeout short enough for a test. + manager.http_client = alert_http_client_with_timeout(Duration::from_millis(200)); + let result = + tokio::time::timeout(Duration::from_secs(5), manager.check_queue_depth("q", 5)) + .await + .expect("the alert request did not time out"); + assert!(result.is_err()); + } + #[tokio::test] async fn test_unreachable_webhook_is_an_error() { let manager = AlertManager::new( diff --git a/src/config.rs b/src/config.rs index e16b98f..65d0492 100644 --- a/src/config.rs +++ b/src/config.rs @@ -43,7 +43,12 @@ mod duration_secs { S: Serializer, { let secs = duration.as_secs(); - if secs == 0 { + if duration.subsec_nanos() != 0 { + // Sub-second precision (e.g. the default 500ms polling interval) is kept in + // milliseconds; whole seconds would round it down, to zero for short ones. + let millis = duration.as_millis().max(1); + serializer.serialize_str(&format!("{millis}ms")) + } else if secs == 0 { serializer.serialize_str("0s") } else if secs.is_multiple_of(3600) { serializer.serialize_str(&format!("{}h", secs / 3600)) @@ -64,7 +69,7 @@ mod duration_secs { parse_duration(&s).map_err(D::Error::custom) } - /// Parse a duration string like "30s", "5m", "1h", "90", etc. + /// Parse a duration string like "500ms", "30s", "5m", "1h", "90", etc. fn parse_duration(s: &str) -> Result { let s = s.trim(); @@ -73,6 +78,14 @@ mod duration_secs { return Ok(Duration::from_secs(secs)); } + if let Some(millis) = s.strip_suffix("ms") { + let millis: u64 = millis + .trim() + .parse() + .map_err(|_| format!("Invalid number in duration: {}", millis))?; + return Ok(Duration::from_millis(millis)); + } + // Handle suffixed durations if s.len() < 2 { return Err(format!("Invalid duration format: {}", s)); @@ -292,6 +305,7 @@ impl HammerworkConfig { pub fn from_file(path: &str) -> crate::Result { let content = std::fs::read_to_string(path)?; let config: Self = toml::from_str(&content)?; + config.worker.validate()?; config.validate_delivery_targets()?; Ok(config) } @@ -345,6 +359,7 @@ impl HammerworkConfig { } config.encryption.apply_env()?; + config.worker.validate()?; Ok(config) } @@ -474,11 +489,14 @@ pub struct WorkerConfig { /// Number of workers in the pool pub pool_size: usize, - /// Polling interval for checking new jobs + /// Polling interval for checking new jobs. Must be greater than zero (see + /// [`WorkerConfig::validate`]). #[serde(with = "duration_secs")] pub polling_interval: StdDuration, - /// Default job timeout + /// Default job timeout, applied by [`Worker::with_config`](crate::Worker::with_config) + /// to every job that has no timeout of its own (default 5 minutes). Must be greater + /// than zero (see [`WorkerConfig::validate`]). #[serde(with = "duration_secs")] pub job_timeout: StdDuration, @@ -518,6 +536,25 @@ impl Default for WorkerConfig { } impl WorkerConfig { + /// Reject settings that cannot work: a zero `polling_interval` (idle workers would + /// poll in a tight loop) or a zero `job_timeout` (every job would time out before + /// its handler ran). Called when a configuration is loaded + /// ([`HammerworkConfig::from_file`], [`HammerworkConfig::from_env`]) and by + /// [`WorkerPool::from_hammerwork_config`](crate::WorkerPool::from_hammerwork_config). + pub fn validate(&self) -> crate::Result<()> { + if self.polling_interval.is_zero() { + return Err(crate::HammerworkError::Config( + "worker.polling_interval must be greater than zero".to_string(), + )); + } + if self.job_timeout.is_zero() { + return Err(crate::HammerworkError::Config( + "worker.job_timeout must be greater than zero".to_string(), + )); + } + Ok(()) + } + /// Build the [`AutoscaleConfig`] described by this configuration. /// /// Returns a disabled autoscale configuration unless `autoscaling_enabled` is set. @@ -1341,6 +1378,47 @@ mod tests { } } + /// #64 M5: zero durations that would hot-loop or time every job out are rejected. + #[test] + fn test_zero_worker_durations_are_rejected() { + assert!(WorkerConfig::default().validate().is_ok()); + let zero_poll = WorkerConfig { + polling_interval: StdDuration::ZERO, + ..WorkerConfig::default() + }; + let err = zero_poll.validate().unwrap_err().to_string(); + assert!(err.contains("polling_interval"), "{err}"); + let zero_timeout = WorkerConfig { + job_timeout: StdDuration::ZERO, + ..WorkerConfig::default() + }; + let err = zero_timeout.validate().unwrap_err().to_string(); + assert!(err.contains("job_timeout"), "{err}"); + + // The default 500ms polling interval survives a save and load (it used to be + // written as "0s", which loaded as a zero interval). + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("default.toml"); + HammerworkConfig::new() + .save_to_file(path.to_str().unwrap()) + .unwrap(); + let loaded = HammerworkConfig::from_file(path.to_str().unwrap()).unwrap(); + assert_eq!( + loaded.worker.polling_interval, + StdDuration::from_millis(500) + ); + + // Loading a file with a zero interval fails. + let path = dir.path().join("zero.toml"); + let mut config = HammerworkConfig::new(); + config.worker.polling_interval = StdDuration::ZERO; + config.save_to_file(path.to_str().unwrap()).unwrap(); + assert!(matches!( + HammerworkConfig::from_file(path.to_str().unwrap()), + Err(crate::HammerworkError::Config(_)) + )); + } + #[test] fn test_duration_serialization() { use tempfile::tempdir; diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs index a6e2b91..8d9281c 100644 --- a/src/migrations/mod.rs +++ b/src/migrations/mod.rs @@ -82,6 +82,24 @@ pub struct MigrationRecord { /// Migration runner trait for database-specific implementations #[async_trait::async_trait] pub trait MigrationRunner { + /// Take the lock that serializes migration runs on the database, waiting while + /// another process holds it. [`MigrationManager::run_migrations`] holds it for the + /// whole run and releases it with + /// [`release_migration_lock`](Self::release_migration_lock). + /// + /// The built-in runners use a session lock (`pg_advisory_lock` on PostgreSQL, + /// `GET_LOCK` on MySQL) on a dedicated connection that also runs every statement + /// of the run; if the run is abandoned the connection is closed, which releases + /// the lock. The default implementation takes no lock. + async fn acquire_migration_lock(&self) -> Result<()> { + Ok(()) + } + + /// Release the lock taken by [`acquire_migration_lock`](Self::acquire_migration_lock). + async fn release_migration_lock(&self) -> Result<()> { + Ok(()) + } + /// Run a specific migration SQL for this database type async fn run_migration(&self, migration: &Migration, sql: &str) -> Result<()>; @@ -128,10 +146,32 @@ impl MigrationManager { .insert(migration.id.clone(), (migration, postgres_sql, mysql_sql)); } - /// Run all pending migrations + /// Run all pending migrations. + /// + /// Safe to call from several processes at once (for example every replica of a + /// service starting with `auto_migrate`, or the CLI while the application starts): + /// the run holds the runner's migration lock + /// ([`MigrationRunner::acquire_migration_lock`]) from before it reads which + /// migrations were applied until the last one is recorded, so concurrent runs wait + /// for each other and each migration runs once. The lock is released on every path, + /// including errors. pub async fn run_migrations(&self) -> Result<()> { info!("Starting migration process..."); + self.runner.acquire_migration_lock().await?; + let result = self.run_pending_migrations().await; + let released = self.runner.release_migration_lock().await; + if let Err(e) = &released { + tracing::warn!("Failed to release the migration lock: {e}"); + } + result?; + released + } + + /// Apply the migrations not yet recorded, in version order. The caller holds the + /// migration lock, so the list of applied migrations is read after any concurrent + /// run finished. + async fn run_pending_migrations(&self) -> Result<()> { // Ensure migration table exists if !self.runner.migration_table_exists().await? { info!("Creating migration tracking table..."); diff --git a/src/migrations/mysql.rs b/src/migrations/mysql.rs index 08863b4..63adbea 100644 --- a/src/migrations/mysql.rs +++ b/src/migrations/mysql.rs @@ -4,26 +4,111 @@ use super::split::{Dialect, split_statements}; use super::{Migration, MigrationRecord, MigrationRunner}; use crate::Result; use chrono::Utc; -use sqlx::{Executor, MySqlPool, Row}; +use sqlx::{Executor, MySql, MySqlConnection, MySqlPool, Row, pool::PoolConnection}; +use tokio::sync::{Mutex, MutexGuard}; use tracing::{debug, info}; +/// Prefix of the `GET_LOCK` name that serializes migration runs. The SHA-1 of the +/// database name is appended, because MySQL lock names are server-wide and at most 64 +/// characters long. +pub const MIGRATION_LOCK_PREFIX: &str = "hammerwork_migrations:"; + +/// How long a run waits for another run's migration lock before failing. +pub const MIGRATION_LOCK_TIMEOUT_SECS: u32 = 600; + /// MySQL migration runner pub struct MySqlMigrationRunner { pool: MySqlPool, + /// The connection holding the migration lock while a run is in progress. Every + /// statement of the run goes through it. + locked: Mutex>>, } impl MySqlMigrationRunner { pub fn new(pool: MySqlPool) -> Self { - Self { pool } + Self { + pool, + locked: Mutex::new(None), + } + } + + /// The connection to run a statement on: the one holding the migration lock, or + /// else a pooled connection. + async fn connection(&self) -> Result> { + let guard = self.locked.lock().await; + if guard.is_some() { + return Ok(Conn::Locked(guard)); + } + drop(guard); + Ok(Conn::Pooled(self.pool.acquire().await?)) + } +} + +/// A connection for one runner operation. +enum Conn<'a> { + Locked(MutexGuard<'a, Option>>), + Pooled(PoolConnection), +} + +impl Conn<'_> { + fn get(&mut self) -> Result<&mut MySqlConnection> { + match self { + Self::Locked(guard) => guard.as_mut().map(|conn| &mut **conn).ok_or_else(|| { + crate::HammerworkError::Queue { + message: "the migration lock connection is gone".to_string(), + } + }), + Self::Pooled(conn) => Ok(&mut **conn), + } } } #[async_trait::async_trait] impl MigrationRunner for MySqlMigrationRunner { + async fn acquire_migration_lock(&self) -> Result<()> { + let mut conn = self.pool.acquire().await?; + // If the run is abandoned (an error, or its future is dropped) the connection is + // closed instead of going back to the pool, which releases the lock. + conn.close_on_drop(); + debug!("Waiting for the MySQL migration lock"); + let acquired: Option = + sqlx::query_scalar("SELECT GET_LOCK(CONCAT(?, SHA1(DATABASE())), ?)") + .bind(MIGRATION_LOCK_PREFIX) + .bind(MIGRATION_LOCK_TIMEOUT_SECS) + .fetch_one(&mut *conn) + .await?; + if acquired != Some(1) { + return Err(crate::HammerworkError::Queue { + message: format!( + "timed out after {MIGRATION_LOCK_TIMEOUT_SECS}s waiting for another \ + migration run to finish (MySQL lock {MIGRATION_LOCK_PREFIX})" + ), + }); + } + debug!("Acquired the MySQL migration lock"); + *self.locked.lock().await = Some(conn); + Ok(()) + } + + async fn release_migration_lock(&self) -> Result<()> { + let Some(mut conn) = self.locked.lock().await.take() else { + return Ok(()); + }; + // Dropping the connection closes it (close_on_drop), so the lock is released + // even if RELEASE_LOCK fails. + sqlx::query("SELECT RELEASE_LOCK(CONCAT(?, SHA1(DATABASE())))") + .bind(MIGRATION_LOCK_PREFIX) + .execute(&mut *conn) + .await?; + debug!("Released the MySQL migration lock"); + Ok(()) + } + async fn run_migration(&self, migration: &Migration, sql: &str) -> Result<()> { debug!("Executing MySQL migration: {}", migration.id); - let mut tx = self.pool.begin().await?; + let mut conn = self.connection().await?; + let mut tx = sqlx::Connection::begin(conn.get()?).await?; // Statements run exactly as written; the splitter only finds top-level `;`. let statements = split_statements(sql, Dialect::MySql); @@ -59,18 +144,20 @@ impl MigrationRunner for MySqlMigrationRunner { } async fn migration_table_exists(&self) -> Result { + let mut conn = self.connection().await?; let row = sqlx::query( - "SELECT COUNT(*) as count FROM information_schema.tables - WHERE table_schema = DATABASE() + "SELECT COUNT(*) as count FROM information_schema.tables + WHERE table_schema = DATABASE() AND table_name = 'hammerwork_migrations'", ) - .fetch_one(&self.pool) + .fetch_one(conn.get()?) .await?; Ok(row.try_get::("count")? > 0) } async fn create_migration_table(&self) -> Result<()> { + let mut conn = self.connection().await?; sqlx::query( r#" CREATE TABLE IF NOT EXISTS hammerwork_migrations ( @@ -80,7 +167,7 @@ impl MigrationRunner for MySqlMigrationRunner { ) "#, ) - .execute(&self.pool) + .execute(conn.get()?) .await?; info!("Created MySQL migration tracking table"); @@ -88,12 +175,13 @@ impl MigrationRunner for MySqlMigrationRunner { } async fn get_executed_migrations(&self) -> Result> { + let mut conn = self.connection().await?; let rows = sqlx::query( - "SELECT migration_id, executed_at, execution_time_ms - FROM hammerwork_migrations + "SELECT migration_id, executed_at, execution_time_ms + FROM hammerwork_migrations ORDER BY executed_at", ) - .fetch_all(&self.pool) + .fetch_all(conn.get()?) .await?; let mut records = Vec::new(); @@ -112,14 +200,16 @@ impl MigrationRunner for MySqlMigrationRunner { } async fn record_migration(&self, migration: &Migration, execution_time_ms: u64) -> Result<()> { + let mut conn = self.connection().await?; + // A run that does not take the lock (an older version) may have recorded it too. sqlx::query( - "INSERT INTO hammerwork_migrations (migration_id, executed_at, execution_time_ms) + "INSERT IGNORE INTO hammerwork_migrations (migration_id, executed_at, execution_time_ms) VALUES (?, ?, ?)", ) .bind(&migration.id) .bind(Utc::now()) - .bind(execution_time_ms as i64) - .execute(&self.pool) + .bind(i64::try_from(execution_time_ms).unwrap_or(i64::MAX)) + .execute(conn.get()?) .await?; debug!("Recorded MySQL migration: {}", migration.id); diff --git a/src/migrations/postgres.rs b/src/migrations/postgres.rs index e2e66b2..3823469 100644 --- a/src/migrations/postgres.rs +++ b/src/migrations/postgres.rs @@ -4,26 +4,97 @@ use super::split::{Dialect, split_statements}; use super::{Migration, MigrationRecord, MigrationRunner}; use crate::Result; use chrono::Utc; -use sqlx::{PgPool, Row}; +use sqlx::{PgConnection, PgPool, Postgres, Row, pool::PoolConnection}; +use tokio::sync::{Mutex, MutexGuard}; use tracing::{debug, error, info}; +/// Key of the session-level advisory lock that serializes migration runs on a database +/// (`pg_advisory_lock`). The ASCII bytes of "hmrwkmig". +pub const MIGRATION_LOCK_KEY: i64 = 0x686d_7277_6b6d_6967; + /// PostgreSQL migration runner pub struct PostgresMigrationRunner { pool: PgPool, + /// The connection holding the migration lock while a run is in progress. Every + /// statement of the run goes through it. + locked: Mutex>>, } impl PostgresMigrationRunner { pub fn new(pool: PgPool) -> Self { - Self { pool } + Self { + pool, + locked: Mutex::new(None), + } + } + + /// The connection to run a statement on: the one holding the migration lock, or + /// else a pooled connection. + async fn connection(&self) -> Result> { + let guard = self.locked.lock().await; + if guard.is_some() { + return Ok(Conn::Locked(guard)); + } + drop(guard); + Ok(Conn::Pooled(self.pool.acquire().await?)) + } +} + +/// A connection for one runner operation. +enum Conn<'a> { + Locked(MutexGuard<'a, Option>>), + Pooled(PoolConnection), +} + +impl Conn<'_> { + fn get(&mut self) -> Result<&mut PgConnection> { + match self { + Self::Locked(guard) => guard.as_mut().map(|conn| &mut **conn).ok_or_else(|| { + crate::HammerworkError::Queue { + message: "the migration lock connection is gone".to_string(), + } + }), + Self::Pooled(conn) => Ok(&mut **conn), + } } } #[async_trait::async_trait] impl MigrationRunner for PostgresMigrationRunner { + async fn acquire_migration_lock(&self) -> Result<()> { + let mut conn = self.pool.acquire().await?; + // If the run is abandoned (an error, or its future is dropped) the connection is + // closed instead of going back to the pool, which releases the session lock. + conn.close_on_drop(); + debug!("Waiting for the PostgreSQL migration lock"); + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(MIGRATION_LOCK_KEY) + .execute(&mut *conn) + .await?; + debug!("Acquired the PostgreSQL migration lock"); + *self.locked.lock().await = Some(conn); + Ok(()) + } + + async fn release_migration_lock(&self) -> Result<()> { + let Some(mut conn) = self.locked.lock().await.take() else { + return Ok(()); + }; + // Dropping the connection closes it (close_on_drop), so the lock is released + // even if the unlock fails. + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(MIGRATION_LOCK_KEY) + .execute(&mut *conn) + .await?; + debug!("Released the PostgreSQL migration lock"); + Ok(()) + } + async fn run_migration(&self, migration: &Migration, sql: &str) -> Result<()> { debug!("Executing PostgreSQL migration: {}", migration.id); - let mut tx = self.pool.begin().await?; + let mut conn = self.connection().await?; + let mut tx = sqlx::Connection::begin(conn.get()?).await?; // Statements run exactly as written; the splitter only finds top-level `;`. let statements = split_statements(sql, Dialect::Postgres); @@ -75,20 +146,23 @@ impl MigrationRunner for PostgresMigrationRunner { } async fn migration_table_exists(&self) -> Result { + let mut conn = self.connection().await?; + // The schema the tables are created in: the first schema of the search path. let row = sqlx::query( "SELECT EXISTS ( - SELECT FROM information_schema.tables - WHERE table_schema = 'public' + SELECT FROM information_schema.tables + WHERE table_schema = current_schema() AND table_name = 'hammerwork_migrations' )", ) - .fetch_one(&self.pool) + .fetch_one(conn.get()?) .await?; Ok(row.try_get::(0)?) } async fn create_migration_table(&self) -> Result<()> { + let mut conn = self.connection().await?; sqlx::query( r#" CREATE TABLE IF NOT EXISTS hammerwork_migrations ( @@ -98,7 +172,7 @@ impl MigrationRunner for PostgresMigrationRunner { ) "#, ) - .execute(&self.pool) + .execute(conn.get()?) .await?; info!("Created PostgreSQL migration tracking table"); @@ -106,12 +180,13 @@ impl MigrationRunner for PostgresMigrationRunner { } async fn get_executed_migrations(&self) -> Result> { + let mut conn = self.connection().await?; let rows = sqlx::query( "SELECT migration_id, executed_at, execution_time_ms FROM hammerwork_migrations ORDER BY executed_at", ) - .fetch_all(&self.pool) + .fetch_all(conn.get()?) .await?; let mut records = Vec::new(); @@ -130,14 +205,16 @@ impl MigrationRunner for PostgresMigrationRunner { } async fn record_migration(&self, migration: &Migration, execution_time_ms: u64) -> Result<()> { + let mut conn = self.connection().await?; + // A run that does not take the lock (an older version) may have recorded it too. sqlx::query( "INSERT INTO hammerwork_migrations (migration_id, executed_at, execution_time_ms) - VALUES ($1, $2, $3)", + VALUES ($1, $2, $3) ON CONFLICT (migration_id) DO NOTHING", ) .bind(&migration.id) .bind(Utc::now()) - .bind(execution_time_ms as i64) - .execute(&self.pool) + .bind(i64::try_from(execution_time_ms).unwrap_or(i64::MAX)) + .execute(conn.get()?) .await?; debug!("Recorded PostgreSQL migration: {}", migration.id); diff --git a/src/queue/lifecycle.rs b/src/queue/lifecycle.rs index b7d94ab..7282557 100644 --- a/src/queue/lifecycle.rs +++ b/src/queue/lifecycle.rs @@ -177,6 +177,9 @@ pub struct RecordedOutcome { /// Jobs failed as a consequence of this one failing: dependents that can no longer /// run, or the remaining jobs of a fail-fast workflow or batch. pub cancelled: Vec, + /// Child jobs enqueued together with the completion, by + /// [`DatabaseQueue::complete_job_run_with_children`](super::DatabaseQueue::complete_job_run_with_children). + pub spawned: Vec, } impl RecordedOutcome { @@ -186,6 +189,7 @@ impl RecordedOutcome { next_run_at: None, unblocked: Vec::new(), cancelled: Vec::new(), + spawned: Vec::new(), } } } diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 8cf7193..0353c94 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -71,6 +71,9 @@ pub trait DatabaseQueue: Send + Sync { /// Claim the next runnable job of `queue_name`: `Pending`, due (by the database /// clock), not waiting on dependencies, highest priority first, then oldest. /// Returns `None` when there is none or the queue is paused. + /// + /// The claim holds a lease of [`DEFAULT_LEASE_DURATION`] (see + /// [`dequeue_leased`](Self::dequeue_leased)). async fn dequeue(&self, queue_name: &str) -> Result>; /// Like [`dequeue`](Self::dequeue), but picks the priority level by weight among @@ -84,6 +87,38 @@ pub trait DatabaseQueue: Send + Sync { weights: &crate::priority::PriorityWeights, ) -> Result>; + /// Claim the next runnable job of `queue_name` and hold a lease on it until + /// `now + lease` (by the database clock). + /// + /// Picks the job like + /// [`dequeue_with_priority_weights`](Self::dequeue_with_priority_weights) when + /// `weights` is given, otherwise like [`dequeue`](Self::dequeue). The lease + /// (`lease_expires_at`, with `last_heartbeat_at`) is written by the statement that + /// claims the job, so a claimed job is never without a lease: + /// [`requeue_stale_jobs`](Self::requeue_stale_jobs) leaves it alone until the lease + /// expires, and the worker extends it with [`heartbeat_job`](Self::heartbeat_job). + /// + /// A zero `lease` never expires: the reaper never reclaims the job, even if its + /// worker dies, so an operator has to (see + /// [`Worker::with_lease_duration`](crate::worker::Worker::with_lease_duration)). + /// + /// The default implementation ignores `lease`, for backends that predate leases. + async fn dequeue_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + ) -> Result> { + let _ = lease; + match weights { + Some(weights) => { + self.dequeue_with_priority_weights(queue_name, weights) + .await + } + None => self.dequeue(queue_name).await, + } + } + /// Manually mark a job `Completed`. /// /// Only applies to `Pending`, `Running` or `Retrying` jobs (see @@ -210,10 +245,27 @@ pub trait DatabaseQueue: Send + Sync { /// Get all recurring jobs for a queue async fn get_recurring_jobs(&self, queue_name: &str) -> Result>; - /// Disable a recurring job (stop future executions) + /// Disable a recurring job: it does not run again until it is enabled. + /// + /// Clears `recurring` and `next_run_at`. A pending occurrence that has not started + /// 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. Disabling a disabled job does nothing. + /// + /// Fails with `JobNotFound` for a missing job, and with a queue error for a job + /// without a cron schedule. async fn disable_recurring_job(&self, job_id: JobId) -> Result<()>; - /// Enable a previously disabled recurring job + /// Enable a recurring job again: it resumes at the next occurrence of its schedule. + /// + /// Sets `recurring` and, unless the job is `Running` (that run's outcome + /// reschedules it), schedules it for the next occurrence after now: `Pending` at + /// `next_run_at`, attempts reset. This revives a job whose last run finished while + /// it was disabled (`Completed`, `Failed`, `Dead` or `TimedOut`) as well as a held + /// pending occurrence. Occurrences missed while it was disabled are not run. + /// + /// Fails with `JobNotFound` for a missing (or archived) job, and with a queue error + /// for a job without a valid cron schedule. async fn enable_recurring_job(&self, job_id: JobId) -> Result<()>; // Throttling configuration @@ -382,7 +434,7 @@ pub trait DatabaseQueue: Send + Sync { /// counters and status are updated in the same transaction. /// /// Terminal transitions ([`fail_job`](Self::fail_job), - /// [`finish_job_run`](Self::finish_job_run) and, on the database backends, + /// [`finish_job_run`](Self::finish_job_run), /// [`mark_job_dead`](Self::mark_job_dead) and /// [`mark_job_timed_out`](Self::mark_job_timed_out)) already apply the policy, so /// calling this afterwards changes nothing and returns an empty list. @@ -775,20 +827,65 @@ pub trait DatabaseQueue: Send + Sync { Ok(Some(recorded)) } + /// Record that a run completed and enqueue the child jobs it spawned, as one unit. + /// + /// Like [`finish_job_run`](Self::finish_job_run) with + /// [`JobOutcome::Completed`], and in the same transaction every job of `children` is + /// enqueued (encrypted first when it or its queue requires it, like + /// [`enqueue`](Self::enqueue)). Either the parent is completed and all its children + /// exist, or nothing is written: if enqueueing a child fails the parent stays + /// `Running` this run and the caller can fail the run so it is retried. Returns + /// `Ok(None)`, and enqueues nothing, when the job is no longer `Running` this run. + /// The ids of the enqueued children are in [`RecordedOutcome::spawned`]. + /// + /// Workers call this for jobs whose [`SpawnManager`](crate::spawn::SpawnManager) + /// handler produced children. + /// + /// The default implementation, for backends without transactions, enqueues the + /// children first and then records the completion, so a failure part-way leaves the + /// parent `Running` (to be retried) rather than completed without its children; a + /// retry may then enqueue the children again. + async fn complete_job_run_with_children( + &self, + run: &Job, + children: Vec, + ) -> Result> { + let Some(current) = self.get_job(run.id).await? else { + return Ok(None); + }; + if !lifecycle::Guard::Run(run).admits(¤t) { + return Ok(None); + } + let mut spawned = Vec::with_capacity(children.len()); + for child in children { + spawned.push(self.enqueue(child).await?); + } + let recorded = self.finish_job_run(run, JobOutcome::Completed).await?; + Ok(recorded.map(|mut recorded| { + recorded.spawned = spawned; + recorded + })) + } + // Lease / stale job recovery - /// Record a heartbeat for a `Running` job and extend its lease to `now + lease`. + /// Record a heartbeat for a run of a `Running` job and extend its lease to + /// `now + lease` (a zero `lease` never expires, as in + /// [`dequeue_leased`](Self::dequeue_leased)). /// - /// Workers call this periodically while a handler runs. The lease tells - /// [`requeue_stale_jobs`](Self::requeue_stale_jobs) that the job is still owned by a - /// live worker. + /// `run` is the job as returned by the dequeue. Workers call this periodically while + /// a handler runs. The lease tells [`requeue_stale_jobs`](Self::requeue_stale_jobs) + /// that the job is still owned by a live worker. /// - /// Returns `false` when the job is no longer `Running` (for example because a reaper - /// already reclaimed it), which means the caller has lost its lease. + /// Only the run that was dequeued is extended (same `attempts` and `started_at`, as + /// in [`finish_job_run`](Self::finish_job_run)). Returns `false` when the job is no + /// longer `Running` that run, for example because a reaper reclaimed it and another + /// worker is running it again: the caller has lost its lease, and its heartbeat does + /// not extend the new run's lease. /// /// The default implementation returns an error, for backends that predate leases. - async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { - let _ = (job_id, lease); + async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result { + let _ = (run, lease); Err(crate::HammerworkError::Queue { message: "job leases are not supported by this queue backend".to_string(), }) @@ -797,19 +894,22 @@ pub trait DatabaseQueue: Send + Sync { /// Reclaim jobs left in `Running` by workers that crashed or were killed. /// /// A `Running` job is stale when: - /// - it has a lease from its current run (a heartbeat recorded after `started_at`) - /// and that lease has expired, or - /// - it has no lease from its current run (it has not heartbeated yet, or was - /// started by a worker that predates leases) and it started more than - /// `older_than` ago. + /// - it has a lease from its current run and that lease has expired. Every job + /// claimed by [`dequeue`](Self::dequeue) or [`dequeue_leased`](Self::dequeue_leased) + /// holds a lease from the moment it is claimed, so it is reclaimed only once its + /// worker stopped renewing it, whatever `older_than` is; or + /// - it has no lease from its current run, because it was claimed by an older + /// Hammerwork version that did not write one at claim time, and it started more + /// than `older_than` ago. Choose `older_than` longer than such jobs run. /// /// Stale jobs whose `attempts` have reached `max_attempts` are moved to `Dead`; /// the others go back to `Pending` and are scheduled immediately. The interrupted /// run already counted as an attempt when the job was dequeued. /// - /// Safe to call from several processes at once: rows are claimed with row locks - /// (`FOR UPDATE SKIP LOCKED`) and only updated while still `Running`, so each stale - /// job is reclaimed exactly once. + /// Safe to call from several pools or processes at once, with different + /// `older_than` values: rows are claimed with row locks (`FOR UPDATE SKIP LOCKED`) + /// and only updated while still `Running`, so each stale job is reclaimed exactly + /// once, and a job whose lease is still valid is never reclaimed. /// /// # Examples /// @@ -997,6 +1097,69 @@ pub(crate) fn prepare_cron_job(mut job: Job) -> Result { 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 @@ -1225,6 +1388,37 @@ pub(crate) fn weighted_seed(queue_name: &str, attempt: usize) -> u64 { hasher.finish() } +/// 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))] diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index 58c76fc..7bc27d5 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -631,10 +631,15 @@ impl crate::queue::JobQueue { /// Lock and claim happen in one transaction. SKIP LOCKED (MySQL 8.0+) lets /// concurrent workers move past rows another worker is claiming instead of /// blocking on them. The claim time comes from the database clock. + /// + /// The lease (`lease` microseconds, capped at the latest time a TIMESTAMP column + /// holds) is written by the claiming UPDATE, so the stale job reaper never sees this + /// run without one (`last_heartbeat_at = started_at` marks it as this run's lease). async fn claim_attempt( &self, queue_name: &str, priority: Option, + lease: i64, ) -> Result> { let mut conn = self.pool.acquire().await?; let mut tx = Self::begin_claim_transaction(&mut conn).await?; @@ -659,12 +664,16 @@ impl crate::queue::JobQueue { let job_row = JobRow::from_row(&row)?; let started_at: DateTime = row.try_get("claimed_at")?; - sqlx::query( - "UPDATE hammerwork_jobs SET status = ?, started_at = ?, attempts = attempts + 1 \ - WHERE id = ?", - ) + sqlx::query(&format!( + "UPDATE hammerwork_jobs SET status = ?, started_at = ?, attempts = attempts + 1, \ + last_heartbeat_at = ?, lease_expires_at = LEAST(DATE_ADD(?, INTERVAL ? MICROSECOND), \ + CAST('{TIMESTAMP_MAX_SQL}' AS DATETIME(6))) WHERE id = ?" + )) .bind(JobStatus::Running) .bind(started_at) + .bind(started_at) + .bind(started_at) + .bind(lease) .bind(&job_row.id) .execute(&mut *tx) .await?; @@ -683,6 +692,7 @@ impl crate::queue::JobQueue { &self, queue_name: &str, weights: &crate::priority::PriorityWeights, + lease: i64, ) -> Result> { // Which priority levels have a runnable job: one index probe per level, so // every level is considered however many jobs of other levels are queued. @@ -707,7 +717,7 @@ impl crate::queue::JobQueue { super::weighted_seed(queue_name, attempt), ) { if let Some(job) = - retry_on_deadlock(|| self.claim_attempt(queue_name, Some(priority))).await? + retry_on_deadlock(|| self.claim_attempt(queue_name, Some(priority), lease)).await? { return Ok(Some(job)); } @@ -767,7 +777,8 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn dequeue(&self, queue_name: &str) -> Result> { - retry_on_deadlock(|| self.claim_attempt(queue_name, None)).await + self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) + .await } async fn dequeue_with_priority_weights( @@ -775,13 +786,26 @@ impl DatabaseQueue for crate::queue::JobQueue { queue_name: &str, weights: &crate::priority::PriorityWeights, ) -> Result> { - if weights.is_strict() { - return self.dequeue(queue_name).await; - } - self.dequeue_with_priority_weights_inner(queue_name, weights) + self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) .await } + async fn dequeue_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + ) -> Result> { + let lease = lease_micros(lease); + match weights { + Some(weights) if !weights.is_strict() => { + self.dequeue_with_priority_weights_inner(queue_name, weights, lease) + .await + } + _ => retry_on_deadlock(|| self.claim_attempt(queue_name, None, lease)).await, + } + } + async fn complete_job(&self, job_id: JobId) -> Result<()> { let transition = JobTransition::Complete; self.transition_job(job_id, Guard::Manual(transition), &Target::Completed, false) @@ -825,6 +849,41 @@ impl DatabaseQueue for crate::queue::JobQueue { .into_run()) } + async fn complete_job_run_with_children( + &self, + run: &Job, + mut children: Vec, + ) -> Result> { + // Encrypt before anything is written, so a child that cannot be encrypted fails + // the whole completion. + self.seal_jobs(&mut children).await?; + super::retry_on_conflict(|| async { + 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( + &mut tx, + run.id, + Guard::Run(run), + &Target::Completed, + true, + ) + .await?; + let Some(mut recorded) = transition.into_run() else { + return Ok(None); + }; + // Children depending on the parent see it Completed in this transaction. + let mut jobs = children.clone(); + insert_dependent_jobs(&mut tx, &mut jobs).await?; + recorded.spawned = jobs.iter().map(|job| job.id).collect(); + Ok(Some(recorded)) + } + .await; + super::end_transaction(tx, result).await + }) + .await + } + async fn get_job(&self, job_id: JobId) -> Result> { let row = sqlx::query_as::<_, JobRow>(&format!( "SELECT {} FROM hammerwork_jobs WHERE id = ?", @@ -1494,21 +1553,68 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn disable_recurring_job(&self, job_id: JobId) -> Result<()> { - sqlx::query("UPDATE hammerwork_jobs SET recurring = FALSE WHERE id = ?") - .bind(job_id.to_string()) - .execute(&self.pool) - .await?; - + // A pending occurrence is held by the dequeue (see RUNNABLE_IN_QUEUE_SQL). + let result = sqlx::query( + "UPDATE hammerwork_jobs SET recurring = FALSE, next_run_at = NULL \ + WHERE id = ? AND cron_schedule IS NOT NULL", + ) + .bind(job_id.to_string()) + .execute(&self.pool) + .await?; + // MySQL counts changed rows, so an already disabled job also reports 0. + if result.rows_affected() == 0 { + return super::disable_recurring_job_not_applied(self.get_job(job_id).await?, job_id); + } Ok(()) } async fn enable_recurring_job(&self, job_id: JobId) -> Result<()> { - sqlx::query("UPDATE hammerwork_jobs SET recurring = TRUE WHERE id = ?") - .bind(job_id.to_string()) - .execute(&self.pool) - .await?; - - Ok(()) + super::retry_on_conflict(|| async { + let mut conn = self.pool.acquire().await?; + let mut tx = Self::begin_claim_transaction(&mut conn).await?; + let result = async { + 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 *tx) + .await?; + let Some(row) = row else { + return Err(crate::HammerworkError::JobNotFound { + id: job_id.to_string(), + }); + }; + let job = row.into_job()?; + let now = db_now(&mut tx).await?; + match super::enabled_recurring_next_run(&job, now)? { + // Running: the run's outcome reschedules it. + None => { + sqlx::query("UPDATE hammerwork_jobs SET recurring = TRUE WHERE id = ?") + .bind(job_id.to_string()) + .execute(&mut *tx) + .await?; + } + Some(next_run_at) => { + sqlx::query( + "UPDATE hammerwork_jobs SET recurring = TRUE, status = 'Pending', \ + scheduled_at = ?, next_run_at = ?, attempts = 0, \ + started_at = NULL, completed_at = NULL, failed_at = NULL, \ + timed_out_at = NULL, error_message = NULL, \ + last_heartbeat_at = NULL, lease_expires_at = NULL WHERE id = ?", + ) + .bind(next_run_at) + .bind(next_run_at) + .bind(job_id.to_string()) + .execute(&mut *tx) + .await?; + } + } + Ok(()) + } + .await; + super::end_transaction(tx, result).await + }) + .await } async fn set_throttle_config(&self, queue_name: &str, config: ThrottleConfig) -> Result<()> { @@ -2177,25 +2283,30 @@ impl DatabaseQueue for crate::queue::JobQueue { rows.iter().map(pause_info_from_row).collect() } - async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result { // The lease is measured on the database clock, like the reaper that checks it, - // and capped at the latest time a TIMESTAMP column holds. - let lease = super::clamp_interval(lease) - .num_microseconds() - .unwrap_or(i64::MAX); + // and capped at the latest time a TIMESTAMP column holds. Only the run that was + // dequeued is extended: a stale worker whose job was reclaimed and claimed again + // must not keep the new run's lease alive. + let started = super::run_started_range(run); let result = sqlx::query(&format!( "UPDATE hammerwork_jobs SET last_heartbeat_at = UTC_TIMESTAMP(6), \ lease_expires_at = LEAST(DATE_ADD(UTC_TIMESTAMP(6), INTERVAL ? MICROSECOND), \ - CAST('{TIMESTAMP_MAX_SQL}' AS DATETIME(6))) WHERE id = ? AND status = ?" + CAST('{TIMESTAMP_MAX_SQL}' AS DATETIME(6))) WHERE id = ? AND status = ? \ + AND attempts = ? AND (? IS NULL OR (started_at > ? AND started_at < ?))" )) - .bind(lease) - .bind(job_id.to_string()) + .bind(lease_micros(lease)) + .bind(run.id.to_string()) .bind(JobStatus::Running) + .bind(run.attempts) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(_, to)| to)) .execute(&self.pool) .await?; // MySQL reports "rows changed", not "rows matched"; the timestamps always change - // (microsecond precision), so 0 means the job is no longer Running. + // (microsecond precision), so 0 means the run is no longer Running. Ok(result.rows_affected() > 0) } @@ -2276,6 +2387,10 @@ impl crate::queue::JobQueue { // Claim stale rows with SKIP LOCKED so concurrent reapers never wait on (or // double-process) the same row. Each UPDATE re-checks `status` as well. + // + // A run's lease is written when it is claimed (`last_heartbeat_at = started_at`), + // so only its expiry counts. The `started_at` cutoff applies only to runs without + // a lease of their own: claimed by an older version that wrote none. let candidates = sqlx::query_as::<_, JobRow>(&format!( r#" SELECT {JOB_SELECT_FIELDS} FROM hammerwork_jobs @@ -2284,7 +2399,8 @@ impl crate::queue::JobQueue { (last_heartbeat_at IS NOT NULL AND last_heartbeat_at >= started_at AND lease_expires_at < ?) - OR ((last_heartbeat_at IS NULL OR last_heartbeat_at < started_at) + OR ((last_heartbeat_at IS NULL OR lease_expires_at IS NULL + OR last_heartbeat_at < started_at) AND started_at < ?) ) FOR UPDATE SKIP LOCKED @@ -2460,6 +2576,15 @@ async fn insert_jobs(conn: &mut sqlx::MySqlConnection, jobs: &[Job]) -> Result<( /// The latest instant a MySQL `TIMESTAMP` column can hold, as SQL. const TIMESTAMP_MAX_SQL: &str = "2038-01-19 03:14:07.999999"; +/// A lease as the microseconds bound to `INTERVAL ? MICROSECOND` (a zero lease never +/// expires; see [`super::lease_interval`]). Statements cap the resulting time at +/// [`TIMESTAMP_MAX_SQL`]. +fn lease_micros(lease: std::time::Duration) -> i64 { + super::lease_interval(lease) + .num_microseconds() + .unwrap_or(i64::MAX) +} + /// The range of instants a MySQL `TIMESTAMP` column can hold: /// 1970-01-01 00:00:01 to 2038-01-19 03:14:07.999999 UTC. fn timestamp_range() -> (DateTime, DateTime) { @@ -2548,8 +2673,12 @@ fn pause_info_from_row(row: &sqlx::mysql::MySqlRow) -> Result { } async fn dequeue(&self, queue_name: &str) -> Result> { - let row = sqlx::query_as::<_, JobRow>(&claim_sql(false)) - .bind(queue_name) - .fetch_optional(&self.pool) - .await?; - - row.map(JobRow::into_job).transpose() + self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) + .await } async fn dequeue_with_priority_weights( @@ -606,10 +602,29 @@ impl DatabaseQueue for crate::queue::JobQueue { queue_name: &str, weights: &crate::priority::PriorityWeights, ) -> Result> { - if weights.is_strict() { - // Use strict priority - same as regular dequeue - return self.dequeue(queue_name).await; - } + self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) + .await + } + + async fn dequeue_leased( + &self, + queue_name: &str, + weights: Option<&crate::priority::PriorityWeights>, + lease: std::time::Duration, + ) -> Result> { + let lease = super::lease_interval(lease); + let weights = match weights { + Some(weights) if !weights.is_strict() => weights, + // Strict priority: the highest priority, then the oldest job. + _ => { + let row = sqlx::query_as::<_, JobRow>(&claim_sql(false)) + .bind(queue_name) + .bind(lease) + .fetch_optional(&self.pool) + .await?; + return row.map(JobRow::into_job).transpose(); + } + }; // Which priority levels have a runnable job: one index probe per level, so // every level is considered however many jobs of other levels are queued. @@ -633,6 +648,7 @@ impl DatabaseQueue for crate::queue::JobQueue { ) { let claimed = sqlx::query_as::<_, JobRow>(&claim_sql(true)) .bind(queue_name) + .bind(lease) .bind(priority.as_i32()) .fetch_optional(&self.pool) .await?; @@ -686,6 +702,40 @@ impl DatabaseQueue for crate::queue::JobQueue { .await? .into_run()) } + + async fn complete_job_run_with_children( + &self, + run: &Job, + mut children: Vec, + ) -> Result> { + // Encrypt before anything is written, so a child that cannot be encrypted fails + // the whole completion. + self.seal_jobs(&mut children).await?; + super::retry_on_conflict(|| async { + let mut tx = self.pool.begin().await?; + let result = async { + let transition = Self::transition_in_tx( + &mut tx, + run.id, + Guard::Run(run), + &Target::Completed, + true, + ) + .await?; + let Some(mut recorded) = transition.into_run() else { + return Ok(None); + }; + // Children depending on the parent see it Completed in this transaction. + let mut jobs = children.clone(); + insert_dependent_jobs(&mut tx, &mut jobs).await?; + recorded.spawned = jobs.iter().map(|job| job.id).collect(); + Ok(Some(recorded)) + } + .await; + super::end_transaction(tx, result).await + }) + .await + } async fn get_job(&self, job_id: JobId) -> Result> { let row = sqlx::query_as::<_, JobRow>(&format!( "SELECT {} FROM hammerwork_jobs WHERE id = $1", @@ -1356,21 +1406,65 @@ impl DatabaseQueue for crate::queue::JobQueue { } async fn disable_recurring_job(&self, job_id: JobId) -> Result<()> { - sqlx::query("UPDATE hammerwork_jobs SET recurring = FALSE WHERE id = $1") - .bind(job_id) - .execute(&self.pool) - .await?; - + // A pending occurrence is held by the dequeue (see RUNNABLE_IN_QUEUE_SQL). + let result = sqlx::query( + "UPDATE hammerwork_jobs SET recurring = FALSE, next_run_at = NULL \ + WHERE id = $1 AND cron_schedule IS NOT NULL", + ) + .bind(job_id) + .execute(&self.pool) + .await?; + if result.rows_affected() == 0 { + return super::disable_recurring_job_not_applied(self.get_job(job_id).await?, job_id); + } Ok(()) } async fn enable_recurring_job(&self, job_id: JobId) -> Result<()> { - sqlx::query("UPDATE hammerwork_jobs SET recurring = TRUE WHERE id = $1") - .bind(job_id) - .execute(&self.pool) - .await?; - - Ok(()) + super::retry_on_conflict(|| async { + let mut tx = self.pool.begin().await?; + let result = async { + 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 *tx) + .await?; + let Some(row) = row else { + return Err(crate::HammerworkError::JobNotFound { + id: job_id.to_string(), + }); + }; + let job = row.into_job()?; + let now = db_now(&mut tx).await?; + match super::enabled_recurring_next_run(&job, now)? { + // Running: the run's outcome reschedules it. + None => { + sqlx::query("UPDATE hammerwork_jobs SET recurring = TRUE WHERE id = $1") + .bind(job_id) + .execute(&mut *tx) + .await?; + } + Some(next_run_at) => { + sqlx::query( + "UPDATE hammerwork_jobs SET recurring = TRUE, status = 'Pending', \ + scheduled_at = $2, next_run_at = $2, attempts = 0, \ + started_at = NULL, completed_at = NULL, failed_at = NULL, \ + timed_out_at = NULL, error_message = NULL, \ + last_heartbeat_at = NULL, lease_expires_at = NULL WHERE id = $1", + ) + .bind(job_id) + .bind(next_run_at) + .execute(&mut *tx) + .await?; + } + } + Ok(()) + } + .await; + super::end_transaction(tx, result).await + }) + .await } async fn set_throttle_config(&self, queue_name: &str, config: ThrottleConfig) -> Result<()> { @@ -2054,15 +2148,22 @@ impl DatabaseQueue for crate::queue::JobQueue { rows.iter().map(pause_info_from_row).collect() } - async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result { // The lease is measured on the database clock, like the reaper that checks it. + // Only the run that was dequeued is extended: a stale worker whose job was + // reclaimed and claimed again must not keep the new run's lease alive. + let started = super::run_started_range(run); let result = sqlx::query( "UPDATE hammerwork_jobs SET last_heartbeat_at = now(), \ - lease_expires_at = now() + $1 WHERE id = $2 AND status = $3", + lease_expires_at = now() + $1 WHERE id = $2 AND status = $3 AND attempts = $4 \ + AND ($5::timestamptz IS NULL OR (started_at > $5 AND started_at < $6))", ) - .bind(super::clamp_interval(lease)) - .bind(job_id) + .bind(super::lease_interval(lease)) + .bind(run.id) .bind(JobStatus::Running) + .bind(run.attempts) + .bind(started.map(|(from, _)| from)) + .bind(started.map(|(_, to)| to)) .execute(&self.pool) .await?; @@ -2146,6 +2247,10 @@ impl crate::queue::JobQueue { // (or double-process) the same row; the outer UPDATE re-checks `status` so a row // that changed state after the snapshot is left alone. All SET expressions read // the pre-update row, so `attempts >= max_attempts` picks Dead vs Pending. + // + // A run's lease is written when it is claimed (`last_heartbeat_at = started_at`), + // so only its expiry counts. The `started_at` cutoff applies only to runs without + // a lease of their own: claimed by an older version that wrote none. let rows = sqlx::query( r#" WITH stale AS ( @@ -2155,7 +2260,8 @@ impl crate::queue::JobQueue { (last_heartbeat_at IS NOT NULL AND last_heartbeat_at >= started_at AND lease_expires_at < $2) - OR ((last_heartbeat_at IS NULL OR last_heartbeat_at < started_at) + OR ((last_heartbeat_at IS NULL OR lease_expires_at IS NULL + OR last_heartbeat_at < started_at) AND started_at < $3) ) FOR UPDATE SKIP LOCKED @@ -2338,22 +2444,30 @@ fn pause_info_from_row(row: &sqlx::postgres::PgRow) -> Result String { format!( "UPDATE hammerwork_jobs SET status = 'Running', started_at = now(), \ - attempts = attempts + 1 \ + attempts = attempts + 1, last_heartbeat_at = now(), lease_expires_at = now() + $2 \ WHERE id = (SELECT j.id FROM hammerwork_jobs j WHERE {RUNNABLE_IN_QUEUE_SQL}{} \ ORDER BY j.priority DESC, j.scheduled_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED) \ RETURNING {JOB_SELECT_FIELDS}", if by_priority { - " AND j.priority = $2" + " AND j.priority = $3" } else { "" } diff --git a/src/queue/test.rs b/src/queue/test.rs index 00cafc2..20f1a80 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -237,6 +237,16 @@ impl Default for MockClock { } } +/// When a lease of `lease` taken at `now` expires: never for a zero lease, as on the +/// database backends. +fn lease_expiry(now: DateTime, lease: std::time::Duration) -> DateTime { + if lease.is_zero() { + DateTime::::MAX_UTC + } else { + super::saturating_add_to(now, lease) + } +} + /// In-memory storage for the test queue #[derive(Debug)] struct TestStorage { @@ -511,6 +521,8 @@ impl TestStorage { .iter() .filter_map(|id| self.jobs.get(id)) .filter(|job| job.scheduled_at <= now) + // A disabled recurring job's pending occurrence is held. + .filter(|job| job.recurring || job.cron_schedule.is_none()) .collect(); if eligible_jobs.is_empty() { @@ -967,6 +979,51 @@ impl TestQueue { } } +impl TestQueue { + /// End `job_id` as `Dead` or `TimedOut` with `error`, like the database backends' + /// terminal transitions. With `apply_policy`, the failure is applied to its + /// dependents, its workflow's [`FailurePolicy`] and a fail-fast batch; returns the + /// jobs failed with it. + async fn end_with_failure( + &self, + job_id: JobId, + status: JobStatus, + error: &str, + apply_policy: bool, + ) -> Result> { + let transition = if status == JobStatus::TimedOut { + crate::queue::JobTransition::MarkTimedOut + } else { + crate::queue::JobTransition::MarkDead + }; + let mut storage = self.storage.write().await; + storage.check_transition(job_id, transition)?; + storage.update_job_status(job_id, status)?; + storage.leases.remove(&job_id); + + let now = storage.clock.now(); + if let Some(job) = storage.jobs.get_mut(&job_id) { + if status == JobStatus::TimedOut { + job.timed_out_at = Some(now); + } else { + job.failed_at = Some(now); + } + job.error_message = Some(error.to_string()); + } + + if !apply_policy { + return Ok(Vec::new()); + } + let mut cancelled = storage.apply_workflow_failure(job_id, now); + for id in storage.apply_batch_failure(job_id, now) { + if !cancelled.contains(&id) { + cancelled.push(id); + } + } + Ok(cancelled) + } +} + impl Default for TestQueue { fn default() -> Self { Self::new() @@ -1008,23 +1065,8 @@ impl DatabaseQueue for TestQueue { } async fn dequeue(&self, queue_name: &str) -> Result> { - let mut storage = self.storage.write().await; - - if let Some(job_id) = storage.get_next_job(queue_name, None) { - // Update job status to Running - storage.update_job_status(job_id, JobStatus::Running)?; - - // Set started_at - let now = storage.clock.now(); - if let Some(job) = storage.jobs.get_mut(&job_id) { - job.started_at = Some(now); - // Like the database backends, every dequeue counts as an attempt. - job.attempts += 1; - return Ok(Some(job.clone())); - } - } - - Ok(None) + self.dequeue_leased(queue_name, None, super::DEFAULT_LEASE_DURATION) + .await } async fn dequeue_with_priority_weights( @@ -1032,23 +1074,34 @@ impl DatabaseQueue for TestQueue { queue_name: &str, weights: &PriorityWeights, ) -> Result> { - let mut storage = self.storage.write().await; + self.dequeue_leased(queue_name, Some(weights), super::DEFAULT_LEASE_DURATION) + .await + } - if let Some(job_id) = storage.get_next_job(queue_name, Some(weights)) { - // Update job status to Running - storage.update_job_status(job_id, JobStatus::Running)?; + async fn dequeue_leased( + &self, + queue_name: &str, + weights: Option<&PriorityWeights>, + lease: std::time::Duration, + ) -> Result> { + let mut storage = self.storage.write().await; - // Set started_at - let now = storage.clock.now(); - if let Some(job) = storage.jobs.get_mut(&job_id) { - job.started_at = Some(now); - // Like the database backends, every dequeue counts as an attempt. - job.attempts += 1; - return Ok(Some(job.clone())); - } - } + let Some(job_id) = storage.get_next_job(queue_name, weights) else { + return Ok(None); + }; + storage.update_job_status(job_id, JobStatus::Running)?; - Ok(None) + let now = storage.clock.now(); + // Like the database backends, the claim holds a lease from the start. + storage + .leases + .insert(job_id, (now, lease_expiry(now, lease))); + Ok(storage.jobs.get_mut(&job_id).map(|job| { + job.started_at = Some(now); + // Like the database backends, every dequeue counts as an attempt. + job.attempts += 1; + job.clone() + })) } async fn complete_job(&self, job_id: JobId) -> Result<()> { @@ -1353,33 +1406,76 @@ impl DatabaseQueue for TestQueue { // Dead job management async fn mark_job_dead(&self, job_id: JobId, error_message: &str) -> Result<()> { - let mut storage = self.storage.write().await; - storage.check_transition(job_id, crate::queue::JobTransition::MarkDead)?; - - storage.update_job_status(job_id, JobStatus::Dead)?; - - let now = storage.clock.now(); - if let Some(job) = storage.jobs.get_mut(&job_id) { - job.failed_at = Some(now); - job.error_message = Some(error_message.to_string()); - } - + self.end_with_failure(job_id, JobStatus::Dead, error_message, true) + .await?; Ok(()) } async fn mark_job_timed_out(&self, job_id: JobId, error_message: &str) -> Result<()> { - let mut storage = self.storage.write().await; - storage.check_transition(job_id, crate::queue::JobTransition::MarkTimedOut)?; - - storage.update_job_status(job_id, JobStatus::TimedOut)?; + self.end_with_failure(job_id, JobStatus::TimedOut, error_message, true) + .await?; + Ok(()) + } - let now = storage.clock.now(); - if let Some(job) = storage.jobs.get_mut(&job_id) { - job.timed_out_at = Some(now); - job.error_message = Some(error_message.to_string()); + async fn finish_job_run( + &self, + run: &Job, + outcome: crate::queue::JobOutcome, + ) -> Result> { + use crate::queue::{JobOutcome, RecordedOutcome}; + + // Like the database backends: only the run that was dequeued is recorded, and a + // recurring job that finished is rescheduled instead of failing its dependents. + let next_run_at = { + let storage = self.storage.read().await; + let Some(current) = storage.jobs.get(&run.id) else { + return Ok(None); + }; + if !lifecycle::Guard::Run(run).admits(current) { + return Ok(None); + } + match outcome.terminal_status() { + Some(_) if current.recurring => { + lifecycle::next_cron_run(current, storage.clock.now()) + } + _ => None, + } + }; + let apply_policy = next_run_at.is_none(); + let mut recorded = match outcome { + JobOutcome::Completed => { + if next_run_at.is_none() { + self.complete_job(run.id).await?; + } + RecordedOutcome::new(JobStatus::Completed) + } + JobOutcome::Retry { retry_at, .. } => { + self.retry_job(run.id, retry_at).await?; + RecordedOutcome::new(JobStatus::Pending) + } + JobOutcome::Dead { error } => { + let mut recorded = RecordedOutcome::new(JobStatus::Dead); + recorded.cancelled = self + .end_with_failure(run.id, JobStatus::Dead, &error, apply_policy) + .await?; + recorded + } + JobOutcome::TimedOut { error } => { + let mut recorded = RecordedOutcome::new(JobStatus::TimedOut); + recorded.cancelled = self + .end_with_failure(run.id, JobStatus::TimedOut, &error, apply_policy) + .await?; + recorded + } + }; + if let Some(next) = next_run_at { + self.reschedule_cron_job(run.id, next).await?; + recorded.status = JobStatus::Pending; + recorded.next_run_at = Some(next); + } else if recorded.status == JobStatus::Completed { + recorded.unblocked = self.resolve_job_dependencies(run.id).await?; } - - Ok(()) + Ok(Some(recorded)) } async fn get_dead_jobs(&self, limit: Option, offset: Option) -> Result> { @@ -1954,13 +2050,11 @@ impl DatabaseQueue for TestQueue { .ok_or_else(|| HammerworkError::JobNotFound { id: job_id.to_string(), })?; - - if !job.recurring { - return Err(HammerworkError::Queue { - message: "Job is not a recurring job".to_string(), - }); + if job.cron_schedule.is_none() { + return Err(super::not_a_cron_job(job_id)); } + // A pending occurrence is held by `get_next_job`, like on the database backends. job.recurring = false; job.next_run_at = None; @@ -1969,56 +2063,37 @@ impl DatabaseQueue for TestQueue { async fn enable_recurring_job(&self, job_id: JobId) -> Result<()> { let mut storage = self.storage.write().await; - - // First, check if job exists and has cron schedule - let cron_schedule = { - let job = storage - .jobs - .get(&job_id) - .ok_or_else(|| HammerworkError::JobNotFound { - id: job_id.to_string(), - })?; - - if job.cron_schedule.is_none() { - return Err(HammerworkError::Queue { - message: "Job does not have a cron schedule".to_string(), - }); - } - - (job.cron_schedule.clone(), job.timezone.clone()) - }; - - // Get current time let now = storage.clock.now(); + let job = storage + .jobs + .get(&job_id) + .ok_or_else(|| HammerworkError::JobNotFound { + id: job_id.to_string(), + })?; + let next_run_at = super::enabled_recurring_next_run(job, now)?; - // Calculate next run time - let next_run_at = - if let Ok(schedule) = cron_schedule.0.as_ref().unwrap().parse::() { - let timezone = cron_schedule - .1 - .as_ref() - .and_then(|tz| tz.parse::().ok()) - .unwrap_or(chrono_tz::UTC); - - let now_in_tz = now.with_timezone(&timezone); - schedule - .after(&now_in_tz) - .next() - .map(|next| next.with_timezone(&Utc)) - } else { - None - }; - - // Now update the job + if next_run_at.is_some() { + // Not running: resume at the next occurrence, like the database backends. + storage.update_job_status(job_id, JobStatus::Pending)?; + storage.leases.remove(&job_id); + } let job = storage .jobs .get_mut(&job_id) .ok_or_else(|| HammerworkError::JobNotFound { id: job_id.to_string(), })?; - job.recurring = true; - job.next_run_at = next_run_at; + if let Some(next_run_at) = next_run_at { + job.scheduled_at = next_run_at; + job.next_run_at = Some(next_run_at); + job.attempts = 0; + job.started_at = None; + job.completed_at = None; + job.failed_at = None; + job.timed_out_at = None; + job.error_message = None; + } Ok(()) } @@ -2654,19 +2729,19 @@ impl DatabaseQueue for TestQueue { Ok(storage.paused_queues.values().cloned().collect()) } - async fn heartbeat_job(&self, job_id: JobId, lease: std::time::Duration) -> Result { + async fn heartbeat_job(&self, run: &Job, lease: std::time::Duration) -> Result { let mut storage = self.storage.write().await; - let running = storage - .jobs - .get(&job_id) - .is_some_and(|job| job.status == JobStatus::Running); - if !running { + // Only the run that was dequeued is extended, as on the database backends. + let same_run = storage.jobs.get(&run.id).is_some_and(|job| { + job.status == JobStatus::Running && lifecycle::is_same_run(job, run) + }); + if !same_run { return Ok(false); } let now = storage.clock.now(); storage .leases - .insert(job_id, (now, super::saturating_add_to(now, lease))); + .insert(run.id, (now, lease_expiry(now, lease))); Ok(true) } @@ -2701,6 +2776,9 @@ impl DatabaseQueue for TestQueue { job.failed_at = Some(now); job.error_message = Some(super::STALE_JOB_ERROR_MESSAGE.to_string()); } + // A terminal failure like any other, as on the database backends. + storage.apply_workflow_failure(job_id, now); + storage.apply_batch_failure(job_id, now); recovery.dead.push(job_id); } else { storage.update_job_status(job_id, JobStatus::Pending)?; @@ -3114,6 +3192,7 @@ mod tests { async fn test_requeue_stale_jobs_uses_leases_and_fallback() { let queue = TestQueue::new(); let clock = queue.clock(); + let lease = std::time::Duration::from_secs(30); let leased = queue .enqueue(Job::new("stale".to_string(), json!({"n": 1}))) @@ -3127,15 +3206,17 @@ mod tests { .enqueue(Job::new("stale".to_string(), json!({"n": 3})).with_max_attempts(0)) .await .unwrap(); + let mut runs = HashMap::new(); for _ in 0..3 { - queue.dequeue("stale").await.unwrap().unwrap(); - } - assert!( - queue - .heartbeat_job(leased, std::time::Duration::from_secs(30)) + let run = queue + .dequeue_leased("stale", None, lease) .await .unwrap() - ); + .unwrap(); + runs.insert(run.id, run); + } + // `unleased` stands for a job claimed by a version that wrote no lease. + queue.storage.write().await.leases.remove(&unleased); // Nothing is stale yet. let recovery = queue @@ -3144,22 +3225,22 @@ mod tests { .unwrap(); assert!(recovery.is_empty()); - // After 60s the lease has expired but the 600s fallback has not. - clock.advance(chrono::Duration::seconds(60)); + // A short staleness window does not reclaim leased jobs. + clock.advance(chrono::Duration::seconds(10)); + assert!(queue.heartbeat_job(&runs[&leased], lease).await.unwrap()); let recovery = queue - .requeue_stale_jobs(std::time::Duration::from_secs(600)) + .requeue_stale_jobs(std::time::Duration::ZERO) .await .unwrap(); - assert_eq!(recovery.requeued, vec![leased]); - assert!(recovery.dead.is_empty()); + assert_eq!(recovery.requeued, vec![unleased]); - // After the fallback window the un-leased jobs are reclaimed too. - clock.advance(chrono::Duration::seconds(600)); + // After 60s the leases have expired but the 600s fallback has not. + clock.advance(chrono::Duration::seconds(60)); let recovery = queue .requeue_stale_jobs(std::time::Duration::from_secs(600)) .await .unwrap(); - assert_eq!(recovery.requeued, vec![unleased]); + assert_eq!(recovery.requeued, vec![leased]); assert_eq!(recovery.dead, vec![exhausted]); let job = queue.get_job(leased).await.unwrap().unwrap(); @@ -3170,11 +3251,169 @@ mod tests { ); // A heartbeat for a job that is no longer Running reports a lost lease. + assert!(!queue.heartbeat_job(&runs[&exhausted], lease).await.unwrap()); + } + + #[tokio::test] + async fn test_stale_heartbeat_does_not_extend_a_new_run() { + let queue = TestQueue::new(); + let clock = queue.clock(); + let lease = std::time::Duration::from_secs(30); + let id = queue + .enqueue(Job::new("rerun".to_string(), json!({}))) + .await + .unwrap(); + + let first = queue + .dequeue_leased("rerun", None, lease) + .await + .unwrap() + .unwrap(); + clock.advance(chrono::Duration::seconds(60)); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(3600)) + .await + .unwrap(); + assert_eq!(recovery.requeued, vec![id]); + + let second = queue + .dequeue_leased("rerun", None, lease) + .await + .unwrap() + .unwrap(); + assert_eq!(second.attempts, 2); + // The first run's worker is still alive and heartbeats: it lost its lease. + assert!(!queue.heartbeat_job(&first, lease).await.unwrap()); + assert!(queue.heartbeat_job(&second, lease).await.unwrap()); + + // Its heartbeats did not keep the second run alive. + clock.advance(chrono::Duration::seconds(60)); + assert!(!queue.heartbeat_job(&first, lease).await.unwrap()); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::from_secs(3600)) + .await + .unwrap(); + assert_eq!(recovery.requeued, vec![id]); + } + + #[tokio::test] + async fn test_zero_lease_never_expires() { + let queue = TestQueue::new(); + let id = queue + .enqueue(Job::new("forever".to_string(), json!({}))) + .await + .unwrap(); + let run = queue + .dequeue_leased("forever", None, std::time::Duration::ZERO) + .await + .unwrap() + .unwrap(); + queue.clock().advance(chrono::Duration::days(365)); + let recovery = queue + .requeue_stale_jobs(std::time::Duration::ZERO) + .await + .unwrap(); + assert!(recovery.is_empty(), "{recovery:?}"); + assert!( + queue + .heartbeat_job(&run, std::time::Duration::ZERO) + .await + .unwrap() + ); + assert_eq!( + queue.get_job(id).await.unwrap().unwrap().status, + JobStatus::Running + ); + } + + #[tokio::test] + async fn test_mark_job_dead_and_timed_out_apply_the_failure_policy() { + use crate::workflow::{FailurePolicy, JobGroup}; + + for timed_out in [false, true] { + let queue = TestQueue::new(); + let a = Job::new("policy".to_string(), json!({"step": "a"})); + let b = Job::new("policy".to_string(), json!({"step": "b"})).depends_on(&a.id); + let other = Job::new("policy".to_string(), json!({"step": "other"})); + let (a_id, b_id, other_id) = (a.id, b.id, other.id); + queue + .enqueue_workflow( + JobGroup::new("policy") + .add_job(a) + .add_job(b) + .add_job(other) + .with_failure_policy(FailurePolicy::FailFast), + ) + .await + .unwrap(); + let run = queue.dequeue("policy").await.unwrap().unwrap(); + let failed_id = run.id; + if timed_out { + queue + .mark_job_timed_out(failed_id, "too slow") + .await + .unwrap(); + } else { + queue.mark_job_dead(failed_id, "broken").await.unwrap(); + } + // Fail-fast: every other unfinished job of the workflow fails with it. + for id in [a_id, b_id, other_id] { + if id == failed_id { + continue; + } + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Failed, "{job:?}"); + } + // Already applied, as on the database backends. + assert!( + queue + .fail_job_dependencies(failed_id) + .await + .unwrap() + .is_empty() + ); + } + } + + #[tokio::test] + async fn test_finish_job_run_reports_the_jobs_failed_with_it() { + use crate::queue::JobOutcome; + use crate::workflow::{FailurePolicy, JobGroup}; + + let queue = TestQueue::new(); + let a = Job::new("finish_policy".to_string(), json!({"step": "a"})); + let b = Job::new("finish_policy".to_string(), json!({"step": "b"})).depends_on(&a.id); + let (a_id, b_id) = (a.id, b.id); + queue + .enqueue_workflow( + JobGroup::new("finish_policy") + .add_job(a) + .add_job(b) + .with_failure_policy(FailurePolicy::ContinueOnFailure), + ) + .await + .unwrap(); + let run = queue.dequeue("finish_policy").await.unwrap().unwrap(); + assert_eq!(run.id, a_id); + let recorded = queue + .finish_job_run( + &run, + JobOutcome::Dead { + error: "broken".to_string(), + }, + ) + .await + .unwrap() + .expect("the run is current"); + assert_eq!(recorded.status, JobStatus::Dead); + assert_eq!(recorded.cancelled, vec![b_id]); + // A second report for the same run is discarded. assert!( - !queue - .heartbeat_job(exhausted, std::time::Duration::from_secs(30)) + queue + .finish_job_run(&run, JobOutcome::Completed) .await .unwrap() + .is_none() ); } diff --git a/src/rate_limit.rs b/src/rate_limit.rs index b63075b..827d6d0 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -177,11 +177,22 @@ impl TokenBucket { } } - /// Refill tokens based on elapsed time + /// Return tokens taken by [`try_consume`](Self::try_consume) that were not used, + /// up to the capacity. + pub fn refund(&mut self, tokens: f64) { + self.refill(); + self.tokens = (self.tokens + tokens).min(self.capacity); + } + + /// Refill tokens based on elapsed time. + /// + /// Uses the elapsed time at full precision: rounding it down to whole milliseconds + /// would drop the remainder on every call, so frequent calls would refill slower + /// than the configured rate (or not at all). fn refill(&mut self) { let now = Instant::now(); let elapsed = now.duration_since(self.last_refill); - let tokens_to_add = self.refill_rate * elapsed.as_millis() as f64; + let tokens_to_add = self.refill_rate * elapsed.as_secs_f64() * 1000.0; self.tokens = (self.tokens + tokens_to_add).min(self.capacity); self.last_refill = now; @@ -263,6 +274,17 @@ impl RateLimiter { self.check() } + /// Hand back a permit taken by [`check`](Self::check), [`acquire`](Self::acquire) or + /// [`try_acquire`](Self::try_acquire) that was not used. + /// + /// Workers take a permit before they poll and refund it when the poll claims no job, + /// so empty or paused polls do not spend the rate limit. + pub fn refund(&self) { + if let Ok(mut bucket) = self.bucket.lock() { + bucket.refund(1.0); + } + } + /// Get the current rate limit configuration pub fn rate_limit(&self) -> &RateLimit { &self.rate_limit @@ -316,31 +338,64 @@ mod tests { #[test] fn test_token_bucket() { - let mut bucket = TokenBucket::new(10.0, 1.0); // 10 tokens, 1 token per ms + // 10 tokens, refilling so slowly that the test never sees a refill + let mut bucket = TokenBucket::new(10.0, 1e-9); + let close = |a: f64, b: f64| (a - b).abs() < 1e-3; // Should start with full capacity - assert_eq!(bucket.available_tokens(), 10.0); + assert!(close(bucket.available_tokens(), 10.0)); // Should be able to consume tokens assert!(bucket.try_consume(5.0)); - assert_eq!(bucket.available_tokens(), 5.0); + assert!(close(bucket.available_tokens(), 5.0)); // Should not be able to consume more than available assert!(!bucket.try_consume(10.0)); - assert_eq!(bucket.available_tokens(), 5.0); + assert!(close(bucket.available_tokens(), 5.0)); // Should be able to consume remaining tokens assert!(bucket.try_consume(5.0)); - assert_eq!(bucket.available_tokens(), 0.0); + assert!(close(bucket.available_tokens(), 0.0)); + } + + #[test] + fn test_token_bucket_refills_between_sub_millisecond_calls() { + // 1 token per ms. Calls closer together than 1ms used to refill nothing (the + // elapsed time was truncated to whole milliseconds and then discarded). + let mut bucket = TokenBucket::new(5.0, 1.0); + assert!(bucket.try_consume(5.0)); + let start = std::time::Instant::now(); + while start.elapsed() < Duration::from_millis(3) { + bucket.available_tokens(); + } + assert!( + bucket.available_tokens() >= 2.5, + "{}", + bucket.available_tokens() + ); + } + + #[test] + fn test_refund_returns_an_unused_permit() { + let limiter = RateLimiter::new(RateLimit::per_hour(1)); + assert!(limiter.try_acquire()); + assert!(!limiter.try_acquire()); + // The permit was not used (an empty poll): hand it back. + limiter.refund(); + assert!(limiter.try_acquire()); + // Refunds never raise the bucket above its capacity. + limiter.refund(); + limiter.refund(); + assert!(limiter.available_tokens() <= 1.0); } #[tokio::test] async fn test_token_bucket_refill() { let mut bucket = TokenBucket::new(10.0, 10.0); // 10 tokens capacity, 10 tokens per ms - // Consume all tokens + // Consume all tokens (refill is continuous, so a sliver may already be back) assert!(bucket.try_consume(10.0)); - assert_eq!(bucket.available_tokens(), 0.0); + assert!(bucket.available_tokens() < 1.0); // Wait for refill (1ms should add 10 tokens, bringing us back to capacity) sleep(Duration::from_millis(2)).await; diff --git a/src/spawn.rs b/src/spawn.rs index cd72663..10676eb 100644 --- a/src/spawn.rs +++ b/src/spawn.rs @@ -398,7 +398,10 @@ impl SpawnManager { /// Execute spawn logic for a completed job. /// /// This method checks if the job has a registered spawn handler and executes it - /// if found. The spawned jobs are automatically enqueued and tracked. + /// if found. The spawned jobs are enqueued one at a time, outside any transaction; + /// [`Worker`](crate::Worker)s instead use [`prepare_spawn`](Self::prepare_spawn) and + /// enqueue the children together with the parent's completion + /// ([`DatabaseQueue::complete_job_run_with_children`]). /// /// # Arguments /// @@ -415,77 +418,103 @@ impl SpawnManager { config: SpawnConfig, queue: Arc + Send + Sync>, ) -> Result> { - if let Some(handler) = self.handlers.get(&job.queue_name) { - // Validate spawn operation - handler.validate_spawn(&job, &config).await?; - - // Create spawn context - let context = SpawnContext { - parent_job: job.clone(), - config: config.clone(), - queue: queue.clone(), - }; - - // Generate child jobs - let mut child_jobs = handler.spawn_jobs(context).await?; - - // Check spawn limits - if let Some(max_count) = config.max_spawn_count - && child_jobs.len() > max_count - { - return Err(HammerworkError::SpawnError( - SpawnError::SpawnLimitExceeded { - attempted: child_jobs.len(), - limit: max_count, - }, - )); - } + let Some(child_jobs) = self.prepare_spawn(&job, &config, queue.clone()).await? else { + return Ok(None); + }; + + // Enqueue child jobs + let mut spawned_job_ids = Vec::new(); + for child_job in child_jobs { + let job_id = queue.enqueue(child_job).await?; + spawned_job_ids.push(job_id); + } - // Apply inheritance settings - for child_job in &mut child_jobs { - if config.inherit_priority { - child_job.priority = job.priority; - } - if config.inherit_retry_strategy { - child_job.retry_strategy = job.retry_strategy.clone(); - } - if config.inherit_timeout { - child_job.timeout = job.timeout; - } - if config.inherit_trace_context { - child_job.trace_id = job.trace_id.clone(); - child_job.correlation_id = job.correlation_id.clone(); - child_job.parent_span_id = job.parent_span_id.clone(); - child_job.span_context = job.span_context.clone(); - } - - // Set up parent-child relationship - child_job.depends_on = vec![job.id]; - child_job.workflow_id = job.workflow_id; - child_job.workflow_name = job.workflow_name.clone(); - } + let spawn_result = SpawnResult { + parent_job_id: job.id, + spawned_jobs: spawned_job_ids, + spawned_at: Utc::now(), + spawn_operation_id: config.operation_id.clone(), + }; + self.notify_spawn_complete(&job, &spawn_result).await?; + Ok(Some(spawn_result)) + } - // Enqueue child jobs - let mut spawned_job_ids = Vec::new(); - for child_job in child_jobs { - let job_id = queue.enqueue(child_job).await?; - spawned_job_ids.push(job_id); + /// Build the child jobs `job` spawns, without enqueueing them. + /// + /// Runs the job type's handler (`validate_spawn`, then `spawn_jobs`), enforces + /// `config.max_spawn_count` and applies the inheritance settings. Every child + /// depends on the parent and joins its workflow. Returns `None` when no handler is + /// registered for the job's queue. + /// + /// Workers call this before recording the parent's completion and then enqueue the + /// children in the same transaction as the completion + /// ([`DatabaseQueue::complete_job_run_with_children`]); an error here fails the + /// parent's run, so it is retried instead of completing without its children. + pub async fn prepare_spawn( + &self, + job: &Job, + config: &SpawnConfig, + queue: Arc + Send + Sync>, + ) -> Result>> { + let Some(handler) = self.handlers.get(&job.queue_name) else { + return Ok(None); + }; + // Validate spawn operation + handler.validate_spawn(job, config).await?; + + // Generate child jobs + let context = SpawnContext { + parent_job: job.clone(), + config: config.clone(), + queue, + }; + let mut child_jobs = handler.spawn_jobs(context).await?; + + // Check spawn limits + if let Some(max_count) = config.max_spawn_count + && child_jobs.len() > max_count + { + return Err(HammerworkError::SpawnError( + SpawnError::SpawnLimitExceeded { + attempted: child_jobs.len(), + limit: max_count, + }, + )); + } + + // Apply inheritance settings + for child_job in &mut child_jobs { + if config.inherit_priority { + child_job.priority = job.priority; + } + if config.inherit_retry_strategy { + child_job.retry_strategy = job.retry_strategy.clone(); + } + if config.inherit_timeout { + child_job.timeout = job.timeout; + } + if config.inherit_trace_context { + child_job.trace_id = job.trace_id.clone(); + child_job.correlation_id = job.correlation_id.clone(); + child_job.parent_span_id = job.parent_span_id.clone(); + child_job.span_context = job.span_context.clone(); } - // Create spawn result - let spawn_result = SpawnResult { - parent_job_id: job.id, - spawned_jobs: spawned_job_ids, - spawned_at: Utc::now(), - spawn_operation_id: config.operation_id.clone(), - }; + // Set up parent-child relationship + child_job.depends_on = vec![job.id]; + child_job.workflow_id = job.workflow_id; + child_job.workflow_name = job.workflow_name.clone(); + } - // Call post-spawn callback - handler.on_spawn_complete(&spawn_result).await?; + Ok(Some(child_jobs)) + } - Ok(Some(spawn_result)) - } else { - Ok(None) + /// Call the post-spawn callback (`on_spawn_complete`) of `parent`'s handler, once + /// its children were enqueued. + pub async fn notify_spawn_complete(&self, parent: &Job, result: &SpawnResult) -> Result<()> { + match self.handlers.get(&parent.queue_name) { + Some(handler) => handler.on_spawn_complete(result).await, + None => Ok(()), } } diff --git a/src/worker.rs b/src/worker.rs index 1ed741e..884596f 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -46,10 +46,18 @@ use tracing::{debug, error, info, warn}; /// Default time a worker waits for an in-flight job to finish after shutdown is requested. pub const DEFAULT_SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(30); -/// Default lease a worker holds on a running job. The worker renews it every third of -/// this period; if the worker dies, the job becomes eligible for -/// [`DatabaseQueue::requeue_stale_jobs`] once the lease expires. -pub const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(300); +/// Default lease a worker holds on a running job. The lease is taken when the job is +/// claimed and renewed every third of this period; if the worker dies, the job becomes +/// eligible for [`DatabaseQueue::requeue_stale_jobs`] once the lease expires. +pub const DEFAULT_LEASE_DURATION: Duration = crate::queue::DEFAULT_LEASE_DURATION; + +/// Default interval at which a worker's monitoring task updates its queue depth metric +/// and checks its alert thresholds ([`Worker::with_monitoring_interval`]). +pub const DEFAULT_MONITORING_INTERVAL: Duration = Duration::from_secs(30); + +/// Floor on the monitoring interval. +#[cfg(any(feature = "metrics", feature = "alerting"))] +const MIN_MONITORING_INTERVAL: Duration = Duration::from_millis(10); /// Default interval at which a [`WorkerPool`] runs the stale job reaper. pub const DEFAULT_STALE_JOB_REAPER_INTERVAL: Duration = Duration::from_secs(60); @@ -65,6 +73,10 @@ const MAX_ERROR_BACKOFF: Duration = Duration::from_secs(60); /// Floor on the error backoff so a zero poll interval can never cause a hot loop. const MIN_ERROR_BACKOFF: Duration = Duration::from_millis(100); +/// Floor on the wait between polls of an idle worker, so a zero poll interval can never +/// cause a hot loop. +pub const MIN_POLL_INTERVAL: Duration = Duration::from_millis(10); + /// Floor on the heartbeat interval derived from the lease duration. const MIN_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(100); @@ -128,6 +140,17 @@ fn effective_attempt_limit(job_max_attempts: i32, worker_cap: Option) -> i3 } } +/// Aborts a background task when dropped, so it never outlives its owner. +#[cfg(any(feature = "metrics", feature = "alerting"))] +struct AbortOnDrop(tokio::task::JoinHandle<()>); + +#[cfg(any(feature = "metrics", feature = "alerting"))] +impl Drop for AbortOnDrop { + fn drop(&mut self) { + self.0.abort(); + } +} + /// Result of one attempt to acquire a job in the worker loop. enum Acquired { // Boxed: a `Job` is much larger than the other variants. @@ -302,6 +325,11 @@ impl JobEventHooks { } /// 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 @@ -442,7 +470,8 @@ impl AutoscaleConfig { /// Metrics for autoscaling decisions #[derive(Debug, Clone, Default)] pub struct AutoscaleMetrics { - /// Current number of active workers + /// 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, @@ -470,10 +499,14 @@ type QueueDepthHistory = Arc, u64)> /// What a [`WorkerPool`] supervisor needs to apply autoscaling decisions. struct Scaling { - /// Cloned for every worker started by a scale-up + /// Cloned for every worker started by a scale-up. Only workers of its queue are + /// started or retired. template: Worker, - /// Desired number of workers, published by the autoscaling task + /// 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 @@ -758,6 +791,8 @@ pub struct Worker { shutdown_grace_period: Duration, /// Lease held on a running job, renewed by heartbeats lease_duration: Duration, + /// How often the monitoring task updates metrics and checks alerts + monitoring_interval: Duration, } impl Clone for Worker @@ -793,6 +828,7 @@ where event_manager: self.event_manager.clone(), shutdown_grace_period: self.shutdown_grace_period, lease_duration: self.lease_duration, + monitoring_interval: self.monitoring_interval, } } } @@ -805,8 +841,11 @@ where /// /// The worker will be created with: /// - 1 second polling interval - /// - 3 maximum retry attempts + /// - no cap on attempts: each job runs up to its own + /// [`max_attempts`](crate::Job::with_max_attempts) (3 unless set); see + /// [`with_max_retries`](Self::with_max_retries) /// - 30 second retry delay + /// - a [lease](Self::with_lease_duration) of [`DEFAULT_LEASE_DURATION`] (5 minutes) /// - No timeout, rate limiting, or priority configuration /// /// # Arguments @@ -876,6 +915,7 @@ where event_manager: None, shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, lease_duration: DEFAULT_LEASE_DURATION, + monitoring_interval: DEFAULT_MONITORING_INTERVAL, } } @@ -951,6 +991,7 @@ where event_manager: None, shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, lease_duration: DEFAULT_LEASE_DURATION, + monitoring_interval: DEFAULT_MONITORING_INTERVAL, } } @@ -997,6 +1038,8 @@ where /// /// Shorter intervals result in lower latency but higher database load. /// Longer intervals reduce database load but increase job processing latency. + /// Intervals below [`MIN_POLL_INTERVAL`] (10ms), including zero, wait + /// [`MIN_POLL_INTERVAL`], so an idle worker never polls in a tight loop. /// /// # Arguments /// @@ -1056,9 +1099,11 @@ where /// # let queue = Arc::new(hammerwork::JobQueue::new(pool)); /// # let handler: hammerwork::worker::JobHandler = Arc::new(|job| Box::pin(async move { Ok(()) })); /// - /// // Critical jobs get more retry attempts - /// let critical_worker = Worker::new(queue, "critical".to_string(), handler) - /// .with_max_retries(10); + /// // Expensive calls: never run a job more than twice on this worker, even if the + /// // job itself allows more attempts. To give jobs *more* attempts, raise their own + /// // limit with `Job::with_max_attempts`; this setting can only lower it. + /// let expensive_worker = Worker::new(queue, "expensive".to_string(), handler) + /// .with_max_retries(2); /// # Ok(()) /// # } /// ``` @@ -1143,6 +1188,8 @@ where /// /// Jobs that don't have their own timeout setting will use this default. /// Job-specific timeouts always take precedence over worker defaults. + /// `Duration::ZERO` means no default timeout (it would otherwise time every job + /// out before its handler ran). /// /// # Arguments /// @@ -1203,12 +1250,19 @@ where /// Set the lease the worker holds on a running job. /// - /// While a handler runs, the worker records a heartbeat and extends the job's lease - /// every third of this duration (via [`DatabaseQueue::heartbeat_job`]). If the - /// worker process dies, the lease stops being renewed and - /// [`DatabaseQueue::requeue_stale_jobs`] reclaims the job once it expires. Shorter - /// leases recover crashed jobs faster at the cost of more heartbeat writes for - /// long-running jobs; jobs that finish within a third of the lease never write one. + /// The lease is taken in the same statement that claims the job + /// ([`DatabaseQueue::dequeue_leased`]). While the handler runs, the worker records a + /// heartbeat and extends the lease every third of this duration (via + /// [`DatabaseQueue::heartbeat_job`]). If the worker process dies, the lease stops + /// being renewed and [`DatabaseQueue::requeue_stale_jobs`] reclaims the job once it + /// expires; a reaper never reclaims a job whose lease is still valid, whatever its + /// own staleness window. Shorter leases recover crashed jobs faster at the cost of + /// more heartbeat writes for long-running jobs; jobs that finish within a third of + /// the lease never write one. + /// + /// `Duration::ZERO` takes a lease that never expires and sends no heartbeats: the + /// reaper never reclaims this worker's jobs, so if the worker dies an operator has + /// to re-run them (for example with `cargo hammerwork job retry`). /// /// Defaults to [`DEFAULT_LEASE_DURATION`] (5 minutes). Requires migration /// `015_add_job_leases`. @@ -1217,6 +1271,20 @@ where self } + /// Set how often the worker's monitoring task runs (default + /// [`DEFAULT_MONITORING_INTERVAL`], 30 seconds). + /// + /// With a [metrics collector](Self::with_metrics_collector) or alerting configured, + /// a background task updates the queue depth metric and checks the alert thresholds + /// (queue depth, worker starvation, and with a statistics collector the error rate + /// and processing time) at this interval. These checks never run in the job polling + /// loop, so a slow alert target or the queue depth `COUNT(*)` never delays + /// dequeuing. Values below 10ms are raised to 10ms. + pub fn with_monitoring_interval(mut self, interval: Duration) -> Self { + self.monitoring_interval = interval; + self + } + /// The lease this worker holds on running jobs. See [`Worker::with_lease_duration`]. pub fn lease_duration(&self) -> Duration { self.lease_duration @@ -1674,9 +1742,11 @@ where pub async fn run(&self, mut shutdown_rx: mpsc::Receiver<()>) -> Result<()> { info!("Worker started for queue: {}", self.queue_name); - // Start background monitoring task for metrics and alerting + // Start background monitoring task for metrics and alerting. The guard aborts it + // however `run` ends: a normal return, an error, a panic, or this future being + // dropped (for example by a pool restarting the worker). #[cfg(any(feature = "metrics", feature = "alerting"))] - let monitoring_task = self.start_monitoring_task(); + let _monitoring_task = AbortOnDrop(self.start_monitoring_task()); let mut consecutive_errors: u32 = 0; @@ -1746,10 +1816,6 @@ where } } - // Stop monitoring task - #[cfg(any(feature = "metrics", feature = "alerting"))] - monitoring_task.abort(); - Ok(()) } @@ -1817,19 +1883,14 @@ where /// 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 { - // Check statistics and alert thresholds periodically - #[cfg(feature = "alerting")] - self.check_alert_thresholds().await; - - // Check rate limit before dequeuing jobs - if let Some(ref rate_limiter) = self.rate_limiter { - // Check if we can process a job (non-blocking) - if !rate_limiter.check() { - debug!( - "Rate limit exceeded for queue: {}, waiting before retry", - self.queue_name - ); - // Wait for the rate limiter to allow processing + // 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. + + // Take a rate limit token before dequeuing. It is handed back when no job is + // claimed, so empty or paused polls never spend the budget. + let rate_token = match &self.rate_limiter { + Some(rate_limiter) => { let permit = tokio::select! { biased; _ = shutdown_rx.recv() => return Ok(Acquired::Shutdown), @@ -1839,9 +1900,32 @@ where warn!("Rate limiter error: {}", e); return Ok(self.idle_wait(shutdown_rx).await); } + Some(rate_limiter) } + None => None, + }; + let job = self.claim_job().await; + if !matches!(job, Ok(Some(_))) + && let Some(rate_limiter) = rate_token + { + rate_limiter.refund(); } + match job? { + Some(job) => { + debug!( + "Processing job: {} with priority: {:?}", + job.id, job.priority + ); + Ok(Acquired::Job(Box::new(job))) + } + // No job available (or the queue is paused): wait before polling again. + None => Ok(self.idle_wait(shutdown_rx).await), + } + } + + /// Claim the next job of this worker's queue, with this worker's lease. + async fn claim_job(&self) -> Result> { // Check if the queue is paused match self.queue.is_queue_paused(&self.queue_name).await { Ok(true) => { @@ -1849,103 +1933,31 @@ where "Queue '{}' is paused, skipping job dequeue", self.queue_name ); - return Ok(self.idle_wait(shutdown_rx).await); - } - Ok(false) => { - // Queue is not paused, continue with normal processing + return Ok(None); } + Ok(false) => {} Err(e) => { + // The dequeue checks the pause itself, so carry on. warn!("Failed to check queue pause status: {}", e); - // Continue with normal processing if we can't check pause status } } - // Update queue depth metrics before dequeuing - #[cfg(feature = "metrics")] - if let Some(metrics_collector) = &self.metrics_collector - && let Ok(queue_depth) = self.queue.get_queue_depth(&self.queue_name).await - && let Err(e) = metrics_collector - .update_queue_depth(&self.queue_name, queue_depth) - .await - { - warn!("Failed to update queue depth metrics: {}", e); - } - - let job = if let Some(ref weights) = self.priority_weights { - // Use priority-aware dequeuing - self.queue - .dequeue_with_priority_weights(&self.queue_name, weights) - .await? - } else { - // Use regular dequeuing - self.queue.dequeue(&self.queue_name).await? - }; - - match job { - Some(job) => { - debug!( - "Processing job: {} with priority: {:?}", - job.id, job.priority - ); - Ok(Acquired::Job(Box::new(job))) - } - None => { - // No jobs available, check for worker starvation - #[cfg(feature = "alerting")] - if let Some(alert_manager) = &self.alert_manager { - let last_time_value = { - if let Ok(last_time) = self.last_job_time.read() { - Some(*last_time) - } else { - None - } - }; - if let Some(last_time_value) = last_time_value - && let Err(e) = alert_manager - .check_worker_starvation(&self.queue_name, last_time_value) - .await - { - warn!("Failed to check worker starvation: {}", e); - } - } - - // Wait before polling again - Ok(self.idle_wait(shutdown_rx).await) - } - } + self.queue + .dequeue_leased( + &self.queue_name, + self.priority_weights.as_ref(), + self.lease_duration, + ) + .await } - /// Sleep for the poll interval, returning early with `Shutdown` if shutdown is - /// requested meanwhile. + /// 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 { tokio::select! { biased; _ = shutdown_rx.recv() => Acquired::Shutdown, - _ = sleep(self.poll_interval) => Acquired::Idle, - } - } - - #[cfg(feature = "alerting")] - async fn check_alert_thresholds(&self) { - if let (Some(alert_manager), Some(stats_collector)) = - (&self.alert_manager, &self.stats_collector) - { - match stats_collector - .get_queue_statistics(&self.queue_name, Duration::from_secs(300)) - .await - { - Ok(stats) => { - if let Err(e) = alert_manager - .check_thresholds(&self.queue_name, &stats) - .await - { - warn!("Failed to check alert thresholds: {}", e); - } - } - Err(e) => { - warn!("Failed to get queue statistics for alerting: {}", e); - } - } + _ = sleep(self.poll_interval.max(MIN_POLL_INTERVAL)) => Acquired::Idle, } } @@ -1981,6 +1993,19 @@ where &self, job: &Job, outcome: JobOutcome, + ) -> Result> { + self.record(job, outcome, None).await + } + + /// Record the outcome of this run of `job`; with `children`, record its completion + /// and enqueue the children in one transaction + /// ([`DatabaseQueue::complete_job_run_with_children`]). See + /// [`record_outcome`](Self::record_outcome). + async fn record( + &self, + job: &Job, + outcome: JobOutcome, + children: Option>, ) -> Result> { // Record the outcome in a spawned task so that it always runs to commit or // rollback, even if this future is dropped (for example when the shutdown grace @@ -1988,12 +2013,20 @@ where // connection in the pool with the transaction still open. let queue = Arc::clone(&self.queue); let finished_job = job.clone(); - let recorded = - tokio::spawn(async move { queue.finish_job_run(&finished_job, outcome).await }) - .await - .map_err(|e| HammerworkError::Worker { - message: format!("recording the outcome of job {} failed: {e}", job.id), - })??; + let recorded = tokio::spawn(async move { + match children { + Some(children) => { + queue + .complete_job_run_with_children(&finished_job, children) + .await + } + None => queue.finish_job_run(&finished_job, outcome).await, + } + }) + .await + .map_err(|e| HammerworkError::Worker { + message: format!("recording the outcome of job {} failed: {e}", job.id), + })??; match recorded { Some(recorded) => { if let Some(next_run_at) = recorded.next_run_at { @@ -2078,8 +2111,11 @@ where // here. let spawn_parent = self.spawn_manager.is_some().then(|| handler_job.clone()); - // Determine timeout duration (job-specific or default) - let timeout_duration = job.timeout.or(self.default_timeout); + // Determine timeout duration (job-specific or default). A zero worker default + // means no default (see `with_default_timeout`). + let timeout_duration = job + .timeout + .or(self.default_timeout.filter(|timeout| !timeout.is_zero())); // Ok(handler result), or Err(timeout) when the handler ran out of time. let handler_result = match timeout_duration { @@ -2091,7 +2127,7 @@ where match handler_result { Ok(Ok(job_result)) => { - self.handle_success(&job, spawn_parent, job_result, start_time) + self.handle_success(&job, spawn_parent, job_result, start_time, attempts_left) .await } Ok(Err(e)) => self.handle_failure(&job, e, attempts_left).await, @@ -2099,12 +2135,46 @@ where } } + /// The child jobs `job` spawns, with their configuration, or `None` when it spawns + /// none (no spawn manager, no `_spawn_config`, or no handler for its queue). + /// + /// `spawn_parent` is the decrypted job: an encrypted job's stored payload does not + /// carry the spawn configuration. A malformed configuration or a failing spawn + /// handler is an error, which fails the run. + async fn prepare_spawn( + &self, + job: &Job, + spawn_parent: Option<&Job>, + ) -> Result, crate::spawn::SpawnConfig)>> { + let Some(spawn_manager) = &self.spawn_manager else { + return Ok(None); + }; + let parent = spawn_parent.unwrap_or(job); + let Some(config) = crate::spawn::spawn_config_from_payload(&parent.payload)? else { + return Ok(None); + }; + match spawn_manager + .prepare_spawn(parent, &config, self.queue.clone()) + .await? + { + Some(children) => Ok(Some((children, config))), + None => { + debug!( + "No spawn handler registered for job type: {}", + job.queue_name + ); + Ok(None) + } + } + } + async fn handle_success( &self, job: &Job, spawn_parent: Option, job_result: JobResult, start_time: DateTime, + attempts_left: bool, ) -> Result<()> { let job_id = job.id; debug!("Job {} completed successfully", job_id); @@ -2132,14 +2202,55 @@ where } } + // Build the children the job spawns before completing it: they are enqueued in + // the transaction that completes the parent, and a spawn failure fails this run + // (so it is retried) instead of completing the parent without its children. + let spawn = match self.prepare_spawn(job, spawn_parent.as_ref()).await { + Ok(spawn) => spawn, + Err(e) => { + warn!("Failed to spawn child jobs for job {}: {}", job_id, e); + return self.handle_failure(job, e, attempts_left).await; + } + }; + let (children, spawn_config) = match spawn { + Some((children, config)) => (Some(children), Some(config)), + None => (None, None), + }; + // Completing also reschedules a recurring job, and makes dependents whose // dependencies have all completed runnable, in the same transaction. - if self - .record_outcome(job, JobOutcome::Completed) - .await? - .is_none() - { - return Ok(()); + let recorded = match self.record(job, JobOutcome::Completed, children).await { + Ok(Some(recorded)) => recorded, + Ok(None) => return Ok(()), + // Enqueueing a child failed, so nothing was written and the job is still + // Running this run: fail the run so it is retried. + Err(e) if spawn_config.is_some() => { + warn!("Failed to enqueue the child jobs of job {}: {}", job_id, e); + return self.handle_failure(job, e, attempts_left).await; + } + Err(e) => return Err(e), + }; + + if let (Some(config), Some(spawn_manager)) = (spawn_config, &self.spawn_manager) { + let spawn_result = crate::spawn::SpawnResult { + parent_job_id: job_id, + spawned_jobs: recorded.spawned.clone(), + spawned_at: Utc::now(), + spawn_operation_id: config.operation_id, + }; + info!( + "Job {} spawned {} child jobs: {:?}", + job_id, + spawn_result.spawned_jobs.len(), + spawn_result.spawned_jobs + ); + let parent = spawn_parent.as_ref().unwrap_or(job); + if let Err(e) = spawn_manager + .notify_spawn_complete(parent, &spawn_result) + .await + { + warn!("Spawn completion callback for job {} failed: {}", job_id, e); + } } // Update batch statistics for successful completion @@ -2160,54 +2271,6 @@ where } } - // Handle job spawning if spawn manager is configured - if let Some(spawn_manager) = &self.spawn_manager { - // The parent handed to spawn handlers is the decrypted job, so encrypted jobs spawn - // like any other (their stored payload does not carry the configuration). - let parent = spawn_parent.as_ref().unwrap_or(job); - match crate::spawn::spawn_config_from_payload(&parent.payload) { - Ok(Some(spawn_config)) => { - match spawn_manager - .execute_spawn(parent.clone(), spawn_config, self.queue.clone()) - .await - { - Ok(Some(spawn_result)) => { - info!( - "Job {} spawned {} child jobs: {:?}", - job_id, - spawn_result.spawned_jobs.len(), - spawn_result.spawned_jobs - ); - - // Call spawn completion hook if present - if let Some(ref hook) = self.event_hooks.on_job_complete { - let hook_event = JobHookEvent { - job: job.clone(), - timestamp: Utc::now(), - duration: Some(Duration::from_millis(processing_time_ms)), - error: None, - }; - hook(hook_event); - } - } - Ok(None) => { - debug!( - "No spawn handler registered for job type: {}", - job.queue_name - ); - } - Err(e) => { - warn!("Failed to spawn child jobs for job {}: {}", job_id, e); - } - } - } - Ok(None) => {} - Err(e) => { - warn!("Not spawning children for job {}: {}", job_id, e); - } - } - } - // Record span success status #[cfg(feature = "tracing")] { @@ -2448,6 +2511,12 @@ where /// renewed in the background. async fn execute_handler(&self, job: Job) -> Result { let job_id = job.id; + // The run whose lease is renewed: the job as dequeued (same id, attempts and + // started_at), without its payload. + let run = Job { + payload: serde_json::Value::Null, + ..job.clone() + }; let handler_future = match std::panic::catch_unwind(AssertUnwindSafe(|| self.start_handler(job))) { Ok(future) => future, @@ -2467,7 +2536,7 @@ where error!("Handler for job {} panicked", job_id); Err(handler_panic_error(payload.as_ref())) }), - () = self.maintain_lease(job_id) => Err(HammerworkError::Worker { + () = self.maintain_lease(&run) => Err(HammerworkError::Worker { message: "job lease heartbeat stopped unexpectedly".to_string(), }), } @@ -2477,19 +2546,20 @@ where /// /// Heartbeats every third of the lease duration; the first one is sent after that /// interval, so short jobs never pay for a heartbeat write. Never completes. - async fn maintain_lease(&self, job_id: crate::job::JobId) { + 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; - match self.queue.heartbeat_job(job_id, self.lease_duration).await { + match self.queue.heartbeat_job(run, self.lease_duration).await { Ok(true) => debug!("Renewed lease on job {}", job_id), Ok(false) => { warn!( - "Lost the lease on job {}: it is no longer Running (it may have been \ - reclaimed as stale); the handler keeps running", + "Lost the lease on job {}: it is no longer Running this run (it may \ + have been reclaimed as stale); the handler keeps running", job_id ); return std::future::pending().await; @@ -2668,6 +2738,7 @@ where #[cfg(any(feature = "metrics", feature = "alerting"))] fn start_monitoring_task(&self) -> tokio::task::JoinHandle<()> { let queue_name = self.queue_name.clone(); + let monitoring_interval = self.monitoring_interval; let queue = Arc::clone(&self.queue); @@ -2684,7 +2755,9 @@ where let stats_collector = self.stats_collector.clone(); tokio::spawn(async move { - let mut interval = tokio::time::interval(Duration::from_secs(30)); // Monitor every 30 seconds + // `interval` panics on a zero period. + let mut interval = + tokio::time::interval(monitoring_interval.max(MIN_MONITORING_INTERVAL)); loop { interval.tick().await; @@ -2820,6 +2893,8 @@ impl WorkerPool where JobQueue: DatabaseQueue + Send + Sync, { + /// Create an empty pool. Autoscaling is off; enable it with + /// [`with_autoscaling`](Self::with_autoscaling). pub fn new() -> Self { Self { workers: Vec::new(), @@ -2830,7 +2905,7 @@ where encrypted_job_purge_interval: None, stats_collector: None, worker_template: None, - autoscale_config: AutoscaleConfig::default(), + 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, @@ -2864,6 +2939,7 @@ where config: &crate::config::HammerworkConfig, ) -> Result { config.encryption.validate()?; + config.worker.validate()?; let mut pool = Self::from_config(worker, &config.worker); pool.encrypted_job_purge_interval = config.encryption.purge_interval(); Ok(pool) @@ -2874,7 +2950,16 @@ where self } - /// Configure autoscaling for the worker pool + /// 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 @@ -2891,12 +2976,15 @@ where /// Every `interval` the pool calls /// [`DatabaseQueue::requeue_stale_jobs`]`(older_than)`, which moves `Running` jobs /// whose lease expired back to `Pending` (or to `Dead` when they have no attempts - /// left). `older_than` only applies to jobs that never recorded a lease; by default - /// it is the longest [lease duration](Worker::with_lease_duration) of the pool's - /// workers. The reaper is enabled by default with a 60 second interval. + /// 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 is safe. + /// 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); @@ -2944,7 +3032,8 @@ where worker.stats_collector = Some(Arc::clone(stats_collector)); } - // If no worker template is set and autoscaling is enabled, use the first worker as template + // 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() @@ -2964,11 +3053,6 @@ where pub async fn start(&mut self) -> Result<()> { info!("Starting worker pool with {} workers", self.workers.len()); - // Update initial worker count metrics - if let Ok(mut metrics) = self.autoscale_metrics.write() { - metrics.active_workers = self.workers.len(); - } - let (signal_tx, signal_rx) = watch::channel(false); let (done_tx, done_rx) = watch::channel(false); self.shutdown_signal = Some(signal_tx); @@ -2983,13 +3067,20 @@ where .flatten() .collect(); - // Start autoscaling task if enabled. It publishes the desired worker count, which - // the supervisor applies by starting workers from the template or retiring them. + // 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.len()) + 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, @@ -3076,7 +3167,11 @@ where desired_rx = None; continue; }; - let active: Vec = (0..senders.len()).filter(|i| !retired[*i]).collect(); + // 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(); @@ -3095,14 +3190,20 @@ where finished[index] = false; } } - info!("Autoscaling: started workers, now {}", desired); + 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, now {}", desired); + info!( + "Autoscaling: retiring workers of queue {}, now {}", + template.queue_name, desired + ); } } } @@ -3222,12 +3323,17 @@ where /// /// 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, initial_workers: usize) -> Option> { - let Some(worker_template) = &self.worker_template else { + 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)); } @@ -3252,6 +3358,7 @@ where Some(Scaling { template, desired: desired_rx, + initial: initial_workers, }) } @@ -3661,9 +3768,9 @@ mod tests { assert!(rate_limiter.try_acquire()); assert!(rate_limiter.try_acquire()); - // Check remaining tokens + // Check remaining tokens (refill is continuous, so a little has come back) let remaining_tokens = rate_limiter.available_tokens(); - assert_eq!(remaining_tokens, 8.0); + assert!((8.0..8.5).contains(&remaining_tokens), "{remaining_tokens}"); } #[test] @@ -4501,6 +4608,12 @@ mod tests { 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"))] @@ -4552,4 +4665,56 @@ mod tests { assert_eq!(error.error_type.as_deref(), error_type); } } + + /// #64 M10: the monitoring task stops however the worker's `run` ends, including + /// when its future is dropped or aborted (as a pool does when a worker panics). + #[cfg(all(feature = "postgres", feature = "metrics"))] + #[tokio::test] + async fn monitoring_task_stops_when_run_is_dropped() { + let metrics = Arc::new( + PrometheusMetricsCollector::new(crate::metrics::MetricsConfig::default()).unwrap(), + ); + let worker = lazy_worker("monitor") + .with_metrics_collector(Arc::clone(&metrics)) + .with_poll_interval(Duration::from_millis(10)); + // This test and the worker. + assert_eq!(Arc::strong_count(&metrics), 2); + let (_shutdown_tx, shutdown_rx) = mpsc::channel(1); + let run = tokio::spawn(async move { worker.run(shutdown_rx).await }); + + // The monitoring task holds its own handle on the collector once it runs. + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while Arc::strong_count(&metrics) < 3 && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!(Arc::strong_count(&metrics), 3); + + run.abort(); + let _ = run.await; + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while Arc::strong_count(&metrics) > 1 && std::time::Instant::now() < deadline { + tokio::time::sleep(Duration::from_millis(5)).await; + } + assert_eq!( + Arc::strong_count(&metrics), + 1, + "the monitoring task outlived the worker" + ); + } + + /// #64 M5: a zero poll interval waits at least MIN_POLL_INTERVAL between polls. + #[cfg(feature = "postgres")] + #[tokio::test] + async fn zero_poll_interval_does_not_hot_loop() { + let worker = lazy_worker("idle").with_poll_interval(Duration::ZERO); + let (_shutdown_tx, mut shutdown_rx) = mpsc::channel(1); + let started = std::time::Instant::now(); + for _ in 0..5 { + assert!(matches!( + worker.idle_wait(&mut shutdown_rx).await, + Acquired::Idle + )); + } + assert!(started.elapsed() >= MIN_POLL_INTERVAL * 5); + } } diff --git a/tests/job_lifecycle_tests.rs b/tests/job_lifecycle_tests.rs index a17d947..07ae21e 100644 --- a/tests/job_lifecycle_tests.rs +++ b/tests/job_lifecycle_tests.rs @@ -168,8 +168,8 @@ where queue.delete_job(id).await.unwrap(); } -/// H2: a worker whose run was reclaimed by the stale-job reaper (and finished by -/// someone else) cannot overwrite the job's newer state when it finally returns. +/// H2: a worker whose run was reclaimed (and finished by someone else) cannot +/// overwrite the job's newer state when it finally returns. async fn zombie_worker_cannot_overwrite_reclaimed_job(queue: Arc>) where DB: sqlx::Database + Send + Sync + 'static, @@ -196,14 +196,13 @@ where }) }) }; - let zombie = RunningWorker::start( - worker(&queue, &queue_name, handler).with_lease_duration(Duration::ZERO), - ); + let zombie = RunningWorker::start(worker(&queue, &queue_name, handler)); started.notified().await; - // The reaper reclaims the run, and another worker runs the job to completion. - let recovery = queue.requeue_stale_jobs(Duration::ZERO).await.unwrap(); - assert!(recovery.requeued.contains(&id), "{recovery:?}"); + // The run is reclaimed while the zombie still works on it (here by an operator: the + // zombie's heartbeats keep its lease valid, so the stale job reaper leaves it alone), + // and another worker runs the job to completion. + queue.retry_job(id, Utc::now()).await.unwrap(); let rerun = queue .dequeue(&queue_name) .await diff --git a/tests/job_spawning_tests.rs b/tests/job_spawning_tests.rs new file mode 100644 index 0000000..2270a7e --- /dev/null +++ b/tests/job_spawning_tests.rs @@ -0,0 +1,350 @@ +//! Spawned child jobs are enqueued in the same transaction that completes their parent +//! (#64 C2): a parent is never `Completed` without its children, and a spawn failure +//! fails the parent's run so it is retried. Each scenario runs on both backends. + +#![cfg(any(feature = "postgres", feature = "mysql"))] + +mod test_utils; + +use hammerwork::{ + HammerworkError, Job, JobId, JobQueue, JobStatus, Worker, + queue::DatabaseQueue, + retry::RetryStrategy, + spawn::{ClosureSpawnHandler, JobSpawnExt, SpawnConfig, SpawnContext, SpawnManager}, + worker::JobHandler, + workflow::DependencyStatus, +}; +use serde_json::json; +use std::{ + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; +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(); + while let Some(job) = queue.dequeue(queue_name).await.unwrap() { + jobs.push(job); + } + jobs +} + +/// Run a worker for `queue_name` with `manager` until `done` holds for job `id`. +async fn run_worker( + queue: &Arc>, + queue_name: &str, + manager: SpawnManager, + id: JobId, + done: F, +) -> Job +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, + F: Fn(&Job) -> bool, +{ + let handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); + let worker = Worker::new(Arc::clone(queue), queue_name.to_string(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_retry_delay(Duration::ZERO) + .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; + shutdown_tx.send(()).await.unwrap(); + task.await.unwrap().unwrap(); + job +} + +/// A spawn handler producing `count` children on `child_queue`; the child at index +/// `bad_index` (if any) carries a closure retry strategy, which cannot be stored, so +/// enqueueing it fails inside the completing transaction. +fn children( + child_queue: &str, + count: usize, + bad_index: Option, +) -> ClosureSpawnHandler< + impl Fn(SpawnContext) -> hammerwork::Result> + Send + Sync + 'static, + DB, +> { + let child_queue = child_queue.to_string(); + ClosureSpawnHandler::new(move |_context: SpawnContext| { + Ok((0..count) + .map(|i| { + let child = Job::new(child_queue.clone(), json!({ "i": i })); + if Some(i) == bad_index { + child.with_retry_strategy(RetryStrategy::custom(|_| Duration::from_secs(1))) + } else { + child + } + }) + .collect()) + }) +} + +/// Children keep their own retry strategy, so the injected bad child stays bad. +fn spawn_config() -> SpawnConfig { + SpawnConfig { + inherit_retry_strategy: false, + ..SpawnConfig::default() + } +} + +/// The parent completes and its children exist, released by the completion. +async fn children_are_enqueued_with_the_completion(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("spawn_ok"); + let child_queue = format!("{queue_name}_child"); + let mut manager: SpawnManager = SpawnManager::new(); + manager.register_handler(queue_name.clone(), children::(&child_queue, 3, None)); + let id = queue + .enqueue( + Job::new(queue_name.clone(), json!({})) + .with_spawn_config(spawn_config()) + .unwrap(), + ) + .await + .unwrap(); + + let parent = run_worker(&queue, &queue_name, manager, id, |job| { + job.status == JobStatus::Completed + }) + .await; + assert_eq!(parent.status, JobStatus::Completed); + assert_eq!(parent.attempts, 1); + + // The children could be claimed: their dependency on the parent is met. + let spawned = drain(&queue, &child_queue).await; + assert_eq!(spawned.len(), 3); + for child in &spawned { + assert_eq!(child.depends_on, vec![id]); + assert_ne!(child.dependency_status, DependencyStatus::Waiting); + queue.delete_job(child.id).await.unwrap(); + } + queue.delete_job(id).await.unwrap(); +} + +/// A failing spawn handler fails the parent's run: it is retried, and the retry +/// spawns the children once. +async fn failing_spawn_handler_retries_the_parent(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("spawn_retry"); + let child_queue = format!("{queue_name}_child"); + let calls = Arc::new(AtomicUsize::new(0)); + let mut manager: SpawnManager = SpawnManager::new(); + { + let (calls, child_queue) = (Arc::clone(&calls), child_queue.clone()); + manager.register_handler( + queue_name.clone(), + ClosureSpawnHandler::new(move |_context: SpawnContext| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(HammerworkError::Processing("spawn backend down".into())); + } + Ok(vec![ + Job::new(child_queue.clone(), json!({ "i": 0 })), + Job::new(child_queue.clone(), json!({ "i": 1 })), + ]) + }), + ); + } + let id = queue + .enqueue( + Job::new(queue_name.clone(), json!({})) + .with_max_attempts(3) + .with_spawning() + .unwrap(), + ) + .await + .unwrap(); + + let parent = run_worker(&queue, &queue_name, manager, id, |job| { + job.status == JobStatus::Completed + }) + .await; + assert_eq!(parent.status, JobStatus::Completed, "{parent:?}"); + assert_eq!(parent.attempts, 2, "the failed spawn retried the parent"); + assert_eq!(calls.load(Ordering::SeqCst), 2); + + let spawned = drain(&queue, &child_queue).await; + assert_eq!(spawned.len(), 2, "children are spawned exactly once"); + for child in spawned { + queue.delete_job(child.id).await.unwrap(); + } + queue.delete_job(id).await.unwrap(); +} + +/// Enqueueing a child fails after the first one was written: the whole completion is +/// rolled back, so the parent is not `Completed` and no child exists. +async fn child_enqueue_failure_rolls_back_the_completion(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("spawn_rollback"); + let child_queue = format!("{queue_name}_child"); + let mut manager: SpawnManager = SpawnManager::new(); + manager.register_handler(queue_name.clone(), children::(&child_queue, 3, Some(2))); + let id = queue + .enqueue( + Job::new(queue_name.clone(), json!({})) + .with_max_attempts(2) + .with_spawn_config(spawn_config()) + .unwrap(), + ) + .await + .unwrap(); + + // Both runs fail to spawn, so the parent ends Dead instead of Completed. + let parent = run_worker(&queue, &queue_name, manager, id, |job| { + job.status == JobStatus::Dead + }) + .await; + assert_eq!(parent.status, JobStatus::Dead, "{parent:?}"); + assert_eq!(parent.attempts, 2); + assert!( + parent + .error_message + .as_deref() + .unwrap_or_default() + .contains("retry strategy"), + "{parent:?}" + ); + assert!( + drain(&queue, &child_queue).await.is_empty(), + "no child of a failed completion may exist" + ); + let stats = queue.get_queue_stats(&child_queue).await.unwrap(); + assert_eq!(stats.pending_count + stats.running_count, 0, "{stats:?}"); + queue.delete_job(id).await.unwrap(); +} + +/// `complete_job_run_with_children` at the API level: atomic, and guarded by the run. +async fn complete_with_children_is_atomic_and_guarded(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("spawn_api"); + let child_queue = format!("{queue_name}_child"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + let run = queue.dequeue(&queue_name).await.unwrap().unwrap(); + let child = |i: u32| Job::new(child_queue.clone(), json!({ "i": i })).depends_on(&id); + + // A failing child rolls back the completion and the children before it. + let bad = child(1).with_retry_strategy(RetryStrategy::custom(|_| Duration::from_secs(1))); + assert!( + queue + .complete_job_run_with_children(&run, vec![child(0), bad]) + .await + .is_err() + ); + assert_eq!( + queue.get_job(id).await.unwrap().unwrap().status, + JobStatus::Running + ); + assert!(drain(&queue, &child_queue).await.is_empty()); + + // A stale run writes nothing. + let mut stale = run.clone(); + stale.attempts += 1; + assert!( + queue + .complete_job_run_with_children(&stale, vec![child(2)]) + .await + .unwrap() + .is_none() + ); + assert!(drain(&queue, &child_queue).await.is_empty()); + + // The current run completes and its children are released. + let recorded = queue + .complete_job_run_with_children(&run, vec![child(3), child(4)]) + .await + .unwrap() + .expect("current run"); + assert_eq!(recorded.status, JobStatus::Completed); + assert_eq!(recorded.spawned.len(), 2); + assert_eq!( + queue.get_job(id).await.unwrap().unwrap().status, + JobStatus::Completed + ); + let spawned = drain(&queue, &child_queue).await; + let mut ids: Vec = spawned.iter().map(|job| job.id).collect(); + let mut expected = recorded.spawned.clone(); + ids.sort(); + expected.sort(); + assert_eq!(ids, expected); + for job in spawned { + queue.delete_job(job.id).await.unwrap(); + } + 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!( + postgres_tests, + test_utils::setup_postgres_queue, + ignore = "requires PostgreSQL: DATABASE_URL", + [ + children_are_enqueued_with_the_completion, + failing_spawn_handler_retries_the_parent, + child_enqueue_failure_rolls_back_the_completion, + complete_with_children_is_atomic_and_guarded, + ] +); + +#[cfg(feature = "mysql")] +backend_tests!( + mysql_tests, + test_utils::setup_mysql_queue, + ignore = "requires MySQL: MYSQL_DATABASE_URL", + [ + children_are_enqueued_with_the_completion, + failing_spawn_handler_retries_the_parent, + child_enqueue_failure_rolls_back_the_completion, + complete_with_children_is_atomic_and_guarded, + ] +); diff --git a/tests/migration_lock_tests.rs b/tests/migration_lock_tests.rs new file mode 100644 index 0000000..8247be7 --- /dev/null +++ b/tests/migration_lock_tests.rs @@ -0,0 +1,259 @@ +//! Concurrent migration runs (several replicas starting with `auto_migrate`, or the CLI +//! while the application starts) must all succeed (#64 H3): the run holds a migration +//! lock, re-reads the applied migrations once it has it, and runs each migration once. + +#![cfg(any(feature = "postgres", feature = "mysql"))] + +mod test_utils; + +use chrono::Utc; +use hammerwork::migrations::{Migration, MigrationManager, MigrationRunner}; + +/// How many runs race each other. +const RUNS: usize = 6; + +/// A migration only this test knows, whose SQL fails if it runs twice: a run that does +/// not wait for the others would replay it and fail. +fn probe_migration() -> (Migration, String) { + let suffix = uuid::Uuid::new_v4().simple().to_string(); + let migration = Migration { + id: format!("900_lock_probe_{suffix}"), + description: "Concurrency probe (test only)".to_string(), + version: 900_000, + created_at: Utc::now(), + }; + (migration, format!("hw_lock_probe_{suffix}")) +} + +/// Build `RUNS` managers (one runner each) that know the built-in migrations plus the +/// probe creating `table`, and run them all at once. Every run must succeed. +async fn race(make_runner: F, migration: &Migration, table: &str) +where + DB: sqlx::Database, + F: Fn() -> Box + Send + Sync>, +{ + let sql = format!("CREATE TABLE {table} (id INT)"); + let mut runs = tokio::task::JoinSet::new(); + for _ in 0..RUNS { + let mut manager = MigrationManager::new(make_runner()); + manager.register_migration(migration.clone(), sql.clone(), sql.clone()); + runs.spawn(async move { manager.run_migrations().await }); + } + while let Some(run) = runs.join_next().await { + run.unwrap() + .expect("every concurrent migration run must succeed"); + } +} + +#[cfg(feature = "postgres")] +mod postgres_tests { + use super::*; + use hammerwork::migrations::postgres::PostgresMigrationRunner; + use sqlx::{ + Connection, Executor, PgConnection, PgPool, + postgres::{PgConnectOptions, PgPoolOptions}, + }; + use std::str::FromStr; + + async fn pool(options: &PgConnectOptions) -> PgPool { + PgPoolOptions::new() + .max_connections(3) + .connect_with(options.clone()) + .await + .unwrap() + } + + /// Concurrent runs against a migrated database each apply a new migration once. + #[tokio::test] + #[ignore = "requires PostgreSQL: DATABASE_URL"] + async fn concurrent_runs_apply_a_new_migration_once() { + let options = PgConnectOptions::from_str(&test_utils::postgres_url()).unwrap(); + let (migration, table) = probe_migration(); + let pools: Vec = futures_pools(&options).await; + let next = std::sync::atomic::AtomicUsize::new(0); + race::( + || { + let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Box::new(PostgresMigrationRunner::new(pools[i % pools.len()].clone())) + }, + &migration, + &table, + ) + .await; + + let pool = &pools[0]; + let recorded: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM hammerwork_migrations WHERE migration_id = $1", + ) + .bind(&migration.id) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(recorded, 1); + sqlx::query(&format!("DROP TABLE {table}")) + .execute(pool) + .await + .expect("the probe migration created its table"); + sqlx::query("DELETE FROM hammerwork_migrations WHERE migration_id = $1") + .bind(&migration.id) + .execute(pool) + .await + .unwrap(); + } + + async fn futures_pools(options: &PgConnectOptions) -> Vec { + let mut pools = Vec::new(); + for _ in 0..RUNS { + pools.push(pool(options).await); + } + pools + } + + /// A fresh deploy: several replicas migrate an empty database at once. + #[tokio::test] + #[ignore = "requires a PostgreSQL server on which the user may CREATE DATABASE"] + async fn concurrent_runs_migrate_a_fresh_database() { + let base = PgConnectOptions::from_str(&test_utils::postgres_url()).unwrap(); + let scratch = format!("hw_lock_{}", uuid::Uuid::new_v4().simple()); + let mut admin = PgConnection::connect_with(&base).await.unwrap(); + admin + .execute(format!("CREATE DATABASE \"{scratch}\"").as_str()) + .await + .unwrap(); + + let options = base.clone().database(&scratch); + let outcome = tokio::spawn(async move { + let pools = futures_pools(&options).await; + let mut runs = tokio::task::JoinSet::new(); + for pool in &pools { + let runner = Box::new(PostgresMigrationRunner::new(pool.clone())); + runs.spawn(async move { MigrationManager::new(runner).run_migrations().await }); + } + while let Some(run) = runs.join_next().await { + run.unwrap() + .expect("every replica's migration run must succeed"); + } + let status = + MigrationManager::new(Box::new(PostgresMigrationRunner::new(pools[0].clone()))) + .get_migration_status() + .await + .unwrap(); + assert!(status.iter().all(|(_, applied)| *applied), "{status:?}"); + for pool in pools { + pool.close().await; + } + }) + .await; + + admin + .execute(format!("DROP DATABASE IF EXISTS \"{scratch}\" WITH (FORCE)").as_str()) + .await + .unwrap(); + outcome.unwrap(); + } +} + +#[cfg(feature = "mysql")] +mod mysql_tests { + use super::*; + use hammerwork::migrations::mysql::MySqlMigrationRunner; + use sqlx::{ + Connection, Executor, MySqlConnection, MySqlPool, + mysql::{MySqlConnectOptions, MySqlPoolOptions}, + }; + use std::str::FromStr; + + async fn pools(options: &MySqlConnectOptions) -> Vec { + let mut pools = Vec::new(); + for _ in 0..RUNS { + pools.push( + MySqlPoolOptions::new() + .max_connections(3) + .connect_with(options.clone()) + .await + .unwrap(), + ); + } + pools + } + + /// Concurrent runs against a migrated database each apply a new migration once. + #[tokio::test] + #[ignore = "requires MySQL: MYSQL_DATABASE_URL"] + async fn mysql_concurrent_runs_apply_a_new_migration_once() { + let options = MySqlConnectOptions::from_str(&test_utils::mysql_url()).unwrap(); + let (migration, table) = probe_migration(); + let pools = pools(&options).await; + let next = std::sync::atomic::AtomicUsize::new(0); + race::( + || { + let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Box::new(MySqlMigrationRunner::new(pools[i % pools.len()].clone())) + }, + &migration, + &table, + ) + .await; + + let pool = &pools[0]; + let recorded: i64 = + sqlx::query_scalar("SELECT COUNT(*) FROM hammerwork_migrations WHERE migration_id = ?") + .bind(&migration.id) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(recorded, 1); + sqlx::query(&format!("DROP TABLE {table}")) + .execute(pool) + .await + .expect("the probe migration created its table"); + sqlx::query("DELETE FROM hammerwork_migrations WHERE migration_id = ?") + .bind(&migration.id) + .execute(pool) + .await + .unwrap(); + } + + /// A fresh deploy: several replicas migrate an empty database at once. + #[tokio::test] + #[ignore = "requires a MySQL server on which the user may CREATE DATABASE"] + async fn mysql_concurrent_runs_migrate_a_fresh_database() { + let base = MySqlConnectOptions::from_str(&test_utils::mysql_url()).unwrap(); + let scratch = format!("hw_lock_{}", uuid::Uuid::new_v4().simple()); + let mut admin = MySqlConnection::connect_with(&base).await.unwrap(); + admin + .execute(format!("CREATE DATABASE `{scratch}`").as_str()) + .await + .unwrap(); + + let options = base.clone().database(&scratch); + let outcome = tokio::spawn(async move { + let pools = pools(&options).await; + let mut runs = tokio::task::JoinSet::new(); + for pool in &pools { + let runner = Box::new(MySqlMigrationRunner::new(pool.clone())); + runs.spawn(async move { MigrationManager::new(runner).run_migrations().await }); + } + while let Some(run) = runs.join_next().await { + run.unwrap() + .expect("every replica's migration run must succeed"); + } + let status = + MigrationManager::new(Box::new(MySqlMigrationRunner::new(pools[0].clone()))) + .get_migration_status() + .await + .unwrap(); + assert!(status.iter().all(|(_, applied)| *applied), "{status:?}"); + for pool in pools { + pool.close().await; + } + }) + .await; + + admin + .execute(format!("DROP DATABASE IF EXISTS `{scratch}`").as_str()) + .await + .unwrap(); + outcome.unwrap(); + } +} diff --git a/tests/queue_api_tests.rs b/tests/queue_api_tests.rs index f2e840d..80b3270 100644 --- a/tests/queue_api_tests.rs +++ b/tests/queue_api_tests.rs @@ -238,6 +238,96 @@ where queue.delete_job(id).await.unwrap(); } +/// #64 M1: disabling a recurring job stops its pending occurrence, and enabling it +/// resumes the schedule, also for a job whose last run finished while disabled. +async fn disable_and_enable_recurring_jobs(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("recurring_toggle"); + let hourly = CronSchedule::new("0 0 * * * *").unwrap(); + let due_cron_job = || { + let mut job = Job::new(queue_name.clone(), json!({})) + .with_cron(hourly.clone()) + .unwrap(); + // Due now (an hour ago, so it is due on TestQueue's mock clock too). + job.scheduled_at = Utc::now() - Duration::hours(1); + job.next_run_at = Some(job.scheduled_at); + job + }; + + // A pending occurrence is held while the job is disabled. + let held = queue.enqueue(due_cron_job()).await.unwrap(); + queue.disable_recurring_job(held).await.unwrap(); + queue.disable_recurring_job(held).await.unwrap(); // idempotent + let job = queue.get_job(held).await.unwrap().unwrap(); + assert!(!job.recurring); + assert_eq!(job.next_run_at, None); + assert_eq!(job.status, JobStatus::Pending); + assert!( + queue.dequeue(&queue_name).await.unwrap().is_none(), + "a disabled recurring job ran" + ); + + // Enabling resumes it at the next occurrence (missed ones are not run). + queue.enable_recurring_job(held).await.unwrap(); + let job = queue.get_job(held).await.unwrap().unwrap(); + assert!(job.recurring); + assert_eq!(job.status, JobStatus::Pending); + assert!( + job.scheduled_at > Utc::now() - Duration::minutes(5), + "{job:?}" + ); + assert_eq!(job.next_run_at, Some(job.scheduled_at)); + assert!(queue.dequeue(&queue_name).await.unwrap().is_none()); + queue.delete_job(held).await.unwrap(); + + // A run in progress finishes; without `recurring` it is not rescheduled. + let finished = queue.enqueue(due_cron_job()).await.unwrap(); + let run = queue.dequeue(&queue_name).await.unwrap().expect("due job"); + assert_eq!(run.id, finished); + queue.disable_recurring_job(finished).await.unwrap(); + queue + .finish_job_run(&run, hammerwork::queue::JobOutcome::Completed) + .await + .unwrap() + .expect("current run"); + assert_eq!( + queue.get_job(finished).await.unwrap().unwrap().status, + JobStatus::Completed + ); + + // Enabling revives the finished job. + queue.enable_recurring_job(finished).await.unwrap(); + let job = queue.get_job(finished).await.unwrap().unwrap(); + assert!(job.recurring); + assert_eq!(job.status, JobStatus::Pending, "{job:?}"); + assert_eq!(job.attempts, 0); + assert!(job.completed_at.is_none()); + assert_eq!(job.next_run_at, Some(job.scheduled_at)); + queue.delete_job(finished).await.unwrap(); + + // Errors: a missing job, and a job without a cron schedule. + let missing = uuid::Uuid::new_v4(); + assert!(matches!( + queue.disable_recurring_job(missing).await, + Err(hammerwork::HammerworkError::JobNotFound { .. }) + )); + assert!(matches!( + queue.enable_recurring_job(missing).await, + Err(hammerwork::HammerworkError::JobNotFound { .. }) + )); + let plain = enqueue(&queue, &queue_name).await; + assert!(queue.disable_recurring_job(plain).await.is_err()); + assert!(queue.enable_recurring_job(plain).await.is_err()); + // A plain job (no cron schedule) is not held. + assert_eq!( + queue.dequeue(&queue_name).await.unwrap().map(|job| job.id), + Some(plain) + ); + queue.delete_job(plain).await.unwrap(); +} + /// The `DatabaseQueue` throttle methods use the queue's throttle registry. async fn throttle_configuration(queue: Arc) where @@ -420,6 +510,7 @@ backend_tests!( dead_job_management, statistics_queries, recurring_jobs, + disable_and_enable_recurring_jobs, throttle_configuration, pause_information, workflow_dependency_helpers, @@ -435,6 +526,7 @@ backend_tests!( dead_job_management, statistics_queries, recurring_jobs, + disable_and_enable_recurring_jobs, throttle_configuration, pause_information, workflow_dependency_helpers, @@ -455,6 +547,7 @@ backend_tests!( dead_job_management, statistics_queries, recurring_jobs, + disable_and_enable_recurring_jobs, throttle_configuration, pause_information, workflow_dependency_helpers, diff --git a/tests/queue_followup_tests.rs b/tests/queue_followup_tests.rs index 5d2a67f..9dbeb7c 100644 --- a/tests/queue_followup_tests.rs +++ b/tests/queue_followup_tests.rs @@ -349,7 +349,7 @@ where // The worker running `a` loses its lease and its outcome is not recorded assert!( !queue - .heartbeat_job(a_id, Duration::from_secs(30)) + .heartbeat_job(&run, Duration::from_secs(30)) .await .unwrap() ); @@ -807,7 +807,7 @@ mod mysql_tests { Err(HammerworkError::InvalidJobPayload { .. }) )); // A lease longer than the column can hold is capped, not an error - assert!(queue.heartbeat_job(id, Duration::MAX).await.unwrap()); + assert!(queue.heartbeat_job(&run, Duration::MAX).await.unwrap()); // A worker's retry far in the future is capped at the latest storable time queue .finish_job_run( diff --git a/tests/worker_config_tests.rs b/tests/worker_config_tests.rs index 1543f1b..e4a2029 100644 --- a/tests/worker_config_tests.rs +++ b/tests/worker_config_tests.rs @@ -430,6 +430,44 @@ where delete_jobs(&queue, &ids).await; } +/// #64 M6: polls that claim no job (empty or paused queue) do not spend the rate limit, +/// so a burst is available when jobs arrive. +async fn rate_limit_is_not_spent_on_empty_polls(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let queue_name = test_utils::unique_queue("cfg_rate_idle"); + let concurrency = Concurrency::default(); + // Three jobs an hour: after the burst, the next token takes 20 minutes. + let worker = Worker::new( + Arc::clone(&queue), + queue_name.clone(), + concurrency.handler(Duration::ZERO), + ) + .with_poll_interval(Duration::from_millis(10)) + .with_rate_limit(hammerwork::RateLimit::per_hour(3)); + let mut pool = WorkerPool::new().without_stale_job_reaper(); + pool.add_worker(worker); + + run_pool_until(&mut pool, async { + // Dozens of empty polls, then a paused stretch. + tokio::time::sleep(Duration::from_millis(300)).await; + queue.pause_queue(&queue_name, Some("test")).await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + queue.resume_queue(&queue_name, Some("test")).await.unwrap(); + + // The whole burst is still there. + let ids = enqueue_many(&queue, &queue_name, 3).await; + assert!( + wait_for_jobs(&queue, &ids, Duration::from_secs(10), completed).await, + "idle polls spent the rate limit" + ); + delete_jobs(&queue, &ids).await; + }) + .await; +} + /// An autoscaling pool starts workers from its template while the queue is deep (up /// to `max_workers`) and retires them down to `min_workers` once it drains. async fn autoscaling_adds_and_retires_workers(queue: Arc>) @@ -506,6 +544,79 @@ where delete_jobs(&queue, &again).await; } +/// #64 H9: autoscaling scales only the template's queue. Workers of other queues are +/// never retired (even when the scaled queue is idle) and never cloned. +async fn autoscaling_only_scales_the_template_queue(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let scaled = test_utils::unique_queue("cfg_scaled"); + let others = [ + test_utils::unique_queue("cfg_other_a"), + test_utils::unique_queue("cfg_other_b"), + ]; + let scaled_load = Concurrency::default(); + let other_load = Concurrency::default(); + let worker = |name: &str, load: &Concurrency| { + Worker::new( + Arc::clone(&queue), + name.to_string(), + load.handler(Duration::from_millis(150)), + ) + .with_poll_interval(Duration::from_millis(20)) + }; + let mut pool = WorkerPool::new() + .with_autoscaling( + hammerwork::worker::AutoscaleConfig::new() + .with_min_workers(1) + .with_max_workers(3) + .with_scale_up_threshold(2) + .with_scale_down_threshold(1) + .with_cooldown_period(Duration::ZERO) + .with_evaluation_window(Duration::from_millis(100)), + ) + .without_stale_job_reaper(); + // The first worker is the template; the scaled queue starts with two workers. + pool.add_worker(worker(&scaled, &scaled_load)); + pool.add_worker(worker(&others[0], &other_load)); + pool.add_worker(worker(&scaled, &scaled_load)); + pool.add_worker(worker(&others[1], &other_load)); + + // Run the pool for many evaluations while the scaled queue is idle, then drop the + // `start` future: the workers keep running in their own tasks. + tokio::select! { + result = pool.start() => panic!("pool stopped early: {result:?}"), + () = tokio::time::sleep(Duration::from_millis(1500)) => {} + } + // The idle scaled queue shrank to min_workers... + assert_eq!( + pool.get_autoscale_metrics().active_workers, + 1, + "metrics: {:?}", + pool.get_autoscale_metrics() + ); + // ...and both other queues are still served. + let mut ids = Vec::new(); + for name in &others { + ids.extend(enqueue_many(&queue, name, 2).await); + } + assert!( + wait_for_jobs(&queue, &ids, Duration::from_secs(10), completed).await, + "a worker of another queue was retired" + ); + delete_jobs(&queue, &ids).await; + + // A backlog on the scaled queue grows it to max_workers with clones of the template. + let backlog = enqueue_many(&queue, &scaled, 24).await; + assert!(wait_for_jobs(&queue, &backlog, Duration::from_secs(30), completed).await); + assert_eq!(scaled_load.peak(), 3, "scaled up to max_workers"); + assert!(other_load.peak() <= 2, "the other queues were not scaled"); + delete_jobs(&queue, &backlog).await; + + pool.shutdown().await.unwrap(); +} + /// A worker leaves a paused queue alone and picks its jobs up once it is resumed. async fn worker_waits_while_queue_is_paused(queue: Arc>) where @@ -748,8 +859,8 @@ async fn next_alert( .unwrap_or_else(|_| panic!("no {alert_type} alert")) } -/// A worker configured with alerting sends queue depth alerts (from its monitoring -/// task) and worker starvation alerts (when it finds no work) to the webhook target. +/// A worker configured with alerting sends queue depth and worker starvation alerts +/// (from its monitoring task) to the webhook target. #[cfg(feature = "alerting")] async fn worker_sends_queue_depth_and_starvation_alerts(queue: Arc>) where @@ -769,6 +880,7 @@ where config.alerting = AlertingConfig::new().alert_on_queue_depth(2).webhook(&url); let worker = Worker::new(Arc::clone(&queue), deep.clone(), Arc::clone(&noop)) .with_poll_interval(Duration::from_millis(20)) + .with_monitoring_interval(Duration::from_millis(50)) .with_hammerwork_config(&config); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); let task = tokio::spawn(async move { worker.run(shutdown_rx).await }); @@ -785,6 +897,7 @@ where let idle = test_utils::unique_queue("cfg_alert_starved"); let worker = Worker::new(Arc::clone(&queue), idle.clone(), noop) .with_poll_interval(Duration::from_millis(20)) + .with_monitoring_interval(Duration::from_millis(50)) .with_alerting_config( AlertingConfig::new() .alert_on_worker_starvation(Duration::from_millis(50)) @@ -798,6 +911,70 @@ where task.await.unwrap().unwrap(); } +/// #64 H10: an alert target that never answers does not hold up job processing; alerts +/// are checked and delivered by the monitoring task, not the polling loop. +#[cfg(feature = "alerting")] +async fn hanging_alert_target_does_not_block_jobs(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + use hammerwork::{alerting::AlertingConfig, stats::InMemoryStatsCollector}; + + // Accepts connections and never answers. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/alert", listener.local_addr().unwrap()); + let accepted = Arc::new(AtomicUsize::new(0)); + let server = { + let accepted = Arc::clone(&accepted); + tokio::spawn(async move { + let mut open = Vec::new(); + while let Ok((socket, _)) = listener.accept().await { + accepted.fetch_add(1, Ordering::SeqCst); + open.push(socket); + } + }) + }; + + let queue_name = test_utils::unique_queue("cfg_alert_hang"); + let noop: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), noop) + .with_poll_interval(Duration::from_millis(20)) + .with_monitoring_interval(Duration::from_millis(20)) + .with_stats_collector(Arc::new(InMemoryStatsCollector::new_default())) + .with_alerting_config( + AlertingConfig::new() + .alert_on_worker_starvation(Duration::from_millis(1)) + .alert_on_queue_depth(0) + .alert_on_high_error_rate(0.0) + .webhook(&url), + ); + let (shutdown_tx, shutdown_rx) = mpsc::channel(1); + 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 { + accepted.load(Ordering::SeqCst) > 0 + }) + .await; + assert!(fired, "no alert was sent"); + let ids = enqueue_many(&queue, &queue_name, 3).await; + assert!( + wait_for_jobs(&queue, &ids, Duration::from_secs(5), completed).await, + "a hanging alert target blocked job processing" + ); + + // Shutdown does not wait for the hanging alert either. + tokio::time::timeout(Duration::from_secs(5), async { + shutdown_tx.send(()).await.unwrap(); + task.await.unwrap().unwrap(); + }) + .await + .expect("shutdown waited for a hanging alert"); + server.abort(); + delete_jobs(&queue, &ids).await; +} + /// A worker with an alert manager and a statistics collector raises a high error rate /// alert once its failed jobs push the error rate over the threshold. #[cfg(feature = "alerting")] @@ -836,6 +1013,7 @@ where )); let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), failing) .with_poll_interval(Duration::from_millis(20)) + .with_monitoring_interval(Duration::from_millis(50)) .with_stats_collector(Arc::new(InMemoryStatsCollector::new_default())) .with_alert_manager(manager); let (shutdown_tx, shutdown_rx) = mpsc::channel(1); @@ -1022,6 +1200,18 @@ mod postgres_tests { 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() { @@ -1054,6 +1244,13 @@ mod postgres_tests { 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 @@ -1122,6 +1319,18 @@ mod mysql_tests { 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() { @@ -1154,6 +1363,13 @@ mod mysql_tests { 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 diff --git a/tests/worker_robustness_tests.rs b/tests/worker_robustness_tests.rs index 1beb072..bfa8d94 100644 --- a/tests/worker_robustness_tests.rs +++ b/tests/worker_robustness_tests.rs @@ -218,8 +218,9 @@ where queue.delete_job(id).await.unwrap(); } -/// Enqueue a job and claim it, leaving it `Running` as a crashed worker would. -async fn start_job(queue: &Arc>, job: Job) -> JobId +/// Enqueue a job and claim it with `lease`, leaving it `Running` as a crashed worker +/// would. Returns the run. +async fn start_job(queue: &Arc>, job: Job, lease: Duration) -> Job where DB: sqlx::Database, JobQueue: DatabaseQueue + Send + Sync + 'static, @@ -227,12 +228,50 @@ where let queue_name = job.queue_name.clone(); let id = queue.enqueue(job).await.unwrap(); let claimed = queue - .dequeue(&queue_name) + .dequeue_leased(&queue_name, None, lease) .await .unwrap() .expect("job claimed"); assert_eq!(claimed.id, id); - id + claimed +} + +/// Raw access the generic scenarios need to simulate rows written by older versions. +#[async_trait::async_trait] +trait LegacyRows { + /// Remove the lease of a `Running` job, as left by a version that claimed jobs + /// without writing one. + async fn forget_lease(&self, id: JobId); +} + +#[cfg(feature = "postgres")] +#[async_trait::async_trait] +impl LegacyRows for JobQueue { + async fn forget_lease(&self, id: JobId) { + sqlx::query( + "UPDATE hammerwork_jobs SET last_heartbeat_at = NULL, lease_expires_at = NULL \ + WHERE id = $1", + ) + .bind(id) + .execute(self.get_pool()) + .await + .unwrap(); + } +} + +#[cfg(feature = "mysql")] +#[async_trait::async_trait] +impl LegacyRows for JobQueue { + async fn forget_lease(&self, id: JobId) { + sqlx::query( + "UPDATE hammerwork_jobs SET last_heartbeat_at = NULL, lease_expires_at = NULL \ + WHERE id = ?", + ) + .bind(id.to_string()) + .execute(self.get_pool()) + .await + .unwrap(); + } } /// Jobs whose lease expired go back to `Pending` (or `Dead` when out of attempts); @@ -240,92 +279,312 @@ where async fn reaper_requeues_expired_leases(queue: Arc>) where DB: sqlx::Database, - JobQueue: DatabaseQueue + Send + Sync + 'static, + JobQueue: DatabaseQueue + LegacyRows + Send + Sync + 'static, { let _serial = test_utils::serial().await; let hour = Duration::from_secs(3600); + let short = Duration::from_millis(500); let expiring = start_job( &queue, Job::new(test_utils::unique_queue("reaper_expiring"), json!({})).with_max_attempts(3), + short, ) .await; let exhausted = start_job( &queue, Job::new(test_utils::unique_queue("reaper_exhausted"), json!({})).with_max_attempts(1), + short, ) .await; let live = start_job( &queue, Job::new(test_utils::unique_queue("reaper_live"), json!({})), + short, ) .await; let unleased = start_job( &queue, Job::new(test_utils::unique_queue("reaper_unleased"), json!({})), + short, ) .await; + queue.forget_lease(unleased.id).await; - assert!( - queue - .heartbeat_job(expiring, Duration::from_millis(500)) - .await - .unwrap() - ); - assert!( - queue - .heartbeat_job(exhausted, Duration::from_millis(500)) - .await - .unwrap() - ); - assert!(queue.heartbeat_job(live, hour).await.unwrap()); + assert!(queue.heartbeat_job(&live, hour).await.unwrap()); tokio::time::sleep(Duration::from_millis(1500)).await; let recovery = queue.requeue_stale_jobs(hour).await.unwrap(); - assert!(recovery.requeued.contains(&expiring), "{recovery:?}"); - assert!(recovery.dead.contains(&exhausted), "{recovery:?}"); - for id in [live, unleased] { + assert!(recovery.requeued.contains(&expiring.id), "{recovery:?}"); + assert!(recovery.dead.contains(&exhausted.id), "{recovery:?}"); + for id in [live.id, unleased.id] { assert!( !recovery.requeued.contains(&id) && !recovery.dead.contains(&id), "job {id} must not be reclaimed: {recovery:?}" ); } - let job = queue.get_job(expiring).await.unwrap().unwrap(); + let job = queue.get_job(expiring.id).await.unwrap().unwrap(); assert_eq!(job.status, JobStatus::Pending); assert_eq!(job.attempts, 1, "the interrupted run counts as an attempt"); assert!(job.started_at.is_none()); assert!(job.error_message.unwrap().contains("lease expired")); // The requeued job can be claimed again. let reclaimed = queue.dequeue(&job.queue_name).await.unwrap().unwrap(); - assert_eq!(reclaimed.id, expiring); + assert_eq!(reclaimed.id, expiring.id); assert_eq!(reclaimed.attempts, 2); - let job = queue.get_job(exhausted).await.unwrap().unwrap(); + let job = queue.get_job(exhausted.id).await.unwrap().unwrap(); assert_eq!(job.status, JobStatus::Dead); assert!(job.failed_at.is_some()); // A worker that lost its lease finds out on its next heartbeat. assert!( !queue - .heartbeat_job(exhausted, Duration::from_secs(1)) + .heartbeat_job(&exhausted, Duration::from_secs(1)) .await .unwrap() ); - // Without a lease, `older_than` (measured from `started_at`) decides. + // Without a lease (claimed by an older version), `older_than` (measured from + // `started_at`) decides. let recovery = queue .requeue_stale_jobs(Duration::from_millis(500)) .await .unwrap(); - assert!(recovery.requeued.contains(&unleased), "{recovery:?}"); - assert!(!recovery.requeued.contains(&live), "{recovery:?}"); + assert!(recovery.requeued.contains(&unleased.id), "{recovery:?}"); + assert!(!recovery.requeued.contains(&live.id), "{recovery:?}"); + + for id in [expiring.id, exhausted.id, live.id, unleased.id] { + queue.delete_job(id).await.unwrap(); + } +} + +/// #64 C1: a job is leased from the moment it is claimed, so a reaper with a short +/// staleness window (another pool's, or `cargo hammerwork job requeue-stale +/// --older-than-secs 1`) never reclaims it while its lease is valid, even before the +/// worker's first heartbeat. Once the lease expires it is reclaimed. +async fn claim_lease_protects_job_from_short_reaper_window(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + + // A worker with a long lease (its first heartbeat would come after 20 minutes), + // and one using the default lease of a plain `dequeue`. + let long = start_job( + &queue, + Job::new(test_utils::unique_queue("lease_long"), json!({})), + Duration::from_secs(3600), + ) + .await; + let queue_name = test_utils::unique_queue("lease_default"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + let default = queue.dequeue(&queue_name).await.unwrap().unwrap(); + assert_eq!(default.id, id); + let short = start_job( + &queue, + Job::new(test_utils::unique_queue("lease_short"), json!({})), + Duration::from_millis(400), + ) + .await; + + tokio::time::sleep(Duration::from_millis(1200)).await; + + // Reapers with any window, down to zero, leave valid leases alone. + for older_than in [ + Duration::ZERO, + Duration::from_millis(1), + Duration::from_secs(1), + ] { + let recovery = queue.requeue_stale_jobs(older_than).await.unwrap(); + for run in [&long, &default] { + assert!( + !recovery.requeued.contains(&run.id) && !recovery.dead.contains(&run.id), + "job {} was reclaimed while its lease is valid: {recovery:?}", + run.id + ); + } + if older_than.is_zero() { + assert!(recovery.requeued.contains(&short.id), "{recovery:?}"); + } + } + for run in [&long, &default] { + let job = queue.get_job(run.id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Running); + assert_eq!(job.attempts, 1); + // The worker still holds the run, so it can extend and finish it. + assert!( + queue + .heartbeat_job(run, Duration::from_secs(60)) + .await + .unwrap() + ); + } + assert_eq!( + queue.get_job(short.id).await.unwrap().unwrap().status, + JobStatus::Pending + ); - for id in [expiring, exhausted, live, unleased] { + for id in [long.id, default.id, short.id] { queue.delete_job(id).await.unwrap(); } } +/// #64 C1: after a run is reclaimed and claimed again, the first run's worker (still +/// alive, still heartbeating) cannot extend the new run's lease. +async fn stale_heartbeat_cannot_extend_new_run(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let lease = Duration::from_millis(400); + let first = start_job( + &queue, + Job::new(test_utils::unique_queue("lease_rerun"), json!({})).with_max_attempts(5), + lease, + ) + .await; + tokio::time::sleep(Duration::from_millis(900)).await; + let recovery = queue + .requeue_stale_jobs(Duration::from_secs(3600)) + .await + .unwrap(); + assert!(recovery.requeued.contains(&first.id), "{recovery:?}"); + + let second = queue + .dequeue_leased(&first.queue_name, None, lease) + .await + .unwrap() + .expect("requeued job"); + assert_eq!(second.id, first.id); + assert_eq!(second.attempts, 2); + + // The old run's heartbeats report the lost lease and change nothing. + for _ in 0..3 { + assert!( + !queue + .heartbeat_job(&first, Duration::from_secs(3600)) + .await + .unwrap() + ); + tokio::time::sleep(Duration::from_millis(300)).await; + } + // So the new run's lease expired on schedule. + let recovery = queue + .requeue_stale_jobs(Duration::from_secs(3600)) + .await + .unwrap(); + assert!( + recovery.requeued.contains(&second.id), + "the stale heartbeat extended the new run's lease: {recovery:?}" + ); + assert!( + !queue + .heartbeat_job(&second, Duration::from_secs(60)) + .await + .unwrap() + ); + queue.delete_job(first.id).await.unwrap(); +} + +/// A zero lease never expires: the reaper never reclaims the job. +async fn zero_lease_is_never_reclaimed(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let run = start_job( + &queue, + Job::new(test_utils::unique_queue("lease_zero"), json!({})), + Duration::ZERO, + ) + .await; + tokio::time::sleep(Duration::from_millis(50)).await; + let recovery = queue.requeue_stale_jobs(Duration::ZERO).await.unwrap(); + assert!( + !recovery.requeued.contains(&run.id) && !recovery.dead.contains(&run.id), + "{recovery:?}" + ); + assert!(queue.heartbeat_job(&run, Duration::ZERO).await.unwrap()); + let recovery = queue.requeue_stale_jobs(Duration::ZERO).await.unwrap(); + assert!(!recovery.requeued.contains(&run.id), "{recovery:?}"); + assert_eq!( + queue.get_job(run.id).await.unwrap().unwrap().status, + JobStatus::Running + ); + queue.delete_job(run.id).await.unwrap(); +} + +/// #64 C1 scenario A: a worker with a long lease runs a job while another pool's reaper +/// uses a tiny staleness window. The job runs once. +async fn other_pools_reaper_does_not_rerun_live_job(queue: Arc>) +where + DB: sqlx::Database + Send + Sync + 'static, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let queue_name = test_utils::unique_queue("lease_two_pools"); + let id = queue + .enqueue(Job::new(queue_name.clone(), json!({}))) + .await + .unwrap(); + + let runs = Arc::new(AtomicUsize::new(0)); + let handler: JobHandler = { + let runs = Arc::clone(&runs); + Arc::new(move |_job: Job| { + let runs = Arc::clone(&runs); + Box::pin(async move { + runs.fetch_add(1, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(1500)).await; + Ok::<(), HammerworkError>(()) + }) + }) + }; + // Service A: two workers with a one hour lease, so no heartbeat during the job. + let worker = Worker::new(Arc::clone(&queue), queue_name.clone(), handler) + .with_poll_interval(Duration::from_millis(50)) + .with_lease_duration(Duration::from_secs(3600)); + let mut service_a = WorkerPool::new().without_stale_job_reaper(); + service_a.add_worker(worker.clone()); + service_a.add_worker(worker); + // Service B: no workers on this queue, only an aggressive reaper. + let idle_handler: JobHandler = Arc::new(|_job: Job| Box::pin(async { Ok(()) })); + let mut service_b = WorkerPool::new() + .with_stale_job_reaper(Duration::from_millis(100), Duration::from_millis(1)); + service_b.add_worker(Worker::new( + Arc::clone(&queue), + test_utils::unique_queue("lease_other_service"), + idle_handler, + )); + + tokio::select! { + 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| { + job.status == JobStatus::Completed + }) => {} + } + // Let the reaper run a few more passes, then stop both pools. + tokio::time::sleep(Duration::from_millis(300)).await; + service_a.shutdown().await.unwrap(); + service_b.shutdown().await.unwrap(); + + let job = queue.get_job(id).await.unwrap().unwrap(); + assert_eq!(job.status, JobStatus::Completed); + assert_eq!(job.attempts, 1, "the job was reclaimed and run again"); + assert_eq!(runs.load(Ordering::SeqCst), 1, "the job ran twice"); + queue.delete_job(id).await.unwrap(); +} + /// Concurrent reapers must reclaim every stale job exactly once. async fn concurrent_reapers_never_double_requeue(queue: Arc>) where @@ -336,18 +595,13 @@ where let queue_name = test_utils::unique_queue("reaper_concurrency"); let mut stale = HashSet::new(); for i in 0..40 { - let id = start_job( + let run = start_job( &queue, Job::new(queue_name.clone(), json!({ "index": i })).with_max_attempts(3), + Duration::from_millis(200), ) .await; - assert!( - queue - .heartbeat_job(id, Duration::from_millis(200)) - .await - .unwrap() - ); - stale.insert(id); + stale.insert(run.id); } tokio::time::sleep(Duration::from_millis(800)).await; @@ -437,84 +691,55 @@ where queue.delete_job(id).await.unwrap(); } -#[cfg(feature = "postgres")] -mod postgres_tests { - use super::*; - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_handler_panic_fails_job_and_worker_survives() { - handler_panic_fails_job_and_worker_survives(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_handler_panic_is_retried() { - handler_panic_is_retried(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_graceful_shutdown_completes_in_flight_job() { - graceful_shutdown_completes_in_flight_job(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_reaper_requeues_expired_leases() { - reaper_requeues_expired_leases(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_concurrent_reapers_never_double_requeue() { - concurrent_reapers_never_double_requeue(test_utils::setup_postgres_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_postgres_worker_heartbeat_keeps_long_job_leased() { - worker_heartbeat_keeps_long_job_leased(test_utils::setup_postgres_queue().await).await; - } +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 = "mysql")] -mod mysql_tests { - use super::*; - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_handler_panic_fails_job_and_worker_survives() { - handler_panic_fails_job_and_worker_survives(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_handler_panic_is_retried() { - handler_panic_is_retried(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_graceful_shutdown_completes_in_flight_job() { - graceful_shutdown_completes_in_flight_job(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_reaper_requeues_expired_leases() { - reaper_requeues_expired_leases(test_utils::setup_mysql_queue().await).await; - } - - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_concurrent_reapers_never_double_requeue() { - concurrent_reapers_never_double_requeue(test_utils::setup_mysql_queue().await).await; - } +#[cfg(feature = "postgres")] +backend_tests!( + postgres_tests, + test_utils::setup_postgres_queue, + ignore = "requires PostgreSQL: DATABASE_URL", + [ + handler_panic_fails_job_and_worker_survives, + handler_panic_is_retried, + graceful_shutdown_completes_in_flight_job, + reaper_requeues_expired_leases, + claim_lease_protects_job_from_short_reaper_window, + stale_heartbeat_cannot_extend_new_run, + zero_lease_is_never_reclaimed, + other_pools_reaper_does_not_rerun_live_job, + concurrent_reapers_never_double_requeue, + worker_heartbeat_keeps_long_job_leased, + ] +); - #[tokio::test] - #[ignore] // Requires database connection - async fn test_mysql_worker_heartbeat_keeps_long_job_leased() { - worker_heartbeat_keeps_long_job_leased(test_utils::setup_mysql_queue().await).await; - } -} +#[cfg(feature = "mysql")] +backend_tests!( + mysql_tests, + test_utils::setup_mysql_queue, + ignore = "requires MySQL: MYSQL_DATABASE_URL", + [ + handler_panic_fails_job_and_worker_survives, + handler_panic_is_retried, + graceful_shutdown_completes_in_flight_job, + reaper_requeues_expired_leases, + claim_lease_protects_job_from_short_reaper_window, + stale_heartbeat_cannot_extend_new_run, + zero_lease_is_never_reclaimed, + other_pools_reaper_does_not_rerun_live_job, + concurrent_reapers_never_double_requeue, + worker_heartbeat_keeps_long_job_leased, + ] +);