From 0f0dbfa0eb4cdb7f531aa3b09d71a234e2330a7f Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 19:51:44 -0400 Subject: [PATCH 1/2] fix: pre-release CLI, dashboard and docs fixes for 3.0 (#131) - hammerwork-web: remove the public __private module (tests moved in-crate), drop the unused metrics feature - job requeue-stale: --queue and --dry-run - monitor health / queue health: stuck means lease expired; lease-less Running jobs reported separately - migration status: applied and pending migrations - docs: upgrade order, own sections for moved notes, azure-kms, CHANGELOG links, CLAUDE.md, doc examples, docker init scripts Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 33 +- CLAUDE.md | 33 +- cargo-hammerwork/README.md | 13 +- cargo-hammerwork/src/commands/job.rs | 190 +++++++++- cargo-hammerwork/src/commands/migration.rs | 319 ++++++++++++++++- cargo-hammerwork/src/commands/monitor.rs | 174 +++++++-- cargo-hammerwork/src/commands/queue.rs | 119 +++++-- cargo-hammerwork/src/config/mod.rs | 12 +- .../src/integration_tests/sql_query.rs | 32 +- cargo-hammerwork/src/utils/database.rs | 16 +- cargo-hammerwork/src/utils/display.rs | 14 +- cargo-hammerwork/src/utils/job_ops.rs | 16 + cargo-hammerwork/tests/cli_binary_tests.rs | 5 +- config/init-mysql.sql | 57 +-- config/init-postgres.sql | 70 +--- docs/integration-testing.md | 11 +- docs/upgrading-to-3.0.md | 67 +++- hammerwork-web/Cargo.toml | 2 +- hammerwork-web/src/api/archive.rs | 100 +++--- hammerwork-web/src/api/jobs.rs | 134 +++---- hammerwork-web/src/api/mod.rs | 82 +++-- hammerwork-web/src/api/queues.rs | 179 +++++----- hammerwork-web/src/api/stats.rs | 197 ++++++----- hammerwork-web/src/api/system.rs | 205 ++++++----- hammerwork-web/{tests => src}/api_tests.rs | 24 +- hammerwork-web/src/auth.rs | 109 +++--- hammerwork-web/src/config.rs | 332 ++++++++---------- hammerwork-web/src/lib.rs | 33 +- hammerwork-web/src/security.rs | 34 +- hammerwork-web/src/websocket.rs | 72 ++-- hammerwork-web/src/websocket_archive_tests.rs | 191 ++++++++++ hammerwork-web/tests/integration_tests.rs | 196 +---------- src/migrations/mod.rs | 12 + 33 files changed, 1854 insertions(+), 1229 deletions(-) rename hammerwork-web/{tests => src}/api_tests.rs (98%) create mode 100644 hammerwork-web/src/websocket_archive_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8eee38b..c231764 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. -- **sqlx 0.9** (#85). Hammerwork now depends on sqlx 0.9 instead of 0.8. sqlx types are +- **sqlx 0.9** ([#85](https://github.com/CodingAnarchy/hammerwork/issues/85)). Hammerwork now depends on sqlx 0.9 instead of 0.8. sqlx types are part of the public API (the pool passed to `JobQueue::new`, `JobQueue`, `DatabaseQueue`, the migration runners, sqlx `Encode`/`Decode` for `JobStatus` and `BatchStatus`), so applications must move their own sqlx dependency to 0.9 as well. @@ -23,14 +23,14 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. connections no longer force the `utf8mb4_unicode_ci` collation. No schema migration is needed. - **MSRV is now Rust 1.94.0** (was 1.91.1), as required by sqlx 0.9. -- **No features are enabled by default** (#92). `default` used to be `["metrics", "alerting", "webhooks"]`, which pulled `warp`, `reqwest`, `lettre` and `prometheus` into every build. It is now empty. Enable what you use, or the new `full` feature (`metrics`, `alerting`, `webhooks`, `streaming`, `tracing`, `encryption`; no database backend, KMS key source, event stream sink or `test-queue`). Code that uses `hammerwork::metrics`, `hammerwork::alerting` or `hammerwork::webhooks` must now enable those features. `cargo-hammerwork` and `hammerwork-web` enable the features they need themselves. -- **`azure-kv` is renamed `azure-kms`**, to match `aws-kms`, `gcp-kms` and `vault-kms` (#92). There is no alias. The same rename applies to the `cargo-hammerwork` feature. -- **`test` is renamed `test-queue`**, after the `TestQueue` it enables (#92). There is no alias. -- **`DatabaseQueue` is sealed** (#87). It can no longer be implemented outside Hammerwork; its implementations are `JobQueue`, `JobQueue` and `TestQueue`, and it stays usable as a bound (`impl DatabaseQueue`, `Q: DatabaseQueue`). Use `TestQueue` (feature `test-queue`) to test without a database. The default method bodies that existed only for implementations outside the crate are gone (the one-at-a-time fallback for batch claims, and the fallbacks of `release_job_run`, `finish_job_run`, `complete_job_run_with_children`, `heartbeat_job`, `start_claimed_run`, `requeue_stale_jobs`, `purge_expired_encrypted_jobs`, `purge_archived_jobs_in_queue` and `list_queue_names`); every backend implements these methods, so behaviour does not change. `queue::RELEASED_JOB_MESSAGE`, the error message of the removed `release_job_run` fallback, is removed. -- **One claim method** (#89). `DatabaseQueue::dequeue(queue, &DequeueOptions)` replaces `dequeue`, `dequeue_with_priority_weights`, `dequeue_leased`, `dequeue_batch` and `dequeue_batch_leased`. It returns `Vec`. The new `#[non_exhaustive]` `queue::DequeueOptions` (also `hammerwork::DequeueOptions`) has `priority_weights: Option`, `lease_duration: Option` (`None` is `DEFAULT_LEASE_DURATION`) and `max_jobs` (default 1), built with `DequeueOptions::new()`/`default()`, `DequeueOptions::batch(n)`, `with_priority_weights`, `with_lease_duration` and `with_max_jobs`. `DatabaseQueue::dequeue_one(queue)` keeps the common case short: it is the 2.x `dequeue(queue)` (one job, strict priority, default lease, `Option`). Claims behave as before: a `max_jobs` of 1 claims like the old single-job methods, larger values like the old batch claims. -- **`Worker::with_batch_processing_enabled` is removed** (#89). `with_batch_size(n)` enables batch mode, as it already did; `with_batch_size(1)` replaces `with_batch_processing_enabled(true)` (batch statistics, one job per poll). New optional `[worker]` settings `batch_size` and `batch_concurrency` (`WorkerConfig::batch_size`, `WorkerConfig::batch_concurrency`) set them from configuration through `Worker::with_config`; `WorkerConfig` is now non-exhaustive (see below), so build it with `WorkerConfig::default().with_batch_size(n)`. -- **`Worker::with_max_retries` is renamed `with_attempt_cap`** (#89), since it can only lower a job's own `max_attempts`. There is no alias. -- **MySQL times are stored as `DATETIME(6)`** (#91). Migration `021_mysql_datetime` converts every `TIMESTAMP` column of every Hammerwork table to `DATETIME(6)`, which lifts the year-2038 limit: jobs can be scheduled, retried, leased and archived up to year 9999. The MySQL backend no longer rejects times after 2038-01-19 03:14:07 UTC (and no longer caps leases at it); only times outside years 1000 to 9999 are rejected with `HammerworkError::InvalidJobPayload`. MySQL rebuilds every table for the conversion, which blocks writes while it runs: run it off-peak. Its UTC column defaults need MySQL 8.0.13 or later. See [MySQL timestamps (migration 021)](docs/upgrading-to-3.0.md#mysql-timestamps-migration-021). +- **No features are enabled by default** ([#92](https://github.com/CodingAnarchy/hammerwork/issues/92)). `default` used to be `["metrics", "alerting", "webhooks"]`, which pulled `warp`, `reqwest`, `lettre` and `prometheus` into every build. It is now empty. Enable what you use, or the new `full` feature (`metrics`, `alerting`, `webhooks`, `streaming`, `tracing`, `encryption`; no database backend, KMS key source, event stream sink or `test-queue`). Code that uses `hammerwork::metrics`, `hammerwork::alerting` or `hammerwork::webhooks` must now enable those features. `cargo-hammerwork` and `hammerwork-web` enable the features they need themselves. +- **`azure-kv` is renamed `azure-kms`**, to match `aws-kms`, `gcp-kms` and `vault-kms` ([#92](https://github.com/CodingAnarchy/hammerwork/issues/92)). There is no alias. The same rename applies to the `cargo-hammerwork` feature. +- **`test` is renamed `test-queue`**, after the `TestQueue` it enables ([#92](https://github.com/CodingAnarchy/hammerwork/issues/92)). There is no alias. +- **`DatabaseQueue` is sealed** ([#87](https://github.com/CodingAnarchy/hammerwork/issues/87)). It can no longer be implemented outside Hammerwork; its implementations are `JobQueue`, `JobQueue` and `TestQueue`, and it stays usable as a bound (`impl DatabaseQueue`, `Q: DatabaseQueue`). Use `TestQueue` (feature `test-queue`) to test without a database. The default method bodies that existed only for implementations outside the crate are gone (the one-at-a-time fallback for batch claims, and the fallbacks of `release_job_run`, `finish_job_run`, `complete_job_run_with_children`, `heartbeat_job`, `start_claimed_run`, `requeue_stale_jobs`, `purge_expired_encrypted_jobs`, `purge_archived_jobs_in_queue` and `list_queue_names`); every backend implements these methods, so behaviour does not change. `queue::RELEASED_JOB_MESSAGE`, the error message of the removed `release_job_run` fallback, is removed. +- **One claim method** ([#89](https://github.com/CodingAnarchy/hammerwork/issues/89)). `DatabaseQueue::dequeue(queue, &DequeueOptions)` replaces `dequeue`, `dequeue_with_priority_weights`, `dequeue_leased`, `dequeue_batch` and `dequeue_batch_leased`. It returns `Vec`. The new `#[non_exhaustive]` `queue::DequeueOptions` (also `hammerwork::DequeueOptions`) has `priority_weights: Option`, `lease_duration: Option` (`None` is `DEFAULT_LEASE_DURATION`) and `max_jobs` (default 1), built with `DequeueOptions::new()`/`default()`, `DequeueOptions::batch(n)`, `with_priority_weights`, `with_lease_duration` and `with_max_jobs`. `DatabaseQueue::dequeue_one(queue)` keeps the common case short: it is the 2.x `dequeue(queue)` (one job, strict priority, default lease, `Option`). Claims behave as before: a `max_jobs` of 1 claims like the old single-job methods, larger values like the old batch claims. +- **`Worker::with_batch_processing_enabled` is removed** ([#89](https://github.com/CodingAnarchy/hammerwork/issues/89)). `with_batch_size(n)` enables batch mode, as it already did; `with_batch_size(1)` replaces `with_batch_processing_enabled(true)` (batch statistics, one job per poll). New optional `[worker]` settings `batch_size` and `batch_concurrency` (`WorkerConfig::batch_size`, `WorkerConfig::batch_concurrency`) set them from configuration through `Worker::with_config`; `WorkerConfig` is now non-exhaustive (see below), so build it with `WorkerConfig::default().with_batch_size(n)`. +- **`Worker::with_max_retries` is renamed `with_attempt_cap`** ([#89](https://github.com/CodingAnarchy/hammerwork/issues/89)), since it can only lower a job's own `max_attempts`. There is no alias. +- **MySQL times are stored as `DATETIME(6)`** ([#91](https://github.com/CodingAnarchy/hammerwork/issues/91)). Migration `021_mysql_datetime` converts every `TIMESTAMP` column of every Hammerwork table to `DATETIME(6)`, which lifts the year-2038 limit: jobs can be scheduled, retried, leased and archived up to year 9999. The MySQL backend no longer rejects times after 2038-01-19 03:14:07 UTC (and no longer caps leases at it); only times outside years 1000 to 9999 are rejected with `HammerworkError::InvalidJobPayload`. MySQL rebuilds every table for the conversion, which blocks writes while it runs: run it off-peak. Its UTC column defaults need MySQL 8.0.13 or later. See [MySQL timestamps (migration 021)](docs/upgrading-to-3.0.md#mysql-timestamps-migration-021). - **Configuration, statistics and record structs are `#[non_exhaustive]`** ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)). Code outside Hammerwork can no longer build them with struct literals (not even with `..Default::default()`); fields stay public for reading and assignment. Configuration types are built from `default()` or a constructor and `with_*` methods, and every field of the configuration sections now has one: new setters on `DatabaseConfig`, `WorkerConfig`, `WebhookConfigs`, `WebhookGlobalSettings`, `StreamingConfigs`, `StreamingGlobalSettings`, `ArchiveConfig`, `RateLimitingConfig` (plus `with_queue_throttle`), `LoggingConfig`, `PayloadEncryptionConfig` (plus `with_decryption_key`), `KeyRotationConfig`, `EventConfig`, `webhooks::RetryPolicy`, `WebhookManagerConfig`, `StreamRetryPolicy`, `BufferConfig`, `StreamManagerConfig`, `SpawnConfig`, `StatsConfig` and `KeyDerivationConfig`; `HammerworkConfig::with_database`/`with_worker`/... for each section; `KeyManagerConfig::with_key_derivation_config`; and new constructors `JobError::new`, `JobLifecycleEvent::new` (with setters), `stats::JobEvent::new` (with setters), `ExternalKmsConfig::new` (with `with_auth`, `with_auth_config`, `with_region`, `with_namespace`), `Migration::new`, `ArchivedJob::new` and `SpawnContext::new`. `stats::QueueStats` now implements `Default`. Also non-exhaustive: `Job`, `ResultConfig`, `JobBatch`, `JobGroup`, `EventFilter`, `WebhookConfig`, `StreamConfig`, `AlertingConfig`, `SmtpConfig`, `ArchivalPolicy`, `ArchivalConfig`, `EncryptionConfig`, `KeyManagerConfig`, `KeyAuditFilter`, `MetricsConfig`, `TracingConfig`, `ThrottleConfig`, `AutoscaleConfig` and `JobEventHooks` (all already had builders), every `*Stats` struct, and the records `WebhookDelivery`, `StreamDelivery`, `StreamedEvent`, `EncryptionKey`, `KeyAuditRecord`, `KmsWrappedKey`, `EncryptionMetadata`, `EncryptedPayload`, `MigrationRecord`, `QueuePauseInfo`, `RecordedOutcome`, `SpawnResult`, `JobHookEvent`, `JobResult`, `BatchResult`, `Alert` and `ScheduledArchivalPass`. In `hammerwork-web`, `DashboardConfig`, `AuthConfig` and `WebSocketConfig` are non-exhaustive, with new setters (`DashboardConfig::with_pool_size`, `with_auth_config`, `with_websocket`, `with_allowed_origins`; every field of `AuthConfig` and `WebSocketConfig`; `AuthConfig::disabled()`). See the upgrade guide for the full list. - **`ArchivedJob` has `workflow_id` and `workflow_name`** ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)), filled in by `list_archived_jobs` on PostgreSQL, MySQL and `TestQueue` from the archive columns added in migration 019. No migration is needed. - **Dropping an `EventSubscription` unregisters it** from its `EventManager` ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)), so `subscription_count` and `payload_wanted` stop counting it without a call to `EventManager::unsubscribe` (which still works). The subscription holds a private reference to the manager's registry, so its `receiver` can no longer be moved out of it: keep the subscription alive while reading. The registry uses a std lock, so dropping works outside a Tokio runtime. The webhook and stream managers' listeners hold their subscriptions and unregister when they stop. @@ -49,9 +49,18 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. - **`Worker::with_attempt_cap` returns `Result`** and rejects a cap below 1 with `HammerworkError::Config` (it silently acted as 1) ([#130](https://github.com/CodingAnarchy/hammerwork/issues/130)). - **`WebhookManager::new` and `new_default` return `Result`** instead of panicking when the HTTP client cannot be built; `WebhookManager::try_new` is removed ([#130](https://github.com/CodingAnarchy/hammerwork/issues/130)). - **`WorkerConfig::validate` checks the batch settings** ([#130](https://github.com/CodingAnarchy/hammerwork/issues/130)): `batch_size = 0` (which turned batch mode on), a `batch_size` above `MAX_DEQUEUE_BATCH_SIZE` and `batch_concurrency = 0` are rejected by `HammerworkConfig::from_file`/`from_env`, `WorkerPool::from_hammerwork_config` and now also `Worker::with_hammerwork_config`. +- **`cargo-hammerwork` is a binary only** ([#88](https://github.com/CodingAnarchy/hammerwork/issues/88)). The crate no longer has a library target: `cargo_hammerwork::commands`, `cargo_hammerwork::config`, `cargo_hammerwork::utils` and their glob re-exports are gone. Drive the CLI through the `cargo hammerwork` executable. +- **`hammerwork-web` exposes only `WebDashboard`, `DashboardConfig`, `AuthConfig` and `WebSocketConfig`** ([#88](https://github.com/CodingAnarchy/hammerwork/issues/88)). The `api`, `auth`, `config`, `live`, `security`, `server` and `websocket` modules are private, so `hammerwork_web::server::app_routes` and the other building blocks are no longer public API. `WebSocketConfig` is now re-exported at the crate root (it was `hammerwork_web::config::WebSocketConfig`). There is no `__private` re-export of the internals either: the crate's own tests live inside the crate. + +### Added + +- **`job requeue-stale --queue ` and `--dry-run`**. `--queue` reclaims only that queue's stale jobs (the unscoped command still uses the library's single atomic reclaim); `--dry-run` counts the jobs the lease rule would reclaim without changing anything. Both use bound parameters on PostgreSQL and MySQL. +- **`migration status` lists applied and pending migrations**, from `hammerwork_migrations` against the migrations the library registers, plus applied migrations this version does not know (it used to list the columns of `hammerwork_jobs`; the column count remains as a summary). New `MigrationManager::registered_migrations()` returns the registered migrations without touching the database. ### Fixed +- **`monitor health` and `queue health` no longer call a `Running` job stuck after an hour.** A job is stuck when its lease expired (the rule of `requeue_stale_jobs`, shared with `maintenance dead-jobs` and `job requeue-stale`), so a long-running job that keeps heartbeating is healthy. `Running` jobs without a lease (left by a Hammerwork 1.x worker) are reported on their own `Lease-less Running Jobs` row; `monitor health --format json` gains that check. + - Building with `encryption` but no database backend (and so with `full`) no longer fails clippy with dead-code and unused-import errors. - Workers publish lifecycle events to an `EventManager` (`Worker::with_event_manager`) without the `webhooks` feature, so streaming-only builds and plain `EventManager` subscribers get them ([#130](https://github.com/CodingAnarchy/hammerwork/issues/130)). In 2.x this worked only because `webhooks` was a default feature. - `TestQueue::set_throttle_config` rejects an enabled throttle with a zero rate, as the PostgreSQL and MySQL queues do ([#130](https://github.com/CodingAnarchy/hammerwork/issues/130)). @@ -60,15 +69,15 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. ### Changed +- `hammerwork-web` no longer enables hammerwork's `metrics` feature, which it never used (the dashboard still reports `prometheus_enabled: false`). +- `config/init-mysql.sql` and `config/init-postgres.sql` (docker-compose) no longer create a `hammerwork_jobs` table and a seed job: the schema comes from `cargo hammerwork migration run`, so it always matches the library. The MySQL script only grants the user's permissions. - CI checks the feature combinations `full`, `postgres,full`, `mysql,full` and `test-queue`. - The library no longer depends on the `rsa` crate (RUSTSEC-2023-0071), which sqlx 0.9 made optional. It stays in the lockfile only through the CLI and dashboard binaries. -- **`cargo-hammerwork` is a binary only** ([#88](https://github.com/CodingAnarchy/hammerwork/issues/88)). The crate no longer has a library target: `cargo_hammerwork::commands`, `cargo_hammerwork::config`, `cargo_hammerwork::utils` and their glob re-exports are gone. Drive the CLI through the `cargo hammerwork` executable. -- **`hammerwork-web` exposes only `WebDashboard`, `DashboardConfig`, `AuthConfig` and `WebSocketConfig`** ([#88](https://github.com/CodingAnarchy/hammerwork/issues/88)). The `api`, `auth`, `config`, `live`, `security`, `server` and `websocket` modules are private, so `hammerwork_web::server::app_routes` and the other building blocks are no longer public API. `WebSocketConfig` is now re-exported at the crate root (it was `hammerwork_web::config::WebSocketConfig`). ### Database -- Migration `021_mysql_datetime` (#91): on MySQL, converts all 39 `TIMESTAMP` / `TIMESTAMP(6)` columns of `hammerwork_jobs`, `hammerwork_jobs_archive`, `hammerwork_batches`, `hammerwork_encryption_keys`, `hammerwork_key_audit_log`, `hammerwork_kms_data_keys`, `hammerwork_queue_pause` and `hammerwork_migrations`, and the 3 second-precision `DATETIME` columns of `hammerwork_workflows` (`created_at`, `completed_at`, `failed_at`), to `DATETIME(6)`, keeping nullability and values. `CURRENT_TIMESTAMP` defaults, which on `DATETIME` are the session's local time, become the UTC expression default `(UTC_TIMESTAMP(6))` (MySQL 8.0.13+), and the `ON UPDATE CURRENT_TIMESTAMP` clause of `hammerwork_queue_pause.updated_at` is dropped (Hammerwork writes `updated_at` itself) (#130). One `ALTER TABLE` per table, run under a UTC session `time_zone`, safe to re-run. A no-op on PostgreSQL. +- Migration `021_mysql_datetime` ([#91](https://github.com/CodingAnarchy/hammerwork/issues/91)): on MySQL, converts all 39 `TIMESTAMP` / `TIMESTAMP(6)` columns of `hammerwork_jobs`, `hammerwork_jobs_archive`, `hammerwork_batches`, `hammerwork_encryption_keys`, `hammerwork_key_audit_log`, `hammerwork_kms_data_keys`, `hammerwork_queue_pause` and `hammerwork_migrations`, and the 3 second-precision `DATETIME` columns of `hammerwork_workflows` (`created_at`, `completed_at`, `failed_at`), to `DATETIME(6)`, keeping nullability, values and defaults (`CURRENT_TIMESTAMP` defaults become `CURRENT_TIMESTAMP(6)`; `hammerwork_queue_pause.updated_at` keeps `ON UPDATE`). One `ALTER TABLE` per table, run under a UTC session `time_zone`, safe to re-run. A no-op on PostgreSQL. ## [2.5.0] - 2026-10-11 diff --git a/CLAUDE.md b/CLAUDE.md index 85f2711..8120d08 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,9 +8,9 @@ Hammerwork is a high-performance, database-driven job queue library for Rust wit ## Development Notes -- SQLx compile-time query checking requires database connections +- Queries are built at run time with `sqlx::query` and bound parameters (no compile-time `query!` macros, so building needs no database) - PostgreSQL uses `FOR UPDATE SKIP LOCKED` for efficient job polling -- MySQL implementation uses transaction-based locking (less optimal) +- MySQL (8.0+) also claims jobs with `FOR UPDATE SKIP LOCKED`, inside a transaction - Priority-aware queries use `ORDER BY priority DESC, scheduled_at ASC` - Weighted selection uses hash-based algorithms for Send compatibility - Tracing is integrated for observability @@ -67,10 +67,15 @@ cargo clippy -- -D warnings ``` ### Feature Flags -The project uses feature flags for database support: -- `postgres`: Enable PostgreSQL support -- `mysql`: Enable MySQL support -- `default`: No database features enabled by default +`default` is empty: a plain `hammerwork` dependency has only the queue, worker and job APIs. Opt in to: +- `postgres`, `mysql`: the database backends (at least one is needed for a `JobQueue`) +- `metrics`, `alerting`, `webhooks`, `streaming`, `tracing`, `encryption`: subsystems; `full` enables all six (not the backends, KMS sources, event sinks or `test-queue`) +- `aws-kms`, `gcp-kms`, `vault-kms`, `azure-kms`: encryption key sources +- `kafka`, `google-pubsub`, `kinesis`: event stream sinks +- `test-queue`: the in-memory `TestQueue` + +A configuration file section for a feature that is not enabled is rejected by `HammerworkConfig::from_file`. +`cargo-hammerwork` and `hammerwork-web` enable the features they need; `hammerwork-web` has a `postgres` (default), `mysql` and `auth` (default) feature. ## Architecture @@ -80,18 +85,18 @@ The codebase follows a modular architecture with clear separation of concerns: 1. **Job (`src/job.rs`)** - Defines the `Job` struct with UUID, payload, status, priority, retry logic - - Job statuses: Pending, Running, Completed, Failed, Retrying, Dead, TimedOut + - Job statuses: Pending, Running, Completed, Failed, Dead, TimedOut, Archived (`Retrying` is only read from rows older versions wrote; a retry goes back to `Pending`) - Job priorities: Background, Low, Normal, High, Critical - Supports delayed execution, configurable retry attempts, and priority levels 2. **Queue (`src/queue/`)** - - `mod.rs`: the `DatabaseQueue` trait (the interface for database operations) and the generic `JobQueue` wrapping a connection pool + - `mod.rs`: the sealed `DatabaseQueue` trait (the interface for database operations; only Hammerwork implements it) and the generic `JobQueue` wrapping a connection pool. Jobs are claimed with `dequeue(queue, &DequeueOptions)` (batch size, priority weights, lease) or the one-job shortcut `dequeue_one(queue)`; a `Running` job holds a lease that heartbeats renew, and `requeue_stale_jobs()` reclaims jobs whose lease expired - `postgres.rs` / `mysql.rs`: the dialect-specific implementations (SQL, row types, locking) - `backend.rs`: helpers shared by both backends (transactions and conflict retries, column encoding, cron and dequeue helpers) - `row.rs`: dialect-independent row decoding (column lists, status, result config and encryption columns) - `lifecycle.rs`: the job lifecycle state machine (manual transitions and worker run outcomes) - `payload_encryption.rs`, `memory_results.rs`: payload sealing and in-memory result storage - - `test.rs`: the in-memory `TestQueue` (feature `test`) + - `test.rs`: the in-memory `TestQueue` (feature `test-queue`) - Priority-aware job selection with weighted algorithms; atomic transitions in transactions 3. **Worker (`src/worker.rs` and `src/worker/`)** @@ -146,13 +151,13 @@ Both PostgreSQL and MySQL implementations use a single table `hammerwork_jobs` w ```bash # 1. Format code according to Rust standards -cargo fmt +cargo fmt --all -# 2. Run all linting checks with strict warnings -cargo clippy --all-features -- -D warnings +# 2. Run all linting checks with strict warnings (as CI does) +cargo clippy --workspace --all-features --all-targets -- -D warnings -# 3. Run complete test suite with all features -cargo test --all-features +# 3. Run the complete test suite with all features (the whole workspace) +cargo test --workspace --all-features # 4. Test CLI crate specifically cargo test -p cargo-hammerwork diff --git a/cargo-hammerwork/README.md b/cargo-hammerwork/README.md index 5797c65..b5ff1ce 100644 --- a/cargo-hammerwork/README.md +++ b/cargo-hammerwork/README.md @@ -44,7 +44,7 @@ The `cargo-hammerwork` crate provides a modular CLI for managing Hammerwork-base # Run migrations to set up the database schema cargo hammerwork migration run --database-url postgres://localhost/mydb -# Check migration status +# Show applied and pending migrations (from the hammerwork_migrations table) cargo hammerwork migration status --database-url postgres://localhost/mydb ``` @@ -183,6 +183,8 @@ cargo hammerwork job purge --completed --older-than-days 30 --confirm cargo hammerwork job purge --queue emails --dead --failed --confirm cargo hammerwork job requeue-stale +cargo hammerwork job requeue-stale --dry-run # count only, change nothing +cargo hammerwork job requeue-stale --queue emails # one queue only ``` - `job enqueue` requires `--queue` and `--payload`; `--payload` must be valid JSON, @@ -198,7 +200,9 @@ cargo hammerwork job requeue-stale reclaimed, however long it runs. A `Running` job without a lease (left by a Hammerwork 1.x worker) is never reclaimed; `maintenance check --fix` gives such jobs an expired lease once every 1.x worker has stopped (see the 3.0 upgrade guide). It is - safe to run alongside workers. (3.0 removed `--older-than-secs`.) + safe to run alongside workers. `--dry-run` counts what would be reclaimed without + changing anything, and `--queue` limits the reclaim to one queue. (3.0 removed + `--older-than-secs`.) - `job show` prints the redacted payload of an encrypted job (the CLI never decrypts) together with its key id, algorithm and retention. @@ -255,6 +259,11 @@ cargo hammerwork monitor metrics --period 24h --queue emails `--refresh` is in seconds (default 5). `--format` is `table` or `json`; `--period` is `1h`, `24h` or `7d`. +`monitor health` and `queue health` call a `Running` job stuck only when its lease has +expired, the rule `job requeue-stale` uses; a long-running job that keeps heartbeating is +healthy. `Running` jobs without a lease (left by a Hammerwork 1.x worker) get their own +`Lease-less Running Jobs` row. + ### Batch Operation Commands Operate on many jobs at once. diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index b70b05b..4cf1c36 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -10,7 +10,7 @@ use crate::config::Config; use crate::utils::database::{DatabasePool, JobQueueWrapper}; use crate::utils::display::JobTable; use crate::utils::job_ops::{ - JobSelector, cancel_many, cancel_one, retry_many, retry_one, select_job_ids, + JobSelector, StaleRunning, cancel_many, cancel_one, retry_many, retry_one, select_job_ids, }; use crate::utils::sql::{ Backend, Bind, FAILURE_STATUSES, FAILURE_STATUSES_SQL, IdText, IntervalUnit, SqlParams, @@ -167,11 +167,26 @@ pub enum JobCommand { upgrade guide for the one-off fix. Stale jobs with attempts left go back to \ Pending; the rest are marked Dead. Safe to run while workers and other \ reapers are running.\n\n\ - Example: cargo hammerwork job requeue-stale" + Use --dry-run to count what would be reclaimed without changing anything, \ + and --queue to reclaim (or count) one queue only.\n\n\ + Examples:\n cargo hammerwork job requeue-stale --dry-run\n \ + cargo hammerwork job requeue-stale --queue emails" )] RequeueStale { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, + #[arg( + short = 'n', + short_alias = 'Q', + long, + help = "Only reclaim jobs in this queue" + )] + queue: Option, + #[arg( + long, + help = "Count the jobs that would be reclaimed without changing them" + )] + dry_run: bool, }, } @@ -276,8 +291,8 @@ impl JobCommand { ) .await?; } - JobCommand::RequeueStale { .. } => { - requeue_stale_jobs(pool).await?; + JobCommand::RequeueStale { queue, dry_run, .. } => { + requeue_stale_jobs(pool, queue.as_deref(), *dry_run).await?; } } Ok(()) @@ -717,10 +732,48 @@ fn delayed_schedule( .ok_or_else(|| anyhow::anyhow!("--delay {} seconds is out of range", delay_secs)) } -async fn requeue_stale_jobs(pool: DatabasePool) -> Result<()> { - let recovery = with_queue!(pool.create_job_queue(), |queue| { - queue.requeue_stale_jobs().await? - }); +/// The `Running` jobs `requeue_stale_jobs` would reclaim (their lease expired), optionally +/// in one queue. The same lease-only rule the library applies. +fn stale_selector(queue: Option<&str>) -> JobSelector { + JobSelector { + statuses: vec![JobStatus::Running], + queue: queue.map(str::to_string), + stale_running: Some(StaleRunning::new(chrono::Utc::now())), + ..Default::default() + } +} + +async fn requeue_stale_jobs(pool: DatabasePool, queue: Option<&str>, dry_run: bool) -> Result<()> { + let scope = queue.map_or_else(|| "all queues".to_string(), |q| format!("queue '{q}'")); + + if dry_run { + let ids = select_job_ids(&pool, &stale_selector(queue)).await?; + for id in &ids { + info!("Would reclaim stale job {}", id); + } + info!( + "šŸ” Dry run: {} stale job(s) in {} would be reclaimed (lease expired). Nothing was changed.", + ids.len(), + scope + ); + return Ok(()); + } + + let recovery = match queue { + // Unscoped: the library's atomic reclaim. + None => with_queue!(pool.create_job_queue(), |queue| { + queue.requeue_stale_jobs().await? + }), + // Scoped: the library reclaims every queue at once, so find this queue's stale jobs + // and send each through the guarded transitions with the library's own outcome + // (Pending while attempts remain, Dead otherwise). + Some(name) => { + let ids = select_job_ids(&pool, &stale_selector(Some(name))).await?; + with_queue!(pool.create_job_queue(), |q| { + reclaim_stale_in_queue(&q, &ids).await? + }) + } + }; for id in &recovery.requeued { info!("ā†©ļø Requeued stale job {}", id); @@ -729,14 +782,50 @@ async fn requeue_stale_jobs(pool: DatabasePool) -> Result<()> { info!("šŸ’€ Marked stale job {} dead (no attempts left)", id); } info!( - "āœ… Reclaimed {} stale jobs ({} requeued, {} dead)", + "āœ… Reclaimed {} stale jobs in {} ({} requeued, {} dead)", recovery.total(), + scope, recovery.requeued.len(), recovery.dead.len() ); Ok(()) } +/// Reclaim the given stale `Running` jobs one by one: a job with attempts left goes back to +/// `Pending`, an exhausted one is marked `Dead`, as `requeue_stale_jobs` does. A job that +/// is no longer `Running` (finished or reclaimed meanwhile) is skipped. +async fn reclaim_stale_in_queue( + queue: &Q, + ids: &[hammerwork::JobId], +) -> Result { + let mut recovery = hammerwork::queue::StaleJobRecovery::default(); + for &id in ids { + let Some(job) = queue.get_job(id).await? else { + continue; + }; + if job.status != JobStatus::Running { + continue; + } + let outcome = if job.attempts >= job.max_attempts { + queue + .mark_job_dead(id, hammerwork::queue::STALE_JOB_ERROR_MESSAGE) + .await + .map(|()| true) + } else { + queue + .retry_job(id, chrono::Utc::now()) + .await + .map(|()| false) + }; + match outcome { + Ok(true) => recovery.dead.push(id), + Ok(false) => recovery.requeued.push(id), + Err(e) => tracing::warn!("Skipped stale job {}: {}", id, e), + } + } + Ok(recovery) +} + async fn retry_jobs( pool: DatabasePool, job_id: Option, @@ -923,19 +1012,40 @@ mod tests { fn test_requeue_stale_parses() { let cli = TestCli::try_parse_from(["test", "requeue-stale"]).unwrap(); match cli.command { - JobCommand::RequeueStale { database_url } => assert!(database_url.is_none()), + JobCommand::RequeueStale { + database_url, + queue, + dry_run, + } => { + assert!(database_url.is_none() && queue.is_none()); + assert!(!dry_run); + } _ => panic!("expected RequeueStale"), } - let cli = - TestCli::try_parse_from(["test", "requeue-stale", "-u", "postgres://localhost/db"]) - .unwrap(); + let cli = TestCli::try_parse_from([ + "test", + "requeue-stale", + "-u", + "postgres://localhost/db", + "--queue", + "emails", + "--dry-run", + ]) + .unwrap(); match cli.command { - JobCommand::RequeueStale { database_url } => { + JobCommand::RequeueStale { + database_url, + queue, + dry_run, + } => { assert_eq!(database_url.as_deref(), Some("postgres://localhost/db")); + assert_eq!(queue.as_deref(), Some("emails")); + assert!(dry_run); } _ => panic!("expected RequeueStale"), } + assert!(TestCli::try_parse_from(["test", "requeue-stale", "-n", "q"]).is_ok()); // The 2.x age threshold for lease-less jobs is gone. assert!( @@ -943,6 +1053,22 @@ mod tests { ); } + #[test] + fn test_stale_selector_is_lease_only_and_scoped_by_bound_queue() { + let (sql, binds) = stale_selector(Some(HOSTILE_QUEUE)).sql(Backend::Postgres); + assert_eq!( + sql, + "SELECT id FROM hammerwork_jobs WHERE status IN ($1) AND queue_name = $2 AND (last_heartbeat_at >= started_at AND lease_expires_at < $3) ORDER BY created_at" + ); + assert_eq!(binds.len(), 3); + assert_eq!(binds[1], Bind::Text(HOSTILE_QUEUE.into())); + assert!(!sql.contains("DROP")); + + let (sql, binds) = stale_selector(None).sql(Backend::MySql); + assert!(!sql.contains("queue_name")); + assert_eq!(binds.len(), 2); + } + #[test] fn test_list_jobs_query_postgres_binds_typed_params() { let (query, params) = build_list_jobs_query( @@ -1611,9 +1737,45 @@ mod tests { let leaseless = seed(pool, &stale).await; let fresh = seed(pool, &SeedJob::new(&q, "Running")).await; backdate(pool, &fresh, "started_at", 0).await; + // another queue's stale job, to prove --queue scopes the reclaim + let other_queue = format!("{q}_other"); + let mut other_stale = SeedJob::new(&other_queue, "Running"); + other_stale.started_long_ago = true; + let other = seed(pool, &other_stale).await; + set_time(pool, &other, "last_heartbeat_at", -60).await; + set_time(pool, &other, "lease_expires_at", -10).await; + let stale_count = |queue: Option<&str>| { + let selector = stale_selector(queue); + async move { select_job_ids(pool, &selector).await.unwrap().len() } + }; + assert_eq!(stale_count(Some(&q)).await, 2); + assert_eq!(stale_count(Some(&other_queue)).await, 1); + + // --dry-run counts the same jobs and changes nothing + run(&["requeue-stale", "--dry-run"]).await.unwrap(); + run(&["requeue-stale", "--dry-run", "--queue", &q]) + .await + .unwrap(); + assert_eq!(job_status(pool, &retryable).await, "Running"); + assert_eq!(job_status(pool, &other).await, "Running"); + assert_eq!(stale_count(Some(&q)).await, 2); + + // --queue reclaims that queue only: retryable goes back to Pending, exhausted dies + run(&["requeue-stale", "--queue", &q]).await.unwrap(); + assert_eq!(job_status(pool, &other).await, "Running"); + assert_eq!(job_status(pool, &leaseless).await, "Running"); + assert_eq!(job_status(pool, &fresh).await, "Running"); + assert_eq!(job_status(pool, &retryable).await, "Pending"); + assert_eq!(job_status(pool, &exhausted).await, "Dead"); + assert_eq!(stale_count(Some(&q)).await, 0); + assert_eq!(stale_count(Some(&other_queue)).await, 1); + + // without --queue every queue is reclaimed run(&["requeue-stale"]).await.unwrap(); + assert_eq!(job_status(pool, &other).await, "Pending"); assert_eq!(job_status(pool, &retryable).await, "Pending"); assert_eq!(job_status(pool, &exhausted).await, "Dead"); + assert_eq!(job_status(pool, &exhausted).await, "Dead"); assert_eq!(job_status(pool, &leaseless).await, "Running"); assert_eq!(job_status(pool, &fresh).await, "Running"); run(&["requeue-stale"]).await.unwrap(); diff --git a/cargo-hammerwork/src/commands/migration.rs b/cargo-hammerwork/src/commands/migration.rs index 9d9bede..c38f39e 100644 --- a/cargo-hammerwork/src/commands/migration.rs +++ b/cargo-hammerwork/src/commands/migration.rs @@ -1,5 +1,10 @@ use anyhow::Result; +use chrono::{DateTime, Utc}; use clap::Subcommand; +use hammerwork::migrations::{ + MigrationManager, MigrationRunner, mysql::MySqlMigrationRunner, + postgres::PostgresMigrationRunner, +}; use sqlx::Row; use tracing::info; @@ -17,7 +22,13 @@ pub enum MigrationCommand { #[arg(short, long, help = "Drop existing tables before migration")] drop: bool, }, - #[command(about = "Check migration status")] + #[command( + about = "Show applied and pending migrations", + long_about = "Show which of this version's migrations the database has applied and \ + which are pending, from the hammerwork_migrations table.\n\n\ + Migrations recorded in the database that this version does not know (applied \ + by a newer Hammerwork) are listed separately." + )] Status { #[arg(short = 'u', long, help = "Database connection URL")] database_url: Option, @@ -102,24 +113,170 @@ pub async fn schema_status(pool: &DatabasePool) -> Result { }) } +/// One migration this version registers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MigrationEntry { + pub id: String, + pub description: String, + pub version: u32, + /// When the database applied it; `None` while pending. + pub applied_at: Option>, +} + +/// The migrations of this version against the `hammerwork_migrations` table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MigrationReport { + /// Whether the `hammerwork_migrations` table exists. + pub table_exists: bool, + /// The registered migrations in version order, applied or pending. + pub migrations: Vec, + /// Applied migration ids this version does not register. + pub unknown: Vec, +} + +impl MigrationReport { + pub fn applied(&self) -> impl Iterator { + self.migrations.iter().filter(|m| m.applied_at.is_some()) + } + + pub fn pending(&self) -> impl Iterator { + self.migrations.iter().filter(|m| m.applied_at.is_none()) + } +} + +/// Compare the registered migrations with the applied records. +fn build_report( + table_exists: bool, + registered: Vec, + records: Vec<(String, DateTime)>, +) -> MigrationReport { + let migrations: Vec = registered + .into_iter() + .map(|m| MigrationEntry { + applied_at: records + .iter() + .find(|(id, _)| *id == m.id) + .map(|(_, at)| *at), + id: m.id, + description: m.description, + version: m.version, + }) + .collect(); + let mut unknown: Vec = records + .iter() + .filter(|(id, _)| !migrations.iter().any(|m| m.id == *id)) + .map(|(id, _)| id.clone()) + .collect(); + unknown.sort(); + MigrationReport { + table_exists, + migrations, + unknown, + } +} + +/// Read-only: the registered migrations and which of them the database recorded. +pub async fn migration_report(pool: &DatabasePool) -> Result { + match pool { + DatabasePool::Postgres(pg) => { + let runner = PostgresMigrationRunner::new(pg.clone()); + let table_exists = runner.migration_table_exists().await?; + let records = if table_exists { + runner + .get_executed_migrations() + .await? + .into_iter() + .map(|r| (r.migration_id, r.executed_at)) + .collect() + } else { + Vec::new() + }; + let registered = MigrationManager::new(Box::new(runner)).registered_migrations(); + Ok(build_report(table_exists, registered, records)) + } + DatabasePool::MySQL(my) => { + let runner = MySqlMigrationRunner::new(my.clone()); + let table_exists = runner.migration_table_exists().await?; + let records = if table_exists { + runner + .get_executed_migrations() + .await? + .into_iter() + .map(|r| (r.migration_id, r.executed_at)) + .collect() + } else { + Vec::new() + }; + let registered = MigrationManager::new(Box::new(runner)).registered_migrations(); + Ok(build_report(table_exists, registered, records)) + } + } +} + +/// The text `migration status` prints. +pub fn render_report(backend: &str, report: &MigrationReport, schema: &SchemaStatus) -> String { + let mut out = String::new(); + out.push_str(&format!("šŸ“‹ {backend} migrations\n")); + if !report.table_exists { + out.push_str( + "āŒ No hammerwork_migrations table: no migration has been applied. \ + Run 'migration run' to create the schema.\n", + ); + } + let applied = report.applied().count(); + let pending = report.pending().count(); + out.push_str(&format!( + "{applied} applied, {pending} pending ({} registered)\n", + report.migrations.len() + )); + if applied > 0 { + out.push_str("\nApplied:\n"); + for m in report.applied() { + let at = m.applied_at.expect("applied"); + out.push_str(&format!( + " āœ… {} ({}) at {}\n", + m.id, + m.description, + at.format("%Y-%m-%d %H:%M:%S UTC") + )); + } + } + if pending > 0 { + out.push_str("\nPending:\n"); + for m in report.pending() { + out.push_str(&format!(" ā³ {} ({})\n", m.id, m.description)); + } + out.push_str("\nRun 'migration run' to apply the pending migrations.\n"); + } + if !report.unknown.is_empty() { + out.push_str( + "\nāš ļø Applied but not known to this version of Hammerwork (applied by a newer \ + version?):\n", + ); + for id in &report.unknown { + out.push_str(&format!(" ? {id}\n")); + } + } + if schema.tables_exist { + out.push_str(&format!( + "\nšŸ“Š hammerwork_jobs table: {} columns\n", + schema.columns.len() + )); + } else { + out.push_str("\nāŒ hammerwork_jobs table does not exist\n"); + } + out +} + async fn check_migration_status(database_url: &str, config: &Config) -> Result<()> { let pool = DatabasePool::connect_with_config(database_url, config).await?; let backend = match pool.backend() { Backend::Postgres => "PostgreSQL", Backend::MySql => "MySQL", }; - let status = schema_status(&pool).await?; - - if status.tables_exist { - println!("āœ… {backend} tables exist"); - println!("šŸ“Š Schema columns: {}", status.columns.len()); - for column in &status.columns { - println!(" - {}", column); - } - } else { - println!("āŒ {backend} tables do not exist. Run 'migration run' to create them."); - } - + let report = migration_report(&pool).await?; + let schema = schema_status(&pool).await?; + print!("{}", render_report(backend, &report, &schema)); Ok(()) } @@ -167,6 +324,90 @@ mod tests { assert!(TestCli::try_parse_from(["test", "rollback"]).is_err()); } + fn registered() -> Vec { + use hammerwork::migrations::Migration; + vec![ + Migration::new("001_initial_schema", "Initial schema", 1), + Migration::new("002_add_priority", "Priority", 2), + Migration::new("003_add_timeouts", "Timeouts", 3), + ] + } + + fn record(id: &str) -> (String, DateTime) { + ( + id.to_string(), + DateTime::parse_from_rfc3339("2030-01-02T03:04:05Z") + .unwrap() + .with_timezone(&Utc), + ) + } + + #[test] + fn the_report_splits_applied_pending_and_unknown_migrations() { + let report = build_report( + true, + registered(), + vec![ + record("001_initial_schema"), + record("002_add_priority"), + record("099_from_the_future"), + ], + ); + assert!(report.table_exists); + let applied: Vec<_> = report.applied().map(|m| m.id.as_str()).collect(); + let pending: Vec<_> = report.pending().map(|m| m.id.as_str()).collect(); + assert_eq!(applied, ["001_initial_schema", "002_add_priority"]); + assert_eq!(pending, ["003_add_timeouts"]); + assert_eq!(report.unknown, ["099_from_the_future"]); + + let schema = SchemaStatus { + tables_exist: true, + columns: vec!["id".into(), "status".into()], + }; + let text = render_report("PostgreSQL", &report, &schema); + assert!( + text.contains("2 applied, 1 pending (3 registered)"), + "{text}" + ); + assert!(text.contains("āœ… 001_initial_schema"), "{text}"); + assert!(text.contains("2030-01-02 03:04:05 UTC"), "{text}"); + assert!(text.contains("ā³ 003_add_timeouts"), "{text}"); + assert!(text.contains("? 099_from_the_future"), "{text}"); + assert!(text.contains("hammerwork_jobs table: 2 columns"), "{text}"); + } + + #[test] + fn a_database_without_the_migrations_table_has_everything_pending() { + let report = build_report(false, registered(), Vec::new()); + assert_eq!(report.applied().count(), 0); + assert_eq!(report.pending().count(), 3); + let schema = SchemaStatus { + tables_exist: false, + columns: Vec::new(), + }; + let text = render_report("MySQL", &report, &schema); + assert!(text.contains("No hammerwork_migrations table"), "{text}"); + assert!(text.contains("0 applied, 3 pending"), "{text}"); + assert!( + text.contains("hammerwork_jobs table does not exist"), + "{text}" + ); + assert!(!text.contains("not known to this version"), "{text}"); + } + + /// The registered list is what a real runner's manager reports, with 021 included. + #[tokio::test] + async fn the_library_registers_its_migrations_in_version_order() { + let pool = sqlx::postgres::PgPoolOptions::new() + .connect_lazy("postgres://u:p@127.0.0.1:1/x") + .unwrap(); + let manager = MigrationManager::new(Box::new(PostgresMigrationRunner::new(pool))); + let migrations = manager.registered_migrations(); + assert!(migrations.len() >= 21); + assert!(migrations.windows(2).all(|w| w[0].version < w[1].version)); + assert!(migrations.iter().any(|m| m.id.starts_with("021_"))); + } + #[tokio::test] async fn a_database_url_is_required() { for cmd in [parse(&["run"]), parse(&["status"])] { @@ -231,6 +472,10 @@ mod tests { let status = schema_status(&db.pool).await.unwrap(); assert!(!status.tables_exist && status.columns.is_empty()); run(&["status"]).await.unwrap(); + let before = migration_report(&db.pool).await.unwrap(); + assert!(!before.table_exists); + assert_eq!(before.applied().count(), 0); + assert!(before.pending().count() >= 21, "everything is pending"); // run creates the schema; the key columns are there run(&["run"]).await.unwrap(); @@ -251,6 +496,54 @@ mod tests { assert_eq!(status.columns, sorted); run(&["status"]).await.unwrap(); + // after: every registered migration is applied, including 021, none pending + let after = migration_report(&db.pool).await.unwrap(); + assert!(after.table_exists); + assert_eq!(after.pending().count(), 0); + assert_eq!(after.applied().count(), after.migrations.len()); + assert!(after.applied().any(|m| m.id.starts_with("021_"))); + assert!(after.unknown.is_empty()); + // a migration this version does not register shows up as unknown, and a + // forgotten record as pending + let sql_for = |verb: &str, ids: &[&str]| { + let mut params = crate::utils::sql::SqlParams::new(db.pool.backend()); + let sql = if verb == "delete" { + format!( + "DELETE FROM hammerwork_migrations WHERE migration_id = {}", + params.text(ids[0]) + ) + } else { + let (id, at) = (params.text(ids[0]), params.time(Utc::now())); + format!( + "INSERT INTO hammerwork_migrations (migration_id, executed_at, execution_time_ms) VALUES ({id}, {at}, 1)" + ) + }; + (sql, params.into_binds()) + }; + let last = after.migrations.last().unwrap().id.clone(); + for (verb, id) in [("delete", last.as_str()), ("insert", "999_from_the_future")] { + let (sql, binds) = sql_for(verb, &[id]); + crate::utils::sql::execute_binds(&db.pool, &sql, &binds) + .await + .unwrap(); + } + let tampered = migration_report(&db.pool).await.unwrap(); + assert_eq!(tampered.unknown, ["999_from_the_future"]); + let pending: Vec<_> = tampered.pending().map(|m| m.id.clone()).collect(); + assert_eq!(pending, std::slice::from_ref(&last)); + run(&["status"]).await.unwrap(); + // put the records back + for (verb, id) in [("delete", "999_from_the_future"), ("insert", last.as_str())] { + let (sql, binds) = sql_for(verb, &[id]); + crate::utils::sql::execute_binds(&db.pool, &sql, &binds) + .await + .unwrap(); + } + assert_eq!( + migration_report(&db.pool).await.unwrap().pending().count(), + 0 + ); + // running again is a no-op that keeps the data let queue = unique_queue("migrate"); seed(&db.pool, &SeedJob::new(&queue, "Pending")).await; diff --git a/cargo-hammerwork/src/commands/monitor.rs b/cargo-hammerwork/src/commands/monitor.rs index cd9aadc..79209a1 100644 --- a/cargo-hammerwork/src/commands/monitor.rs +++ b/cargo-hammerwork/src/commands/monitor.rs @@ -7,6 +7,7 @@ use tokio::time::interval; use crate::commands::job::priority_display; use crate::config::Config; use crate::utils::database::DatabasePool; +use crate::utils::job_ops::StaleRunning; use crate::utils::sql::{ Backend, Bind, FAILURE_STATUSES_SQL, FAILURE_TIME_SQL, IdText, IntervalUnit, SqlParams, bind_mysql, bind_pg, fetch_i64, fetch_rows, @@ -317,8 +318,11 @@ async fn display_dashboard_data(pool: &DatabasePool, queue: &Option) -> /// The counts behind `monitor health`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HealthCount { - /// Jobs `Running` for more than an hour. + /// `Running` jobs whose lease expired: the jobs `requeue-stale` would reclaim. Stuck, + /// `Running` jobs without a lease (left by a Hammerwork 1.x worker), which the lease + /// rule can neither call stuck nor reclaim. + Leaseless, /// Jobs created in the last hour. RecentJobs, /// Jobs that failed (`Failed`, `Dead` or `TimedOut`) in the last hour. @@ -326,15 +330,28 @@ pub enum HealthCount { } /// `COUNT(*) as count` for one health figure; the one-hour window is a bound parameter on -/// the database clock. -pub fn build_health_count_query(backend: Backend, which: HealthCount) -> (String, Vec) { +/// the database clock, and a `Running` job is stuck by the lease rule at `now`. +pub fn build_health_count_query( + backend: Backend, + which: HealthCount, + now: chrono::DateTime, +) -> (String, Vec) { let mut params = SqlParams::new(backend); - let hour_ago = params.ago(1, IntervalUnit::Hour); let condition = match which { - HealthCount::Stuck => format!("status = 'Running' AND started_at < {hour_ago}"), - HealthCount::RecentJobs => format!("created_at > {hour_ago}"), + HealthCount::Stuck => format!( + "status = 'Running' AND {}", + StaleRunning::new(now).condition(&mut params) + ), + HealthCount::Leaseless => format!( + "status = 'Running' AND {}", + StaleRunning::leaseless_condition() + ), + HealthCount::RecentJobs => format!("created_at > {}", params.ago(1, IntervalUnit::Hour)), HealthCount::RecentFailures => { - format!("status IN {FAILURE_STATUSES_SQL} AND {FAILURE_TIME_SQL} > {hour_ago}") + format!( + "status IN {FAILURE_STATUSES_SQL} AND {FAILURE_TIME_SQL} > {}", + params.ago(1, IntervalUnit::Hour) + ) } }; ( @@ -375,11 +392,14 @@ pub struct HealthCheck { pub value: String, } -/// Grade the measurements: any stuck job is a warning (critical from five); the failure rate -/// of the last hour is a warning from 5% and critical from 15%. +/// Grade the measurements: any stuck job (a `Running` job whose lease expired) is a warning +/// (critical from five); `Running` jobs without a lease are a separate warning, since the +/// lease rule cannot judge them; the failure rate of the last hour is a warning from 5% and +/// critical from 15%. pub fn evaluate_health( database: std::result::Result<(), String>, stuck: i64, + leaseless: i64, recent_jobs: i64, recent_failures: i64, ) -> Vec { @@ -428,7 +448,20 @@ pub fn evaluate_health( name: "Failure Rate", value: format!("{rate:.1}%"), }; - vec![database, stuck_check, failure_check] + let leaseless_check = if leaseless == 0 { + HealthCheck { + level: HealthLevel::Healthy, + name: "Lease-less Running Jobs", + value: "None".to_string(), + } + } else { + HealthCheck { + level: HealthLevel::Warning, + name: "Lease-less Running Jobs", + value: format!("{leaseless} jobs (no lease; see the 3.0 upgrade guide)"), + } + }; + vec![database, stuck_check, leaseless_check, failure_check] } /// The report for `format` (`json` or a table). @@ -468,18 +501,20 @@ async fn check_health(pool: DatabasePool, format: Option) -> Result<()> .map_err(|e| e.to_string()); let backend = pool.backend(); - let mut counts = [0i64; 3]; + let now = chrono::Utc::now(); + let mut counts = [0i64; 4]; for (slot, which) in counts.iter_mut().zip([ HealthCount::Stuck, + HealthCount::Leaseless, HealthCount::RecentJobs, HealthCount::RecentFailures, ]) { - let (sql, binds) = build_health_count_query(backend, which); + let (sql, binds) = build_health_count_query(backend, which, now); *slot = fetch_i64(&pool, &sql, &binds, "count").await?; } - let [stuck, recent_jobs, recent_failures] = counts; + let [stuck, leaseless, recent_jobs, recent_failures] = counts; - let checks = evaluate_health(database, stuck, recent_jobs, recent_failures); + let checks = evaluate_health(database, stuck, leaseless, recent_jobs, recent_failures); println!( "{}", render_health(&checks, format.as_deref(), chrono::Utc::now())? @@ -794,18 +829,21 @@ mod tests { #[test] fn health_query_windows_use_the_database_clock() { - let (sql, binds) = build_health_count_query(Backend::Postgres, HealthCount::Stuck); + let now = chrono::Utc::now(); + let (sql, binds) = + build_health_count_query(Backend::Postgres, HealthCount::RecentJobs, now); assert_eq!( sql, - "SELECT COUNT(*) as count FROM hammerwork_jobs WHERE status = 'Running' AND started_at < NOW() - make_interval(hours => $1::int)" + "SELECT COUNT(*) as count FROM hammerwork_jobs WHERE created_at > NOW() - make_interval(hours => $1::int)" ); assert_eq!(binds, vec![Bind::Int(1)]); - let (sql, _) = build_health_count_query(Backend::MySql, HealthCount::RecentJobs); + let (sql, _) = build_health_count_query(Backend::MySql, HealthCount::RecentJobs, now); assert!( sql.ends_with("created_at > DATE_SUB(UTC_TIMESTAMP(6), INTERVAL ? HOUR)"), "{sql}" ); - let (sql, binds) = build_health_count_query(Backend::MySql, HealthCount::RecentFailures); + let (sql, binds) = + build_health_count_query(Backend::MySql, HealthCount::RecentFailures, now); assert!( sql.ends_with( "status IN ('Failed', 'Dead', 'TimedOut') AND COALESCE(failed_at, timed_out_at) > DATE_SUB(UTC_TIMESTAMP(6), INTERVAL ? HOUR)" @@ -815,27 +853,61 @@ mod tests { assert_eq!(binds, vec![Bind::Int(1)]); } + #[test] + fn stuck_jobs_follow_the_lease_rule_not_the_start_time() { + let now = chrono::Utc::now(); + let (sql, binds) = build_health_count_query(Backend::Postgres, HealthCount::Stuck, now); + assert_eq!( + sql, + "SELECT COUNT(*) as count FROM hammerwork_jobs WHERE status = 'Running' AND (last_heartbeat_at >= started_at AND lease_expires_at < $1)" + ); + assert_eq!(binds, vec![Bind::Time(now)]); + assert!(!sql.contains("INTERVAL") && !sql.contains("make_interval")); + + let (sql, binds) = build_health_count_query(Backend::MySql, HealthCount::Stuck, now); + assert!(sql.ends_with("lease_expires_at < ?)"), "{sql}"); + assert_eq!(binds.len(), 1); + + let (sql, binds) = build_health_count_query(Backend::Postgres, HealthCount::Leaseless, now); + assert!( + sql.contains("status = 'Running' AND (last_heartbeat_at IS NULL"), + "{sql}" + ); + assert!(sql.contains("lease_expires_at IS NULL"), "{sql}"); + assert!(binds.is_empty()); + } + #[test] fn health_levels_follow_the_thresholds() { let level = |checks: &[HealthCheck], name: &str| { checks.iter().find(|c| c.name == name).unwrap().level }; - let ok = evaluate_health(Ok(()), 0, 0, 0); + let ok = evaluate_health(Ok(()), 0, 0, 0, 0); assert!(ok.iter().all(|c| c.level == HealthLevel::Healthy)); assert_eq!(ok[1].value, "None"); - assert_eq!(ok[2].value, "0.0%"); + assert_eq!(ok[2].value, "None"); + assert_eq!(ok[3].value, "0.0%"); - let stuck = evaluate_health(Ok(()), 3, 100, 4); + let stuck = evaluate_health(Ok(()), 3, 0, 100, 4); assert_eq!(level(&stuck, "Stuck Jobs"), HealthLevel::Warning); assert_eq!(level(&stuck, "Failure Rate"), HealthLevel::Healthy); assert_eq!(stuck[1].value, "3 jobs"); - let bad = evaluate_health(Ok(()), 5, 100, 5); + let bad = evaluate_health(Ok(()), 5, 0, 100, 5); assert_eq!(level(&bad, "Stuck Jobs"), HealthLevel::Critical); assert_eq!(level(&bad, "Failure Rate"), HealthLevel::Warning); - assert_eq!(bad[2].value, "5.0%"); + assert_eq!(bad[3].value, "5.0%"); - let worst = evaluate_health(Err("boom".into()), 0, 10, 2); + // Running jobs without a lease are their own warning, never "stuck" + let leaseless = evaluate_health(Ok(()), 0, 2, 100, 0); + assert_eq!(level(&leaseless, "Stuck Jobs"), HealthLevel::Healthy); + assert_eq!( + level(&leaseless, "Lease-less Running Jobs"), + HealthLevel::Warning + ); + assert!(leaseless[2].value.starts_with("2 jobs")); + + let worst = evaluate_health(Err("boom".into()), 0, 0, 10, 2); assert_eq!(level(&worst, "Database"), HealthLevel::Critical); assert_eq!(worst[0].value, "Connection Failed: boom"); assert_eq!(level(&worst, "Failure Rate"), HealthLevel::Critical); @@ -843,7 +915,7 @@ mod tests { #[test] fn health_renders_as_a_table_or_json() { - let checks = evaluate_health(Ok(()), 1, 10, 1); + let checks = evaluate_health(Ok(()), 1, 2, 10, 1); let ts = chrono::DateTime::parse_from_rfc3339("2030-01-02T03:04:05Z") .unwrap() .with_timezone(&chrono::Utc); @@ -856,12 +928,14 @@ mod tests { let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); assert_eq!(parsed["timestamp"], "2030-01-02T03:04:05+00:00"); let list = parsed["checks"].as_array().unwrap(); - assert_eq!(list.len(), 3); + assert_eq!(list.len(), 4); assert_eq!(list[0]["check"], "Database"); assert_eq!(list[0]["status"], "healthy"); assert_eq!(list[1]["status"], "warning"); + assert_eq!(list[2]["check"], "Lease-less Running Jobs"); assert_eq!(list[2]["status"], "warning"); - assert_eq!(list[2]["value"], "10.0%"); + assert_eq!(list[3]["status"], "warning"); + assert_eq!(list[3]["value"], "10.0%"); } #[test] @@ -971,14 +1045,52 @@ mod tests { None ); - // health counts: our long-running job is stuck, our failure is recent + // health counts: a long-running job with no lease is lease-less, not stuck; only a + // job whose lease expired is stuck, and one that keeps heartbeating never is + let count = |which: HealthCount| { + let pool = pool.clone(); + async move { + let (sql, binds) = + build_health_count_query(pool.backend(), which, chrono::Utc::now()); + fetch_i64(&pool, &sql, &binds, "count").await.unwrap() + } + }; + let mut expired = SeedJob::new(&queue, "Running"); + expired.started_long_ago = true; + let expired_id = seed(&pool, &expired).await; + set_time(&pool, &expired_id, "last_heartbeat_at", -60).await; + set_time(&pool, &expired_id, "lease_expires_at", -10).await; + let mut alive = SeedJob::new(&queue, "Running"); + alive.started_long_ago = true; + let alive_id = seed(&pool, &alive).await; + set_time(&pool, &alive_id, "last_heartbeat_at", -1).await; + set_time(&pool, &alive_id, "lease_expires_at", 10).await; + // the counts are database-wide (other tests share the database): ours are lower + // bounds, and the shared predicate is checked exactly within our queue + assert!(count(HealthCount::Stuck).await >= 1); + assert!(count(HealthCount::Leaseless).await >= 1); + use crate::utils::job_ops::{JobSelector, select_job_ids}; + let in_queue = |stale: bool| JobSelector { + queue: Some(queue.clone()), + stale_running: stale.then(|| StaleRunning::new(chrono::Utc::now())), + leaseless_running: !stale, + statuses: vec![hammerwork::JobStatus::Running], + ..Default::default() + }; + let stuck_ids = select_job_ids(&pool, &in_queue(true)).await.unwrap(); + assert_eq!(stuck_ids.len(), 1); + assert_eq!(stuck_ids[0].to_string(), expired_id); + let leaseless_ids = select_job_ids(&pool, &in_queue(false)).await.unwrap(); + assert_eq!( + leaseless_ids.len(), + 1, + "only the first seeded job has no lease" + ); for (which, minimum) in [ - (HealthCount::Stuck, 1), (HealthCount::RecentJobs, 5), (HealthCount::RecentFailures, 1), ] { - let (sql, binds) = build_health_count_query(pool.backend(), which); - let n = fetch_i64(&pool, &sql, &binds, "count").await.unwrap(); + let n = count(which).await; assert!(n >= minimum, "{which:?}: {n}"); } diff --git a/cargo-hammerwork/src/commands/queue.rs b/cargo-hammerwork/src/commands/queue.rs index 9094a81..818aaf4 100644 --- a/cargo-hammerwork/src/commands/queue.rs +++ b/cargo-hammerwork/src/commands/queue.rs @@ -11,6 +11,7 @@ use crate::commands::monitor::build_status_counts_query; use crate::config::Config; use crate::utils::database::DatabasePool; use crate::utils::display::StatsTable; +use crate::utils::job_ops::StaleRunning; use crate::utils::sql::{ Backend, Bind, FAILURE_STATUSES_SQL, FAILURE_TIME_SQL, IntervalUnit, SqlParams, execute_binds, fetch_i64, fetch_rows, @@ -274,7 +275,10 @@ pub fn build_detailed_stats_query(backend: Backend, queue: Option<&str>) -> (Str pub enum HealthMetric { Total, RecentFailures, - LongRunning, + /// `Running` jobs whose lease expired (what `job requeue-stale` reclaims). + Stuck, + /// `Running` jobs without a lease (left by a Hammerwork 1.x worker). + Leaseless, } /// A `COUNT(*) as count` query for one health metric, optionally for one queue. @@ -282,6 +286,7 @@ pub fn build_health_query( backend: Backend, metric: HealthMetric, queue: Option<&str>, + now: chrono::DateTime, ) -> (String, Vec) { let mut params = SqlParams::new(backend); let mut conditions = Vec::new(); @@ -298,12 +303,15 @@ pub fn build_health_query( params.ago(1, IntervalUnit::Hour) )); } - HealthMetric::LongRunning => { + HealthMetric::Stuck => { + // The lease rule of `requeue_stale_jobs`: a long-running job that keeps + // heartbeating is healthy. conditions.push("status = 'Running'".to_string()); - conditions.push(format!( - "started_at < {}", - params.ago(1, IntervalUnit::Hour) - )); + conditions.push(StaleRunning::new(now).condition(&mut params)); + } + HealthMetric::Leaseless => { + conditions.push("status = 'Running'".to_string()); + conditions.push(StaleRunning::leaseless_condition().to_string()); } } let where_clause = if conditions.is_empty() { @@ -458,16 +466,18 @@ async fn show_queue_health(pool: DatabasePool, queue: Option) -> Result< health_table.set_header(vec!["Metric", "Value", "Status"]); let backend = pool.backend(); - let mut counts = [0i64; 3]; + let now = chrono::Utc::now(); + let mut counts = [0i64; 4]; for (slot, metric) in counts.iter_mut().zip([ HealthMetric::Total, HealthMetric::RecentFailures, - HealthMetric::LongRunning, + HealthMetric::Stuck, + HealthMetric::Leaseless, ]) { - let (sql, binds) = build_health_query(backend, metric, queue.as_deref()); + let (sql, binds) = build_health_query(backend, metric, queue.as_deref(), now); *slot = fetch_i64(&pool, &sql, &binds, "count").await?; } - let [total_jobs, recent_failures, long_running] = counts; + let [total_jobs, recent_failures, stuck, leaseless] = counts; health_table.add_row(vec![ "Total Jobs".to_string(), @@ -494,11 +504,11 @@ async fn show_queue_health(pool: DatabasePool, queue: Option) -> Result< ]); health_table.add_row(vec![ - "Long-running Jobs (>1h)".to_string(), - long_running.to_string(), - if long_running == 0 { + "Stuck Jobs (lease expired)".to_string(), + stuck.to_string(), + if stuck == 0 { "🟢 Good" - } else if long_running < 5 { + } else if stuck < 5 { "🟔 Moderate" } else { "šŸ”“ High" @@ -506,6 +516,17 @@ async fn show_queue_health(pool: DatabasePool, queue: Option) -> Result< .to_string(), ]); + health_table.add_row(vec![ + "Lease-less Running Jobs".to_string(), + leaseless.to_string(), + if leaseless == 0 { + "🟢 Good" + } else { + "🟔 No lease (see the 3.0 upgrade guide)" + } + .to_string(), + ]); + println!("šŸ„ Queue Health"); if let Some(q) = &queue { println!("Queue: {}", q); @@ -581,10 +602,12 @@ mod tests { #[test] fn test_health_queries_bind_queue_then_window() { + let now = chrono::Utc::now(); let (sql, binds) = build_health_query( Backend::Postgres, HealthMetric::RecentFailures, Some(HOSTILE_QUEUE), + now, ); assert_eq!( sql, @@ -594,24 +617,38 @@ mod tests { let (sql, binds) = build_health_query( Backend::MySql, - HealthMetric::LongRunning, + HealthMetric::Stuck, Some(HOSTILE_QUEUE), + now, ); assert_eq!( sql, - "SELECT COUNT(*) as count FROM hammerwork_jobs WHERE queue_name = ? AND status = 'Running' AND started_at < DATE_SUB(UTC_TIMESTAMP(6), INTERVAL ? HOUR)" + "SELECT COUNT(*) as count FROM hammerwork_jobs WHERE queue_name = ? AND status = 'Running' AND (last_heartbeat_at >= started_at AND lease_expires_at < ?)" + ); + assert_eq!( + binds, + vec![Bind::Text(HOSTILE_QUEUE.into()), Bind::Time(now)] ); - assert_eq!(binds.len(), 2); - let (sql, binds) = build_health_query(Backend::Postgres, HealthMetric::Total, None); + let (sql, binds) = build_health_query(Backend::Postgres, HealthMetric::Total, None, now); assert_eq!(sql, "SELECT COUNT(*) as count FROM hammerwork_jobs"); assert!(binds.is_empty()); - let (sql, binds) = build_health_query(Backend::Postgres, HealthMetric::LongRunning, None); + // "stuck" is the lease rule, not the age of the run + let (sql, binds) = build_health_query(Backend::Postgres, HealthMetric::Stuck, None, now); assert!(sql.contains( - "WHERE status = 'Running' AND started_at < NOW() - make_interval(hours => $1::int)" + "WHERE status = 'Running' AND (last_heartbeat_at >= started_at AND lease_expires_at < $1)" )); - assert_eq!(binds, vec![Bind::Int(1)]); + assert!(!sql.contains("make_interval")); + assert_eq!(binds, vec![Bind::Time(now)]); + + let (sql, binds) = + build_health_query(Backend::Postgres, HealthMetric::Leaseless, Some("q"), now); + assert!( + sql.contains("queue_name = $1 AND status = 'Running' AND (last_heartbeat_at IS NULL"), + "{sql}" + ); + assert_eq!(binds, vec![Bind::Text("q".into())]); } async fn queue_roundtrip(pool: DatabasePool) { @@ -630,19 +667,39 @@ mod tests { let (sql, binds) = build_queue_total_query(backend, Some(&hostile)); assert_eq!(fetch_i64(&pool, &sql, &binds, "total").await.unwrap(), 3); - let (sql, binds) = build_health_query(backend, HealthMetric::Total, Some(&hostile)); - assert_eq!(fetch_i64(&pool, &sql, &binds, "count").await.unwrap(), 3); - let (sql, binds) = - build_health_query(backend, HealthMetric::RecentFailures, Some(&hostile)); - assert_eq!(fetch_i64(&pool, &sql, &binds, "count").await.unwrap(), 1); - let (sql, binds) = build_health_query(backend, HealthMetric::LongRunning, Some(&hostile)); - assert_eq!(fetch_i64(&pool, &sql, &binds, "count").await.unwrap(), 1); + let now = chrono::Utc::now(); + let count = |metric: HealthMetric| { + let (sql, binds) = build_health_query(backend, metric, Some(&hostile), now); + let pool = pool.clone(); + async move { fetch_i64(&pool, &sql, &binds, "count").await.unwrap() } + }; + assert_eq!(count(HealthMetric::Total).await, 3); + assert_eq!(count(HealthMetric::RecentFailures).await, 1); + // the seeded Running job started two hours ago and has no lease: it is lease-less, + // not stuck, however long it has run + assert_eq!(count(HealthMetric::Stuck).await, 0); + assert_eq!(count(HealthMetric::Leaseless).await, 1); + let mut expired = SeedJob::new(&hostile, "Running"); + expired.started_long_ago = true; + let expired_id = seed(&pool, &expired).await; + set_time(&pool, &expired_id, "last_heartbeat_at", -60).await; + set_time(&pool, &expired_id, "lease_expires_at", -10).await; + let mut alive = SeedJob::new(&hostile, "Running"); + alive.started_long_ago = true; + let alive_id = seed(&pool, &alive).await; + set_time(&pool, &alive_id, "last_heartbeat_at", -1).await; + set_time(&pool, &alive_id, "lease_expires_at", 10).await; + assert_eq!( + count(HealthMetric::Stuck).await, + 1, + "only the expired lease" + ); + assert_eq!(count(HealthMetric::Leaseless).await, 1); + assert_eq!(count(HealthMetric::Total).await, 5); // a TimedOut job has no failed_at, and still counts as a recent failure let timed_out = seed(&pool, &SeedJob::new(&hostile, "TimedOut")).await; set_time(&pool, &timed_out, "timed_out_at", -5).await; - let (sql, binds) = - build_health_query(backend, HealthMetric::RecentFailures, Some(&hostile)); - assert_eq!(fetch_i64(&pool, &sql, &binds, "count").await.unwrap(), 2); + assert_eq!(count(HealthMetric::RecentFailures).await, 2); let (sql, binds) = build_detailed_stats_query(backend, Some(&hostile)); let statuses = column_strings(&pool, &sql, &binds, "status").await; diff --git a/cargo-hammerwork/src/config/mod.rs b/cargo-hammerwork/src/config/mod.rs index 63b501a..6f8609d 100644 --- a/cargo-hammerwork/src/config/mod.rs +++ b/cargo-hammerwork/src/config/mod.rs @@ -18,7 +18,7 @@ //! //! ## Loading Configuration //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::config::Config; //! //! // Load configuration from file and environment @@ -35,7 +35,7 @@ //! //! ## Creating and Saving Configuration //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::config::Config; //! //! // Create a new configuration with custom values @@ -51,7 +51,7 @@ //! //! ## Environment Variable Override //! -//! ```rust,ignore +//! ```text //! use std::env; //! use cargo_hammerwork::config::Config; //! @@ -107,7 +107,7 @@ use std::path::{Path, PathBuf}; /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::config::Config; /// /// // Create configuration with defaults @@ -191,7 +191,7 @@ impl Config { /// /// # Examples /// - /// ```rust,ignore + /// ```text /// use cargo_hammerwork::config::Config; /// /// let config = Config::load().expect("Failed to load configuration"); @@ -317,7 +317,7 @@ impl Config { /// /// # Examples /// - /// ```rust,ignore + /// ```text /// use cargo_hammerwork::config::Config; /// /// let mut config = Config::default(); diff --git a/cargo-hammerwork/src/integration_tests/sql_query.rs b/cargo-hammerwork/src/integration_tests/sql_query.rs index a04a0f3..577beb6 100644 --- a/cargo-hammerwork/src/integration_tests/sql_query.rs +++ b/cargo-hammerwork/src/integration_tests/sql_query.rs @@ -305,9 +305,13 @@ mod builder_tests { for metric in [ HealthMetric::Total, HealthMetric::RecentFailures, - HealthMetric::LongRunning, + HealthMetric::Stuck, + HealthMetric::Leaseless, ] { - add("health", build_health_query(backend, metric, q)); + add( + "health", + build_health_query(backend, metric, q, chrono::Utc::now()), + ); } add("backup", build_backup_query(backend, q, false, false)); add("spawn_list", build_spawn_list_query(backend, q, true, 20)); @@ -343,6 +347,7 @@ mod builder_tests { created_before: Some(now), started_before: Some(now), stale_running: Some(StaleRunning::new(now)), + leaseless_running: true, never_started: true, attempts_exhausted: true, } @@ -471,13 +476,19 @@ mod builder_tests { use crate::commands::queue::{HealthMetric, build_health_query}; for backend in [Backend::Postgres, Backend::MySql] { - let (sql, _) = build_health_query(backend, HealthMetric::RecentFailures, None); + let (sql, _) = build_health_query( + backend, + HealthMetric::RecentFailures, + None, + chrono::Utc::now(), + ); assert!( sql.contains("status IN ('Failed', 'Dead', 'TimedOut')") && sql.contains("COALESCE(failed_at, timed_out_at) >"), "{sql}" ); - let (sql, _) = build_health_count_query(backend, HealthCount::RecentFailures); + let (sql, _) = + build_health_count_query(backend, HealthCount::RecentFailures, chrono::Utc::now()); assert!( sql.contains("status IN ('Failed', 'Dead', 'TimedOut')") && sql.contains("COALESCE(failed_at, timed_out_at) >"), @@ -493,6 +504,19 @@ mod builder_tests { } } + #[test] + fn test_leaseless_running_selector_is_the_complement_of_the_lease_rule() { + let selector = JobSelector { + statuses: vec![JobStatus::Running], + leaseless_running: true, + ..Default::default() + }; + let (sql, binds) = selector.sql(Backend::Postgres); + assert!(sql.contains("last_heartbeat_at IS NULL"), "{sql}"); + assert!(sql.contains("lease_expires_at IS NULL"), "{sql}"); + assert_eq!(binds, vec![Bind::Text("Running".into())]); + } + #[test] fn test_stale_running_selector_follows_the_lease_rule() { let now = chrono::Utc::now(); diff --git a/cargo-hammerwork/src/utils/database.rs b/cargo-hammerwork/src/utils/database.rs index 572a08b..d55bf94 100644 --- a/cargo-hammerwork/src/utils/database.rs +++ b/cargo-hammerwork/src/utils/database.rs @@ -8,7 +8,7 @@ //! //! ## Connecting to a Database //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::database::DatabasePool; //! //! # #[tokio::main] @@ -30,7 +30,7 @@ //! //! ## Running Migrations //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::database::DatabasePool; //! //! # #[tokio::main] @@ -48,7 +48,7 @@ //! //! ## Creating a Job Queue //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::database::DatabasePool; //! //! # #[tokio::main] @@ -116,7 +116,7 @@ fn connect_error(err: sqlx::Error, timeout: Duration) -> anyhow::Error { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::database::DatabasePool; /// /// # #[tokio::main] @@ -149,7 +149,7 @@ impl DatabasePool { /// /// # Examples /// - /// ```rust,ignore + /// ```text /// use cargo_hammerwork::utils::database::DatabasePool; /// /// # #[tokio::main] @@ -238,7 +238,7 @@ impl DatabasePool { /// /// # Examples /// - /// ```rust,ignore + /// ```text /// use cargo_hammerwork::utils::database::DatabasePool; /// /// # #[tokio::main] @@ -308,7 +308,7 @@ impl DatabasePool { /// /// # Examples /// - /// ```rust,ignore + /// ```text /// use cargo_hammerwork::utils::database::DatabasePool; /// /// # #[tokio::main] @@ -377,7 +377,7 @@ impl DatabasePool { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::database::{DatabasePool, JobQueueWrapper}; /// /// # #[tokio::main] diff --git a/cargo-hammerwork/src/utils/display.rs b/cargo-hammerwork/src/utils/display.rs index e9f4d6b..1b3f442 100644 --- a/cargo-hammerwork/src/utils/display.rs +++ b/cargo-hammerwork/src/utils/display.rs @@ -7,7 +7,7 @@ //! //! ## Creating a Job Table //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::display::JobTable; //! //! let mut table = JobTable::new(); @@ -27,7 +27,7 @@ //! //! ## Creating a Statistics Table //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::display::StatsTable; //! //! let mut stats = StatsTable::new(); @@ -40,7 +40,7 @@ //! //! ## Formatting Helpers //! -//! ```rust,ignore +//! ```text //! use cargo_hammerwork::utils::display::{format_duration, format_size}; //! //! // Format durations @@ -73,7 +73,7 @@ pub fn create_table() -> Table { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::display::JobTable; /// /// let mut table = JobTable::new(); @@ -189,7 +189,7 @@ impl fmt::Display for JobTable { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::display::StatsTable; /// /// let mut stats = StatsTable::new(); @@ -254,7 +254,7 @@ impl fmt::Display for StatsTable { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::display::format_duration; /// /// assert_eq!(format_duration(Some(30)), "30s"); @@ -277,7 +277,7 @@ pub fn format_duration(seconds: Option) -> String { /// /// # Examples /// -/// ```rust,ignore +/// ```text /// use cargo_hammerwork::utils::display::format_size; /// /// assert_eq!(format_size(Some(100)), "100B"); diff --git a/cargo-hammerwork/src/utils/job_ops.rs b/cargo-hammerwork/src/utils/job_ops.rs index 2056cf3..179bb98 100644 --- a/cargo-hammerwork/src/utils/job_ops.rs +++ b/cargo-hammerwork/src/utils/job_ops.rs @@ -33,6 +33,9 @@ pub struct JobSelector { pub started_before: Option>, /// Only `Running` jobs that `requeue_stale_jobs` would reclaim (see [`StaleRunning`]). pub stale_running: Option, + /// Only `Running` jobs without a lease of their current run (see + /// [`StaleRunning::leaseless_condition`]). + pub leaseless_running: bool, /// Only jobs with no `started_at`. pub never_started: bool, /// Only jobs that used all their attempts. @@ -60,6 +63,16 @@ impl StaleRunning { let now = params.time(self.now); format!("(last_heartbeat_at >= started_at AND lease_expires_at < {now})") } + + /// The SQL condition for a `Running` job that has no lease of its current run (left + /// by a Hammerwork 1.x worker). The library never reclaims such a job, so it is + /// neither stale nor stuck by the lease rule; it needs the one-off fix in the 3.0 + /// upgrade guide. The complement of "has a lease": a heartbeat at or after the start, + /// and an expiry. + pub fn leaseless_condition() -> &'static str { + "(last_heartbeat_at IS NULL OR started_at IS NULL OR last_heartbeat_at < started_at \ + OR lease_expires_at IS NULL)" + } } impl JobSelector { @@ -95,6 +108,9 @@ impl JobSelector { if let Some(stale) = &self.stale_running { conditions.push(stale.condition(&mut params)); } + if self.leaseless_running { + conditions.push(StaleRunning::leaseless_condition().to_string()); + } if self.never_started { conditions.push("started_at IS NULL".to_string()); } diff --git a/cargo-hammerwork/tests/cli_binary_tests.rs b/cargo-hammerwork/tests/cli_binary_tests.rs index bf7764d..db88658 100644 --- a/cargo-hammerwork/tests/cli_binary_tests.rs +++ b/cargo-hammerwork/tests/cli_binary_tests.rs @@ -273,8 +273,9 @@ fn db_flow(url: &str) { let (code, out) = cli(&["migration", "status"]); assert_eq!(code, 0, "{out}"); - assert!(out.contains("tables exist"), "{out}"); - assert!(out.contains("queue_name"), "{out}"); + assert!(out.contains("0 pending"), "{out}"); + assert!(out.contains("021_"), "{out}"); + assert!(out.contains("hammerwork_jobs table:"), "{out}"); // enqueue, list and show let (code, out) = cli(&[ diff --git a/config/init-mysql.sql b/config/init-mysql.sql index eb8320e..acd1930 100644 --- a/config/init-mysql.sql +++ b/config/init-mysql.sql @@ -1,53 +1,12 @@ --- MySQL initialization script for Hammerwork job queue --- This script sets up the database with proper permissions and indexes +-- MySQL initialization script for the docker-compose test database. +-- +-- Only the database user's permissions are set up here. The schema is created by the +-- migrations, so it always matches the library: +-- +-- cargo hammerwork migration run --database-url mysql://hammerwork:password@localhost:3306/hammerwork_test +-- +-- (a pre-created hammerwork_jobs table would be an outdated copy of the schema). --- Use the hammerwork_test database -USE hammerwork_test; - --- Create the hammerwork_jobs table if it doesn't exist --- This matches the schema from src/queue.rs mysql implementation -CREATE TABLE IF NOT EXISTS hammerwork_jobs ( - id CHAR(36) PRIMARY KEY, - queue_name VARCHAR(255) NOT NULL, - payload JSON NOT NULL, - status VARCHAR(50) NOT NULL, - attempts INT NOT NULL DEFAULT 0, - max_attempts INT NOT NULL DEFAULT 3, - created_at TIMESTAMP(6) NOT NULL, - scheduled_at TIMESTAMP(6) NOT NULL, - started_at TIMESTAMP(6) NULL, - completed_at TIMESTAMP(6) NULL, - error_message TEXT NULL, - INDEX idx_queue_status_scheduled (queue_name, status, scheduled_at), - INDEX idx_created_at (created_at), - INDEX idx_status (status) -); - --- Grant necessary permissions to the hammerwork user GRANT ALL PRIVILEGES ON hammerwork_test.* TO 'hammerwork'@'%'; GRANT ALL PRIVILEGES ON hammerwork_test.* TO 'hammerwork'@'localhost'; FLUSH PRIVILEGES; - --- Insert some initial test data for validation -INSERT IGNORE INTO hammerwork_jobs ( - id, - queue_name, - payload, - status, - attempts, - max_attempts, - created_at, - scheduled_at -) VALUES ( - UUID(), - 'test_queue', - JSON_OBJECT('message', 'Initial test job', 'type', 'validation'), - 'Pending', - 0, - 3, - NOW(6), - NOW(6) -); - --- Log successful initialization -SELECT 'Hammerwork MySQL database initialized successfully' AS message; \ No newline at end of file diff --git a/config/init-postgres.sql b/config/init-postgres.sql index 20cf2e2..873b6b8 100644 --- a/config/init-postgres.sql +++ b/config/init-postgres.sql @@ -1,60 +1,10 @@ --- PostgreSQL initialization script for Hammerwork job queue --- This script sets up the database with proper permissions and indexes - --- Create the hammerwork_jobs table if it doesn't exist --- This matches the schema from src/queue.rs postgres implementation -CREATE TABLE IF NOT EXISTS hammerwork_jobs ( - id UUID PRIMARY KEY, - queue_name VARCHAR NOT NULL, - payload JSONB NOT NULL, - status VARCHAR NOT NULL, - attempts INTEGER NOT NULL DEFAULT 0, - max_attempts INTEGER NOT NULL DEFAULT 3, - created_at TIMESTAMPTZ NOT NULL, - scheduled_at TIMESTAMPTZ NOT NULL, - started_at TIMESTAMPTZ, - completed_at TIMESTAMPTZ, - error_message TEXT -); - --- Create optimized indexes for job queue polling -CREATE INDEX IF NOT EXISTS idx_hammerwork_jobs_queue_status_scheduled -ON hammerwork_jobs (queue_name, status, scheduled_at); - --- Additional indexes for monitoring and cleanup -CREATE INDEX IF NOT EXISTS idx_hammerwork_jobs_created_at -ON hammerwork_jobs (created_at); - -CREATE INDEX IF NOT EXISTS idx_hammerwork_jobs_status -ON hammerwork_jobs (status); - --- Grant necessary permissions -GRANT ALL PRIVILEGES ON TABLE hammerwork_jobs TO postgres; -GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO postgres; - --- Insert some initial test data for validation -INSERT INTO hammerwork_jobs ( - id, - queue_name, - payload, - status, - attempts, - max_attempts, - created_at, - scheduled_at -) VALUES ( - gen_random_uuid(), - 'test_queue', - '{"message": "Initial test job", "type": "validation"}', - 'Pending', - 0, - 3, - NOW(), - NOW() -) ON CONFLICT DO NOTHING; - --- Log successful initialization -DO $$ -BEGIN - RAISE NOTICE 'Hammerwork PostgreSQL database initialized successfully'; -END $$; \ No newline at end of file +-- PostgreSQL initialization script for the docker-compose test database. +-- +-- Nothing to set up here: the database and user come from the POSTGRES_* variables in +-- docker-compose.yml, and the schema is created by the migrations, so it always matches +-- the library: +-- +-- cargo hammerwork migration run --database-url postgres://postgres:password@localhost:5432/hammerwork_test +-- +-- (a pre-created hammerwork_jobs table would be an outdated copy of the schema). +SELECT 1; diff --git a/docs/integration-testing.md b/docs/integration-testing.md index fd7cf7d..b8981bb 100644 --- a/docs/integration-testing.md +++ b/docs/integration-testing.md @@ -60,8 +60,8 @@ hammerwork/ │ ā”œā”€ā”€ setup-db.sh # Database management │ └── cleanup.sh # Environment cleanup ā”œā”€ā”€ config/ -│ ā”œā”€ā”€ init-postgres.sql # PostgreSQL initialization -│ └── init-mysql.sql # MySQL initialization +│ ā”œā”€ā”€ init-postgres.sql # PostgreSQL initialization (no schema) +│ └── init-mysql.sql # MySQL initialization (user permissions) ā”œā”€ā”€ integrations/ │ ā”œā”€ā”€ shared/ │ │ └── test_scenarios.rs # Common test scenarios @@ -350,9 +350,10 @@ docker system prune ### Database Schema Changes -1. **Update Initialization Scripts**: - - Modify `config/init-postgres.sql` - - Modify `config/init-mysql.sql` +1. **Add a Migration**: + - Add the versioned migration files under `src/migrations/` and register them. The + schema is created by `cargo hammerwork migration run`, never by + `config/init-postgres.sql` or `config/init-mysql.sql`, which set up no tables 2. **Update Database Queue Implementations**: - Modify PostgreSQL implementation in `src/queue/postgres.rs` diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.md index 755d7ae..5285ae1 100644 --- a/docs/upgrading-to-3.0.md +++ b/docs/upgrading-to-3.0.md @@ -4,6 +4,27 @@ Hammerwork 3.0 is a major release. This guide lists each breaking change, what i affects and what you need to change in your code, configuration or deployment. Read it together with the `3.0.0` entry in the [CHANGELOG](../CHANGELOG.md). +## Upgrade order + +Do the upgrade in this order. Each step links to the section with the details. + +1. **Stop every Hammerwork 1.x worker**, and anything else built on 1.x that claims + jobs. 3.0 never reclaims a `Running` job that has no lease, and 1.x workers claimed + jobs without one ([Stop every 1.x worker first](#stop-every-1x-worker-first)). +2. **Update your code and build.** Use Rust 1.94 and sqlx 0.9 + ([sqlx 0.9 and Rust 1.94](#sqlx-09-and-rust-194)), name the Cargo features you use + ([Feature flags](#feature-flags)), and fix the breaking API changes this guide lists. +3. **Drain the 2.x workers, back up the database and run `cargo hammerwork migration + run` off-peak.** On MySQL, migration 021 rewrites every table and blocks writes to it + while it does ([MySQL timestamps](#mysql-timestamps-migration-021)). Confirm the + result with `cargo hammerwork migration status`, which lists the applied and + pending migrations. +4. **Run `cargo hammerwork maintenance check --fix`** to give the `Running` jobs a 1.x + worker left behind a lease. Preview what the reaper would reclaim with + `cargo hammerwork job requeue-stale --dry-run` (add `--queue ` to look at one + queue). +5. **Start the 3.0 workers.** + ## sqlx 0.9 and Rust 1.94 Hammerwork 3.0 depends on [sqlx](https://crates.io/crates/sqlx) 0.9 instead of 0.8, @@ -106,7 +127,7 @@ For other sqlx 0.9 changes that may affect your own sqlx code (`RawSql`, Three changes to the Cargo features of `hammerwork` (#92): 1. **No default features.** In 2.x, `default = ["metrics", "alerting", "webhooks"]`. In 3.0, `default = []`, so a plain `hammerwork` dependency builds only the queue, worker and job APIs, without `warp`, `reqwest`, `lettre` or `prometheus`. -2. **`azure-kv` is now `azure-kms`**, like `aws-kms`, `gcp-kms` and `vault-kms`. There is no alias. +2. **`azure-kv` is now `azure-kms`**, like `aws-kms`, `gcp-kms` and `vault-kms`. There is no alias. The `cargo-hammerwork` crate renames its own `azure-kv` feature the same way, so `cargo install cargo-hammerwork --features azure-kv` becomes `--features azure-kms`. 3. **`test` is now `test-queue`.** There is no alias. New: a `full` feature that enables `metrics`, `alerting`, `webhooks`, `streaming`, `tracing` and `encryption`. It does not include a database backend (`postgres`, `mysql`), a KMS key source, an event stream sink (`kafka`, `google-pubsub`, `kinesis`) or `test-queue`. @@ -181,6 +202,20 @@ on. Use the CLI through the `cargo hammerwork` executable. If you need job, queu migration operations from Rust code, use the `hammerwork` crate (`DatabaseQueue`, `JobQueue`) directly. +#### CLI behavior changes + +- `job requeue-stale` takes `--queue ` and `--dry-run`. The dry run counts the + jobs the lease rule would reclaim and changes nothing. +- `monitor health` and `queue health` no longer call a `Running` job stuck because it + started more than an hour ago. A job is stuck when its lease expired, the rule the + reaper uses; a long-running job that keeps heartbeating is healthy. `Running` jobs + without a lease (left by a 1.x worker) are reported on their own row + (`Lease-less Running Jobs`) and are not counted as stuck. The JSON output of + `monitor health` gains that check. +- `migration status` lists the migrations this version registers as applied or pending, + from the `hammerwork_migrations` table, instead of the columns of `hammerwork_jobs`. + Applied migrations this version does not know are listed separately. + ### hammerwork-web The public API is `WebDashboard`, `DashboardConfig`, `AuthConfig` and `WebSocketConfig`, @@ -209,6 +244,13 @@ Migrate imports as follows: | `hammerwork_web::server::WebDashboard` | `hammerwork_web::WebDashboard` | | `hammerwork_web::server::app_routes`, `api::*`, `auth::*`, `security::*`, `websocket::*`, `live::*` | removed; mount the dashboard with `WebDashboard` | +### Dashboard metrics endpoint + +`GET /api/system/metrics` no longer returns `metrics_endpoint`, `custom_metrics_count` +or `last_scrape`. The dashboard serves no `/metrics` route and keeps no metrics registry, +so they were always `"/metrics"`, `null` and `null`. Only `prometheus_enabled` (always +`false`) remains. + ## DatabaseQueue is sealed `DatabaseQueue` is now a sealed trait (#87): only Hammerwork can implement it. Its @@ -376,8 +418,7 @@ column of every Hammerwork table (39 columns in `hammerwork_jobs`, `hammerwork_migrations`) to `DATETIME(6)`, which holds years 1000 to 9999. The three second-precision `DATETIME` columns of `hammerwork_workflows` (`created_at`, `completed_at`, `failed_at`) also become `DATETIME(6)`, so every MySQL time keeps -microseconds. The 2038 checks -are gone, and a new install gets the same schema by running all migrations. +microseconds. The 2038 checks are gone, and a new install gets the same schema by running all migrations. What the migration keeps: @@ -432,8 +473,8 @@ migration has finished. 2.x only ever binds UTC `DateTime` values and write ignores the migration record it does not know. What 2.x does not gain is the longer range: it still rejects times after 2038 itself. -The migration blocks writes while it runs, so 2.x workers will stall (and may time out -waiting on locks) during the conversion, so stop them or let them drain first. +The migration blocks writes while it runs, so 2.x workers stall (and may time out +waiting on locks) during the conversion. Stop them or let them drain first. ## Non-exhaustive structs and enums @@ -570,13 +611,13 @@ These stay exhaustive, so matching every variant keeps working: `JobStatus` and fixed scale, like `JobPriority`) and `alerting::SmtpTls` (the three ways to connect to an SMTP server). -### `ArchivedJob` lists the workflow +## `ArchivedJob` lists the workflow `ArchivedJob` has two new fields, `workflow_id` and `workflow_name`, filled in by `list_archived_jobs` on PostgreSQL, MySQL and `TestQueue` (the archive has stored them since migration 019). Both are `None` for a job outside a workflow. -### Event subscriptions unregister when dropped +## Event subscriptions unregister when dropped Dropping an `EventSubscription` now unregisters it from its `EventManager`: its filter stops counting toward `subscription_count` and `payload_wanted` without a call to @@ -603,20 +644,13 @@ drop(subscription); // unregisters # } ``` -### Webhook statistics count failed attempts +## Webhook statistics count failed attempts `WebhookStats` and `WebhookManagerStats` have a new `failed_attempts` counter: HTTP delivery attempts that failed, retries included, next to `total_attempts`. The per-delivery counters (`successful_deliveries`, `failed_deliveries`, `success_rate`) are unchanged. Serialized statistics without the field read it as 0. -### Dashboard metrics endpoint - -`GET /api/system/metrics` no longer returns `metrics_endpoint`, `custom_metrics_count` -or `last_scrape`. The dashboard serves no `/metrics` route and keeps no metrics registry, -so they were always `"/metrics"`, `null` and `null`. Only `prometheus_enabled` (always -`false`) remains. - ## Removed legacy compatibility 3.0 drops code that only existed for Hammerwork 1.x and for APIs deprecated in 2.0 @@ -654,7 +688,8 @@ So before you start any 3.0 worker: lease of their own alone. (`check --fix` retries `Running` jobs without a start time instead of giving them a lease.) 3. Let the reaper reclaim them: a `WorkerPool` does within a minute of starting, or run - `cargo hammerwork job requeue-stale`. Jobs with attempts left go back to `Pending`, + `cargo hammerwork job requeue-stale` (`--dry-run` counts what it would reclaim + without changing anything, `--queue ` limits it to one queue). Jobs with attempts left go back to `Pending`, the others to `Dead`, with the usual side effects (recurring jobs are rescheduled, dependents, workflows and batches see the failure). diff --git a/hammerwork-web/Cargo.toml b/hammerwork-web/Cargo.toml index 24ebeeb..d875596 100644 --- a/hammerwork-web/Cargo.toml +++ b/hammerwork-web/Cargo.toml @@ -19,7 +19,7 @@ path = "src/main.rs" [dependencies] # Core Hammerwork functionality -hammerwork = { workspace = true, features = ["postgres", "mysql", "metrics", "encryption"] } +hammerwork = { workspace = true, features = ["postgres", "mysql", "encryption"] } # Web framework and HTTP warp = { workspace = true } diff --git a/hammerwork-web/src/api/archive.rs b/hammerwork-web/src/api/archive.rs index ae3810e..786a049 100644 --- a/hammerwork-web/src/api/archive.rs +++ b/hammerwork-web/src/api/archive.rs @@ -11,55 +11,6 @@ //! - `POST /api/archive/jobs/{id}/restore` - Restore an archived job //! - `DELETE /api/archive/purge` - Purge old archived jobs //! - `GET /api/archive/stats` - Get archival statistics -//! -//! # Examples -//! -//! ## Archive Jobs -//! -//! ```rust -//! use hammerwork_web::__private::api::archive::{ArchiveRequest, ArchiveResponse}; -//! use hammerwork::archive::{ArchivalReason, ArchivalPolicy}; -//! use chrono::Duration; -//! -//! let request = ArchiveRequest { -//! queue_name: Some("completed_jobs".to_string()), -//! reason: ArchivalReason::Automatic, -//! archived_by: Some("scheduler".to_string()), -//! dry_run: false, -//! policy: Some(ArchivalPolicy::new() -//! .archive_completed_after(Duration::days(7))), -//! config: None, -//! }; -//! -//! // This would be sent to POST /api/archive/jobs -//! assert_eq!(request.queue_name, Some("completed_jobs".to_string())); -//! assert!(!request.dry_run); -//! ``` -//! -//! ## List Archived Jobs -//! -//! ```rust -//! use hammerwork_web::__private::api::archive::ArchivedJobInfo; -//! use hammerwork::archive::{ArchivalReason, ArchivedJob}; -//! use hammerwork::{JobId, JobStatus}; -//! use chrono::Utc; -//! use uuid::Uuid; -//! -//! let archived_job = ArchivedJobInfo { -//! id: Uuid::new_v4(), -//! queue_name: "email_queue".to_string(), -//! status: JobStatus::Completed, -//! created_at: Utc::now(), -//! archived_at: Utc::now(), -//! archival_reason: ArchivalReason::Automatic, -//! original_payload_size: Some(1024), -//! payload_compressed: true, -//! archived_by: Some("system".to_string()), -//! }; -//! -//! assert_eq!(archived_job.queue_name, "email_queue"); -//! assert!(archived_job.payload_compressed); -//! ``` use super::history::JobHistory; use super::{ @@ -121,6 +72,7 @@ pub struct ArchiveResponse { /// Request to restore an archived job #[derive(Debug, Deserialize)] pub struct RestoreRequest { + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Optional reason for restoration pub reason: Option, /// Who initiated the restoration @@ -145,6 +97,7 @@ pub struct PurgeRequest { pub older_than: chrono::DateTime, /// Whether this is a dry run pub dry_run: bool, + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Who initiated the purge pub purged_by: Option, } @@ -578,3 +531,52 @@ mod tests { assert_eq!(request.purged_by, Some("admin".to_string())); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::archive::ArchiveRequest; + use chrono::Duration; + use hammerwork::archive::{ArchivalPolicy, ArchivalReason}; + + let request = ArchiveRequest { + queue_name: Some("completed_jobs".to_string()), + reason: ArchivalReason::Automatic, + archived_by: Some("scheduler".to_string()), + dry_run: false, + policy: Some(ArchivalPolicy::new().archive_completed_after(Duration::days(7))), + config: None, + }; + + // This would be sent to POST /api/archive/jobs + assert_eq!(request.queue_name, Some("completed_jobs".to_string())); + assert!(!request.dry_run); + } + + #[test] + fn example_2() { + use crate::api::archive::ArchivedJobInfo; + use chrono::Utc; + use hammerwork::JobStatus; + use hammerwork::archive::ArchivalReason; + use uuid::Uuid; + + let archived_job = ArchivedJobInfo { + id: Uuid::new_v4(), + queue_name: "email_queue".to_string(), + status: JobStatus::Completed, + created_at: Utc::now(), + archived_at: Utc::now(), + archival_reason: ArchivalReason::Automatic, + original_payload_size: Some(1024), + payload_compressed: true, + archived_by: Some("system".to_string()), + }; + + assert_eq!(archived_job.queue_name, "email_queue"); + assert!(archived_job.payload_compressed); + } +} diff --git a/hammerwork-web/src/api/jobs.rs b/hammerwork-web/src/api/jobs.rs index 343c74f..06b1011 100644 --- a/hammerwork-web/src/api/jobs.rs +++ b/hammerwork-web/src/api/jobs.rs @@ -11,72 +11,6 @@ //! - `POST /api/jobs/{id}/actions` - Perform actions on a job (retry, cancel, delete) //! - `POST /api/jobs/bulk` - Perform bulk actions on multiple jobs //! - `POST /api/jobs/search` - Search jobs with full-text queries -//! -//! # Examples -//! -//! ## Creating a Job -//! -//! ```rust -//! use hammerwork_web::__private::api::jobs::CreateJobRequest; -//! use serde_json::json; -//! -//! let create_request = CreateJobRequest { -//! queue_name: "email_queue".to_string(), -//! payload: json!({ -//! "to": "user@example.com", -//! "subject": "Welcome!", -//! "template": "welcome_email" -//! }), -//! priority: Some("high".to_string()), -//! scheduled_at: None, -//! max_attempts: Some(3), -//! cron_schedule: None, -//! trace_id: Some("trace-123".to_string()), -//! correlation_id: Some("corr-456".to_string()), -//! }; -//! -//! // This would be sent as JSON in a POST request to /api/jobs -//! let json_payload = serde_json::to_string(&create_request).unwrap(); -//! assert!(json_payload.contains("email_queue")); -//! assert!(json_payload.contains("high")); -//! ``` -//! -//! ## Job Actions -//! -//! ```rust -//! use hammerwork_web::__private::api::jobs::JobActionRequest; -//! -//! let retry_request = JobActionRequest { -//! action: "retry".to_string(), -//! reason: Some("Network issue resolved".to_string()), -//! }; -//! -//! let cancel_request = JobActionRequest { -//! action: "cancel".to_string(), -//! reason: Some("No longer needed".to_string()), -//! }; -//! -//! assert_eq!(retry_request.action, "retry"); -//! assert_eq!(cancel_request.action, "cancel"); -//! ``` -//! -//! ## Bulk Operations -//! -//! ```rust -//! use hammerwork_web::__private::api::jobs::BulkJobActionRequest; -//! -//! let bulk_delete = BulkJobActionRequest { -//! job_ids: vec![ -//! "550e8400-e29b-41d4-a716-446655440000".to_string(), -//! "550e8400-e29b-41d4-a716-446655440001".to_string(), -//! ], -//! action: "delete".to_string(), -//! reason: Some("Cleanup old failed jobs".to_string()), -//! }; -//! -//! assert_eq!(bulk_delete.job_ids.len(), 2); -//! assert_eq!(bulk_delete.action, "delete"); -//! ``` use super::history::JobHistory; use super::{ @@ -130,6 +64,7 @@ pub struct CreateJobRequest { #[derive(Debug, Deserialize)] pub struct JobActionRequest { pub action: String, // "retry", "cancel", "delete" + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests pub reason: Option, } @@ -141,6 +76,7 @@ pub const MAX_BULK_JOB_IDS: usize = 1000; pub struct BulkJobActionRequest { pub job_ids: Vec, pub action: String, + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests pub reason: Option, } @@ -1178,3 +1114,69 @@ mod tests { assert_eq!(request.action, "delete"); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::jobs::CreateJobRequest; + use serde_json::json; + + let create_request = CreateJobRequest { + queue_name: "email_queue".to_string(), + payload: json!({ + "to": "user@example.com", + "subject": "Welcome!", + "template": "welcome_email" + }), + priority: Some("high".to_string()), + scheduled_at: None, + max_attempts: Some(3), + cron_schedule: None, + trace_id: Some("trace-123".to_string()), + correlation_id: Some("corr-456".to_string()), + }; + + // This would be sent as JSON in a POST request to /api/jobs + let json_payload = serde_json::to_string(&create_request).unwrap(); + assert!(json_payload.contains("email_queue")); + assert!(json_payload.contains("high")); + } + + #[test] + fn example_2() { + use crate::api::jobs::JobActionRequest; + + let retry_request = JobActionRequest { + action: "retry".to_string(), + reason: Some("Network issue resolved".to_string()), + }; + + let cancel_request = JobActionRequest { + action: "cancel".to_string(), + reason: Some("No longer needed".to_string()), + }; + + assert_eq!(retry_request.action, "retry"); + assert_eq!(cancel_request.action, "cancel"); + } + + #[test] + fn example_3() { + use crate::api::jobs::BulkJobActionRequest; + + let bulk_delete = BulkJobActionRequest { + job_ids: vec![ + "550e8400-e29b-41d4-a716-446655440000".to_string(), + "550e8400-e29b-41d4-a716-446655440001".to_string(), + ], + action: "delete".to_string(), + reason: Some("Cleanup old failed jobs".to_string()), + }; + + assert_eq!(bulk_delete.job_ids.len(), 2); + assert_eq!(bulk_delete.action, "delete"); + } +} diff --git a/hammerwork-web/src/api/mod.rs b/hammerwork-web/src/api/mod.rs index 22c4120..ce0bd53 100644 --- a/hammerwork-web/src/api/mod.rs +++ b/hammerwork-web/src/api/mod.rs @@ -8,45 +8,9 @@ //! //! All API endpoints return responses in a consistent format: //! -//! ```rust -//! use hammerwork_web::__private::api::ApiResponse; -//! use serde_json::json; -//! -//! // Success response -//! let success_response = ApiResponse::success(json!({"count": 42})); -//! assert!(success_response.success); -//! assert!(success_response.data.is_some()); -//! assert!(success_response.error.is_none()); -//! -//! // Error response -//! let error_response: ApiResponse<()> = ApiResponse::error("Something went wrong".to_string()); -//! assert!(!error_response.success); -//! assert!(error_response.data.is_none()); -//! assert!(error_response.error.is_some()); -//! ``` -//! //! # Pagination //! //! Many endpoints support pagination using query parameters: -//! -//! ```rust -//! use hammerwork_web::__private::api::{PaginationParams, PaginationMeta}; -//! -//! let params = PaginationParams { -//! page: Some(2), -//! limit: Some(50), -//! offset: None, -//! }; -//! -//! assert_eq!(params.get_limit(), 50); -//! assert_eq!(params.get_offset(), 50); // (page-1) * limit -//! -//! let meta = PaginationMeta::new(¶ms, 200); // 200 total items -//! assert_eq!(meta.page, 2); -//! assert_eq!(meta.total_pages, 4); -//! assert!(meta.has_next); -//! assert!(meta.has_prev); -//! ``` /// Unwrap a `Result` inside a warp handler returning `Ok(reply)`; on error log it /// and return a `500` JSON error response instead of swallowing the failure. @@ -272,6 +236,7 @@ impl SortParams { .is_some_and(|order| order.trim().eq_ignore_ascii_case("asc")) } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests pub fn get_order_by(&self) -> (String, String) { let field = self.sort_by.as_deref().unwrap_or("created_at").to_string(); let direction = if self.is_ascending() { "ASC" } else { "DESC" }.to_string(); @@ -279,6 +244,7 @@ impl SortParams { } } +#[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Common error handling for API endpoints pub async fn handle_api_error( err: warp::Rejection, @@ -968,3 +934,47 @@ mod undecodable_row_tests { listings_skip_undecodable_rows(queue, sql, true).await; } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::ApiResponse; + use serde_json::json; + + // Success response + let success_response = ApiResponse::success(json!({"count": 42})); + assert!(success_response.success); + assert!(success_response.data.is_some()); + assert!(success_response.error.is_none()); + + // Error response + let error_response: ApiResponse<()> = + ApiResponse::error("Something went wrong".to_string()); + assert!(!error_response.success); + assert!(error_response.data.is_none()); + assert!(error_response.error.is_some()); + } + + #[test] + fn example_2() { + use crate::api::{PaginationMeta, PaginationParams}; + + let params = PaginationParams { + page: Some(2), + limit: Some(50), + offset: None, + }; + + assert_eq!(params.get_limit(), 50); + assert_eq!(params.get_offset(), 50); // (page-1) * limit + + let meta = PaginationMeta::new(¶ms, 200); // 200 total items + assert_eq!(meta.page, 2); + assert_eq!(meta.total_pages, 4); + assert!(meta.has_next); + assert!(meta.has_prev); + } +} diff --git a/hammerwork-web/src/api/queues.rs b/hammerwork-web/src/api/queues.rs index 0264f5f..c0d64d0 100644 --- a/hammerwork-web/src/api/queues.rs +++ b/hammerwork-web/src/api/queues.rs @@ -9,95 +9,6 @@ //! - `GET /api/queues/{name}` - Get detailed statistics for a specific queue //! - `POST /api/queues/{name}/actions` - Perform actions on a queue (pause, resume, clear) //! - `GET /api/queues/{name}/jobs` - List jobs in a specific queue -//! -//! # Examples -//! -//! ## Queue Information Structure -//! -//! ```rust -//! use hammerwork_web::__private::api::queues::QueueInfo; -//! use chrono::Utc; -//! -//! let queue_info = QueueInfo { -//! name: "email_queue".to_string(), -//! pending_count: 25, -//! running_count: 3, -//! completed_count: 1500, -//! failed_count: 12, -//! dead_count: 2, -//! avg_processing_time_ms: 250.5, -//! throughput_per_minute: 45.0, -//! error_rate: 0.008, -//! last_job_at: Some(Utc::now()), -//! oldest_pending_job: Some(Utc::now()), -//! is_paused: false, -//! paused_at: None, -//! paused_by: None, -//! }; -//! -//! assert_eq!(queue_info.name, "email_queue"); -//! assert_eq!(queue_info.pending_count, 25); -//! assert_eq!(queue_info.running_count, 3); -//! ``` -//! -//! ## Queue Actions -//! -//! ```rust -//! use hammerwork_web::__private::api::queues::QueueActionRequest; -//! -//! let clear_dead_request = QueueActionRequest { -//! action: "clear_dead".to_string(), -//! confirm: Some(true), -//! }; -//! -//! let pause_request = QueueActionRequest { -//! action: "pause".to_string(), -//! confirm: None, -//! }; -//! -//! assert_eq!(clear_dead_request.action, "clear_dead"); -//! assert_eq!(pause_request.action, "pause"); -//! ``` -//! -//! ## Detailed Queue Statistics -//! -//! ```rust -//! use hammerwork_web::__private::api::queues::{DetailedQueueStats, QueueInfo, HourlyThroughput, RecentError}; -//! use std::collections::HashMap; -//! use chrono::Utc; -//! -//! let queue_info = QueueInfo { -//! name: "default".to_string(), -//! pending_count: 10, -//! running_count: 2, -//! completed_count: 500, -//! failed_count: 5, -//! dead_count: 1, -//! avg_processing_time_ms: 180.0, -//! throughput_per_minute: 30.0, -//! error_rate: 0.01, -//! last_job_at: None, -//! oldest_pending_job: None, -//! is_paused: false, -//! paused_at: None, -//! paused_by: None, -//! }; -//! -//! let mut priority_breakdown = HashMap::new(); -//! priority_breakdown.insert("high".to_string(), 5); -//! priority_breakdown.insert("normal".to_string(), 15); -//! -//! let detailed_stats = DetailedQueueStats { -//! queue_info, -//! priority_breakdown, -//! status_breakdown: HashMap::new(), -//! hourly_throughput: vec![], -//! recent_errors: vec![], -//! }; -//! -//! assert_eq!(detailed_stats.queue_info.name, "default"); -//! assert_eq!(detailed_stats.priority_breakdown.get("high"), Some(&5)); -//! ``` use super::history::{FinishedKind, JobHistory}; use super::{ @@ -161,6 +72,7 @@ pub struct RecentError { #[derive(Debug, Deserialize)] pub struct QueueActionRequest { pub action: String, // "pause", "resume", "clear_dead", "clear_completed" + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests pub confirm: Option, } @@ -790,3 +702,92 @@ mod tests { assert!(json.contains("is_paused")); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::queues::QueueInfo; + use chrono::Utc; + + let queue_info = QueueInfo { + name: "email_queue".to_string(), + pending_count: 25, + running_count: 3, + completed_count: 1500, + failed_count: 12, + dead_count: 2, + avg_processing_time_ms: 250.5, + throughput_per_minute: 45.0, + error_rate: 0.008, + last_job_at: Some(Utc::now()), + oldest_pending_job: Some(Utc::now()), + is_paused: false, + paused_at: None, + paused_by: None, + }; + + assert_eq!(queue_info.name, "email_queue"); + assert_eq!(queue_info.pending_count, 25); + assert_eq!(queue_info.running_count, 3); + } + + #[test] + fn example_2() { + use crate::api::queues::QueueActionRequest; + + let clear_dead_request = QueueActionRequest { + action: "clear_dead".to_string(), + confirm: Some(true), + }; + + let pause_request = QueueActionRequest { + action: "pause".to_string(), + confirm: None, + }; + + assert_eq!(clear_dead_request.action, "clear_dead"); + assert_eq!(pause_request.action, "pause"); + } + + #[test] + fn example_3() { + use crate::api::queues::{DetailedQueueStats, QueueInfo}; + + use std::collections::HashMap; + + let queue_info = QueueInfo { + name: "default".to_string(), + pending_count: 10, + running_count: 2, + completed_count: 500, + failed_count: 5, + dead_count: 1, + avg_processing_time_ms: 180.0, + throughput_per_minute: 30.0, + error_rate: 0.01, + last_job_at: None, + oldest_pending_job: None, + is_paused: false, + paused_at: None, + paused_by: None, + }; + + let mut priority_breakdown = HashMap::new(); + priority_breakdown.insert("high".to_string(), 5); + priority_breakdown.insert("normal".to_string(), 15); + + let detailed_stats = DetailedQueueStats { + queue_info, + priority_breakdown, + status_breakdown: HashMap::new(), + hourly_throughput: vec![], + recent_errors: vec![], + }; + + assert_eq!(detailed_stats.queue_info.name, "default"); + assert_eq!(detailed_stats.priority_breakdown.get("high"), Some(&5)); + } +} diff --git a/hammerwork-web/src/api/stats.rs b/hammerwork-web/src/api/stats.rs index aaded0f..7a6ba18 100644 --- a/hammerwork-web/src/api/stats.rs +++ b/hammerwork-web/src/api/stats.rs @@ -9,105 +9,6 @@ //! - `GET /api/stats/detailed` - Detailed statistics with historical trends //! - `GET /api/stats/trends` - Hourly/daily trend analysis //! - `GET /api/stats/health` - System health check and alerts -//! -//! # Examples -//! -//! ## System Overview -//! -//! ```rust -//! use hammerwork_web::__private::api::stats::{SystemOverview, SystemHealth, SystemAlert}; -//! use chrono::Utc; -//! -//! let overview = SystemOverview { -//! total_queues: 5, -//! total_jobs: 10000, -//! pending_jobs: 50, -//! running_jobs: 10, -//! completed_jobs: 9800, -//! failed_jobs: 125, -//! dead_jobs: 15, -//! overall_throughput: 150.5, -//! overall_error_rate: 0.0125, -//! avg_processing_time_ms: 250.0, -//! system_health: SystemHealth { -//! status: "healthy".to_string(), -//! database_healthy: true, -//! high_error_rate: false, -//! queue_backlog: false, -//! slow_processing: false, -//! alerts: vec![], -//! }, -//! uptime_seconds: 86400, -//! last_updated: Utc::now(), -//! }; -//! -//! assert_eq!(overview.total_queues, 5); -//! assert_eq!(overview.overall_error_rate, 0.0125); -//! assert_eq!(overview.system_health.status, "healthy"); -//! ``` -//! -//! ## Statistics Queries -//! -//! ```rust -//! use hammerwork_web::__private::api::stats::{StatsQuery, TimeRange}; -//! use chrono::{Utc, Duration}; -//! -//! let time_range = TimeRange { -//! start: Utc::now() - Duration::hours(24), -//! end: Utc::now(), -//! }; -//! -//! let query = StatsQuery { -//! time_range: Some(time_range), -//! queues: Some(vec!["email".to_string(), "notifications".to_string()]), -//! granularity: Some("hour".to_string()), -//! hours: None, -//! }; -//! -//! assert!(query.time_range.is_some()); -//! assert_eq!(query.queues.as_ref().unwrap().len(), 2); -//! assert_eq!(query.granularity, Some("hour".to_string())); -//! ``` -//! -//! ## System Alerts -//! -//! ```rust -//! use hammerwork_web::__private::api::stats::SystemAlert; -//! use chrono::Utc; -//! -//! let alert = SystemAlert { -//! severity: "warning".to_string(), -//! message: "Queue backlog detected".to_string(), -//! queue: Some("image_processing".to_string()), -//! metric: Some("pending_count".to_string()), -//! value: Some(1500.0), -//! threshold: Some(1000.0), -//! timestamp: Utc::now(), -//! }; -//! -//! assert_eq!(alert.severity, "warning"); -//! assert_eq!(alert.queue, Some("image_processing".to_string())); -//! assert_eq!(alert.value, Some(1500.0)); -//! ``` -//! -//! ## Performance Metrics -//! -//! ```rust -//! use hammerwork_web::__private::api::stats::PerformanceMetrics; -//! -//! let metrics = PerformanceMetrics { -//! database_response_time_ms: Some(5.2), -//! average_queue_depth: 15.5, -//! jobs_per_second: 8.3, -//! memory_usage_mb: Some(512.0), -//! cpu_usage_percent: Some(45.2), -//! active_workers: None, // not tracked: there is no worker registry -//! worker_utilization: None, -//! }; -//! -//! assert_eq!(metrics.database_response_time_ms, Some(5.2)); -//! assert_eq!(metrics.active_workers, None); -//! ``` use super::history::{ErrorGroup, JobHistory, MAX_BUCKETS, hour_floor}; use super::{ApiResponse, error_reply, json_reply, with_shared}; @@ -1318,3 +1219,101 @@ mod tests { assert!(json.contains("High error rate")); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::stats::{SystemHealth, SystemOverview}; + use chrono::Utc; + + let overview = SystemOverview { + total_queues: 5, + total_jobs: 10000, + pending_jobs: 50, + running_jobs: 10, + completed_jobs: 9800, + failed_jobs: 125, + dead_jobs: 15, + overall_throughput: 150.5, + overall_error_rate: 0.0125, + avg_processing_time_ms: 250.0, + system_health: SystemHealth { + status: "healthy".to_string(), + database_healthy: true, + high_error_rate: false, + queue_backlog: false, + slow_processing: false, + alerts: vec![], + }, + uptime_seconds: 86400, + last_updated: Utc::now(), + }; + + assert_eq!(overview.total_queues, 5); + assert_eq!(overview.overall_error_rate, 0.0125); + assert_eq!(overview.system_health.status, "healthy"); + } + + #[test] + fn example_2() { + use crate::api::stats::{StatsQuery, TimeRange}; + use chrono::{Duration, Utc}; + + let time_range = TimeRange { + start: Utc::now() - Duration::hours(24), + end: Utc::now(), + }; + + let query = StatsQuery { + time_range: Some(time_range), + queues: Some(vec!["email".to_string(), "notifications".to_string()]), + granularity: Some("hour".to_string()), + hours: None, + }; + + assert!(query.time_range.is_some()); + assert_eq!(query.queues.as_ref().unwrap().len(), 2); + assert_eq!(query.granularity, Some("hour".to_string())); + } + + #[test] + fn example_3() { + use crate::api::stats::SystemAlert; + use chrono::Utc; + + let alert = SystemAlert { + severity: "warning".to_string(), + message: "Queue backlog detected".to_string(), + queue: Some("image_processing".to_string()), + metric: Some("pending_count".to_string()), + value: Some(1500.0), + threshold: Some(1000.0), + timestamp: Utc::now(), + }; + + assert_eq!(alert.severity, "warning"); + assert_eq!(alert.queue, Some("image_processing".to_string())); + assert_eq!(alert.value, Some(1500.0)); + } + + #[test] + fn example_4() { + use crate::api::stats::PerformanceMetrics; + + let metrics = PerformanceMetrics { + database_response_time_ms: Some(5.2), + average_queue_depth: 15.5, + jobs_per_second: 8.3, + memory_usage_mb: Some(512.0), + cpu_usage_percent: Some(45.2), + active_workers: None, // not tracked: there is no worker registry + worker_utilization: None, + }; + + assert_eq!(metrics.database_response_time_ms, Some(5.2)); + assert_eq!(metrics.active_workers, None); + } +} diff --git a/hammerwork-web/src/api/system.rs b/hammerwork-web/src/api/system.rs index 54edbf3..3fbcb6e 100644 --- a/hammerwork-web/src/api/system.rs +++ b/hammerwork-web/src/api/system.rs @@ -10,109 +10,6 @@ //! - `GET /api/system/metrics` - Metrics and monitoring information //! - `POST /api/system/maintenance` - Perform maintenance operations //! - `GET /api/version` - Basic version information -//! -//! # Examples -//! -//! ## System Information -//! -//! ```rust -//! use hammerwork_web::__private::api::system::{SystemInfo, BuildInfo, RuntimeInfo, DatabaseInfo}; -//! use chrono::Utc; -//! -//! let build_info = BuildInfo { -//! version: "1.3.0".to_string(), -//! git_commit: Some("a1b2c3d".to_string()), -//! build_date: Some("2024-01-15".to_string()), -//! rust_version: "1.70.0".to_string(), -//! target_triple: "x86_64-unknown-linux-gnu".to_string(), -//! }; -//! -//! let runtime_info = RuntimeInfo { -//! process_id: 12345, -//! memory_usage_bytes: Some(134217728), // 128MB -//! cpu_usage_percent: Some(5.2), -//! thread_count: Some(8), -//! gc_collections: None, // Not applicable for Rust -//! }; -//! -//! let database_info = DatabaseInfo { -//! database_type: "PostgreSQL".to_string(), -//! connection_url: "***masked***".to_string(), -//! pool_size: 10, -//! active_connections: Some(3), -//! connection_health: true, -//! last_migration: Some("20240101_initial".to_string()), -//! }; -//! -//! let system_info = SystemInfo { -//! version: "1.3.0".to_string(), -//! build_info, -//! runtime_info, -//! database_info, -//! features: vec!["postgres".to_string(), "auth".to_string()], -//! uptime_seconds: 86400, -//! started_at: Utc::now(), -//! }; -//! -//! assert_eq!(system_info.version, "1.3.0"); -//! assert!(system_info.features.contains(&"postgres".to_string())); -//! assert_eq!(system_info.runtime_info.process_id, 12345); -//! ``` -//! -//! ## Maintenance Operations -//! -//! ```rust -//! use hammerwork_web::__private::api::system::MaintenanceRequest; -//! use serde_json::json; -//! -//! let cleanup_request = MaintenanceRequest { -//! operation: "cleanup".to_string(), -//! target: Some("old_jobs".to_string()), -//! dry_run: Some(true), -//! }; -//! -//! let vacuum_request = MaintenanceRequest { -//! operation: "vacuum".to_string(), -//! target: Some("hammerwork_jobs".to_string()), -//! dry_run: Some(false), -//! }; -//! -//! assert_eq!(cleanup_request.operation, "cleanup"); -//! assert_eq!(cleanup_request.dry_run, Some(true)); -//! assert_eq!(vacuum_request.operation, "vacuum"); -//! ``` -//! -//! ## Server Configuration -//! -//! ```rust -//! use hammerwork_web::__private::api::system::ServerConfig; -//! -//! let config = ServerConfig { -//! bind_address: "0.0.0.0".to_string(), -//! port: 8080, -//! authentication_enabled: true, -//! cors_enabled: false, -//! websocket_max_connections: 100, -//! static_assets_path: "/var/www/dashboard".to_string(), -//! }; -//! -//! assert_eq!(config.bind_address, "0.0.0.0"); -//! assert_eq!(config.port, 8080); -//! assert!(config.authentication_enabled); -//! assert!(!config.cors_enabled); -//! ``` -//! -//! ## Metrics Information -//! -//! ```rust -//! use hammerwork_web::__private::api::system::MetricsInfo; -//! -//! let metrics_info = MetricsInfo { -//! prometheus_enabled: false, -//! }; -//! -//! assert!(!metrics_info.prometheus_enabled); -//! ``` use super::history::{FinishedKind, JobHistory, TableMaintenance, maintenance_tables}; use super::{ApiResponse, error_reply, json_reply, with_shared}; @@ -216,6 +113,7 @@ pub struct MetricsInfo { pub prometheus_enabled: bool, } +#[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Configuration update request #[derive(Debug, Deserialize)] pub struct ConfigUpdateRequest { @@ -632,3 +530,104 @@ mod tests { assert!(target.contains("-")); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::api::system::{BuildInfo, DatabaseInfo, RuntimeInfo, SystemInfo}; + use chrono::Utc; + + let build_info = BuildInfo { + version: "1.3.0".to_string(), + git_commit: Some("a1b2c3d".to_string()), + build_date: Some("2024-01-15".to_string()), + rust_version: "1.70.0".to_string(), + target_triple: "x86_64-unknown-linux-gnu".to_string(), + }; + + let runtime_info = RuntimeInfo { + process_id: 12345, + memory_usage_bytes: Some(134217728), // 128MB + cpu_usage_percent: Some(5.2), + thread_count: Some(8), + gc_collections: None, // Not applicable for Rust + }; + + let database_info = DatabaseInfo { + database_type: "PostgreSQL".to_string(), + connection_url: "***masked***".to_string(), + pool_size: 10, + active_connections: Some(3), + connection_health: true, + last_migration: Some("20240101_initial".to_string()), + }; + + let system_info = SystemInfo { + version: "1.3.0".to_string(), + build_info, + runtime_info, + database_info, + features: vec!["postgres".to_string(), "auth".to_string()], + uptime_seconds: 86400, + started_at: Utc::now(), + }; + + assert_eq!(system_info.version, "1.3.0"); + assert!(system_info.features.contains(&"postgres".to_string())); + assert_eq!(system_info.runtime_info.process_id, 12345); + } + + #[test] + fn example_2() { + use crate::api::system::MaintenanceRequest; + + let cleanup_request = MaintenanceRequest { + operation: "cleanup".to_string(), + target: Some("old_jobs".to_string()), + dry_run: Some(true), + }; + + let vacuum_request = MaintenanceRequest { + operation: "vacuum".to_string(), + target: Some("hammerwork_jobs".to_string()), + dry_run: Some(false), + }; + + assert_eq!(cleanup_request.operation, "cleanup"); + assert_eq!(cleanup_request.dry_run, Some(true)); + assert_eq!(vacuum_request.operation, "vacuum"); + } + + #[test] + fn example_3() { + use crate::api::system::ServerConfig; + + let config = ServerConfig { + bind_address: "0.0.0.0".to_string(), + port: 8080, + authentication_enabled: true, + cors_enabled: false, + websocket_max_connections: 100, + static_assets_path: "/var/www/dashboard".to_string(), + }; + + assert_eq!(config.bind_address, "0.0.0.0"); + assert_eq!(config.port, 8080); + assert!(config.authentication_enabled); + assert!(!config.cors_enabled); + } + + #[test] + fn example_4() { + use crate::api::system::MetricsInfo; + + let metrics_info = MetricsInfo { + prometheus_enabled: false, + }; + + assert!(!metrics_info.prometheus_enabled); + } +} diff --git a/hammerwork-web/tests/api_tests.rs b/hammerwork-web/src/api_tests.rs similarity index 98% rename from hammerwork-web/tests/api_tests.rs rename to hammerwork-web/src/api_tests.rs index 240020d..44317af 100644 --- a/hammerwork-web/tests/api_tests.rs +++ b/hammerwork-web/src/api_tests.rs @@ -2,16 +2,16 @@ //! static files) served over a real database, once per backend, with authentication on and //! off. Every endpoint is exercised for its success and its error paths. +use crate::api::history::JobHistory; +use crate::api::system::SystemState; +use crate::auth::AuthState; +use crate::config::{AuthConfig, DashboardConfig}; +use crate::security::AllowedOrigins; +use crate::server::app_routes; +use crate::websocket::WebSocketState; use hammerwork::archive::{ArchivalConfig, ArchivalPolicy, ArchivalReason}; use hammerwork::queue::DatabaseQueue; use hammerwork::{Job, JobPriority, JobQueue}; -use hammerwork_web::__private::api::history::JobHistory; -use hammerwork_web::__private::api::system::SystemState; -use hammerwork_web::__private::auth::AuthState; -use hammerwork_web::__private::config::{AuthConfig, DashboardConfig}; -use hammerwork_web::__private::security::AllowedOrigins; -use hammerwork_web::__private::server::app_routes; -use hammerwork_web::__private::websocket::WebSocketState; use serde_json::{Value, json}; use std::sync::Arc; use tokio::sync::RwLock; @@ -41,9 +41,11 @@ impl App { std::fs::create_dir(static_dir.path().join("assets")).unwrap(); std::fs::write(static_dir.path().join("asset.txt"), "static file").unwrap(); - let mut config = DashboardConfig::default(); - config.static_dir = static_dir.path().to_path_buf(); - config.auth = auth.clone(); + let config = DashboardConfig { + static_dir: static_dir.path().to_path_buf(), + auth: auth.clone(), + ..DashboardConfig::default() + }; let system_state = Arc::new(RwLock::new(SystemState::new( config.clone(), database_type.to_string(), @@ -1487,7 +1489,7 @@ async fn request_hardening(app: &App) { ) .await; assert_eq!(status, 413); - let ids: Vec = (0..=hammerwork_web::__private::api::jobs::MAX_BULK_JOB_IDS) + let ids: Vec = (0..=crate::api::jobs::MAX_BULK_JOB_IDS) .map(|_| uuid::Uuid::new_v4().to_string()) .collect(); let (status, body) = app diff --git a/hammerwork-web/src/auth.rs b/hammerwork-web/src/auth.rs index df2c2af..9625c1b 100644 --- a/hammerwork-web/src/auth.rs +++ b/hammerwork-web/src/auth.rs @@ -19,43 +19,6 @@ //! addresses. After `max_failed_attempts` failures the client is refused for //! `lockout_duration`; afterwards the count starts over, and a successful login resets it. //! At most [`MAX_TRACKED_CLIENTS`] clients are tracked. -//! -//! # Examples -//! -//! ## Basic Authentication Setup -//! -//! ```rust -//! use hammerwork_web::__private::auth::AuthState; -//! use hammerwork_web::__private::config::AuthConfig; -//! -//! let auth_config = AuthConfig::default() -//! .with_enabled(true) -//! .with_username("admin".to_string()) -//! // A bcrypt hash, for example from `bcrypt::hash(password, bcrypt::DEFAULT_COST)`. -//! .with_password_hash( -//! "$2b$12$abcdefghijklmnopqrstuuJ0Y7gZ8z5d0FQqfJb8yX3QZpGQ0lW6e".to_string(), -//! ); -//! -//! let auth_state = AuthState::new(auth_config); -//! assert!(auth_state.is_enabled()); -//! ``` -//! -//! ## Extracting Basic Auth Credentials -//! -//! ```rust -//! use hammerwork_web::__private::auth::extract_basic_auth; -//! -//! // "admin:password" in base64 is "YWRtaW46cGFzc3dvcmQ=" -//! let auth_header = "Basic YWRtaW46cGFzc3dvcmQ="; -//! let (username, password) = extract_basic_auth(auth_header).unwrap(); -//! -//! assert_eq!(username, "admin"); -//! assert_eq!(password, "password"); -//! -//! // Invalid format returns None -//! let result = extract_basic_auth("Bearer token123"); -//! assert!(result.is_none()); -//! ``` use crate::config::AuthConfig; use crate::security::RequestRefused; @@ -198,6 +161,7 @@ impl AuthState { self.inner.config.enabled } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Verify credentials from an unknown client address. /// /// Equivalent to [`check`](Self::check) with no client address, returning whether the @@ -313,11 +277,13 @@ impl AuthState { verified.insert(credentials, now + ttl); } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Whether `username` is locked out when connecting from an unknown address. pub async fn is_locked_out(&self, username: &str) -> bool { self.is_locked_out_from(None, username).await } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Whether `username` is locked out when connecting from `client`. pub async fn is_locked_out_from(&self, client: Option, username: &str) -> bool { self.key_locked_out(self.attempt_key(client, username)) @@ -372,6 +338,7 @@ impl AuthState { lock(&self.inner.verified).retain(|_, expires| *expires > now); } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// The number of clients with failure records (for tests and monitoring). pub fn tracked_clients(&self) -> usize { lock(&self.inner.failed_attempts).len() @@ -384,21 +351,6 @@ impl AuthState { /// The header format should be: `Basic ` /// where credentials are in the format `username:password`. /// -/// # Examples -/// -/// ```rust -/// use hammerwork_web::__private::auth::extract_basic_auth; -/// -/// // Valid basic auth header -/// let auth_header = "Basic YWRtaW46cGFzc3dvcmQ="; // admin:password -/// let (username, password) = extract_basic_auth(auth_header).unwrap(); -/// assert_eq!(username, "admin"); -/// assert_eq!(password, "password"); -/// -/// // Invalid format returns None -/// assert!(extract_basic_auth("Bearer token123").is_none()); -/// assert!(extract_basic_auth("Basic invalid_base64").is_none()); -/// ``` /// /// # Returns /// @@ -1116,3 +1068,56 @@ mod tests { assert_eq!(custom.status(), 400); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::auth::AuthState; + use crate::config::AuthConfig; + + let auth_config = AuthConfig::default() + .with_enabled(true) + .with_username("admin".to_string()) + // A bcrypt hash, for example from `bcrypt::hash(password, bcrypt::DEFAULT_COST)`. + .with_password_hash( + "$2b$12$abcdefghijklmnopqrstuuJ0Y7gZ8z5d0FQqfJb8yX3QZpGQ0lW6e".to_string(), + ); + + let auth_state = AuthState::new(auth_config); + assert!(auth_state.is_enabled()); + } + + #[test] + fn example_2() { + use crate::auth::extract_basic_auth; + + // "admin:password" in base64 is "YWRtaW46cGFzc3dvcmQ=" + let auth_header = "Basic YWRtaW46cGFzc3dvcmQ="; + let (username, password) = extract_basic_auth(auth_header).unwrap(); + + assert_eq!(username, "admin"); + assert_eq!(password, "password"); + + // Invalid format returns None + let result = extract_basic_auth("Bearer token123"); + assert!(result.is_none()); + } + + #[test] + fn example_3() { + use crate::auth::extract_basic_auth; + + // Valid basic auth header + let auth_header = "Basic YWRtaW46cGFzc3dvcmQ="; // admin:password + let (username, password) = extract_basic_auth(auth_header).unwrap(); + assert_eq!(username, "admin"); + assert_eq!(password, "password"); + + // Invalid format returns None + assert!(extract_basic_auth("Bearer token123").is_none()); + assert!(extract_basic_auth("Basic invalid_base64").is_none()); + } +} diff --git a/hammerwork-web/src/config.rs b/hammerwork-web/src/config.rs index 320c6dd..acc32d1 100644 --- a/hammerwork-web/src/config.rs +++ b/hammerwork-web/src/config.rs @@ -2,64 +2,6 @@ //! //! This module provides comprehensive configuration options for the web dashboard, //! including server settings, authentication, WebSocket configuration, and more. -//! -//! # Examples -//! -//! ## Basic Configuration -//! -//! ```rust -//! use hammerwork_web::__private::config::DashboardConfig; -//! -//! let config = DashboardConfig::new() -//! .with_bind_address("127.0.0.1", 8080) -//! .with_database_url("postgresql://localhost/hammerwork"); -//! -//! assert_eq!(config.bind_addr(), "127.0.0.1:8080"); -//! ``` -//! -//! ## Configuration with Authentication -//! -//! ```rust -//! use hammerwork_web::__private::config::{DashboardConfig, AuthConfig}; -//! use std::time::Duration; -//! -//! let config = DashboardConfig::new() -//! .with_auth("admin", "$2b$12$hash...") -//! .with_cors(true); -//! -//! assert!(config.auth.enabled); -//! assert_eq!(config.auth.username, "admin"); -//! assert!(config.enable_cors); -//! ``` -//! -//! ## Loading from File -//! -//! ```rust,no_run -//! use hammerwork_web::__private::config::DashboardConfig; -//! -//! // Create a configuration file (dashboard.toml) -//! let config_content = r#" -//! bind_address = "0.0.0.0" -//! port = 9090 -//! database_url = "postgresql://localhost/hammerwork" -//! enable_cors = true -//! -//! [auth] -//! enabled = true -//! username = "admin" -//! "#; -//! -//! std::fs::write("dashboard.toml", config_content)?; -//! -//! // Load the configuration -//! let config = DashboardConfig::from_file("dashboard.toml")?; -//! assert_eq!(config.port, 9090); -//! assert!(config.enable_cors); -//! -//! // Clean up -//! std::fs::remove_file("dashboard.toml")?; -//! # Ok::<(), Box>(()) -//! ``` use serde::{Deserialize, Serialize}; use std::path::PathBuf; @@ -70,26 +12,6 @@ use std::time::Duration; /// This struct contains all configuration options for the Hammerwork web dashboard, /// including server settings, database connection, authentication, and WebSocket options. /// -/// # Examples -/// -/// ```rust -/// use hammerwork_web::__private::config::DashboardConfig; -/// use std::path::PathBuf; -/// -/// // Create with defaults -/// let config = DashboardConfig::default(); -/// assert_eq!(config.bind_address, "127.0.0.1"); -/// assert_eq!(config.port, 8080); -/// -/// // Use builder pattern -/// let config = DashboardConfig::new() -/// .with_bind_address("0.0.0.0", 9090) -/// .with_database_url("postgresql://localhost/hammerwork") -/// .with_cors(true); -/// -/// assert_eq!(config.bind_addr(), "0.0.0.0:9090"); -/// assert!(config.enable_cors); -/// ``` /// /// `Debug` shows `database_url` with its password replaced by `***`. #[derive(Clone, Serialize, Deserialize)] @@ -149,34 +71,12 @@ impl Default for DashboardConfig { impl DashboardConfig { /// Create a new configuration with defaults. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// - /// let config = DashboardConfig::new(); - /// assert_eq!(config.bind_address, "127.0.0.1"); - /// assert_eq!(config.port, 8080); - /// assert_eq!(config.database_url, "postgresql://localhost/hammerwork"); - /// ``` pub fn new() -> Self { Self::default() } /// Set the server bind address and port. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// - /// let config = DashboardConfig::new() - /// .with_bind_address("0.0.0.0", 9090); - /// - /// assert_eq!(config.bind_address, "0.0.0.0"); - /// assert_eq!(config.port, 9090); - /// assert_eq!(config.bind_addr(), "0.0.0.0:9090"); - /// ``` pub fn with_bind_address(mut self, address: &str, port: u16) -> Self { self.bind_address = address.to_string(); self.port = port; @@ -187,21 +87,6 @@ impl DashboardConfig { /// /// Supports both PostgreSQL and MySQL database URLs. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// - /// // PostgreSQL - /// let pg_config = DashboardConfig::new() - /// .with_database_url("postgresql://user:pass@localhost/hammerwork"); - /// assert_eq!(pg_config.database_url, "postgresql://user:pass@localhost/hammerwork"); - /// - /// // MySQL - /// let mysql_config = DashboardConfig::new() - /// .with_database_url("mysql://root:password@localhost/hammerwork"); - /// assert_eq!(mysql_config.database_url, "mysql://root:password@localhost/hammerwork"); - /// ``` pub fn with_database_url(mut self, url: &str) -> Self { self.database_url = url.to_string(); self @@ -209,17 +94,6 @@ impl DashboardConfig { /// Set the static assets directory. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// use std::path::PathBuf; - /// - /// let config = DashboardConfig::new() - /// .with_static_dir(PathBuf::from("/var/www/dashboard")); - /// - /// assert_eq!(config.static_dir, PathBuf::from("/var/www/dashboard")); - /// ``` pub fn with_static_dir(mut self, dir: PathBuf) -> Self { self.static_dir = dir; self @@ -230,18 +104,6 @@ impl DashboardConfig { /// The password should be a bcrypt hash for security. When authentication is enabled, /// all API endpoints and WebSocket connections will require basic authentication. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// - /// let config = DashboardConfig::new() - /// .with_auth("admin", "$2b$12$hash..."); - /// - /// assert!(config.auth.enabled); - /// assert_eq!(config.auth.username, "admin"); - /// assert_eq!(config.auth.password_hash, "$2b$12$hash..."); - /// ``` pub fn with_auth(mut self, username: &str, password_hash: &str) -> Self { self.auth.enabled = true; self.auth.username = username.to_string(); @@ -254,23 +116,6 @@ impl DashboardConfig { /// When enabled, browsers on the origins in [`allowed_origins`](Self::allowed_origins) /// may call the API; [`validate`](Self::validate) requires at least one of them. /// - /// # Examples - /// - /// ```rust - /// use hammerwork_web::__private::config::DashboardConfig; - /// - /// let config = DashboardConfig::new() - /// .with_cors(true) - /// .with_allowed_origin("https://ops.example.com"); - /// - /// assert!(config.enable_cors); - /// assert_eq!(config.allowed_origins, ["https://ops.example.com"]); - /// - /// let config = DashboardConfig::new() - /// .with_cors(false); - /// - /// assert!(!config.enable_cors); - /// ``` pub fn with_cors(mut self, enabled: bool) -> Self { self.enable_cors = enabled; self @@ -352,30 +197,6 @@ impl DashboardConfig { /// Controls authentication behavior including credentials, session management, /// and security policies like rate limiting and account lockout. /// -/// # Examples -/// -/// ```rust -/// use hammerwork_web::__private::config::AuthConfig; -/// use std::time::Duration; -/// -/// // Default configuration (authentication enabled) -/// let auth_config = AuthConfig::default(); -/// assert!(auth_config.enabled); -/// assert_eq!(auth_config.username, "admin"); -/// assert_eq!(auth_config.max_failed_attempts, 5); -/// -/// // Custom configuration -/// let auth_config = AuthConfig::default() -/// .with_enabled(true) -/// .with_username("dashboard_admin".to_string()) -/// .with_password_hash("$2b$12$hash...".to_string()) -/// .with_session_timeout(Duration::from_secs(4 * 60 * 60)) // 4 hours -/// .with_max_failed_attempts(3) -/// .with_lockout_duration(Duration::from_secs(30 * 60)); // 30 minutes -/// -/// assert_eq!(auth_config.username, "dashboard_admin"); -/// assert_eq!(auth_config.max_failed_attempts, 3); -/// ``` /// /// `Debug` never shows `password_hash`. #[derive(Clone, Serialize, Deserialize)] @@ -392,7 +213,7 @@ pub struct AuthConfig { pub password_hash: String, /// Upper bound on how long a successful credential check is remembered (at most - /// [`crate::auth::VERIFIED_CREDENTIALS_TTL`]); zero re-verifies every request. + /// 60 seconds, the `VERIFIED_CREDENTIALS_TTL` of the auth module); zero re-verifies every request. #[serde(with = "hammerwork::config::serde_duration")] pub session_timeout: Duration, @@ -848,3 +669,154 @@ mod tests { assert_eq!(config.allowed_origins, ["https://ops.example.com"]); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new() + .with_bind_address("127.0.0.1", 8080) + .with_database_url("postgresql://localhost/hammerwork"); + + assert_eq!(config.bind_addr(), "127.0.0.1:8080"); + } + + #[test] + fn example_2() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new() + .with_auth("admin", "$2b$12$hash...") + .with_cors(true); + + assert!(config.auth.enabled); + assert_eq!(config.auth.username, "admin"); + assert!(config.enable_cors); + } + + #[test] + fn example_3() { + use crate::config::DashboardConfig; + + // Create with defaults + let config = DashboardConfig::default(); + assert_eq!(config.bind_address, "127.0.0.1"); + assert_eq!(config.port, 8080); + + // Use builder pattern + let config = DashboardConfig::new() + .with_bind_address("0.0.0.0", 9090) + .with_database_url("postgresql://localhost/hammerwork") + .with_cors(true); + + assert_eq!(config.bind_addr(), "0.0.0.0:9090"); + assert!(config.enable_cors); + } + + #[test] + fn example_4() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new(); + assert_eq!(config.bind_address, "127.0.0.1"); + assert_eq!(config.port, 8080); + assert_eq!(config.database_url, "postgresql://localhost/hammerwork"); + } + + #[test] + fn example_5() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new().with_bind_address("0.0.0.0", 9090); + + assert_eq!(config.bind_address, "0.0.0.0"); + assert_eq!(config.port, 9090); + assert_eq!(config.bind_addr(), "0.0.0.0:9090"); + } + + #[test] + fn example_6() { + use crate::config::DashboardConfig; + + // PostgreSQL + let pg_config = + DashboardConfig::new().with_database_url("postgresql://user:pass@localhost/hammerwork"); + assert_eq!( + pg_config.database_url, + "postgresql://user:pass@localhost/hammerwork" + ); + + // MySQL + let mysql_config = + DashboardConfig::new().with_database_url("mysql://root:password@localhost/hammerwork"); + assert_eq!( + mysql_config.database_url, + "mysql://root:password@localhost/hammerwork" + ); + } + + #[test] + fn example_7() { + use crate::config::DashboardConfig; + use std::path::PathBuf; + + let config = DashboardConfig::new().with_static_dir(PathBuf::from("/var/www/dashboard")); + + assert_eq!(config.static_dir, PathBuf::from("/var/www/dashboard")); + } + + #[test] + fn example_8() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new().with_auth("admin", "$2b$12$hash..."); + + assert!(config.auth.enabled); + assert_eq!(config.auth.username, "admin"); + assert_eq!(config.auth.password_hash, "$2b$12$hash..."); + } + + #[test] + fn example_9() { + use crate::config::DashboardConfig; + + let config = DashboardConfig::new() + .with_cors(true) + .with_allowed_origin("https://ops.example.com"); + + assert!(config.enable_cors); + assert_eq!(config.allowed_origins, ["https://ops.example.com"]); + + let config = DashboardConfig::new().with_cors(false); + + assert!(!config.enable_cors); + } + + #[test] + fn example_10() { + use crate::config::AuthConfig; + use std::time::Duration; + + // Default configuration (authentication enabled) + let auth_config = AuthConfig::default(); + assert!(auth_config.enabled); + assert_eq!(auth_config.username, "admin"); + assert_eq!(auth_config.max_failed_attempts, 5); + + // Custom configuration + let auth_config = AuthConfig::default() + .with_enabled(true) + .with_username("dashboard_admin".to_string()) + .with_password_hash("$2b$12$hash...".to_string()) + .with_session_timeout(Duration::from_secs(4 * 60 * 60)) // 4 hours + .with_max_failed_attempts(3) + .with_lockout_duration(Duration::from_secs(30 * 60)); // 30 minutes + + assert_eq!(auth_config.username, "dashboard_admin"); + assert_eq!(auth_config.max_failed_attempts, 3); + } +} diff --git a/hammerwork-web/src/lib.rs b/hammerwork-web/src/lib.rs index 2638af8..4a510fb 100644 --- a/hammerwork-web/src/lib.rs +++ b/hammerwork-web/src/lib.rs @@ -98,45 +98,20 @@ compile_error!( ); mod api; +#[cfg(test)] +mod api_tests; mod auth; mod config; mod live; mod security; mod server; mod websocket; +#[cfg(test)] +mod websocket_archive_tests; pub use config::{AuthConfig, DashboardConfig, WebSocketConfig}; pub use server::WebDashboard; -/// Internals re-exported for this crate's own integration tests and doc examples. -/// -/// Not part of the public API: it is hidden from the documentation and may change in any -/// release, including patch releases. -#[doc(hidden)] -pub mod __private { - pub mod api { - pub use crate::api::*; - } - pub mod auth { - pub use crate::auth::*; - } - pub mod config { - pub use crate::config::*; - } - pub mod live { - pub use crate::live::*; - } - pub mod security { - pub use crate::security::*; - } - pub mod server { - pub use crate::server::*; - } - pub mod websocket { - pub use crate::websocket::*; - } -} - /// Result type alias for consistent error handling pub type Result = std::result::Result; diff --git a/hammerwork-web/src/security.rs b/hammerwork-web/src/security.rs index 77f045b..0929369 100644 --- a/hammerwork-web/src/security.rs +++ b/hammerwork-web/src/security.rs @@ -13,20 +13,6 @@ //! - [`json_body`] only accepts bodies sent as `Content-Type: application/json`, which a page //! on another origin cannot send without a CORS preflight, and at most //! [`MAX_JSON_BODY_BYTES`] of them. -//! -//! ```rust -//! use hammerwork_web::__private::security::{AllowedOrigins, normalize_origin}; -//! -//! assert_eq!( -//! normalize_origin("https://Ops.Example.com/").as_deref(), -//! Some("https://ops.example.com") -//! ); -//! assert!(normalize_origin("https://ops.example.com/path").is_none()); -//! -//! let allowed = AllowedOrigins::new(["https://ops.example.com"]).unwrap(); -//! assert!(allowed.contains("https://ops.example.com")); -//! assert!(!allowed.contains("https://evil.example")); -//! ``` use serde::de::DeserializeOwned; use std::sync::Arc; @@ -477,3 +463,23 @@ mod tests { assert_eq!(get.status(), 403, "same_origin checks every method"); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::security::{AllowedOrigins, normalize_origin}; + + assert_eq!( + normalize_origin("https://Ops.Example.com/").as_deref(), + Some("https://ops.example.com") + ); + assert!(normalize_origin("https://ops.example.com/path").is_none()); + + let allowed = AllowedOrigins::new(["https://ops.example.com"]).unwrap(); + assert!(allowed.contains("https://ops.example.com")); + assert!(!allowed.contains("https://evil.example")); + } +} diff --git a/hammerwork-web/src/websocket.rs b/hammerwork-web/src/websocket.rs index 7c17b7a..83d39f5 100644 --- a/hammerwork-web/src/websocket.rs +++ b/hammerwork-web/src/websocket.rs @@ -8,37 +8,6 @@ //! //! The WebSocket API supports several message types for different events: //! -//! ```rust -//! use hammerwork_web::__private::websocket::{ClientMessage, ServerMessage, AlertSeverity}; -//! use serde_json::json; -//! -//! // Client messages (sent from browser to server) -//! let subscribe_msg = ClientMessage::Subscribe { -//! event_types: vec!["queue_updates".to_string(), "job_updates".to_string()], -//! }; -//! -//! let ping_msg = ClientMessage::Ping; -//! -//! // Server messages (sent from server to browser) -//! let alert_msg = ServerMessage::SystemAlert { -//! message: "High error rate detected".to_string(), -//! severity: AlertSeverity::Warning, -//! }; -//! -//! let pong_msg = ServerMessage::Pong; -//! ``` -//! -//! # Connection Management -//! -//! ```rust -//! use hammerwork_web::__private::websocket::WebSocketState; -//! use hammerwork_web::__private::config::WebSocketConfig; -//! -//! let config = WebSocketConfig::default(); -//! let ws_state = WebSocketState::new(config); -//! -//! assert_eq!(ws_state.connection_count(), 0); -//! ``` use crate::config::WebSocketConfig; use chrono::{DateTime, Utc}; @@ -111,6 +80,7 @@ pub struct WebSocketState { config: WebSocketConfig, connections: HashMap>, subscriptions: HashMap, + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests broadcast_sender: mpsc::UnboundedSender, broadcast_receiver: Option>, } @@ -308,6 +278,7 @@ impl WebSocketState { Ok(()) } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Broadcast a message to all connected clients pub async fn broadcast_to_all(&self, message: ServerMessage) -> crate::Result<()> { let json_message = serde_json::to_string(&message)?; @@ -344,6 +315,7 @@ impl WebSocketState { Ok(()) } + #[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Publish an archive event to all connected clients pub async fn publish_archive_event( &self, @@ -585,6 +557,7 @@ pub enum ServerMessage { Pong, } +#[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Internal broadcast messages #[derive(Debug)] pub enum BroadcastMessage { @@ -653,6 +626,7 @@ pub struct JobUpdate { pub updated_at: chrono::DateTime, } +#[allow(dead_code)] // not reached from the running dashboard; exercised by tests /// Alert severity levels #[derive(Debug, Serialize)] pub enum AlertSeverity { @@ -1270,3 +1244,39 @@ mod tests { assert!(serde_json::from_str::(r#"{"type": "Subscribe"}"#).is_err()); } } + +/// Examples that used to be doctests (moved in-crate when `hammerwork_web::__private` was removed). +#[cfg(test)] +mod doc_examples { + + #[test] + fn example_1() { + use crate::websocket::{AlertSeverity, ClientMessage, ServerMessage}; + + // Client messages (sent from browser to server) + let _subscribe_msg = ClientMessage::Subscribe { + event_types: vec!["queue_updates".to_string(), "job_updates".to_string()], + }; + + let _ping_msg = ClientMessage::Ping; + + // Server messages (sent from server to browser) + let _alert_msg = ServerMessage::SystemAlert { + message: "High error rate detected".to_string(), + severity: AlertSeverity::Warning, + }; + + let _pong_msg = ServerMessage::Pong; + } + + #[test] + fn example_2() { + use crate::config::WebSocketConfig; + use crate::websocket::WebSocketState; + + let config = WebSocketConfig::default(); + let ws_state = WebSocketState::new(config); + + assert_eq!(ws_state.connection_count(), 0); + } +} diff --git a/hammerwork-web/src/websocket_archive_tests.rs b/hammerwork-web/src/websocket_archive_tests.rs new file mode 100644 index 0000000..6c74322 --- /dev/null +++ b/hammerwork-web/src/websocket_archive_tests.rs @@ -0,0 +1,191 @@ +//! WebSocket archive-event broadcast tests. + +use crate::config::WebSocketConfig; +use crate::websocket::{BroadcastMessage, WebSocketState}; +use chrono::Utc; +use hammerwork::archive::{ArchivalReason, ArchivalStats, ArchiveEvent}; +use std::time::Duration; +use uuid::Uuid; + +#[tokio::test] +async fn test_websocket_publish_archive_event() { + let config = WebSocketConfig::default(); + let ws_state = WebSocketState::new(config); + + // Test each type of archive event + let test_events = vec![ + ArchiveEvent::JobArchived { + job_id: Uuid::new_v4(), + queue: "test_queue".to_string(), + reason: ArchivalReason::Manual, + }, + ArchiveEvent::JobRestored { + job_id: Uuid::new_v4(), + queue: "restore_queue".to_string(), + restored_by: Some("admin".to_string()), + }, + ArchiveEvent::BulkArchiveStarted { + operation_id: "test_op_123".to_string(), + estimated_jobs: 1000, + }, + ArchiveEvent::BulkArchiveProgress { + operation_id: "test_op_123".to_string(), + jobs_processed: 500, + total: 1000, + }, + ArchiveEvent::BulkArchiveCompleted { + operation_id: "test_op_123".to_string(), + stats: { + let mut value = ArchivalStats::default(); + value.jobs_archived = 1000; + value.jobs_purged = 0; + value.bytes_archived = 50000; + value.bytes_purged = 0; + value.compression_ratio = 0.8; + value.operation_duration = std::time::Duration::from_secs(30); + value.last_run_at = Utc::now(); + value + }, + }, + ArchiveEvent::JobsPurged { + count: 100, + older_than: Utc::now(), + }, + ]; + + // Test that each event can be published without errors + for event in test_events { + let result = ws_state.publish_archive_event(event).await; + assert!(result.is_ok(), "Failed to publish archive event"); + } +} + +#[test] +fn test_websocket_broadcast_message_conversion() { + let job_id = Uuid::new_v4(); + let operation_id = "test_op_456".to_string(); + let queue_name = "test_queue".to_string(); + + // Test JobArchived event conversion + let job_archived = ArchiveEvent::JobArchived { + job_id, + queue: queue_name.clone(), + reason: ArchivalReason::Automatic, + }; + + // Manually convert to verify the logic (similar to what happens in publish_archive_event) + match job_archived { + ArchiveEvent::JobArchived { + job_id, + queue, + reason, + } => { + let broadcast_msg = BroadcastMessage::JobArchived { + job_id: job_id.to_string(), + queue, + reason, + }; + + // Test that the conversion produces valid data + assert!(matches!( + broadcast_msg, + BroadcastMessage::JobArchived { .. } + )); + } + _ => panic!("Expected JobArchived event"), + } + + // Test BulkArchiveStarted event conversion + let bulk_started = ArchiveEvent::BulkArchiveStarted { + operation_id: operation_id.clone(), + estimated_jobs: 500, + }; + + match bulk_started { + ArchiveEvent::BulkArchiveStarted { + operation_id, + estimated_jobs, + } => { + let broadcast_msg = BroadcastMessage::BulkArchiveStarted { + operation_id, + estimated_jobs, + }; + + assert!(matches!( + broadcast_msg, + BroadcastMessage::BulkArchiveStarted { .. } + )); + } + _ => panic!("Expected BulkArchiveStarted event"), + } +} + +#[test] +fn test_websocket_config_defaults() { + let config = WebSocketConfig::default(); + + // Verify default WebSocket configuration supports archive events + assert!(config.max_connections > 0); + assert!(config.ping_interval.as_secs() > 0); + assert!(config.message_buffer_size > 0); + assert!(config.max_message_size > 0); +} + +#[tokio::test] +async fn test_websocket_state_connection_management() { + let config = WebSocketConfig::default() + .with_max_connections(5) + .with_ping_interval(Duration::from_secs(30)) + .with_message_buffer_size(1024) + .with_max_message_size(64 * 1024); + + let ws_state = WebSocketState::new(config); + + // Test initial state + assert_eq!(ws_state.connection_count(), 0); + + // Test that archive events can be published even with no connections + let test_event = ArchiveEvent::JobArchived { + job_id: Uuid::new_v4(), + queue: "test_queue".to_string(), + reason: ArchivalReason::Manual, + }; + + let result = ws_state.publish_archive_event(test_event).await; + assert!( + result.is_ok(), + "Should handle publishing to empty connection list" + ); +} + +#[test] +fn test_archive_event_serialization_for_websocket() { + let events = vec![ + ArchiveEvent::JobArchived { + job_id: Uuid::new_v4(), + queue: "serialize_test".to_string(), + reason: ArchivalReason::Compliance, + }, + ArchiveEvent::BulkArchiveProgress { + operation_id: "progress_op".to_string(), + jobs_processed: 75, + total: 100, + }, + ]; + + // Test that all archive events can be serialized for WebSocket transmission + for event in events { + let serialized = serde_json::to_string(&event); + assert!(serialized.is_ok(), "Archive event should be serializable"); + + let json_value = serialized.unwrap(); + assert!(!json_value.is_empty()); + + // Verify it can be deserialized back + let deserialized: Result = serde_json::from_str(&json_value); + assert!( + deserialized.is_ok(), + "Serialized event should be deserializable" + ); + } +} diff --git a/hammerwork-web/tests/integration_tests.rs b/hammerwork-web/tests/integration_tests.rs index 76fbce2..3a22bb6 100644 --- a/hammerwork-web/tests/integration_tests.rs +++ b/hammerwork-web/tests/integration_tests.rs @@ -209,7 +209,7 @@ mod tests { #[tokio::test] async fn test_websocket_config_validation() { - use hammerwork_web::__private::config::WebSocketConfig; + use hammerwork_web::WebSocketConfig; let ws_config = WebSocketConfig::default() .with_ping_interval(Duration::from_secs(10)) @@ -262,197 +262,3 @@ mod tests { assert_eq!(config_standard.port, 8080); } } - -// WebSocket Archive Event Tests -#[cfg(test)] -mod websocket_archive_tests { - use super::*; - use chrono::Utc; - use hammerwork::archive::{ArchivalReason, ArchivalStats, ArchiveEvent}; - use hammerwork_web::__private::config::WebSocketConfig; - use hammerwork_web::__private::websocket::{BroadcastMessage, WebSocketState}; - use uuid::Uuid; - - #[tokio::test] - async fn test_websocket_publish_archive_event() { - let config = WebSocketConfig::default(); - let ws_state = WebSocketState::new(config); - - // Test each type of archive event - let test_events = vec![ - ArchiveEvent::JobArchived { - job_id: Uuid::new_v4(), - queue: "test_queue".to_string(), - reason: ArchivalReason::Manual, - }, - ArchiveEvent::JobRestored { - job_id: Uuid::new_v4(), - queue: "restore_queue".to_string(), - restored_by: Some("admin".to_string()), - }, - ArchiveEvent::BulkArchiveStarted { - operation_id: "test_op_123".to_string(), - estimated_jobs: 1000, - }, - ArchiveEvent::BulkArchiveProgress { - operation_id: "test_op_123".to_string(), - jobs_processed: 500, - total: 1000, - }, - ArchiveEvent::BulkArchiveCompleted { - operation_id: "test_op_123".to_string(), - stats: { - let mut value = ArchivalStats::default(); - value.jobs_archived = 1000; - value.jobs_purged = 0; - value.bytes_archived = 50000; - value.bytes_purged = 0; - value.compression_ratio = 0.8; - value.operation_duration = std::time::Duration::from_secs(30); - value.last_run_at = Utc::now(); - value - }, - }, - ArchiveEvent::JobsPurged { - count: 100, - older_than: Utc::now(), - }, - ]; - - // Test that each event can be published without errors - for event in test_events { - let result = ws_state.publish_archive_event(event).await; - assert!(result.is_ok(), "Failed to publish archive event"); - } - } - - #[test] - fn test_websocket_broadcast_message_conversion() { - let job_id = Uuid::new_v4(); - let operation_id = "test_op_456".to_string(); - let queue_name = "test_queue".to_string(); - - // Test JobArchived event conversion - let job_archived = ArchiveEvent::JobArchived { - job_id, - queue: queue_name.clone(), - reason: ArchivalReason::Automatic, - }; - - // Manually convert to verify the logic (similar to what happens in publish_archive_event) - match job_archived { - ArchiveEvent::JobArchived { - job_id, - queue, - reason, - } => { - let broadcast_msg = BroadcastMessage::JobArchived { - job_id: job_id.to_string(), - queue, - reason, - }; - - // Test that the conversion produces valid data - assert!(matches!( - broadcast_msg, - BroadcastMessage::JobArchived { .. } - )); - } - _ => panic!("Expected JobArchived event"), - } - - // Test BulkArchiveStarted event conversion - let bulk_started = ArchiveEvent::BulkArchiveStarted { - operation_id: operation_id.clone(), - estimated_jobs: 500, - }; - - match bulk_started { - ArchiveEvent::BulkArchiveStarted { - operation_id, - estimated_jobs, - } => { - let broadcast_msg = BroadcastMessage::BulkArchiveStarted { - operation_id, - estimated_jobs, - }; - - assert!(matches!( - broadcast_msg, - BroadcastMessage::BulkArchiveStarted { .. } - )); - } - _ => panic!("Expected BulkArchiveStarted event"), - } - } - - #[test] - fn test_websocket_config_defaults() { - let config = WebSocketConfig::default(); - - // Verify default WebSocket configuration supports archive events - assert!(config.max_connections > 0); - assert!(config.ping_interval.as_secs() > 0); - assert!(config.message_buffer_size > 0); - assert!(config.max_message_size > 0); - } - - #[tokio::test] - async fn test_websocket_state_connection_management() { - let config = WebSocketConfig::default() - .with_max_connections(5) - .with_ping_interval(Duration::from_secs(30)) - .with_message_buffer_size(1024) - .with_max_message_size(64 * 1024); - - let ws_state = WebSocketState::new(config); - - // Test initial state - assert_eq!(ws_state.connection_count(), 0); - - // Test that archive events can be published even with no connections - let test_event = ArchiveEvent::JobArchived { - job_id: Uuid::new_v4(), - queue: "test_queue".to_string(), - reason: ArchivalReason::Manual, - }; - - let result = ws_state.publish_archive_event(test_event).await; - assert!( - result.is_ok(), - "Should handle publishing to empty connection list" - ); - } - - #[test] - fn test_archive_event_serialization_for_websocket() { - let events = vec![ - ArchiveEvent::JobArchived { - job_id: Uuid::new_v4(), - queue: "serialize_test".to_string(), - reason: ArchivalReason::Compliance, - }, - ArchiveEvent::BulkArchiveProgress { - operation_id: "progress_op".to_string(), - jobs_processed: 75, - total: 100, - }, - ]; - - // Test that all archive events can be serialized for WebSocket transmission - for event in events { - let serialized = serde_json::to_string(&event); - assert!(serialized.is_ok(), "Archive event should be serializable"); - - let json_value = serialized.unwrap(); - assert!(!json_value.is_empty()); - - // Verify it can be deserialized back - let deserialized: Result = serde_json::from_str(&json_value); - assert!( - deserialized.is_ok(), - "Serialized event should be deserializable" - ); - } - } -} diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs index 01087c1..2a85ef0 100644 --- a/src/migrations/mod.rs +++ b/src/migrations/mod.rs @@ -267,6 +267,18 @@ impl MigrationManager { Ok(()) } + /// The migrations this version of the library registers, in version order, whether or + /// not they were applied. Reads no database state. + pub fn registered_migrations(&self) -> Vec { + let mut migrations: Vec<_> = self + .migrations + .values() + .map(|(migration, _, _)| migration.clone()) + .collect(); + migrations.sort_by_key(|migration| migration.version); + migrations + } + /// Get status of all migrations pub async fn get_migration_status(&self) -> Result> { let executed = self.runner.get_executed_migrations().await?; From e6c50265501051a6b0cd706d3243da91d16b1831 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 20:16:52 -0400 Subject: [PATCH 2/2] feat!: requeue_stale_jobs takes an optional queue name (atomic scoped requeue) The queue filter is part of the same statement as the lease check on PostgreSQL, MySQL and TestQueue, so job requeue-stale --queue never reclaims a job whose worker renews its lease. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- CLAUDE.md | 2 +- cargo-hammerwork/src/commands/job.rs | 56 +++------------------- docs/upgrading-to-3.0.md | 10 ++-- docs/worker-configuration.md | 2 +- src/queue/mod.rs | 9 +++- src/queue/mysql.rs | 19 ++++++-- src/queue/postgres.rs | 18 +++++-- src/queue/test.rs | 72 +++++++++++++++++++++++----- src/worker/pool.rs | 2 +- tests/batch_dequeue_tests.rs | 4 +- tests/undecodable_row_tests.rs | 2 +- tests/worker_robustness_tests.rs | 66 ++++++++++++++++++++----- 13 files changed, 173 insertions(+), 93 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c231764..7cf59ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. - **`WebhookStats::failed_attempts`** and **`WebhookManagerStats::failed_attempts`** ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)) count failed HTTP delivery attempts, retries included, next to `total_attempts` and the per-delivery counters. - **`GET /api/system/metrics` drops `metrics_endpoint`, `custom_metrics_count` and `last_scrape`** ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)). The dashboard serves no `/metrics` route and keeps no metrics registry, so they were always `"/metrics"`, `null` and `null`; only `prometheus_enabled` remains. - **Growing public enums are `#[non_exhaustive]`** ([#86](https://github.com/CodingAnarchy/hammerwork/issues/86)). A `match` on them outside Hammerwork needs a wildcard arm. Affected: the errors `HammerworkError`, `EncryptionError`, `CronError`, `SpawnError` and `PriorityError`; the events `JobLifecycleEventType`, `stats::JobEventType`, `ArchiveEvent`, `AlertType` and `KeyOperation`; and the backend and option choices `StreamBackend`, `SerializationFormat`, `PartitioningStrategy`, `PartitionField`, `AlertTarget`, `SecretSource`, `WebhookAuth`, `HttpMethod`, `KeySource`, `RetentionPolicy`, `EncryptionAlgorithm`, `PayloadEncryptionAlgorithm`, `KeyPurpose`, `ArchivalReason`, `PartialFailureMode`, `ResultStorage`, `PrioritySelectionStrategy`, `RetryStrategy`, `JitterType`, `FailurePolicy`, `JobHandlerType`, `JobTransition` and `JobOutcome`. `JobStatus`, `JobPriority`, `BatchStatus`, `WorkflowStatus`, `DependencyStatus`, `KeyStatus`, `AlertSeverity` and `SmtpTls` stay exhaustive. The CLI refuses to `webhook test` a webhook whose HTTP method or authentication it does not know, and the dashboard shows an unknown job event as status `Unknown` and does not forward unknown archive events. -- **The stale job reaper relies on leases alone** ([#90](https://github.com/CodingAnarchy/hammerwork/issues/90)). `DatabaseQueue::requeue_stale_jobs()` takes no argument: the `older_than` window only reclaimed `Running` jobs that Hammerwork 1.x had claimed without a lease, and that fallback is gone. A `Running` job without a lease of its current run is never reclaimed; every 2.x and 3.x claim writes one. `WorkerPool::with_stale_job_reaper(interval)` loses its `older_than` argument too. **Stop every 1.x worker before upgrading**, and fix the jobs they left `Running` once (`cargo hammerwork maintenance check --fix`, or the SQL in the upgrade guide). +- **The stale job reaper relies on leases alone** ([#90](https://github.com/CodingAnarchy/hammerwork/issues/90)). `DatabaseQueue::requeue_stale_jobs(queue_name: Option<&str>)` loses its `older_than` argument and takes an optional queue name (`None` reclaims every queue; `Some(name)` reclaims that queue only, atomically with the lease check): the `older_than` window only reclaimed `Running` jobs that Hammerwork 1.x had claimed without a lease, and that fallback is gone. A `Running` job without a lease of its current run is never reclaimed; every 2.x and 3.x claim writes one. `WorkerPool::with_stale_job_reaper(interval)` loses its `older_than` argument too. **Stop every 1.x worker before upgrading**, and fix the jobs they left `Running` once (`cargo hammerwork maintenance check --fix`, or the SQL in the upgrade guide). - **CLI: `job requeue-stale --older-than-secs` and `maintenance dead-jobs --stale-hours` are removed** ([#90](https://github.com/CodingAnarchy/hammerwork/issues/90)). Both commands now use the lease rule only: a `Running` job is stale when its lease expired; lease-less jobs (left by 1.x) are left alone. `maintenance check` reports `Running` jobs without a lease, and `check --fix` gives them a lease that has already expired, so the next reaper pass reclaims them. - **`AlertingConfig::email(recipient)` is removed** ([#90](https://github.com/CodingAnarchy/hammerwork/issues/90)), deprecated since 2.0.0 because the target it created could not send. Use `email_via_smtp(recipient, SmtpConfig)`. `AlertTarget::Email::smtp` is now a required `SmtpConfig` (was `Option`), so a configuration file with an email target without an `smtp` table fails to load with a missing-field error instead of a "no SMTP settings" validation error. - **`JobArchiver` holds no pool** ([#90](https://github.com/CodingAnarchy/hammerwork/issues/90)). `JobArchiver::new()` takes no argument and `JobArchiver` is no longer generic over the database (`JobArchiver` is now `JobArchiver`); the pool it took was never used, since every operation takes the queue it works on. `JobArchiver` now implements `Default`. @@ -54,7 +54,7 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. ### Added -- **`job requeue-stale --queue ` and `--dry-run`**. `--queue` reclaims only that queue's stale jobs (the unscoped command still uses the library's single atomic reclaim); `--dry-run` counts the jobs the lease rule would reclaim without changing anything. Both use bound parameters on PostgreSQL and MySQL. +- **`job requeue-stale --queue ` and `--dry-run`**. `--queue` reclaims only that queue's stale jobs through `requeue_stale_jobs(Some(queue))`; `--dry-run` counts the jobs the lease rule would reclaim without changing anything. Both use bound parameters on PostgreSQL and MySQL. - **`migration status` lists applied and pending migrations**, from `hammerwork_migrations` against the migrations the library registers, plus applied migrations this version does not know (it used to list the columns of `hammerwork_jobs`; the column count remains as a summary). New `MigrationManager::registered_migrations()` returns the registered migrations without touching the database. ### Fixed diff --git a/CLAUDE.md b/CLAUDE.md index 8120d08..1da5f7c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -90,7 +90,7 @@ The codebase follows a modular architecture with clear separation of concerns: - Supports delayed execution, configurable retry attempts, and priority levels 2. **Queue (`src/queue/`)** - - `mod.rs`: the sealed `DatabaseQueue` trait (the interface for database operations; only Hammerwork implements it) and the generic `JobQueue` wrapping a connection pool. Jobs are claimed with `dequeue(queue, &DequeueOptions)` (batch size, priority weights, lease) or the one-job shortcut `dequeue_one(queue)`; a `Running` job holds a lease that heartbeats renew, and `requeue_stale_jobs()` reclaims jobs whose lease expired + - `mod.rs`: the sealed `DatabaseQueue` trait (the interface for database operations; only Hammerwork implements it) and the generic `JobQueue` wrapping a connection pool. Jobs are claimed with `dequeue(queue, &DequeueOptions)` (batch size, priority weights, lease) or the one-job shortcut `dequeue_one(queue)`; a `Running` job holds a lease that heartbeats renew, and `requeue_stale_jobs(queue_name: Option<&str>)` reclaims jobs whose lease expired (one queue or all) - `postgres.rs` / `mysql.rs`: the dialect-specific implementations (SQL, row types, locking) - `backend.rs`: helpers shared by both backends (transactions and conflict retries, column encoding, cron and dequeue helpers) - `row.rs`: dialect-independent row decoding (column lists, status, result config and encryption columns) diff --git a/cargo-hammerwork/src/commands/job.rs b/cargo-hammerwork/src/commands/job.rs index 4cf1c36..c7d6e7a 100644 --- a/cargo-hammerwork/src/commands/job.rs +++ b/cargo-hammerwork/src/commands/job.rs @@ -759,21 +759,12 @@ async fn requeue_stale_jobs(pool: DatabasePool, queue: Option<&str>, dry_run: bo return Ok(()); } - let recovery = match queue { - // Unscoped: the library's atomic reclaim. - None => with_queue!(pool.create_job_queue(), |queue| { - queue.requeue_stale_jobs().await? - }), - // Scoped: the library reclaims every queue at once, so find this queue's stale jobs - // and send each through the guarded transitions with the library's own outcome - // (Pending while attempts remain, Dead otherwise). - Some(name) => { - let ids = select_job_ids(&pool, &stale_selector(Some(name))).await?; - with_queue!(pool.create_job_queue(), |q| { - reclaim_stale_in_queue(&q, &ids).await? - }) - } - }; + // One atomic reclaim in the library, scoped to the queue when given: the queue filter + // sits in the same statement as the lease check, so a job whose worker renews its + // lease meanwhile is never touched. + let recovery = with_queue!(pool.create_job_queue(), |q| { + q.requeue_stale_jobs(queue).await? + }); for id in &recovery.requeued { info!("ā†©ļø Requeued stale job {}", id); @@ -791,41 +782,6 @@ async fn requeue_stale_jobs(pool: DatabasePool, queue: Option<&str>, dry_run: bo Ok(()) } -/// Reclaim the given stale `Running` jobs one by one: a job with attempts left goes back to -/// `Pending`, an exhausted one is marked `Dead`, as `requeue_stale_jobs` does. A job that -/// is no longer `Running` (finished or reclaimed meanwhile) is skipped. -async fn reclaim_stale_in_queue( - queue: &Q, - ids: &[hammerwork::JobId], -) -> Result { - let mut recovery = hammerwork::queue::StaleJobRecovery::default(); - for &id in ids { - let Some(job) = queue.get_job(id).await? else { - continue; - }; - if job.status != JobStatus::Running { - continue; - } - let outcome = if job.attempts >= job.max_attempts { - queue - .mark_job_dead(id, hammerwork::queue::STALE_JOB_ERROR_MESSAGE) - .await - .map(|()| true) - } else { - queue - .retry_job(id, chrono::Utc::now()) - .await - .map(|()| false) - }; - match outcome { - Ok(true) => recovery.dead.push(id), - Ok(false) => recovery.requeued.push(id), - Err(e) => tracing::warn!("Skipped stale job {}: {}", id, e), - } - } - Ok(recovery) -} - async fn retry_jobs( pool: DatabasePool, job_id: Option, diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.md index 5285ae1..2cc3348 100644 --- a/docs/upgrading-to-3.0.md +++ b/docs/upgrading-to-3.0.md @@ -700,7 +700,10 @@ them by hand; `cargo hammerwork maintenance check` reports how many there are. ### Stale job API `DatabaseQueue::requeue_stale_jobs` and `WorkerPool::with_stale_job_reaper` lose their -`older_than` argument, which only applied to lease-less jobs: +`older_than` argument, which only applied to lease-less jobs. `requeue_stale_jobs` takes +an optional queue name instead: `None` reclaims every queue, as before, and +`Some("emails")` reclaims that queue only, inside the same atomic statement as the lease +check: ```rust,no_run # async fn example(queue: std::sync::Arc>) -> hammerwork::Result<()> { @@ -712,10 +715,11 @@ use std::time::Duration; // let pool = WorkerPool::new().with_stale_job_reaper(Duration::from_secs(30), Duration::from_secs(600)); // After (3.0): -let recovery = queue.requeue_stale_jobs().await?; +let recovery = queue.requeue_stale_jobs(None).await?; +let emails_only = queue.requeue_stale_jobs(Some("emails")).await?; let pool: WorkerPool = WorkerPool::new().with_stale_job_reaper(Duration::from_secs(30)); -# let _ = (recovery, pool); +# let _ = (recovery, emails_only, pool); # Ok(()) # } ``` diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index b3cb3ba..0b16057 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -384,7 +384,7 @@ Hammerwork recovers these jobs with leases (requires migration `015_add_job_leas - 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()` reclaims `Running` jobs whose lease has +- `DatabaseQueue::requeue_stale_jobs(None)` reclaims (`Some(queue)` limits it to one queue) `Running` jobs whose lease has expired. A job whose lease is valid is never reclaimed, so pools with different lease durations (or `cargo hammerwork job requeue-stale`) can share a database safely. A `Running` job without a lease is never reclaimed: only Hammerwork 1.x claimed jobs diff --git a/src/queue/mod.rs b/src/queue/mod.rs index 0c5a2a7..b3a7670 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -1017,6 +1017,11 @@ pub trait DatabaseQueue: private::Sealed + Send + Sync { /// the others go back to `Pending` and are scheduled immediately. The interrupted /// run already counted as an attempt when the job was dequeued. /// + /// With `queue_name` set, only the stale jobs of that queue are reclaimed; the + /// queue filter is part of the same atomic statement (or transaction) as the lease + /// check, so a job whose worker renews its lease meanwhile is never touched. `None` + /// reclaims every queue. + /// /// Safe to call from several pools or 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, and a job whose lease is still valid is @@ -1028,7 +1033,7 @@ pub trait DatabaseQueue: private::Sealed + Send + Sync { /// use hammerwork::queue::DatabaseQueue; /// /// # async fn example(queue: &impl DatabaseQueue) -> hammerwork::Result<()> { - /// let recovery = queue.requeue_stale_jobs().await?; + /// let recovery = queue.requeue_stale_jobs(None).await?; /// println!( /// "requeued {} jobs, marked {} dead", /// recovery.requeued.len(), @@ -1037,7 +1042,7 @@ pub trait DatabaseQueue: private::Sealed + Send + Sync { /// # Ok(()) /// # } /// ``` - async fn requeue_stale_jobs(&self) -> Result; + async fn requeue_stale_jobs(&self, queue_name: Option<&str>) -> Result; /// Enforces the retention policies of encrypted jobs: deletes finished encrypted jobs /// whose retention period has ended. diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index a8d0859..5753409 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -2061,8 +2061,12 @@ impl DatabaseQueue for crate::queue::JobQueue { Ok(true) } - async fn requeue_stale_jobs(&self) -> Result { - let recovery = super::retry_on_conflict(|| self.requeue_stale_jobs_once()).await?; + async fn requeue_stale_jobs( + &self, + queue_name: Option<&str>, + ) -> Result { + let recovery = + super::retry_on_conflict(|| self.requeue_stale_jobs_once(queue_name)).await?; if !recovery.is_empty() { tracing::warn!( @@ -2114,16 +2118,20 @@ impl DatabaseQueue for crate::queue::JobQueue { } impl crate::queue::JobQueue { - async fn requeue_stale_jobs_once(&self) -> Result { + async fn requeue_stale_jobs_once( + &self, + queue_name: Option<&str>, + ) -> Result { let mut conn = self.pool.acquire().await?; // READ COMMITTED, like the dequeue: no gap locks on the Running range. let mut tx = Self::begin_claim_transaction(&mut conn).await?; - let result = Self::requeue_stale_jobs_in_tx(&mut tx).await; + let result = Self::requeue_stale_jobs_in_tx(&mut tx, queue_name).await; super::end_transaction(tx, result).await } async fn requeue_stale_jobs_in_tx( conn: &mut sqlx::MySqlConnection, + queue_name: Option<&str>, ) -> Result { let now = db_now(conn).await?; @@ -2139,11 +2147,14 @@ impl crate::queue::JobQueue { WHERE status = ? AND last_heartbeat_at >= started_at AND lease_expires_at < ? + AND (? IS NULL OR queue_name = ?) FOR UPDATE SKIP LOCKED "# ))) .bind(JobStatus::Running) .bind(now) + .bind(queue_name) + .bind(queue_name) .fetch_all(&mut *conn) .await?; diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index 4931a44..548c6fa 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -1870,8 +1870,12 @@ impl DatabaseQueue for crate::queue::JobQueue { } } - async fn requeue_stale_jobs(&self) -> Result { - let recovery = super::retry_on_conflict(|| self.requeue_stale_jobs_once()).await?; + async fn requeue_stale_jobs( + &self, + queue_name: Option<&str>, + ) -> Result { + let recovery = + super::retry_on_conflict(|| self.requeue_stale_jobs_once(queue_name)).await?; if !recovery.is_empty() { tracing::warn!( @@ -1923,14 +1927,18 @@ impl DatabaseQueue for crate::queue::JobQueue { } impl crate::queue::JobQueue { - async fn requeue_stale_jobs_once(&self) -> Result { + async fn requeue_stale_jobs_once( + &self, + queue_name: Option<&str>, + ) -> Result { let mut tx = self.pool.begin().await?; - let result = Self::requeue_stale_jobs_in_tx(&mut tx).await; + let result = Self::requeue_stale_jobs_in_tx(&mut tx, queue_name).await; super::end_transaction(tx, result).await } async fn requeue_stale_jobs_in_tx( conn: &mut sqlx::PgConnection, + queue_name: Option<&str>, ) -> Result { let now = db_now(conn).await?; @@ -1949,6 +1957,7 @@ impl crate::queue::JobQueue { WHERE status = $1 AND last_heartbeat_at >= started_at AND lease_expires_at < $2 + AND ($6::text IS NULL OR queue_name = $6) FOR UPDATE SKIP LOCKED ) UPDATE hammerwork_jobs AS j @@ -1971,6 +1980,7 @@ impl crate::queue::JobQueue { .bind(JobStatus::Dead) .bind(JobStatus::Pending) .bind(super::STALE_JOB_ERROR_MESSAGE) + .bind(queue_name) .fetch_all(&mut *conn) .await?; diff --git a/src/queue/test.rs b/src/queue/test.rs index 604c93f..5713cc1 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -3052,7 +3052,10 @@ impl DatabaseQueue for TestQueue { Ok(true) } - async fn requeue_stale_jobs(&self) -> Result { + async fn requeue_stale_jobs( + &self, + queue_name: Option<&str>, + ) -> Result { let mut storage = self.storage.write().await; let now = storage.clock.now(); @@ -3060,6 +3063,7 @@ impl DatabaseQueue for TestQueue { .jobs .values() .filter(|job| job.status == JobStatus::Running) + .filter(|job| queue_name.is_none_or(|name| job.queue_name == name)) .filter_map(|job| { let started_at = job.started_at?; // Only a lease of the current run counts; a row without one is left alone. @@ -3182,7 +3186,7 @@ mod tests { assert!(claimed.iter().all(|job| job.attempts == 1)); assert_eq!(queue.get_job_count("batch", &JobStatus::Running).await, 2); // Leased: the reaper leaves them alone. - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.is_empty()); // Paused queues hand out nothing. @@ -3237,7 +3241,7 @@ mod tests { .unwrap(); assert_eq!(short.len(), 1); queue.clock().advance(chrono::Duration::seconds(30)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert_eq!(recovery.requeued, [short[0].id]); assert!(queue.dequeue_one("missing").await.unwrap().is_none()); } @@ -3671,6 +3675,52 @@ mod tests { assert_eq!(stats.statistics.total_processed, 3); // 2 completed + 1 dead } + #[tokio::test] + async fn test_scoped_requeue_stale_jobs_leaves_other_queues_alone() { + let queue = TestQueue::new(); + let clock = queue.clock(); + let lease = std::time::Duration::from_secs(30); + let mut ids = Vec::new(); + for name in ["mine", "other", "mine"] { + let id = queue + .enqueue(Job::new(name.to_string(), json!({}))) + .await + .unwrap(); + queue + .dequeue(name, &DequeueOptions::new().with_lease_duration(lease)) + .await + .unwrap(); + ids.push(id); + } + // The second "mine" job keeps its lease alive. + clock.advance(chrono::Duration::seconds(40)); + let run = queue.get_job(ids[2]).await.unwrap().unwrap(); + queue.storage.write().await.leases.insert( + run.id, + (clock.now(), clock.now() + chrono::Duration::seconds(3600)), + ); + + let recovery = queue.requeue_stale_jobs(Some("mine")).await.unwrap(); + assert_eq!(recovery.requeued, vec![ids[0]]); + assert_eq!( + queue.get_job(ids[1]).await.unwrap().unwrap().status, + JobStatus::Running + ); + assert_eq!( + queue.get_job(ids[2]).await.unwrap().unwrap().status, + JobStatus::Running + ); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); + assert_eq!(recovery.requeued, vec![ids[1]]); + assert!( + queue + .requeue_stale_jobs(Some("nothing")) + .await + .unwrap() + .is_empty() + ); + } + #[tokio::test] async fn test_requeue_stale_jobs_uses_leases_only() { let queue = TestQueue::new(); @@ -3703,18 +3753,18 @@ mod tests { queue.storage.write().await.leases.remove(&unleased); // Nothing is stale yet. - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.is_empty()); // A heartbeat keeps a lease alive. clock.advance(chrono::Duration::seconds(10)); assert!(queue.heartbeat_job(&runs[&leased], lease).await.unwrap()); - assert!(queue.requeue_stale_jobs().await.unwrap().is_empty()); + assert!(queue.requeue_stale_jobs(None).await.unwrap().is_empty()); // Once the leases expire, the leased jobs are reclaimed; the lease-less one is // not, however long ago it started. clock.advance(chrono::Duration::days(30)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert_eq!(recovery.requeued, vec![leased]); assert_eq!(recovery.dead, vec![exhausted]); assert_eq!( @@ -3750,7 +3800,7 @@ mod tests { .unwrap() .unwrap(); clock.advance(chrono::Duration::seconds(60)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert_eq!(recovery.requeued, vec![id]); let second = queue @@ -3767,7 +3817,7 @@ mod tests { // 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().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert_eq!(recovery.requeued, vec![id]); } @@ -3803,7 +3853,7 @@ mod tests { ); // The lease was renewed from the new start. clock.advance(chrono::Duration::seconds(20)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.requeued.is_empty()); // The claim as first dequeued no longer identifies the run. @@ -3834,7 +3884,7 @@ mod tests { .unwrap() .unwrap(); queue.clock().advance(chrono::Duration::days(365)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.is_empty(), "{recovery:?}"); assert!( queue @@ -4405,7 +4455,7 @@ mod tests { assert_eq!(run.id, id); clock.advance(chrono::Duration::minutes(5)); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert_eq!(recovery.dead, vec![id]); let job = queue.get_job(id).await.unwrap().unwrap(); diff --git a/src/worker/pool.rs b/src/worker/pool.rs index f07c5e7..926396e 100644 --- a/src/worker/pool.rs +++ b/src/worker/pool.rs @@ -663,7 +663,7 @@ where ) -> Option> { let interval = self.reaper_interval?; spawn_queue_task(workers, interval, signal_rx, |queue| async move { - match queue.requeue_stale_jobs().await { + match queue.requeue_stale_jobs(None).await { Ok(recovery) if !recovery.is_empty() => info!( "Stale job reaper requeued {} and marked {} dead", recovery.requeued.len(), diff --git a/tests/batch_dequeue_tests.rs b/tests/batch_dequeue_tests.rs index d658211..33981ba 100644 --- a/tests/batch_dequeue_tests.rs +++ b/tests/batch_dequeue_tests.rs @@ -282,7 +282,7 @@ where .unwrap(); assert_eq!(claimed.len(), 3); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); for job in &claimed { assert!( !recovery.requeued.contains(&job.id) && !recovery.dead.contains(&job.id), @@ -642,7 +642,7 @@ mod worker { let deadline = Instant::now() + Duration::from_secs(20); loop { - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); for id in &ids { assert!( !recovery.requeued.contains(id) && !recovery.dead.contains(id), diff --git a/tests/undecodable_row_tests.rs b/tests/undecodable_row_tests.rs index 0f082ed..7cd451b 100644 --- a/tests/undecodable_row_tests.rs +++ b/tests/undecodable_row_tests.rs @@ -200,7 +200,7 @@ where // Another test's reaper may reclaim some of them first; either way they end up // reclaimed and this call succeeds. queue - .requeue_stale_jobs() + .requeue_stale_jobs(None) .await .expect("an undecodable stale row must not fail the reaper"); let counts = queue.get_job_counts_by_status(&name).await.unwrap(); diff --git a/tests/worker_robustness_tests.rs b/tests/worker_robustness_tests.rs index 2e29bcc..c08f146 100644 --- a/tests/worker_robustness_tests.rs +++ b/tests/worker_robustness_tests.rs @@ -487,7 +487,7 @@ where // Reclaim anything earlier tests left behind, so the fix below changes only our row. queue.expire_leaseless_runs().await; - queue.requeue_stale_jobs().await.unwrap(); + queue.requeue_stale_jobs(None).await.unwrap(); let expiring = start_job( &queue, @@ -519,7 +519,7 @@ where tokio::time::sleep(Duration::from_millis(1500)).await; - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.requeued.contains(&expiring.id), "{recovery:?}"); assert!(recovery.dead.contains(&exhausted.id), "{recovery:?}"); for id in [live.id, unleased.id] { @@ -551,7 +551,7 @@ where ); // A row without a lease is never reclaimed, however long ago it started. - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!( !recovery.requeued.contains(&unleased.id) && !recovery.dead.contains(&unleased.id), "{recovery:?}" @@ -564,7 +564,7 @@ where // The upgrade guide's one-off fix gives it an expired lease (and leaves leased // runs alone); the next pass reclaims it. assert!(queue.expire_leaseless_runs().await >= 1); - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.requeued.contains(&unleased.id), "{recovery:?}"); assert!(!recovery.requeued.contains(&live.id), "{recovery:?}"); let job = queue.get_job(unleased.id).await.unwrap().unwrap(); @@ -611,7 +611,7 @@ where tokio::time::sleep(Duration::from_millis(1200)).await; // The reaper leaves valid leases alone and reclaims the expired one. - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); for run in [&long, &default] { assert!( !recovery.requeued.contains(&run.id) && !recovery.dead.contains(&run.id), @@ -658,7 +658,7 @@ where ) .await; tokio::time::sleep(Duration::from_millis(900)).await; - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(recovery.requeued.contains(&first.id), "{recovery:?}"); let second = queue @@ -684,7 +684,7 @@ where tokio::time::sleep(Duration::from_millis(300)).await; } // So the new run's lease expired on schedule. - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!( recovery.requeued.contains(&second.id), "the stale heartbeat extended the new run's lease: {recovery:?}" @@ -698,6 +698,48 @@ where queue.delete_job(first.id).await.unwrap(); } +/// `requeue_stale_jobs(Some(queue))` reclaims that queue's expired leases only; another +/// queue's stale job and a live lease in the same queue are left alone. +async fn scoped_reaper_leaves_other_queues_alone(queue: Arc>) +where + DB: sqlx::Database, + JobQueue: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let short = Duration::from_millis(300); + let mine = test_utils::unique_queue("scoped_mine"); + let other = test_utils::unique_queue("scoped_other"); + let stale_mine = start_job(&queue, Job::new(mine.clone(), json!({})), short).await; + let stale_other = start_job(&queue, Job::new(other.clone(), json!({})), short).await; + let live_mine = start_job( + &queue, + Job::new(mine.clone(), json!({})), + Duration::from_secs(3600), + ) + .await; + tokio::time::sleep(Duration::from_millis(1200)).await; + + let recovery = queue.requeue_stale_jobs(Some(&mine)).await.unwrap(); + assert_eq!(recovery.requeued, vec![stale_mine.id], "{recovery:?}"); + assert!(recovery.dead.is_empty(), "{recovery:?}"); + let status = |id| { + let queue = queue.clone(); + async move { queue.get_job(id).await.unwrap().unwrap().status } + }; + assert_eq!(status(stale_mine.id).await, JobStatus::Pending); + assert_eq!(status(stale_other.id).await, JobStatus::Running); + assert_eq!(status(live_mine.id).await, JobStatus::Running); + + // Unscoped, the other queue's job is reclaimed too. + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); + assert!(recovery.requeued.contains(&stale_other.id), "{recovery:?}"); + assert_eq!(status(stale_other.id).await, JobStatus::Pending); + assert_eq!(status(live_mine.id).await, JobStatus::Running); + for id in [stale_mine.id, stale_other.id, live_mine.id] { + queue.delete_job(id).await.unwrap(); + } +} + /// A zero lease never expires: the reaper never reclaims the job. async fn zero_lease_is_never_reclaimed(queue: Arc>) where @@ -712,13 +754,13 @@ where ) .await; tokio::time::sleep(Duration::from_millis(50)).await; - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).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().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!(!recovery.requeued.contains(&run.id), "{recovery:?}"); assert_eq!( queue.get_job(run.id).await.unwrap().unwrap().status, @@ -813,7 +855,7 @@ where for _ in 0..8 { let queue = Arc::clone(&queue); reapers.push(tokio::spawn(async move { - queue.requeue_stale_jobs().await.unwrap() + queue.requeue_stale_jobs(None).await.unwrap() })); } @@ -870,7 +912,7 @@ where let deadline = Instant::now() + Duration::from_secs(10); loop { - let recovery = queue.requeue_stale_jobs().await.unwrap(); + let recovery = queue.requeue_stale_jobs(None).await.unwrap(); assert!( !recovery.requeued.contains(&id) && !recovery.dead.contains(&id), "a live, heartbeating job was reclaimed" @@ -904,6 +946,7 @@ crate::test_utils::backend_tests!( claim_lease_protects_job_from_short_reaper_window, stale_heartbeat_cannot_extend_new_run, zero_lease_is_never_reclaimed, + scoped_reaper_leaves_other_queues_alone, other_pools_reaper_does_not_rerun_live_job, concurrent_reapers_never_double_requeue, worker_heartbeat_keeps_long_job_leased, @@ -925,6 +968,7 @@ crate::test_utils::backend_tests!( claim_lease_protects_job_from_short_reaper_window, stale_heartbeat_cannot_extend_new_run, zero_lease_is_never_reclaimed, + scoped_reaper_leaves_other_queues_alone, other_pools_reaper_does_not_rerun_live_job, concurrent_reapers_never_double_requeue, worker_heartbeat_keeps_long_job_leased,