From 3b94cce965ed726bfe6114b339094bf681acf952 Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 17:33:49 -0400 Subject: [PATCH 1/2] feat!: mark config, stats and record structs #[non_exhaustive] (#81) Configuration sections, statistics and record types are now Every configuration field users set has a `with_*` setter (generated by a private `with_setters!` macro) or a constructor, and the library's tests, examples, docs, CLI and dashboard use them instead of struct literals. Also from the #81 follow-ups: - `ArchivedJob` gains `workflow_id` and `workflow_name`, filled in by `list_archived_jobs` on PostgreSQL, MySQL and TestQueue (and the dashboard's archive listing), plus a public constructor. - Dropping an `EventSubscription` unregisters it: it keeps a Weak reference to the manager's subscription map, now behind a std RwLock so the drop works without a runtime. Webhook and stream listeners hold their whole subscription. - `WebhookStats`/`WebhookManagerStats` gain a `failed_attempts` counter. - hammerwork-web `MetricsInfo` drops the never-served `metrics_endpoint`, `custom_metrics_count` and `last_scrape`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- cargo-hammerwork/src/commands/archive.rs | 37 +- cargo-hammerwork/src/commands/webhook.rs | 70 ++-- docs/job-spawning.md | 27 +- docs/monitoring.md | 8 +- docs/streaming.md | 13 +- docs/upgrading-to-3.0.md | 142 +++++++- docs/webhooks.md | 10 +- examples/key_management_example.rs | 49 ++- examples/spawn_example.rs | 30 +- hammerwork-web/README.md | 17 +- hammerwork-web/src/api/archive.rs | 29 +- hammerwork-web/src/api/history.rs | 52 +-- hammerwork-web/src/api/stats.rs | 15 +- hammerwork-web/src/api/system.rs | 31 +- hammerwork-web/src/auth.rs | 12 +- hammerwork-web/src/config.rs | 123 ++++++- hammerwork-web/src/lib.rs | 24 +- hammerwork-web/src/live.rs | 20 +- hammerwork-web/src/main.rs | 12 +- hammerwork-web/src/server.rs | 30 +- hammerwork-web/tests/api_tests.rs | 46 +-- hammerwork-web/tests/integration_tests.rs | 134 +++----- src/alerting.rs | 3 + src/archive.rs | 132 +++++-- src/batch.rs | 2 + src/config.rs | 378 +++++++++++++++++++++ src/encryption.rs | 4 + src/encryption/key_manager.rs | 96 +++++- src/events.rs | 297 +++++++++++++--- src/job.rs | 2 + src/lib.rs | 18 +- src/macros.rs | 56 +++ src/metrics.rs | 1 + src/migrations/mod.rs | 20 ++ src/priority.rs | 1 + src/queue/lifecycle.rs | 1 + src/queue/mod.rs | 1 + src/queue/mysql.rs | 7 +- src/queue/postgres.rs | 4 +- src/queue/test.rs | 2 + src/rate_limit.rs | 1 + src/spawn.rs | 98 ++++-- src/stats.rs | 68 +++- src/streaming.rs | 297 +++++++++------- src/tracing.rs | 1 + src/webhooks.rs | 183 ++++++---- src/worker.rs | 2 + src/worker/autoscale.rs | 2 + src/worker/hooks.rs | 2 + src/workflow.rs | 1 + tests/archive_tests.rs | 18 +- tests/archive_workflow_regression_tests.rs | 38 +++ tests/comprehensive_archive_tests.rs | 18 +- tests/encryption_basic_tests.rs | 223 ++---------- tests/job_spawning_tests.rs | 5 +- tests/migration_datetime_tests.rs | 7 +- tests/migration_lock_tests.rs | 12 +- tests/priority_tests.rs | 48 ++- tests/result_config_test.rs | 16 +- tests/result_storage_tests.rs | 8 +- tests/worker_batch_tests.rs | 20 +- tests/worker_config_tests.rs | 12 +- tests/worker_pool_archival_tests.rs | 29 +- 64 files changed, 2064 insertions(+), 1008 deletions(-) create mode 100644 src/macros.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5beb4a2..6f0bd5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,9 +28,14 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. - **`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`; code that builds `WorkerConfig` with a struct literal must add them (or use `..Default::default()`). +- **`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. 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`, `SimpleEventFilter`, `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. +- **`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. ### Fixed diff --git a/cargo-hammerwork/src/commands/archive.rs b/cargo-hammerwork/src/commands/archive.rs index 99c41f3..3867819 100644 --- a/cargo-hammerwork/src/commands/archive.rs +++ b/cargo-hammerwork/src/commands/archive.rs @@ -889,17 +889,18 @@ mod tests { let at = chrono::DateTime::parse_from_rfc3339("2030-01-02T03:04:05Z") .unwrap() .with_timezone(&chrono::Utc); - ArchivedJob { - id: uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(), - queue_name: queue.to_string(), - status: JobStatus::Completed, - created_at: at, - archived_at: at, - archival_reason: ArchivalReason::Manual, - original_payload_size: Some(10), - payload_compressed: true, - archived_by: by.map(String::from), - } + let mut job = ArchivedJob::new( + uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(), + queue, + JobStatus::Completed, + at, + at, + ArchivalReason::Manual, + ) + .with_original_payload_size(10) + .with_payload_compressed(true); + job.archived_by = by.map(String::from); + job } #[test] @@ -943,14 +944,12 @@ mod tests { #[test] fn stats_render_as_table_or_json() { - let stats = ArchivalStats { - jobs_archived: 7, - jobs_purged: 2, - bytes_archived: 1234, - bytes_purged: 56, - compression_ratio: 2.5, - ..ArchivalStats::default() - }; + let mut stats = ArchivalStats::default(); + stats.jobs_archived = 7; + stats.jobs_purged = 2; + stats.bytes_archived = 1234; + stats.bytes_purged = 56; + stats.compression_ratio = 2.5; let table = render_archival_stats(&stats, Some("emails"), "table").unwrap(); for expected in [ "Queue: emails", diff --git a/cargo-hammerwork/src/commands/webhook.rs b/cargo-hammerwork/src/commands/webhook.rs index 82599b4..bde2e9a 100644 --- a/cargo-hammerwork/src/commands/webhook.rs +++ b/cargo-hammerwork/src/commands/webhook.rs @@ -398,26 +398,18 @@ fn build_test_event( let mut metadata = HashMap::new(); metadata.insert("test".to_string(), "true".to_string()); - Ok(JobLifecycleEvent { - event_id: Uuid::new_v4(), - job_id, - queue_name: queue.to_string(), - event_type, - priority: JobPriority::Normal, - timestamp: chrono::Utc::now(), - processing_time_ms: is_completed.then_some(123), - error: is_error.then(|| JobError { - message: "Test error from `cargo hammerwork webhook test`".to_string(), - error_type: Some("test".to_string()), - details: None, - retry_attempt: None, - }), - payload: webhook - .filter - .include_payload - .then(|| json!({"test": true})), - metadata, - }) + let mut event = JobLifecycleEvent::new(job_id, queue, event_type, JobPriority::Normal); + event.processing_time_ms = is_completed.then_some(123); + event.error = is_error.then(|| { + JobError::new("Test error from `cargo hammerwork webhook test`") + .with_error_type("test".to_string()) + }); + event.payload = webhook + .filter + .include_payload + .then(|| json!({"test": true})); + event.metadata = metadata; + Ok(event) } /// Sends `event` to the webhook the way the library's delivery does: configured @@ -666,29 +658,23 @@ fn create_webhook_config( } filter.include_payload = include_payload; - let retry_policy = RetryPolicy { + let retry_policy = RetryPolicy::default() // `max_attempts` counts the first delivery, so N retries is N + 1 attempts - max_attempts: max_retries.saturating_add(1), - initial_delay_secs: 1, - max_delay_secs: 300, - backoff_multiplier: 2.0, - retry_on_status_codes: vec![408, 429, 500, 502, 503, 504], - }; - - Ok(WebhookConfig { - id: Uuid::new_v4(), - name, - url, - method: http_method, - headers: parsed_headers, - filter, - retry_policy, - auth, - timeout_secs: timeout, - enabled: true, - secret, - payload_template: None, - }) + .with_max_attempts(max_retries.saturating_add(1)) + .with_initial_delay_secs(1) + .with_max_delay_secs(300) + .with_backoff_multiplier(2.0) + .with_retry_on_status_codes(vec![408, 429, 500, 502, 503, 504]); + + let mut webhook = WebhookConfig::new(name, url) + .with_method(http_method) + .with_filter(filter) + .with_retry_policy(retry_policy) + .with_timeout_secs(timeout); + webhook.headers = parsed_headers; + webhook.auth = auth; + webhook.secret = secret; + Ok(webhook) } fn parse_http_method(method: &str) -> Result { diff --git a/docs/job-spawning.md b/docs/job-spawning.md index 6caa525..1eccc43 100644 --- a/docs/job-spawning.md +++ b/docs/job-spawning.md @@ -150,11 +150,9 @@ use hammerwork::spawn::{JobSpawnExt, SpawnConfig}; use hammerwork::Job; use serde_json::json; -let spawn_config = SpawnConfig { - max_spawn_count: Some(15), - operation_id: Some("op-dataset-123".to_string()), - ..SpawnConfig::default() -}; +let spawn_config = SpawnConfig::default() + .with_max_spawn_count(15) + .with_operation_id("op-dataset-123".to_string()); // The payload must be a JSON object; anything else is rejected with // `HammerworkError::InvalidJobPayload` instead of silently losing the configuration. @@ -214,7 +212,7 @@ encrypted jobs. ### SpawnConfig Fields -`SpawnConfig` is a plain struct with public fields. `SpawnConfig::default()` allows 100 children, inherits priority, retry strategy and trace context, and does not inherit the timeout. +`SpawnConfig` has public fields and is `#[non_exhaustive]`: start from `SpawnConfig::default()` and use its `with_*` methods. The default allows 100 children, inherits priority, retry strategy and trace context, and does not inherit the timeout. ```rust,no_run # #[allow(unused_imports)] use hammerwork::queue::DatabaseQueue; @@ -222,14 +220,13 @@ encrypted jobs. # async fn doc(queue: std::sync::Arc>, handler: hammerwork::worker::JobHandler, payload: serde_json::Value, job: hammerwork::Job) -> std::result::Result<(), Box> { use hammerwork::spawn::SpawnConfig; -let config = SpawnConfig { - max_spawn_count: Some(50), // Maximum children one parent may spawn (None = unlimited) - inherit_priority: true, // Children get the parent's priority - inherit_retry_strategy: true, // Children get the parent's retry strategy - inherit_timeout: false, // Children keep their own timeout - inherit_trace_context: true, // Children get trace_id, correlation_id, parent_span_id, span_context - operation_id: Some("custom-op-123".to_string()), // Identifier reported in SpawnResult -}; +let config = SpawnConfig::default() + .with_max_spawn_count(50) // Maximum children one parent may spawn (unlimited when unset) + .with_inherit_priority(true) // Children get the parent's priority + .with_inherit_retry_strategy(true) // Children get the parent's retry strategy + .with_inherit_timeout(false) // Children keep their own timeout + .with_inherit_trace_context(true) // Children get trace_id, correlation_id, parent_span_id, span_context + .with_operation_id("custom-op-123".to_string()); // Identifier reported in SpawnResult let defaults = SpawnConfig::default(); assert_eq!(defaults.max_spawn_count, Some(100)); @@ -237,7 +234,7 @@ assert_eq!(defaults.max_spawn_count, Some(100)); # } ``` -The manager runs the handler first and then applies the inheritance flags, so inherited values overwrite whatever the handler set on the child. If you want children with their own priority, set `inherit_priority: false`. +The manager runs the handler first and then applies the inheritance flags, so inherited values overwrite whatever the handler set on the child. If you want children with their own priority, use `.with_inherit_priority(false)`. ### Children Use Their Own Queue diff --git a/docs/monitoring.md b/docs/monitoring.md index 4cb761b..0490c99 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -193,11 +193,9 @@ to `tracing_endpoint` as `service_name`; call `hammerwork::tracing::shutdown_tra before exiting to flush them. ```rust -let logging = hammerwork::config::LoggingConfig { - level: "warn,hammerwork=debug".to_string(), - json_format: true, - ..Default::default() -}; +let logging = hammerwork::config::LoggingConfig::default() + .with_level("warn,hammerwork=debug".to_string()) + .with_json_format(true); # let _ = &logging; // logging.try_init()?; ``` diff --git a/docs/streaming.md b/docs/streaming.md index cb5ef3a..9ec2176 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -23,13 +23,12 @@ let stream = StreamConfig::new( }, ) .with_filter(EventFilter::new().with_event_types(vec![JobLifecycleEventType::Failed])) -.with_retry_policy(StreamRetryPolicy { - max_attempts: 5, - initial_delay_secs: 1, - max_delay_secs: 60, - backoff_multiplier: 2.0, - use_jitter: true, -}); +.with_retry_policy(StreamRetryPolicy::default() + .with_max_attempts(5) + .with_initial_delay_secs(1) + .with_max_delay_secs(60) + .with_backoff_multiplier(2.0) + .with_use_jitter(true)); streams.add_stream(stream).await?; // ... on shutdown: diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.md index 11b0707..fcb3e33 100644 --- a/docs/upgrading-to-3.0.md +++ b/docs/upgrading-to-3.0.md @@ -308,8 +308,9 @@ turn batch mode off, do not call `with_batch_size`. Batch settings can now also come from configuration: the optional `[worker]` keys `batch_size` and `batch_concurrency` (`WorkerConfig::batch_size` and `WorkerConfig::batch_concurrency`, both `Option`) are applied by -`Worker::with_config` when set. If you build a `WorkerConfig` with a struct literal, add -the two fields or end it with `..WorkerConfig::default()`. +`Worker::with_config` when set. `WorkerConfig` is now `#[non_exhaustive]` (see +[below](#non-exhaustive-structs-and-enums)): build it with +`WorkerConfig::default().with_batch_size(n).with_batch_concurrency(m)`. ### `with_max_retries` is now `with_attempt_cap` @@ -398,3 +399,140 @@ 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. + +## Non-exhaustive structs and enums + +Configuration, statistics and record types that gain fields from release to release are +`#[non_exhaustive]` in 3.0 ([#81](https://github.com/CodingAnarchy/hammerwork/issues/81)), +so a new field is no longer a breaking change. Outside Hammerwork you can still read and +assign their public fields and match them with `..`, but you cannot build them with a +struct literal, not even one that ends in `..Default::default()`. Start from `default()` or +a constructor and chain the `with_*` methods instead: + +```rust +use hammerwork::config::{HammerworkConfig, WorkerConfig}; +use std::time::Duration; + +// Before (2.x): +// let worker = WorkerConfig { +// pool_size: 8, +// job_timeout: Duration::from_secs(60), +// batch_size: Some(25), +// ..WorkerConfig::default() +// }; + +// After (3.0): +let worker = WorkerConfig::default() + .with_pool_size(8) + .with_job_timeout(Duration::from_secs(60)) + .with_batch_size(25); // `Option` fields take the value and store `Some(value)` +let config = HammerworkConfig::new().with_worker(worker); + +// Assigning fields of a default value works too: +let mut worker = WorkerConfig::default(); +worker.pool_size = 8; +# let _ = (config, worker); +``` + +### Configuration types + +Every public field of these types has a `with_` method unless noted otherwise. + +| Module | Types | How to build them | +| --- | --- | --- | +| `config` | `HammerworkConfig` | `new()` / `default()`, one setter per section (`with_database`, `with_worker`, `with_events`, `with_webhooks`, `with_streaming`, `with_alerting`, `with_metrics`, `with_archive`, `with_rate_limiting`, `with_logging`, `with_encryption`) and the existing shortcuts | +| `config` | `DatabaseConfig`, `WorkerConfig`, `WebhookConfigs`, `WebhookGlobalSettings`, `StreamingConfigs`, `StreamingGlobalSettings`, `SimpleEventFilter`, `ArchiveConfig`, `RateLimitingConfig`, `LoggingConfig`, `PayloadEncryptionConfig`, `KeyRotationConfig` | `default()` and the new `with_*` setters; also `RateLimitingConfig::with_queue_throttle(queue, throttle)` and `PayloadEncryptionConfig::with_decryption_key(key_id, source)` | +| `events` | `EventConfig` | `default()` and the new setters | +| `events` | `EventFilter` | `new()` and its existing builders | +| `events` | `JobLifecycleEvent` | the `JobLifecycleEventBuilder` constructors (`enqueued`, `failed`, ...) or the new `JobLifecycleEvent::new(job_id, queue, event_type, priority)`, then `with_timestamp`, `with_processing_time_ms`, `with_error`, `with_payload`, `with_metadata` | +| `events` | `JobError` | new `JobError::new(message)`, then `with_error_type`, `with_details`, `with_retry_attempt` | +| `webhooks` | `WebhookConfig` | `new(name, url)` and its existing builders | +| `webhooks` | `RetryPolicy`, `WebhookManagerConfig` | `default()` and the new setters | +| `streaming` | `StreamConfig` | `new(name, backend)` and its existing builders | +| `streaming` | `StreamRetryPolicy`, `BufferConfig`, `StreamManagerConfig` | `default()` and the new setters | +| `alerting` | `AlertingConfig`, `SmtpConfig` | `new()` / `SmtpConfig::new(host, from)` and their existing builders | +| `archive` | `ArchivalPolicy`, `ArchivalConfig` | `new()` and their existing builders | +| `encryption` | `EncryptionConfig`, `KeyManagerConfig`, `KeyAuditFilter` | `new()` and their existing builders; new `KeyManagerConfig::with_key_derivation_config` | +| `encryption` | `ExternalKmsConfig` | new `ExternalKmsConfig::new(service_type, endpoint)`, then `with_auth(key, value)`, `with_auth_config`, `with_region`, `with_namespace` | +| `encryption` | `KeyDerivationConfig` | `default()` and the new setters | +| `metrics`, `tracing`, `rate_limit`, `worker` | `MetricsConfig`, `TracingConfig`, `ThrottleConfig`, `AutoscaleConfig`, `JobEventHooks` | `new()` and their existing builders | +| `spawn`, `stats` | `SpawnConfig`, `StatsConfig` | `default()` and the new setters | +| `stats` | `JobEvent` | new `JobEvent::new(job_id, queue, event_type, priority)`, then `with_processing_time_ms`, `with_error_message`, `with_timestamp` | +| `job`, `batch`, `workflow` | `Job`, `ResultConfig`, `JobBatch`, `JobGroup` | `Job::new` / `Job::with_delay` / `Job::with_cron_schedule`, `ResultConfig::new`, `JobBatch::new`, `JobGroup::new` and their existing builders | +| `migrations` | `Migration` | new `Migration::new(id, description, version)` (and `with_created_at`) | +| `archive` | `ArchivedJob` | new `ArchivedJob::new(id, queue, status, created_at, archived_at, reason)`, then `with_original_payload_size`, `with_payload_compressed`, `with_archived_by`, `with_workflow_id`, `with_workflow_name` | +| `spawn` | `SpawnContext` | new `SpawnContext::new(parent_job, config, queue)`, for testing a `SpawnHandler` | +| `hammerwork_web` | `DashboardConfig` | `new()` and its builders, plus the new `with_pool_size`, `with_auth_config`, `with_websocket`, `with_allowed_origins` | +| `hammerwork_web` | `AuthConfig`, `WebSocketConfig` | `default()` and the new setters; `AuthConfig::disabled()` | + +### Statistics and records + +These are returned by Hammerwork and have no builders. Read their fields as before. In +tests, start from `default()` where the type has one and assign the fields you need +(`QueueStats` now implements `Default` for this). + +- Statistics: `stats::JobStatistics`, `stats::QueueStats`, `stats::DeadJobSummary`, + `priority::PriorityStats`, `worker::BatchProcessingStats`, `worker::AutoscaleMetrics`, + `archive::ArchivalStats`, `archive::ScheduledArchivalPass`, + `encryption::EncryptionStats`, `encryption::KeyManagerStats`, + `events::EventManagerStats`, `webhooks::WebhookStats`, `webhooks::WebhookManagerStats`, + `streaming::StreamStats`, `streaming::StreamManagerGlobalStats`. +- Records: `webhooks::WebhookDelivery`, `streaming::StreamDelivery`, + `streaming::StreamedEvent`, `encryption::EncryptionKey`, `encryption::KeyAuditRecord`, + `encryption::KmsWrappedKey`, `encryption::EncryptionMetadata`, + `encryption::EncryptedPayload`, `migrations::MigrationRecord`, + `queue::QueuePauseInfo`, `queue::RecordedOutcome`, `spawn::SpawnResult`, + `worker::JobHookEvent`, `worker::JobResult` (still built with `JobResult::success()` and + `JobResult::with_data`), `batch::BatchResult`, `alerting::Alert`. + +Small types that are complete by definition stay exhaustive: `queue::StaleJobRecovery` +(`requeued`, `dead`), `queue::EncryptedJobPurge` (`jobs`, `archived_jobs`), +`rate_limit::RateLimit` (`rate`, `per`, `burst_limit`) and the newtypes +`tracing::TraceId`, `tracing::CorrelationId` and `config::KeySourceRef`. + +### `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 + +Dropping an `EventSubscription` now unregisters it from its `EventManager`: its filter +stops counting toward `subscription_count` and `payload_wanted` without a call to +`EventManager::unsubscribe` (which still works, for example to unregister by id). The +subscription keeps a reference to the manager's registry, so its fields can be borrowed +but no longer moved out: keep the whole subscription alive while you read from it. + +```rust +# async fn example(events: hammerwork::events::EventManager) -> hammerwork::Result<()> { +use hammerwork::events::EventFilter; + +// Before (2.x): +// let receiver = events.subscribe(EventFilter::new()).await?.receiver; +// ... later: events.unsubscribe(id).await?; + +// After (3.0): +let mut subscription = events.subscribe(EventFilter::new()).await?; +while let Ok(event) = subscription.receiver.recv().await { + println!("{} {}", event.job_id, event.event_type); +# break; +} +drop(subscription); // unregisters +# Ok(()) +# } +``` + +### 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. diff --git a/docs/webhooks.md b/docs/webhooks.md index ccd0038..7e057b3 100644 --- a/docs/webhooks.md +++ b/docs/webhooks.md @@ -82,12 +82,10 @@ retries per its `RetryPolicy`) for every matching event. ```rust use hammerwork::webhooks::WebhookManagerConfig; -let config = WebhookManagerConfig { - max_concurrent_deliveries: 50, - default_timeout_secs: 10, - max_pending_deliveries: 500, - ..Default::default() -}; +let config = WebhookManagerConfig::default() + .with_max_concurrent_deliveries(50) + .with_default_timeout_secs(10) + .with_max_pending_deliveries(500); assert_eq!(config.max_response_body_size, 64 * 1024); ``` diff --git a/examples/key_management_example.rs b/examples/key_management_example.rs index 02741ee..5542f5d 100644 --- a/examples/key_management_example.rs +++ b/examples/key_management_example.rs @@ -50,13 +50,10 @@ async fn main() -> Result<(), Box> { aws_auth.insert("access_key_id".to_string(), "AKIA...".to_string()); aws_auth.insert("secret_access_key".to_string(), "secret123".to_string()); - let external_kms = ExternalKmsConfig { - service_type: "AWS".to_string(), - endpoint: "https://kms.us-east-1.amazonaws.com".to_string(), - auth_config: aws_auth, - region: Some("us-east-1".to_string()), - namespace: Some("hammerwork-production".to_string()), - }; + let external_kms = ExternalKmsConfig::new("AWS", "https://kms.us-east-1.amazonaws.com") + .with_auth_config(aws_auth) + .with_region("us-east-1".to_string()) + .with_namespace("hammerwork-production".to_string()); let _kms_config = KeyManagerConfig::new().with_external_kms(external_kms); @@ -67,14 +64,15 @@ async fn main() -> Result<(), Box> { // Example 3: Key derivation configuration for password-based keys println!("3. Key derivation configuration:"); - let _derivation_config = KeyDerivationConfig { - memory_cost: 65536, // 64 MB - time_cost: 3, // 3 iterations - parallelism: 4, // 4 threads - salt_length: 32, // 32 bytes salt - }; + let derivation_config = KeyDerivationConfig::default() + .with_memory_cost(65536) // 64 MB + .with_time_cost(3) // 3 iterations + .with_parallelism(4) // 4 threads + .with_salt_length(32); // 32 bytes salt - let _password_config = KeyManagerConfig::new().with_audit_enabled(true); + let _password_config = KeyManagerConfig::new() + .with_key_derivation_config(derivation_config) + .with_audit_enabled(true); println!(" Algorithm: Argon2id"); println!(" Memory cost: 64 MB"); @@ -127,18 +125,17 @@ async fn main() -> Result<(), Box> { println!("6. Key management statistics and monitoring:"); // Mock statistics for demonstration - let stats = hammerwork::encryption::KeyManagerStats { - total_keys: 25, - active_keys: 20, - retired_keys: 4, - revoked_keys: 1, - expired_keys: 0, - total_access_operations: 15420, - rotations_performed: 8, - average_key_age_days: 45.5, - keys_expiring_soon: 2, - keys_due_for_rotation: 1, - }; + let mut stats = hammerwork::encryption::KeyManagerStats::default(); + stats.total_keys = 25; + stats.active_keys = 20; + stats.retired_keys = 4; + stats.revoked_keys = 1; + stats.expired_keys = 0; + stats.total_access_operations = 15420; + stats.rotations_performed = 8; + stats.average_key_age_days = 45.5; + stats.keys_expiring_soon = 2; + stats.keys_due_for_rotation = 1; println!(" 📊 Key Management Statistics:"); println!(" Total keys managed: {}", stats.total_keys); diff --git a/examples/spawn_example.rs b/examples/spawn_example.rs index a48cc1f..8812172 100644 --- a/examples/spawn_example.rs +++ b/examples/spawn_example.rs @@ -298,14 +298,13 @@ async fn main() -> std::result::Result<(), Box> { "data/file4.csv" ], "batch_id": "batch_001", - "_spawn_config": SpawnConfig { - max_spawn_count: Some(10), - inherit_priority: true, - inherit_retry_strategy: true, - inherit_timeout: false, - inherit_trace_context: true, - operation_id: Some("file_processing_001".to_string()), - } + "_spawn_config": SpawnConfig::default() + .with_max_spawn_count(10) + .with_inherit_priority(true) + .with_inherit_retry_strategy(true) + .with_inherit_timeout(false) + .with_inherit_trace_context(true) + .with_operation_id("file_processing_001".to_string()) }), ) .as_high_priority() @@ -327,14 +326,13 @@ async fn main() -> std::result::Result<(), Box> { "total_records": 5000, "chunk_size": 1000, "operation": "monthly_summary", - "_spawn_config": SpawnConfig { - max_spawn_count: Some(20), - inherit_priority: false, // Let chunks have normal priority - inherit_retry_strategy: true, - inherit_timeout: true, - inherit_trace_context: true, - operation_id: Some("data_agg_001".to_string()), - } + "_spawn_config": SpawnConfig::default() + .with_max_spawn_count(20) + .with_inherit_priority(false) // Let chunks have normal priority + .with_inherit_retry_strategy(true) + .with_inherit_timeout(true) + .with_inherit_trace_context(true) + .with_operation_id("data_agg_001".to_string()) }), ) .as_high_priority() diff --git a/hammerwork-web/README.md b/hammerwork-web/README.md index 000b8ce..6212e67 100644 --- a/hammerwork-web/README.md +++ b/hammerwork-web/README.md @@ -135,17 +135,14 @@ use hammerwork_web::{WebDashboard, DashboardConfig}; #[tokio::main] async fn main() -> Result<(), Box> { - let config = DashboardConfig { - bind_address: "127.0.0.1".to_string(), - port: 8080, - database_url: "postgresql://localhost/hammerwork".to_string(), - pool_size: 5, - static_dir: "./assets".into(), - enable_cors: true, + let config = DashboardConfig::new() + .with_bind_address("127.0.0.1", 8080) + .with_database_url("postgresql://localhost/hammerwork") + .with_pool_size(5) + .with_static_dir("./assets".into()) + .with_cors(true) // CORS is only granted to listed origins; enabling it without any is an error. - allowed_origins: vec!["https://ops.example.com".to_string()], - ..Default::default() - }; + .with_allowed_origin("https://ops.example.com"); let dashboard = WebDashboard::new(config).await?; dashboard.start().await?; diff --git a/hammerwork-web/src/api/archive.rs b/hammerwork-web/src/api/archive.rs index a349776..ae3810e 100644 --- a/hammerwork-web/src/api/archive.rs +++ b/hammerwork-web/src/api/archive.rs @@ -318,9 +318,10 @@ where "Failed to count archivable jobs" ); let response = ArchiveResponse { - stats: ArchivalStats { - jobs_archived: would_archive, - ..ArchivalStats::default() + stats: { + let mut stats = ArchivalStats::default(); + stats.jobs_archived = would_archive; + stats }, dry_run: true, policy_used: policy, @@ -547,17 +548,17 @@ mod tests { #[test] fn test_archived_job_info_conversion() { - let archived_job = ArchivedJob { - id: uuid::Uuid::new_v4(), - queue_name: "test_queue".to_string(), - status: JobStatus::Completed, - created_at: chrono::Utc::now(), - archived_at: chrono::Utc::now(), - archival_reason: ArchivalReason::Automatic, - original_payload_size: Some(1024), - payload_compressed: true, - archived_by: Some("system".to_string()), - }; + let archived_job = ArchivedJob::new( + uuid::Uuid::new_v4(), + "test_queue", + JobStatus::Completed, + chrono::Utc::now(), + chrono::Utc::now(), + ArchivalReason::Automatic, + ) + .with_original_payload_size(1024) + .with_payload_compressed(true) + .with_archived_by("system".to_string()); let info: ArchivedJobInfo = archived_job.into(); assert_eq!(info.queue_name, "test_queue"); diff --git a/hammerwork-web/src/api/history.rs b/hammerwork-web/src/api/history.rs index cf5f4f6..7ad14ac 100644 --- a/hammerwork-web/src/api/history.rs +++ b/hammerwork-web/src/api/history.rs @@ -592,7 +592,8 @@ macro_rules! bind_archive_filter { /// Columns of an archived job listing. const ARCHIVED_JOB_COLUMNS: &str = "id, queue_name, status, created_at, archived_at, \ - archival_reason, original_payload_size, payload_compressed, archived_by"; + archival_reason, original_payload_size, payload_compressed, archived_by, workflow_id, \ + workflow_name"; /// The status stored in the archive (possibly JSON-quoted); unknown values read as `Dead`, /// as the core library does. @@ -628,8 +629,9 @@ pub(crate) fn decodable(rows: impl IntoIterator)>) .collect() } -/// An archived job from a row of [`ARCHIVED_JOB_COLUMNS`], with the id already decoded. -fn archived_job(row: &R, id: uuid::Uuid) -> Result +/// An archived job from a row of [`ARCHIVED_JOB_COLUMNS`], with the id and workflow id +/// already decoded (their column types differ between PostgreSQL and MySQL). +fn archived_job(row: &R, id: uuid::Uuid, workflow_id: Option) -> Result where R: Row, for<'a> &'a str: sqlx::ColumnIndex, @@ -639,22 +641,23 @@ where for<'a> bool: sqlx::Decode<'a, R::Database> + sqlx::Type, for<'a> DateTime: sqlx::Decode<'a, R::Database> + sqlx::Type, { - Ok(ArchivedJob { + let mut job = ArchivedJob::new( id, - queue_name: row.try_get("queue_name")?, - status: archived_status(&row.try_get::("status")?), - created_at: row.try_get("created_at")?, - archived_at: row.try_get("archived_at")?, - archival_reason: ArchivalReason::parse_from_db( - &row.try_get::("archival_reason")?, - ) - .unwrap_or_default(), - original_payload_size: row - .try_get::, _>("original_payload_size")? - .and_then(|size| usize::try_from(size).ok()), - payload_compressed: row.try_get("payload_compressed")?, - archived_by: row.try_get("archived_by")?, - }) + row.try_get::("queue_name")?, + archived_status(&row.try_get::("status")?), + row.try_get("created_at")?, + row.try_get("archived_at")?, + ArchivalReason::parse_from_db(&row.try_get::("archival_reason")?) + .unwrap_or_default(), + ) + .with_payload_compressed(row.try_get("payload_compressed")?); + job.original_payload_size = row + .try_get::, _>("original_payload_size")? + .and_then(|size| usize::try_from(size).ok()); + job.archived_by = row.try_get("archived_by")?; + job.workflow_id = workflow_id; + job.workflow_name = row.try_get("workflow_name")?; + Ok(job) } /// Filters shared by count and delete: `$n`/`?` placeholders, queue then cutoff. @@ -898,7 +901,10 @@ impl JobHistory for JobQueue { let label = id.as_ref().map(|id| id.to_string()).unwrap_or_default(); ( label, - id.map_err(Into::into).and_then(|id| archived_job(row, id)), + id.map_err(Into::into).and_then(|id| { + let workflow_id = row.try_get::, _>("workflow_id")?; + archived_job(row, id, workflow_id) + }), ) })); Ok((jobs, to_u64(total))) @@ -1188,7 +1194,13 @@ impl JobHistory for JobQueue { let label = row.try_get::("id").unwrap_or_default(); let job = uuid::Uuid::parse_str(&label) .map_err(Into::into) - .and_then(|id| archived_job(row, id)); + .and_then(|id| { + let workflow_id = row + .try_get::, _>("workflow_id")? + .map(|id| uuid::Uuid::parse_str(&id)) + .transpose()?; + archived_job(row, id, workflow_id) + }); (label, job) })); Ok((jobs, to_u64(total))) diff --git a/hammerwork-web/src/api/stats.rs b/hammerwork-web/src/api/stats.rs index 3334455..aaded0f 100644 --- a/hammerwork-web/src/api/stats.rs +++ b/hammerwork-web/src/api/stats.rs @@ -1019,15 +1019,12 @@ mod tests { #[test] fn test_overview_counts_failed_dead_and_timed_out_jobs_as_failed() { - let mut stats = hammerwork::stats::QueueStats { - queue_name: "q".to_string(), - pending_count: 1, - running_count: 0, - dead_count: 2, - timed_out_count: 3, - completed_count: 4, - statistics: Default::default(), - }; + let mut stats = hammerwork::stats::QueueStats::default(); + stats.queue_name = "q".to_string(); + stats.pending_count = 1; + stats.dead_count = 2; + stats.timed_out_count = 3; + stats.completed_count = 4; // Jobs in status `Failed` (a failed dependency, a fail-fast batch, `fail_job`) stats.statistics.failed = 5; let overview = generate_overview_from_stats(&[stats], 0); diff --git a/hammerwork-web/src/api/system.rs b/hammerwork-web/src/api/system.rs index 3d95adb..54edbf3 100644 --- a/hammerwork-web/src/api/system.rs +++ b/hammerwork-web/src/api/system.rs @@ -106,18 +106,12 @@ //! //! ```rust //! use hammerwork_web::__private::api::system::MetricsInfo; -//! use chrono::Utc; //! //! let metrics_info = MetricsInfo { -//! prometheus_enabled: true, -//! metrics_endpoint: "/metrics".to_string(), -//! custom_metrics_count: Some(15), -//! last_scrape: Some(Utc::now()), +//! prometheus_enabled: false, //! }; //! -//! assert!(metrics_info.prometheus_enabled); -//! assert_eq!(metrics_info.metrics_endpoint, "/metrics"); -//! assert_eq!(metrics_info.custom_metrics_count, Some(15)); +//! assert!(!metrics_info.prometheus_enabled); //! ``` use super::history::{FinishedKind, JobHistory, TableMaintenance, maintenance_tables}; @@ -215,15 +209,11 @@ pub struct ServerConfig { /// Metrics endpoint information #[derive(Debug, Serialize)] +/// +/// The dashboard serves no `/metrics` route and keeps no metrics registry: scrape the +/// metrics of the application that embeds the library instead. pub struct MetricsInfo { pub prometheus_enabled: bool, - /// Deprecated and not served: the dashboard has no `/metrics` route (it always reports - /// `"/metrics"` for compatibility). Scrape the metrics of the application that embeds - /// the library instead. - pub metrics_endpoint: String, - /// `null`: the dashboard keeps no metrics registry, so there is nothing to count. - pub custom_metrics_count: Option, - pub last_scrape: Option>, } /// Configuration update request @@ -383,9 +373,6 @@ async fn metrics_info_handler( // hammerwork-web does not serve a Prometheus endpoint itself (there is no // `metrics` feature on this crate), so this is always false. prometheus_enabled: false, - metrics_endpoint: "/metrics".to_string(), - custom_metrics_count: None, - last_scrape: None, }; Ok(json_reply(&ApiResponse::success(metrics_info))) @@ -579,16 +566,12 @@ mod tests { } #[test] - fn test_unavailable_metrics_are_none_not_zero() { + fn test_metrics_info_reports_only_what_is_served() { let json = serde_json::to_value(MetricsInfo { prometheus_enabled: false, - metrics_endpoint: "/metrics".to_string(), - custom_metrics_count: None, - last_scrape: None, }) .unwrap(); - assert!(json["custom_metrics_count"].is_null()); - assert!(json["last_scrape"].is_null()); + assert_eq!(json, serde_json::json!({ "prometheus_enabled": false })); } #[tokio::test] diff --git a/hammerwork-web/src/auth.rs b/hammerwork-web/src/auth.rs index fa348f8..df2c2af 100644 --- a/hammerwork-web/src/auth.rs +++ b/hammerwork-web/src/auth.rs @@ -28,13 +28,13 @@ //! use hammerwork_web::__private::auth::AuthState; //! use hammerwork_web::__private::config::AuthConfig; //! -//! let auth_config = AuthConfig { -//! enabled: true, -//! username: "admin".to_string(), +//! 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)`. -//! password_hash: "$2b$12$abcdefghijklmnopqrstuuJ0Y7gZ8z5d0FQqfJb8yX3QZpGQ0lW6e".to_string(), -//! ..Default::default() -//! }; +//! .with_password_hash( +//! "$2b$12$abcdefghijklmnopqrstuuJ0Y7gZ8z5d0FQqfJb8yX3QZpGQ0lW6e".to_string(), +//! ); //! //! let auth_state = AuthState::new(auth_config); //! assert!(auth_state.is_enabled()); diff --git a/hammerwork-web/src/config.rs b/hammerwork-web/src/config.rs index ab68328..320c6dd 100644 --- a/hammerwork-web/src/config.rs +++ b/hammerwork-web/src/config.rs @@ -93,6 +93,7 @@ use std::time::Duration; /// /// `Debug` shows `database_url` with its password replaced by `***`. #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct DashboardConfig { /// Server bind address pub bind_address: String, @@ -364,14 +365,13 @@ impl DashboardConfig { /// assert_eq!(auth_config.max_failed_attempts, 5); /// /// // Custom configuration -/// let auth_config = AuthConfig { -/// enabled: true, -/// username: "dashboard_admin".to_string(), -/// password_hash: "$2b$12$hash...".to_string(), -/// session_timeout: Duration::from_secs(4 * 60 * 60), // 4 hours -/// max_failed_attempts: 3, -/// lockout_duration: Duration::from_secs(30 * 60), // 30 minutes -/// }; +/// 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); @@ -379,6 +379,7 @@ impl DashboardConfig { /// /// `Debug` never shows `password_hash`. #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct AuthConfig { /// Whether authentication is enabled pub enabled: bool, @@ -418,6 +419,7 @@ impl Default for AuthConfig { /// WebSocket configuration #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebSocketConfig { /// Ping interval to keep connections alive #[serde(with = "hammerwork::config::serde_duration")] @@ -471,6 +473,62 @@ impl Default for WebSocketConfig { } } +/// Generate `with_*` builder methods that set one public field each (the configuration +/// structs are `#[non_exhaustive]`, so callers outside the crate cannot use literals). +macro_rules! with_setters { + ($ty:ty { $($name:ident($field:ident): $fty:ty),* $(,)? }) => { + impl $ty { + $( + #[doc = concat!("Sets [`", stringify!($field), "`](Self::", stringify!($field), ").")] + #[must_use] + pub fn $name(mut self, value: $fty) -> Self { + self.$field = value; + self + } + )* + } + }; +} + +with_setters! { + DashboardConfig { + with_pool_size(pool_size): u32, + with_auth_config(auth): AuthConfig, + with_websocket(websocket): WebSocketConfig, + with_allowed_origins(allowed_origins): Vec, + } +} + +with_setters! { + AuthConfig { + with_enabled(enabled): bool, + with_username(username): String, + with_password_hash(password_hash): String, + with_session_timeout(session_timeout): Duration, + with_max_failed_attempts(max_failed_attempts): u32, + with_lockout_duration(lockout_duration): Duration, + } +} + +impl AuthConfig { + /// The default settings with authentication turned off (for local development and + /// tests; never expose an unauthenticated dashboard). + pub fn disabled() -> Self { + Self::default().with_enabled(false) + } +} + +with_setters! { + WebSocketConfig { + with_ping_interval(ping_interval): Duration, + with_max_connections(max_connections): usize, + with_message_buffer_size(message_buffer_size): usize, + with_max_message_size(max_message_size): usize, + with_live_update_interval(live_update_interval): Duration, + with_live_update_max_jobs(live_update_max_jobs): u32, + } +} + impl std::fmt::Debug for DashboardConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DashboardConfig") @@ -740,4 +798,53 @@ mod tests { config.websocket.live_update_interval = Duration::ZERO; assert!(config.validate().is_ok()); } + + #[test] + fn test_config_builders() { + let auth = AuthConfig::default() + .with_enabled(true) + .with_username("ops".to_string()) + .with_password_hash("$2b$hash".to_string()) + .with_session_timeout(Duration::from_secs(60)) + .with_max_failed_attempts(2) + .with_lockout_duration(Duration::from_secs(30)); + assert!(auth.enabled); + assert_eq!( + (auth.username.as_str(), auth.password_hash.as_str()), + ("ops", "$2b$hash") + ); + assert_eq!(auth.session_timeout, Duration::from_secs(60)); + assert_eq!(auth.max_failed_attempts, 2); + assert_eq!(auth.lockout_duration, Duration::from_secs(30)); + assert!(!AuthConfig::disabled().enabled); + + let websocket = WebSocketConfig::default() + .with_ping_interval(Duration::from_secs(5)) + .with_max_connections(3) + .with_message_buffer_size(8) + .with_max_message_size(256) + .with_live_update_interval(Duration::ZERO) + .with_live_update_max_jobs(7); + assert_eq!(websocket.ping_interval, Duration::from_secs(5)); + assert_eq!( + ( + websocket.max_connections, + websocket.message_buffer_size, + websocket.max_message_size + ), + (3, 8, 256) + ); + assert!(websocket.live_update_interval.is_zero()); + assert_eq!(websocket.live_update_max_jobs, 7); + + let config = DashboardConfig::new() + .with_pool_size(4) + .with_auth_config(auth) + .with_websocket(websocket) + .with_allowed_origins(vec!["https://ops.example.com".to_string()]); + assert_eq!(config.pool_size, 4); + assert_eq!(config.auth.username, "ops"); + assert_eq!(config.websocket.max_connections, 3); + assert_eq!(config.allowed_origins, ["https://ops.example.com"]); + } } diff --git a/hammerwork-web/src/lib.rs b/hammerwork-web/src/lib.rs index 2fcbb25..2638af8 100644 --- a/hammerwork-web/src/lib.rs +++ b/hammerwork-web/src/lib.rs @@ -30,12 +30,9 @@ //! //! #[tokio::main] //! async fn main() -> Result<(), Box> { -//! let config = DashboardConfig { -//! bind_address: "127.0.0.1".to_string(), -//! port: 8080, -//! database_url: "postgresql://localhost/hammerwork".to_string(), -//! ..Default::default() -//! }; +//! let config = DashboardConfig::new() +//! .with_bind_address("127.0.0.1", 8080) +//! .with_database_url("postgresql://localhost/hammerwork"); //! //! let dashboard = WebDashboard::new(config).await?; //! dashboard.start().await?; @@ -82,14 +79,13 @@ //! use hammerwork_web::AuthConfig; //! use std::time::Duration; //! -//! let auth_config = AuthConfig { -//! enabled: true, -//! username: "admin".to_string(), -//! password_hash: "$2b$12$hash...".to_string(), -//! session_timeout: Duration::from_secs(8 * 60 * 60), // 8 hours -//! max_failed_attempts: 5, -//! lockout_duration: Duration::from_secs(15 * 60), // 15 minutes -//! }; +//! let auth_config = AuthConfig::default() +//! .with_enabled(true) +//! .with_username("admin".to_string()) +//! .with_password_hash("$2b$12$hash...".to_string()) +//! .with_session_timeout(Duration::from_secs(8 * 60 * 60)) // 8 hours +//! .with_max_failed_attempts(5) +//! .with_lockout_duration(Duration::from_secs(15 * 60)); // 15 minutes //! //! assert!(auth_config.enabled); //! assert_eq!(auth_config.max_failed_attempts, 5); diff --git a/hammerwork-web/src/live.rs b/hammerwork-web/src/live.rs index bc75b42..1f5cb6f 100644 --- a/hammerwork-web/src/live.rs +++ b/hammerwork-web/src/live.rs @@ -401,12 +401,7 @@ mod tests { id, "emails".to_string(), JobPriority::High, - hammerwork::events::JobError { - message: "boom".to_string(), - error_type: None, - details: None, - retry_attempt: Some(2), - }, + hammerwork::events::JobError::new("boom".to_string()).with_retry_attempt(2), ); let update = job_update_from_event(&event); assert_eq!(update.id, id.to_string()); @@ -522,14 +517,11 @@ mod tests { new_state(), 10, ); - let stats = |name: &str, pending: u64| hammerwork::stats::QueueStats { - queue_name: name.to_string(), - pending_count: pending, - running_count: 0, - dead_count: 0, - timed_out_count: 0, - completed_count: 0, - statistics: Default::default(), + let stats = |name: &str, pending: u64| { + let mut stats = hammerwork::stats::QueueStats::default(); + stats.queue_name = name.to_string(); + stats.pending_count = pending; + stats }; let first = live.changed_queues(vec![stats("a", 1), stats("b", 0)]); assert_eq!(first.len(), 2); diff --git a/hammerwork-web/src/main.rs b/hammerwork-web/src/main.rs index 25d415b..690e544 100644 --- a/hammerwork-web/src/main.rs +++ b/hammerwork-web/src/main.rs @@ -475,13 +475,11 @@ mod tests { let empty_url = write_config( &dir, - &toml::to_string(&DashboardConfig { - database_url: String::new(), - auth: hammerwork_web::AuthConfig { - enabled: false, - ..Default::default() - }, - ..DashboardConfig::new() + &toml::to_string(&{ + let mut value = DashboardConfig::new(); + value.database_url = String::new(); + value.auth = hammerwork_web::AuthConfig::default().with_enabled(false); + value }) .unwrap(), ); diff --git a/hammerwork-web/src/server.rs b/hammerwork-web/src/server.rs index 9461bdc..1b827b9 100644 --- a/hammerwork-web/src/server.rs +++ b/hammerwork-web/src/server.rs @@ -513,13 +513,13 @@ mod tests { // The application's settings: its engine, with its key let var = format!("HW_WEB_TEST_KEY_{}", uuid::Uuid::new_v4().simple()); - let settings = hammerwork::config::PayloadEncryptionConfig { - enabled: true, - key_source: hammerwork::config::KeySourceRef::parse(&format!("env://{var}")).unwrap(), - key_id: Some("web-key".to_string()), - encrypted_queues: vec!["payments".to_string()], - ..Default::default() - }; + let settings = hammerwork::config::PayloadEncryptionConfig::default() + .with_enabled(true) + .with_key_source( + hammerwork::config::KeySourceRef::parse(&format!("env://{var}")).unwrap(), + ) + .with_key_id("web-key".to_string()) + .with_encrypted_queues(vec!["payments".to_string()]); let err = job_queue(pool(), &settings) .await .err() @@ -591,19 +591,13 @@ mod tests { fn routes(websocket: crate::config::WebSocketConfig) -> (Router, tempfile::TempDir) { let dir = tempdir().unwrap(); std::fs::write(dir.path().join("index.html"), "SPA").unwrap(); - let config = DashboardConfig { - websocket: websocket.clone(), - ..DashboardConfig::new() - }; + let config = DashboardConfig::new().with_websocket(websocket.clone()); let system_state = Arc::new(RwLock::new(SystemState::new( config.clone(), "PostgreSQL".into(), 1, ))); - let auth = AuthState::new(crate::config::AuthConfig { - enabled: false, - ..Default::default() - }); + let auth = AuthState::new(crate::config::AuthConfig::default().with_enabled(false)); let routes = app_routes( crate::api::test_support::unreachable_queue(), auth, @@ -756,10 +750,8 @@ mod tests { /// M12: messages above `max_message_size` end the connection instead of being buffered. #[tokio::test] async fn websocket_messages_are_size_limited() { - let (routes, _dir) = routes(crate::config::WebSocketConfig { - max_message_size: 1024, - ..Default::default() - }); + let (routes, _dir) = + routes(crate::config::WebSocketConfig::default().with_max_message_size(1024)); let mut client = warp::test::ws() .path("/ws") .handshake(routes.clone()) diff --git a/hammerwork-web/tests/api_tests.rs b/hammerwork-web/tests/api_tests.rs index f605d79..240020d 100644 --- a/hammerwork-web/tests/api_tests.rs +++ b/hammerwork-web/tests/api_tests.rs @@ -41,11 +41,9 @@ 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 config = DashboardConfig { - static_dir: static_dir.path().to_path_buf(), - auth: auth.clone(), - ..DashboardConfig::default() - }; + let mut config = DashboardConfig::default(); + config.static_dir = static_dir.path().to_path_buf(); + config.auth = auth.clone(); let system_state = Arc::new(RwLock::new(SystemState::new( config.clone(), database_type.to_string(), @@ -826,7 +824,9 @@ async fn system_endpoints(app: &App, database_type: let (status, body) = app.get("/api/system/metrics").await; assert_eq!(status, 200); assert_eq!(body["data"]["prometheus_enabled"], false); - assert!(body["data"]["custom_metrics_count"].is_null()); + assert!(body["data"].get("metrics_endpoint").is_none()); + assert!(body["data"].get("custom_metrics_count").is_none()); + assert!(body["data"].get("last_scrape").is_none()); let (status, body) = app.get("/api/version").await; assert_eq!(status, 200); @@ -1225,13 +1225,11 @@ async fn authentication(queue: Arc, database_type: & let hash = bcrypt::hash("s3cret", 4).unwrap(); let app = App::new( queue, - AuthConfig { - enabled: true, - username: "admin".into(), - password_hash: hash.clone(), - max_failed_attempts: 1000, - ..AuthConfig::default() - }, + AuthConfig::default() + .with_enabled(true) + .with_username("admin".into()) + .with_password_hash(hash.clone()) + .with_max_failed_attempts(1000), database_type, ); use base64::Engine; @@ -1303,13 +1301,11 @@ async fn authentication(queue: Arc, database_type: & // repeated failures lock the account: even the right password is refused for a while let strict = App::new( app.queue.clone(), - AuthConfig { - enabled: true, - username: "admin".into(), - password_hash: hash, - max_failed_attempts: 3, - ..AuthConfig::default() - }, + AuthConfig::default() + .with_enabled(true) + .with_username("admin".into()) + .with_password_hash(hash) + .with_max_failed_attempts(3), database_type, ); for _ in 0..3 { @@ -1572,10 +1568,7 @@ async fn request_hardening(app: &App) { async fn run_all(queue: Arc, database_type: &str) { let app = App::new( queue.clone(), - AuthConfig { - enabled: false, - ..AuthConfig::default() - }, + AuthConfig::default().with_enabled(false), database_type, ); health_and_static_files(&app).await; @@ -1629,10 +1622,7 @@ async fn test_http_api_reports_a_dead_database() { .unwrap(); let app = App::new( Arc::new(JobQueue::new(pool)), - AuthConfig { - enabled: false, - ..AuthConfig::default() - }, + AuthConfig::default().with_enabled(false), "PostgreSQL", ); for path in [ diff --git a/hammerwork-web/tests/integration_tests.rs b/hammerwork-web/tests/integration_tests.rs index 06a3909..76fbce2 100644 --- a/hammerwork-web/tests/integration_tests.rs +++ b/hammerwork-web/tests/integration_tests.rs @@ -48,22 +48,17 @@ mod tests { async fn test_dashboard_startup_with_postgres() { let temp_dir = tempdir().unwrap(); - let config = DashboardConfig { - bind_address: "127.0.0.1".to_string(), - port: 0, // Use random port - database_url: std::env::var("DATABASE_URL").unwrap_or_else(|_| { - "postgresql://postgres:hammerwork@localhost:5433/hammerwork".to_string() - }), - pool_size: 2, - static_dir: temp_dir.path().to_path_buf(), - auth: AuthConfig { - enabled: false, - ..Default::default() - }, - enable_cors: true, - allowed_origins: vec!["https://ops.example.com".to_string()], - ..Default::default() - }; + let mut config = DashboardConfig::default(); + config.bind_address = "127.0.0.1".to_string(); + config.port = 0; + config.database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| { + "postgresql://postgres:hammerwork@localhost:5433/hammerwork".to_string() + }); + config.pool_size = 2; + config.static_dir = temp_dir.path().to_path_buf(); + config.auth = AuthConfig::default().with_enabled(false); + config.enable_cors = true; + config.allowed_origins = vec!["https://ops.example.com".to_string()]; // Create minimal static files write_index(temp_dir.path()); @@ -78,20 +73,15 @@ mod tests { let temp_dir = tempdir().unwrap(); write_index(temp_dir.path()); - let config = DashboardConfig { - bind_address: "127.0.0.1".to_string(), - port: 0, - database_url: std::env::var("DATABASE_URL").unwrap_or_else(|_| { - "postgres://postgres:hammerwork@localhost:5433/hammerwork".to_string() - }), - static_dir: temp_dir.path().to_path_buf(), - auth: AuthConfig { - enabled: false, - ..Default::default() - }, - enable_cors: false, - ..Default::default() - }; + let mut config = DashboardConfig::default(); + config.bind_address = "127.0.0.1".to_string(); + config.port = 0; + config.database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| { + "postgres://postgres:hammerwork@localhost:5433/hammerwork".to_string() + }); + config.static_dir = temp_dir.path().to_path_buf(); + config.auth = AuthConfig::default().with_enabled(false); + config.enable_cors = false; assert_dashboard_starts(config).await; } @@ -102,21 +92,15 @@ mod tests { async fn test_dashboard_startup_with_mysql() { let temp_dir = tempdir().unwrap(); - let config = DashboardConfig { - bind_address: "127.0.0.1".to_string(), - port: 0, // Use random port - database_url: std::env::var("MYSQL_DATABASE_URL").unwrap_or_else(|_| { - "mysql://root:hammerwork@localhost:3307/hammerwork".to_string() - }), - pool_size: 2, - static_dir: temp_dir.path().to_path_buf(), - auth: AuthConfig { - enabled: false, - ..Default::default() - }, - enable_cors: false, - ..Default::default() - }; + let mut config = DashboardConfig::default(); + config.bind_address = "127.0.0.1".to_string(); + config.port = 0; + config.database_url = std::env::var("MYSQL_DATABASE_URL") + .unwrap_or_else(|_| "mysql://root:hammerwork@localhost:3307/hammerwork".to_string()); + config.pool_size = 2; + config.static_dir = temp_dir.path().to_path_buf(); + config.auth = AuthConfig::default().with_enabled(false); + config.enable_cors = false; // Create minimal static files write_index(temp_dir.path()); @@ -179,13 +163,11 @@ mod tests { let temp_dir = tempdir().unwrap(); write_index(temp_dir.path()); - let config = DashboardConfig { - bind_address: "127.0.0.1".to_string(), - port: 0, - database_url: "invalid://url".to_string(), - static_dir: temp_dir.path().to_path_buf(), - ..Default::default() - }; + let mut config = DashboardConfig::default(); + config.bind_address = "127.0.0.1".to_string(); + config.port = 0; + config.database_url = "invalid://url".to_string(); + config.static_dir = temp_dir.path().to_path_buf(); // The database URL is only used when the server starts, which must fail fast. let dashboard = WebDashboard::new(config).await.unwrap(); @@ -203,10 +185,8 @@ mod tests { fn test_static_directory_validation() { let non_existent_dir = PathBuf::from("/non/existent/directory"); - let config = DashboardConfig { - static_dir: non_existent_dir, - ..Default::default() - }; + let mut config = DashboardConfig::default(); + config.static_dir = non_existent_dir; // This should be handled gracefully or produce appropriate error assert!(!config.static_dir.exists()); @@ -231,13 +211,11 @@ mod tests { async fn test_websocket_config_validation() { use hammerwork_web::__private::config::WebSocketConfig; - let ws_config = WebSocketConfig { - ping_interval: Duration::from_secs(10), - max_connections: 50, - message_buffer_size: 512, - max_message_size: 32 * 1024, - ..Default::default() - }; + let ws_config = WebSocketConfig::default() + .with_ping_interval(Duration::from_secs(10)) + .with_max_connections(50) + .with_message_buffer_size(512) + .with_max_message_size(32 * 1024); assert_eq!(ws_config.ping_interval, Duration::from_secs(10)); assert_eq!(ws_config.max_connections, 50); @@ -323,14 +301,16 @@ mod websocket_archive_tests { }, ArchiveEvent::BulkArchiveCompleted { operation_id: "test_op_123".to_string(), - stats: ArchivalStats { - jobs_archived: 1000, - jobs_purged: 0, - bytes_archived: 50000, - bytes_purged: 0, - compression_ratio: 0.8, - operation_duration: std::time::Duration::from_secs(30), - last_run_at: Utc::now(), + 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 { @@ -419,13 +399,11 @@ mod websocket_archive_tests { #[tokio::test] async fn test_websocket_state_connection_management() { - let config = WebSocketConfig { - max_connections: 5, - ping_interval: Duration::from_secs(30), - message_buffer_size: 1024, - max_message_size: 64 * 1024, - ..Default::default() - }; + 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); diff --git a/src/alerting.rs b/src/alerting.rs index 14b2f45..1398636 100644 --- a/src/alerting.rs +++ b/src/alerting.rs @@ -14,6 +14,7 @@ pub const FAILED_ALERT_RETRY_DELAY: Duration = Duration::from_secs(60); /// Configuration for alerting thresholds and targets #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct AlertingConfig { /// Error rate threshold (0.0 to 1.0) that triggers alerts pub error_rate_threshold: Option, @@ -238,6 +239,7 @@ fn default_smtp_timeout_secs() -> u64 { /// config.validate().unwrap(); /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] pub struct SmtpConfig { /// SMTP server host name. pub host: String, @@ -433,6 +435,7 @@ impl std::fmt::Display for AlertType { /// An alert that has been triggered #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct Alert { /// Type of alert pub alert_type: AlertType, diff --git a/src/archive.rs b/src/archive.rs index fdcad6e..bae734d 100644 --- a/src/archive.rs +++ b/src/archive.rs @@ -209,6 +209,7 @@ pub enum ArchiveEvent { /// .purge_archived_after(Duration::days(365)); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ArchivalPolicy { /// How long to keep completed jobs before archiving. pub archive_completed_after: Option, @@ -462,6 +463,7 @@ impl ArchivalPolicy { /// Configuration for archive storage and compression settings. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ArchivalConfig { /// Default compression level (0-9, where 9 is maximum compression). pub compression_level: u32, @@ -555,15 +557,14 @@ impl ArchivalConfig { /// use chrono::Utc; /// use std::time::Duration; /// -/// let stats = ArchivalStats { -/// jobs_archived: 150, -/// jobs_purged: 25, -/// bytes_archived: 1024 * 1024, // 1MB -/// bytes_purged: 500 * 1024, // 500KB -/// compression_ratio: 0.7, // 30% size reduction -/// operation_duration: Duration::from_secs(45), -/// last_run_at: Utc::now(), -/// }; +/// let mut stats = ArchivalStats::default(); +/// stats.jobs_archived = 150; +/// stats.jobs_purged = 25; +/// stats.bytes_archived = 1024 * 1024; +/// stats.bytes_purged = 500 * 1024; +/// stats.compression_ratio = 0.7; +/// stats.operation_duration = Duration::from_secs(45); +/// stats.last_run_at = Utc::now(); /// /// assert_eq!(stats.jobs_archived, 150); /// assert_eq!(stats.compression_ratio, 0.7); @@ -575,6 +576,7 @@ impl ArchivalConfig { /// assert_eq!(default_stats.compression_ratio, 1.0); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ArchivalStats { /// Number of jobs archived in the last operation. pub jobs_archived: u64, @@ -622,17 +624,17 @@ impl Default for ArchivalStats { /// let job_id = Uuid::new_v4(); /// let now = Utc::now(); /// -/// let archived_job = ArchivedJob { -/// id: job_id, -/// queue_name: "email_queue".to_string(), -/// status: JobStatus::Completed, -/// created_at: now, -/// archived_at: now, -/// archival_reason: ArchivalReason::Automatic, -/// original_payload_size: Some(1024), -/// payload_compressed: true, -/// archived_by: Some("scheduler".to_string()), -/// }; +/// let archived_job = ArchivedJob::new( +/// job_id, +/// "email_queue", +/// JobStatus::Completed, +/// now, +/// now, +/// ArchivalReason::Automatic, +/// ) +/// .with_original_payload_size(1024) +/// .with_payload_compressed(true) +/// .with_archived_by("scheduler".to_string()); /// /// assert_eq!(archived_job.queue_name, "email_queue"); /// assert_eq!(archived_job.status, JobStatus::Completed); @@ -640,6 +642,7 @@ impl Default for ArchivalStats { /// assert!(archived_job.payload_compressed); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ArchivedJob { /// Unique identifier of the archived job. pub id: JobId, @@ -659,6 +662,51 @@ pub struct ArchivedJob { pub payload_compressed: bool, /// Who or what archived the job. pub archived_by: Option, + /// The workflow the job belonged to, if any. + #[serde(default)] + pub workflow_id: Option, + /// The name of the workflow the job belonged to, if any. + #[serde(default)] + pub workflow_name: Option, +} + +impl ArchivedJob { + /// An archived job record with no payload size, an uncompressed payload, and no + /// `archived_by` or workflow. Queue backends build these when listing the archive; + /// the constructor is public for code that lists archived jobs itself (such as the + /// dashboard) and for tests. + pub fn new( + id: JobId, + queue_name: impl Into, + status: JobStatus, + created_at: DateTime, + archived_at: DateTime, + archival_reason: ArchivalReason, + ) -> Self { + Self { + id, + queue_name: queue_name.into(), + status, + created_at, + archived_at, + archival_reason, + original_payload_size: None, + payload_compressed: false, + archived_by: None, + workflow_id: None, + workflow_name: None, + } + } +} + +with_setters! { + ArchivedJob { + with_original_payload_size(original_payload_size): Some(usize), + with_payload_compressed(payload_compressed): bool, + with_archived_by(archived_by): Some(String), + with_workflow_id(workflow_id): Some(crate::workflow::WorkflowId), + with_workflow_name(workflow_name): Some(String), + } } /// Upper bound on the number of `batch_size` batches a single @@ -688,6 +736,7 @@ where /// Result of one [`JobArchiver::run_scheduled_pass`]. #[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] pub struct ScheduledArchivalPass { /// Jobs moved to the archive table. pub jobs_archived: u64, @@ -1734,4 +1783,47 @@ mod tests { assert_eq!(ArchivalReason::Compliance.to_string(), "Compliance"); assert_eq!(ArchivalReason::Maintenance.to_string(), "Maintenance"); } + + /// #81: `ArchivedJob` built with its constructor and setters. + #[test] + fn test_archived_job_builder() { + let id = Uuid::new_v4(); + let workflow = Uuid::new_v4(); + let now = Utc::now(); + let job = ArchivedJob::new( + id, + "emails", + JobStatus::Dead, + now, + now, + ArchivalReason::Automatic, + ); + assert_eq!( + (job.original_payload_size, job.payload_compressed), + (None, false) + ); + assert_eq!((job.archived_by.as_deref(), job.workflow_id), (None, None)); + + let job = job + .with_original_payload_size(10) + .with_payload_compressed(true) + .with_archived_by("cli".to_string()) + .with_workflow_id(workflow) + .with_workflow_name("nightly".to_string()); + assert_eq!(job.id, id); + assert_eq!(job.queue_name, "emails"); + assert_eq!(job.original_payload_size, Some(10)); + assert!(job.payload_compressed); + assert_eq!(job.archived_by.as_deref(), Some("cli")); + assert_eq!(job.workflow_id, Some(workflow)); + assert_eq!(job.workflow_name.as_deref(), Some("nightly")); + + // Archives listed by older versions have no workflow fields. + let mut value = serde_json::to_value(&job).unwrap(); + let object = value.as_object_mut().unwrap(); + object.remove("workflow_id"); + object.remove("workflow_name"); + let decoded: ArchivedJob = serde_json::from_value(value).unwrap(); + assert_eq!((decoded.workflow_id, decoded.workflow_name), (None, None)); + } } diff --git a/src/batch.rs b/src/batch.rs index 97e1058..f86d19e 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -155,6 +155,7 @@ impl Decode<'_, MySql> for BatchStatus { /// Summary of batch processing results. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct BatchResult { /// Unique identifier for the batch. pub batch_id: BatchId, @@ -180,6 +181,7 @@ pub struct BatchResult { /// Configuration and container for a batch of jobs to be processed together. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct JobBatch { /// Unique identifier for this batch. pub id: BatchId, diff --git a/src/config.rs b/src/config.rs index 5a335d6..31a8440 100644 --- a/src/config.rs +++ b/src/config.rs @@ -268,6 +268,7 @@ mod chrono_duration_days_option { /// .with_job_timeout(std::time::Duration::from_secs(300)); /// ``` #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct HammerworkConfig { /// Database configuration pub database: DatabaseConfig, @@ -467,6 +468,7 @@ impl HammerworkConfig { /// /// `Debug` shows `url` with its password replaced by `***` ([`redact_url`]). #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct DatabaseConfig { /// Database connection URL pub url: String, @@ -572,6 +574,7 @@ impl Default for DatabaseConfig { /// Worker configuration #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WorkerConfig { /// Number of workers in the pool pub pool_size: usize, @@ -704,6 +707,7 @@ impl WorkerConfig { /// Webhook configurations container #[cfg(feature = "webhooks")] #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct WebhookConfigs { /// List of configured webhooks pub webhooks: Vec, @@ -715,6 +719,7 @@ pub struct WebhookConfigs { /// Global webhook settings #[cfg(feature = "webhooks")] #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebhookGlobalSettings { /// Maximum concurrent webhook deliveries pub max_concurrent_deliveries: usize, @@ -771,6 +776,7 @@ impl Default for WebhookGlobalSettings { feature = "kinesis" ))] #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct StreamingConfigs { /// List of configured streams pub streams: Vec, @@ -782,6 +788,7 @@ pub struct StreamingConfigs { /// Simple event filter for when webhooks feature is disabled #[cfg(not(feature = "webhooks"))] #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct SimpleEventFilter { /// Event types to include pub event_types: Vec, @@ -812,6 +819,7 @@ impl Default for SimpleEventFilter { feature = "kinesis" ))] #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamingGlobalSettings { /// Maximum concurrent stream processors pub max_concurrent_processors: usize, @@ -854,6 +862,7 @@ fn default_archive_check_interval() -> StdDuration { /// `delete_after`, every `check_interval` (see /// [`WorkerPool::with_archival`](crate::WorkerPool::with_archival)). #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ArchiveConfig { /// Whether automatic archiving is enabled pub enabled: bool, @@ -929,6 +938,7 @@ impl Default for ArchiveConfig { /// Rate limiting configuration #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct RateLimitingConfig { /// Whether rate limiting is enabled pub enabled: bool, @@ -967,6 +977,7 @@ type LoggingSubscriber = /// [`LoggingConfig::try_init`] (for example `config.logging.try_init()?`) once at /// startup to apply this section. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct LoggingConfig { /// Log filter: a level (trace, debug, info, warn, error) or any /// [`EnvFilter`](tracing_subscriber::EnvFilter) directive, such as @@ -1236,6 +1247,7 @@ impl std::fmt::Display for KeySourceRef { /// ``` #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] +#[non_exhaustive] pub struct PayloadEncryptionConfig { /// Whether the queue encrypts payloads. pub enabled: bool, @@ -1287,6 +1299,7 @@ pub struct PayloadEncryptionConfig { /// Several processes can rotate at once: each due key gets exactly one new version. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] +#[non_exhaustive] pub struct KeyRotationConfig { /// Whether the worker pool rotates due keys (default `false`). pub enabled: bool, @@ -1640,6 +1653,192 @@ impl HammerworkConfig { } } +// Builders for the `#[non_exhaustive]` configuration sections. Start from `default()` +// (or `HammerworkConfig::new()`) and chain these instead of writing struct literals. + +with_setters! { + HammerworkConfig { + with_database(database): DatabaseConfig, + with_worker(worker): WorkerConfig, + with_events(events): EventConfig, + #[cfg(feature = "webhooks")] + with_webhooks(webhooks): WebhookConfigs, + #[cfg(any( + feature = "streaming", + feature = "kafka", + feature = "google-pubsub", + feature = "kinesis" + ))] + with_streaming(streaming): StreamingConfigs, + #[cfg(feature = "alerting")] + with_alerting(alerting): AlertingConfig, + #[cfg(feature = "metrics")] + with_metrics(metrics): MetricsConfig, + with_archive(archive): ArchiveConfig, + with_rate_limiting(rate_limiting): RateLimitingConfig, + with_logging(logging): LoggingConfig, + with_encryption(encryption): PayloadEncryptionConfig, + } +} + +with_setters! { + DatabaseConfig { + with_url(url): Into(String), + with_pool_size(pool_size): u32, + with_connection_timeout_secs(connection_timeout_secs): u64, + with_auto_migrate(auto_migrate): bool, + } +} + +with_setters! { + WorkerConfig { + with_pool_size(pool_size): usize, + with_polling_interval(polling_interval): StdDuration, + with_job_timeout(job_timeout): StdDuration, + with_priority_weights(priority_weights): PriorityWeights, + with_retry_strategy(retry_strategy): RetryStrategy, + with_autoscaling_enabled(autoscaling_enabled): bool, + with_min_workers(min_workers): usize, + with_max_workers(max_workers): usize, + with_result_cleanup_enabled(result_cleanup_enabled): bool, + with_result_cleanup_interval(result_cleanup_interval): StdDuration, + with_batch_size(batch_size): Some(usize), + with_batch_concurrency(batch_concurrency): Some(usize), + } +} + +#[cfg(feature = "webhooks")] +with_setters! { + WebhookConfigs { + with_webhooks(webhooks): Vec, + with_global_settings(global_settings): WebhookGlobalSettings, + } +} + +#[cfg(feature = "webhooks")] +with_setters! { + WebhookGlobalSettings { + with_max_concurrent_deliveries(max_concurrent_deliveries): usize, + with_max_response_body_size(max_response_body_size): usize, + with_log_deliveries(log_deliveries): bool, + with_user_agent(user_agent): Into(String), + with_default_timeout_secs(default_timeout_secs): u64, + with_max_pending_deliveries(max_pending_deliveries): usize, + } +} + +#[cfg(any( + feature = "streaming", + feature = "kafka", + feature = "google-pubsub", + feature = "kinesis" +))] +with_setters! { + StreamingConfigs { + with_streams(streams): Vec, + with_global_settings(global_settings): StreamingGlobalSettings, + } +} + +#[cfg(any( + feature = "streaming", + feature = "kafka", + feature = "google-pubsub", + feature = "kinesis" +))] +with_setters! { + StreamingGlobalSettings { + with_max_concurrent_processors(max_concurrent_processors): usize, + with_log_operations(log_operations): bool, + with_global_flush_interval_secs(global_flush_interval_secs): u64, + } +} + +#[cfg(not(feature = "webhooks"))] +with_setters! { + SimpleEventFilter { + with_event_types(event_types): Vec, + with_queue_names(queue_names): Vec, + with_include_payload(include_payload): bool, + } +} + +with_setters! { + ArchiveConfig { + with_enabled(enabled): bool, + with_compression_level(compression_level): u32, + with_archive_after(archive_after): Duration, + with_delete_after(delete_after): Some(Duration), + with_check_interval(check_interval): StdDuration, + } +} + +with_setters! { + RateLimitingConfig { + with_enabled(enabled): bool, + with_default_throttle(default_throttle): ThrottleConfig, + with_queue_throttles(queue_throttles): HashMap, + } +} + +impl RateLimitingConfig { + /// Adds (or replaces) the throttle of one queue in + /// [`queue_throttles`](Self::queue_throttles). + #[must_use] + pub fn with_queue_throttle( + mut self, + queue_name: impl Into, + throttle: ThrottleConfig, + ) -> Self { + self.queue_throttles.insert(queue_name.into(), throttle); + self + } +} + +with_setters! { + LoggingConfig { + with_level(level): Into(String), + with_json_format(json_format): bool, + with_include_location(include_location): bool, + with_enable_tracing(enable_tracing): bool, + with_tracing_endpoint(tracing_endpoint): Some(String), + with_service_name(service_name): Into(String), + } +} + +with_setters! { + PayloadEncryptionConfig { + with_enabled(enabled): bool, + with_algorithm(algorithm): PayloadEncryptionAlgorithm, + with_key_source(key_source): KeySourceRef, + with_key_id(key_id): Some(String), + with_compression(compression): bool, + with_default_retention_secs(default_retention_secs): Some(u64), + with_purge_interval_secs(purge_interval_secs): Some(u64), + with_encrypted_queues(encrypted_queues): Vec, + with_key_rotation(key_rotation): KeyRotationConfig, + } +} + +impl PayloadEncryptionConfig { + /// Adds (or replaces) a key in [`decryption_keys`](Self::decryption_keys), for + /// payloads sealed under an earlier `key_id`. + #[must_use] + pub fn with_decryption_key(mut self, key_id: impl Into, source: KeySourceRef) -> Self { + self.decryption_keys.insert(key_id.into(), source); + self + } +} + +with_setters! { + KeyRotationConfig { + with_enabled(enabled): bool, + with_master_key_source(master_key_source): KeySourceRef, + with_check_interval_secs(check_interval_secs): u64, + with_max_key_versions(max_key_versions): u32, + } +} + #[cfg(test)] mod tests { use super::*; @@ -2875,4 +3074,183 @@ retry_strategy = { type = "Fixed", duration_ms = 1000 } KeySource::Environment("ROTATION_MASTER".to_string()) ); } + + /// #81: every configuration section can be built from its default with `with_*` + /// setters (the structs are `#[non_exhaustive]`). + #[test] + fn test_section_builders_set_their_fields() { + let worker = WorkerConfig::default() + .with_pool_size(8) + .with_polling_interval(StdDuration::from_millis(250)) + .with_job_timeout(StdDuration::from_secs(60)) + .with_retry_strategy(RetryStrategy::fixed(StdDuration::from_secs(5))) + .with_autoscaling_enabled(true) + .with_min_workers(2) + .with_max_workers(16) + .with_result_cleanup_enabled(false) + .with_result_cleanup_interval(StdDuration::from_secs(120)) + .with_batch_size(25) + .with_batch_concurrency(4); + assert_eq!(worker.pool_size, 8); + assert_eq!(worker.polling_interval, StdDuration::from_millis(250)); + assert_eq!(worker.job_timeout, StdDuration::from_secs(60)); + assert!(worker.autoscaling_enabled); + assert_eq!((worker.min_workers, worker.max_workers), (2, 16)); + assert!(!worker.result_cleanup_enabled); + assert_eq!(worker.result_cleanup_interval, StdDuration::from_secs(120)); + assert_eq!( + (worker.batch_size, worker.batch_concurrency), + (Some(25), Some(4)) + ); + worker.validate().unwrap(); + + let database = DatabaseConfig::default() + .with_url("postgres://localhost/jobs") + .with_pool_size(3) + .with_connection_timeout_secs(7) + .with_auto_migrate(true); + assert_eq!(database.url, "postgres://localhost/jobs"); + assert_eq!(database.pool_size, 3); + assert_eq!(database.connection_timeout(), StdDuration::from_secs(7)); + assert!(database.auto_migrate); + + let archive = ArchiveConfig::default() + .with_enabled(true) + .with_compression_level(9) + .with_archive_after(Duration::days(2)) + .with_delete_after(Duration::days(30)) + .with_check_interval(StdDuration::from_secs(600)); + assert!(archive.enabled); + assert_eq!(archive.compression_level, 9); + assert_eq!(archive.archive_after, Duration::days(2)); + assert_eq!(archive.delete_after, Some(Duration::days(30))); + assert_eq!(archive.check_interval, StdDuration::from_secs(600)); + + let throttle = ThrottleConfig::new().max_concurrent(2); + let rate_limiting = RateLimitingConfig::default() + .with_enabled(true) + .with_default_throttle(ThrottleConfig::new().rate_per_minute(60)) + .with_queue_throttle("emails", throttle.clone()); + assert!(rate_limiting.enabled); + assert_eq!(rate_limiting.default_throttle.rate_per_minute, Some(60)); + assert_eq!( + rate_limiting.throttle_for("emails").unwrap().max_concurrent, + Some(2) + ); + + let logging = LoggingConfig::default() + .with_level("debug") + .with_json_format(true) + .with_include_location(true) + .with_enable_tracing(true) + .with_tracing_endpoint("http://otel:4317".to_string()) + .with_service_name("billing"); + assert_eq!(logging.level, "debug"); + assert!(logging.json_format && logging.include_location && logging.enable_tracing); + assert_eq!( + logging.tracing_endpoint.as_deref(), + Some("http://otel:4317") + ); + assert_eq!(logging.service_name, "billing"); + + let rotation = KeyRotationConfig::default() + .with_enabled(true) + .with_master_key_source(KeySourceRef::parse("env://MASTER").unwrap()) + .with_check_interval_secs(30) + .with_max_key_versions(4); + let encryption = PayloadEncryptionConfig::default() + .with_enabled(true) + .with_algorithm(PayloadEncryptionAlgorithm::ChaCha20Poly1305) + .with_key_source(KeySourceRef::parse("env://PAYLOAD_KEY").unwrap()) + .with_key_id("k2".to_string()) + .with_compression(true) + .with_default_retention_secs(3600) + .with_purge_interval_secs(60) + .with_encrypted_queues(vec!["payments".to_string()]) + .with_decryption_key("k1", KeySourceRef::parse("env://OLD_KEY").unwrap()) + .with_key_rotation(rotation.clone()); + assert!(encryption.enabled && encryption.compression); + assert_eq!( + encryption.algorithm, + PayloadEncryptionAlgorithm::ChaCha20Poly1305 + ); + assert_eq!(encryption.key_source.as_str(), "env://PAYLOAD_KEY"); + assert_eq!(encryption.key_id.as_deref(), Some("k2")); + assert_eq!(encryption.default_retention_secs, Some(3600)); + assert_eq!( + encryption.purge_interval(), + Some(StdDuration::from_secs(60)) + ); + assert!(encryption.encrypts_queue("payments")); + assert_eq!(encryption.decryption_keys["k1"].as_str(), "env://OLD_KEY"); + assert_eq!(encryption.key_rotation, rotation); + + let events = EventConfig::default() + .with_max_buffer_size(10) + .with_include_payload_default(true) + .with_max_payload_size_bytes(1024) + .with_log_events(true); + + let config = HammerworkConfig::new() + .with_database(database.clone()) + .with_worker(worker.clone()) + .with_events(events) + .with_archive(archive) + .with_rate_limiting(rate_limiting) + .with_logging(logging) + .with_encryption(encryption); + assert_eq!(config.database.url, database.url); + assert_eq!(config.worker.batch_size, Some(25)); + assert_eq!(config.events.max_buffer_size, 10); + assert!(config.events.include_payload_default); + assert!(config.archive.enabled); + assert!(config.rate_limiting.enabled); + assert_eq!(config.logging.service_name, "billing"); + assert!(config.encryption.enabled); + } + + #[cfg(feature = "webhooks")] + #[test] + fn test_webhook_section_builders() { + let settings = WebhookGlobalSettings::default() + .with_max_concurrent_deliveries(5) + .with_max_response_body_size(512) + .with_log_deliveries(false) + .with_user_agent("acme/1.0") + .with_default_timeout_secs(9) + .with_max_pending_deliveries(50); + let webhooks = WebhookConfigs::default() + .with_webhooks(vec![WebhookConfig::new( + "hook".to_string(), + "https://example.com/hook".to_string(), + )]) + .with_global_settings(settings); + let manager: crate::webhooks::WebhookManagerConfig = (&webhooks.global_settings).into(); + assert_eq!(manager.max_concurrent_deliveries, 5); + assert_eq!(manager.max_response_body_size, 512); + assert!(!manager.log_deliveries); + assert_eq!(manager.user_agent, "acme/1.0"); + assert_eq!(manager.default_timeout_secs, 9); + assert_eq!(manager.max_pending_deliveries, 50); + let config = HammerworkConfig::new().with_webhooks(webhooks); + assert_eq!(config.webhooks.webhooks.len(), 1); + } + + #[cfg(feature = "streaming")] + #[test] + fn test_streaming_section_builders() { + let settings = StreamingGlobalSettings::default() + .with_max_concurrent_processors(3) + .with_log_operations(false) + .with_global_flush_interval_secs(2); + let streaming = StreamingConfigs::default() + .with_streams(vec![StreamConfig::default()]) + .with_global_settings(settings); + assert_eq!(streaming.streams.len(), 1); + assert_eq!(streaming.global_settings.max_concurrent_processors, 3); + assert!(!streaming.global_settings.log_operations); + assert_eq!(streaming.global_settings.global_flush_interval_secs, 2); + let config = HammerworkConfig::new().with_streaming(streaming); + assert_eq!(config.streaming.streams.len(), 1); + } } diff --git a/src/encryption.rs b/src/encryption.rs index 93b0488..eb59acb 100644 --- a/src/encryption.rs +++ b/src/encryption.rs @@ -220,6 +220,7 @@ impl Default for KeySource { /// # } /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct EncryptionConfig { /// The encryption algorithm to use. pub algorithm: EncryptionAlgorithm, @@ -584,6 +585,7 @@ impl RetentionPolicy { /// Contains information needed to decrypt the payload and manage /// its lifecycle according to retention policies. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct EncryptionMetadata { /// The encryption algorithm used. pub algorithm: EncryptionAlgorithm, @@ -746,6 +748,7 @@ impl EncryptionMetadata { /// Contains the encrypted payload along with all metadata needed /// for decryption and lifecycle management. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct EncryptedPayload { /// Base64-encoded encrypted data. pub ciphertext: String, @@ -831,6 +834,7 @@ impl EncryptedPayload { /// /// Provides metrics for monitoring encryption performance and usage. #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct EncryptionStats { /// Total number of jobs encrypted. pub jobs_encrypted: u64, diff --git a/src/encryption/key_manager.rs b/src/encryption/key_manager.rs index 163df9d..8186ae0 100644 --- a/src/encryption/key_manager.rs +++ b/src/encryption/key_manager.rs @@ -154,6 +154,7 @@ use uuid::Uuid; /// Configuration for the key management system #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct KeyManagerConfig { /// Source for the master key used to encrypt data encryption keys pub master_key_source: KeySource, @@ -181,6 +182,7 @@ pub struct KeyManagerConfig { /// /// `Debug` shows the names of the `auth_config` entries but never their values. #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ExternalKmsConfig { /// KMS service type (AWS, GCP, Azure, HashiCorp Vault, etc.) pub service_type: String, @@ -220,6 +222,7 @@ impl std::fmt::Debug for ExternalKmsConfig { /// Configuration for key derivation from passwords or passphrases #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct KeyDerivationConfig { /// Argon2 memory cost parameter (in KB) pub memory_cost: u32, @@ -236,6 +239,7 @@ pub struct KeyDerivationConfig { /// Represents an encryption key with its metadata #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct EncryptionKey { /// Unique identifier for the key pub id: Uuid, @@ -322,6 +326,7 @@ pub enum KeyStatus { /// Key usage audit record #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct KeyAuditRecord { /// Unique audit record ID pub id: Uuid, @@ -393,6 +398,7 @@ pub const DEFAULT_AUDIT_LOG_LIMIT: u32 = 100; /// # } /// ``` #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] pub struct KeyAuditFilter { /// Only records of this key pub key_id: Option, @@ -466,6 +472,7 @@ impl KeyAuditFilter { /// Statistics about key management operations #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct KeyManagerStats { /// Total number of keys managed pub total_keys: u64, @@ -515,6 +522,7 @@ const KMS_MASTER_KEY_NAME: &str = "key-manager/master"; /// key is stored, and it is decrypted with the KMS on load. #[doc(hidden)] #[derive(Debug, Clone)] +#[non_exhaustive] pub struct KmsWrappedKey { /// Row ID pub id: Uuid, @@ -772,13 +780,9 @@ impl KeyManagerConfig { /// auth_config.insert("access_key".to_string(), "AKIA...".to_string()); /// auth_config.insert("secret_key".to_string(), "secret...".to_string()); /// - /// let kms_config = ExternalKmsConfig { - /// service_type: "aws-kms".to_string(), - /// endpoint: "https://kms.us-east-1.amazonaws.com".to_string(), - /// auth_config, - /// region: Some("us-east-1".to_string()), - /// namespace: None, - /// }; + /// let kms_config = ExternalKmsConfig::new("aws-kms".to_string(), "https://kms.us-east-1.amazonaws.com".to_string()) + /// .with_auth_config(auth_config) + /// .with_region("us-east-1".to_string()); /// /// let config = KeyManagerConfig::new() /// .with_external_kms(kms_config); @@ -3903,6 +3907,50 @@ impl std::fmt::Display for KeyOperation { } } +impl ExternalKmsConfig { + /// A KMS configuration for `service_type` (such as `"AWS"`, `"GCP"`, `"Azure"` or + /// `"Vault"`) at `endpoint`, with no authentication settings, region or namespace. + pub fn new(service_type: impl Into, endpoint: impl Into) -> Self { + Self { + service_type: service_type.into(), + endpoint: endpoint.into(), + auth_config: HashMap::new(), + region: None, + namespace: None, + } + } + + /// Adds (or replaces) one entry of [`auth_config`](Self::auth_config). + #[must_use] + pub fn with_auth(mut self, key: impl Into, value: impl Into) -> Self { + self.auth_config.insert(key.into(), value.into()); + self + } +} + +with_setters! { + ExternalKmsConfig { + with_auth_config(auth_config): HashMap, + with_region(region): Some(String), + with_namespace(namespace): Some(String), + } +} + +with_setters! { + KeyDerivationConfig { + with_memory_cost(memory_cost): u32, + with_time_cost(time_cost): u32, + with_parallelism(parallelism): u32, + with_salt_length(salt_length): usize, + } +} + +with_setters! { + KeyManagerConfig { + with_key_derivation_config(key_derivation_config): KeyDerivationConfig, + } +} + #[cfg(test)] #[cfg_attr(not(any(feature = "postgres", feature = "mysql")), allow(dead_code))] mod tests { @@ -6228,4 +6276,38 @@ mod tests { assert_eq!(context["session_id"], "s"); assert!(audit_context(None, None, None).is_empty()); } + + /// #81: external KMS and key derivation settings built with constructors and + /// setters. + #[test] + fn test_kms_and_derivation_builders() { + let kms = ExternalKmsConfig::new("AWS", "https://kms.example.com") + .with_auth("access_key_id", "AKIA") + .with_region("us-east-1".to_string()) + .with_namespace("jobs".to_string()); + assert_eq!(kms.service_type, "AWS"); + assert_eq!(kms.endpoint, "https://kms.example.com"); + assert_eq!(kms.auth_config["access_key_id"], "AKIA"); + assert_eq!(kms.region.as_deref(), Some("us-east-1")); + assert_eq!(kms.namespace.as_deref(), Some("jobs")); + let kms = kms.with_auth_config(HashMap::new()); + assert!(kms.auth_config.is_empty()); + + let derivation = KeyDerivationConfig::default() + .with_memory_cost(1024) + .with_time_cost(2) + .with_parallelism(1) + .with_salt_length(16); + assert_eq!( + ( + derivation.memory_cost, + derivation.time_cost, + derivation.parallelism, + derivation.salt_length + ), + (1024, 2, 1, 16) + ); + let config = KeyManagerConfig::new().with_key_derivation_config(derivation); + assert_eq!(config.key_derivation_config.memory_cost, 1024); + } } diff --git a/src/events.rs b/src/events.rs index 0980df1..b88899f 100644 --- a/src/events.rs +++ b/src/events.rs @@ -103,20 +103,20 @@ //! job_id, //! queue_name, //! JobPriority::High, -//! JobError { -//! message: "Database connection failed".to_string(), -//! error_type: Some("ConnectionError".to_string()), -//! details: None, -//! retry_attempt: Some(2), -//! }, +//! JobError::new("Database connection failed".to_string()) +//! .with_error_type("ConnectionError".to_string()) +//! .with_retry_attempt(2), //! ); //! ``` use crate::priority::JobPriority; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, sync::Arc}; -use tokio::sync::{RwLock, broadcast}; +use std::{ + collections::HashMap, + sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak}, +}; +use tokio::sync::broadcast; use uuid::Uuid; /// Module for serializing UUID as string for TOML compatibility @@ -155,24 +155,23 @@ mod uuid_string { /// use chrono::Utc; /// use std::collections::HashMap; /// -/// let event = JobLifecycleEvent { -/// event_id: Uuid::new_v4(), -/// job_id: Uuid::new_v4(), -/// queue_name: "email_queue".to_string(), -/// event_type: JobLifecycleEventType::Completed, -/// priority: JobPriority::Normal, -/// timestamp: Utc::now(), -/// processing_time_ms: Some(1500), -/// error: None, -/// payload: Some(serde_json::json!({"recipient": "user@example.com"})), -/// metadata: { -/// let mut meta = HashMap::new(); -/// meta.insert("tenant_id".to_string(), "acme_corp".to_string()); -/// meta -/// }, -/// }; +/// let mut metadata = HashMap::new(); +/// metadata.insert("tenant_id".to_string(), "acme_corp".to_string()); +/// +/// let event = JobLifecycleEvent::new( +/// Uuid::new_v4(), +/// "email_queue", +/// JobLifecycleEventType::Completed, +/// JobPriority::Normal, +/// ) +/// .with_timestamp(Utc::now()) +/// .with_processing_time_ms(1500) +/// .with_payload(serde_json::json!({"recipient": "user@example.com"})) +/// .with_metadata(metadata); +/// assert!(event.error.is_none()); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct JobLifecycleEvent { /// Unique identifier for this event #[serde(with = "uuid_string")] @@ -226,6 +225,7 @@ pub enum JobLifecycleEventType { /// Error information for failed jobs #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct JobError { /// Error message pub message: String, @@ -271,6 +271,7 @@ pub struct JobError { /// ]); /// ``` #[derive(Debug, Clone, Serialize, Deserialize, Default)] +#[non_exhaustive] pub struct EventFilter { /// Filter by event types (empty means all types) pub event_types: Vec, @@ -392,11 +393,28 @@ impl EventFilter { } } +/// The registered filters of an [`EventManager`], keyed by subscription id. +/// +/// A std lock (not tokio's) so that [`EventSubscription`]'s `Drop` can unregister +/// without an async runtime. It is never held across an `.await`. +type SubscriptionMap = RwLock>; + +fn read_map(map: &SubscriptionMap) -> RwLockReadGuard<'_, HashMap> { + // The map stays consistent even if a holder panicked: every update is one call. + map.read().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn write_map(map: &SubscriptionMap) -> RwLockWriteGuard<'_, HashMap> { + map.write().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + /// Event subscription for receiving filtered events. /// -/// Dropping a subscription does not unregister it: call -/// [`EventManager::unsubscribe`] with its `id` when done, so its filter stops counting -/// toward [`EventManager::subscription_count`] and [`EventManager::payload_wanted`]. +/// Dropping a subscription unregisters it from its [`EventManager`], so its filter +/// stops counting toward [`EventManager::subscription_count`] and +/// [`EventManager::payload_wanted`]. [`EventManager::unsubscribe`] does the same +/// ahead of the drop. Keep the subscription (not just its `receiver`) alive for as +/// long as you read events: the fields can be borrowed but not moved out. #[derive(Debug)] pub struct EventSubscription { /// Unique identifier for this subscription @@ -405,6 +423,16 @@ pub struct EventSubscription { pub filter: EventFilter, /// Channel receiver for receiving events pub receiver: broadcast::Receiver, + /// The manager's subscription map, to unregister from on drop. + registry: Weak, +} + +impl Drop for EventSubscription { + fn drop(&mut self) { + if let Some(registry) = self.registry.upgrade() { + write_map(®istry).remove(&self.id); + } + } } /// Event manager for publishing and subscribing to job lifecycle events. @@ -429,12 +457,11 @@ pub struct EventSubscription { /// # #[tokio::main] /// # async fn main() -> Result<(), Box> { /// // Create a manager with custom configuration -/// let config = EventConfig { -/// max_buffer_size: 5000, -/// include_payload_default: true, -/// max_payload_size_bytes: 128 * 1024, // 128KB -/// log_events: true, -/// }; +/// let config = EventConfig::default() +/// .with_max_buffer_size(5000) +/// .with_include_payload_default(true) +/// .with_max_payload_size_bytes(128 * 1024) +/// .with_log_events(true); /// let manager = Arc::new(EventManager::new(config)); /// /// // Subscribe to events @@ -450,12 +477,9 @@ pub struct EventSubscription { /// Uuid::new_v4(), /// "background_queue".to_string(), /// JobPriority::Low, -/// hammerwork::events::JobError { -/// message: "Service unavailable".to_string(), -/// error_type: Some("ServiceError".to_string()), -/// details: None, -/// retry_attempt: Some(1), -/// }, +/// hammerwork::events::JobError::new("Service unavailable".to_string()) +/// .with_error_type("ServiceError".to_string()) +/// .with_retry_attempt(1), /// ); /// let _ = manager_clone.publish_event(event).await; /// }); @@ -477,13 +501,14 @@ pub struct EventManager { /// Broadcast sender for publishing events to all subscribers sender: broadcast::Sender, /// Active subscriptions (for management purposes) - subscriptions: Arc>>, + subscriptions: Arc, /// Configuration for event publishing config: EventConfig, } /// Configuration for the event system #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct EventConfig { /// Maximum number of events to buffer in broadcast channel pub max_buffer_size: usize, @@ -631,9 +656,7 @@ impl EventManager { if self.config.include_payload_default { return true; } - self.subscriptions - .read() - .await + read_map(&self.subscriptions) .values() .any(|filter| filter.include_payload) } @@ -646,8 +669,8 @@ impl EventManager { /// Subscribe to job lifecycle events with a filter. /// - /// Call [`unsubscribe`](Self::unsubscribe) with the subscription's `id` when done: - /// dropping the subscription leaves its filter registered. + /// Dropping the returned subscription unregisters it (as does + /// [`unsubscribe`](Self::unsubscribe) with its `id`). /// /// Creates a new subscription that will receive events matching the provided filter. /// The returned `EventSubscription` contains a broadcast receiver that will receive @@ -690,36 +713,35 @@ impl EventManager { let receiver = self.sender.subscribe(); // Store subscription for management - { - let mut subscriptions = self.subscriptions.write().await; - subscriptions.insert(subscription_id, filter.clone()); - } + write_map(&self.subscriptions).insert(subscription_id, filter.clone()); Ok(EventSubscription { id: subscription_id, filter, receiver, + registry: Arc::downgrade(&self.subscriptions), }) } - /// Unsubscribe from events + /// Unregister a subscription ahead of dropping it. + /// + /// Dropping an [`EventSubscription`] unregisters it too; this is for code that + /// only kept the id, or that wants the filter gone before the subscription drops. pub async fn unsubscribe(&self, subscription_id: Uuid) -> crate::Result<()> { - let mut subscriptions = self.subscriptions.write().await; - subscriptions.remove(&subscription_id); + write_map(&self.subscriptions).remove(&subscription_id); Ok(()) } /// Get count of active subscriptions pub async fn subscription_count(&self) -> usize { - let subscriptions = self.subscriptions.read().await; - subscriptions.len() + read_map(&self.subscriptions).len() } /// Get event manager statistics pub async fn get_stats(&self) -> EventManagerStats { - let subscriptions = self.subscriptions.read().await; + let active_subscriptions = read_map(&self.subscriptions).len(); EventManagerStats { - active_subscriptions: subscriptions.len(), + active_subscriptions, buffer_capacity: self.config.max_buffer_size, buffer_current_size: self.sender.len(), } @@ -728,6 +750,7 @@ impl EventManager { /// Statistics about the event manager #[derive(Debug, Serialize, Deserialize)] +#[non_exhaustive] pub struct EventManagerStats { /// Number of active subscriptions pub active_subscriptions: usize, @@ -919,6 +942,71 @@ impl std::fmt::Display for JobLifecycleEventType { } } +impl JobLifecycleEvent { + /// An event of `event_type` for the job `job_id`, with a new event id, timestamped + /// now, and no processing time, error, payload or metadata. The + /// [`JobLifecycleEventBuilder`] constructors (`enqueued`, `failed`, ...) cover the + /// common event types. + pub fn new( + job_id: Uuid, + queue_name: impl Into, + event_type: JobLifecycleEventType, + priority: JobPriority, + ) -> Self { + Self { + event_id: Uuid::new_v4(), + job_id, + queue_name: queue_name.into(), + event_type, + priority, + timestamp: Utc::now(), + processing_time_ms: None, + error: None, + payload: None, + metadata: HashMap::new(), + } + } +} + +with_setters! { + JobLifecycleEvent { + with_timestamp(timestamp): DateTime, + with_processing_time_ms(processing_time_ms): Some(u64), + with_error(error): Some(JobError), + with_payload(payload): Some(serde_json::Value), + with_metadata(metadata): HashMap, + } +} + +with_setters! { + EventConfig { + with_max_buffer_size(max_buffer_size): usize, + with_include_payload_default(include_payload_default): bool, + with_max_payload_size_bytes(max_payload_size_bytes): usize, + with_log_events(log_events): bool, + } +} + +impl JobError { + /// An error with `message` and no type, details or retry attempt. + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + error_type: None, + details: None, + retry_attempt: None, + } + } +} + +with_setters! { + JobError { + with_error_type(error_type): Some(String), + with_details(details): Some(String), + with_retry_attempt(retry_attempt): Some(u32), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1592,4 +1680,101 @@ mod tests { assert!(defaulted.delivers_payload(&EventFilter::new())); assert!(defaulted.payload_wanted().await); } + + /// Dropping a subscription unregisters it: the count drops and its + /// `include_payload` filter stops making `payload_wanted` true. + #[tokio::test] + async fn dropping_subscription_unregisters_it() { + let manager = EventManager::new_default(); + let keep = manager.subscribe(EventFilter::new()).await.unwrap(); + let wants = manager + .subscribe(EventFilter::new().include_payload()) + .await + .unwrap(); + assert_eq!(manager.subscription_count().await, 2); + assert!(manager.payload_wanted().await); + + drop(wants); + assert_eq!(manager.subscription_count().await, 1); + assert!(!manager.payload_wanted().await); + assert_eq!(manager.get_stats().await.active_subscriptions, 1); + + // Unsubscribing first and dropping afterwards is fine. + manager.unsubscribe(keep.id).await.unwrap(); + drop(keep); + assert_eq!(manager.subscription_count().await, 0); + } + + /// A subscription can be dropped outside a runtime, and after its manager. + #[test] + fn subscription_drop_needs_no_runtime() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let manager = EventManager::new_default(); + let first = runtime + .block_on(manager.subscribe(EventFilter::new())) + .unwrap(); + let second = runtime + .block_on(manager.subscribe(EventFilter::new())) + .unwrap(); + drop(runtime); + + drop(first); + let count = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(manager.subscription_count()); + assert_eq!(count, 1); + + drop(manager); + drop(second); + } + + /// #81: events and errors built with constructors and setters. + #[test] + fn test_event_and_error_builders() { + let error = JobError::new("boom") + .with_error_type("Timeout".to_string()) + .with_details("after 30s".to_string()) + .with_retry_attempt(2); + assert_eq!(error.message, "boom"); + assert_eq!(error.error_type.as_deref(), Some("Timeout")); + assert_eq!(error.details.as_deref(), Some("after 30s")); + assert_eq!(error.retry_attempt, Some(2)); + + let job_id = Uuid::new_v4(); + let at = Utc::now() - chrono::Duration::seconds(5); + let event = JobLifecycleEvent::new( + job_id, + "emails", + JobLifecycleEventType::Failed, + JobPriority::High, + ) + .with_timestamp(at) + .with_processing_time_ms(42) + .with_error(error) + .with_payload(serde_json::json!({"a": 1})) + .with_metadata(HashMap::from([("k".to_string(), "v".to_string())])); + assert_eq!( + (event.job_id, event.queue_name.as_str()), + (job_id, "emails") + ); + assert_eq!(event.event_type, JobLifecycleEventType::Failed); + assert_eq!(event.priority, JobPriority::High); + assert_eq!(event.timestamp, at); + assert_eq!(event.processing_time_ms, Some(42)); + assert_eq!(event.error.unwrap().message, "boom"); + assert_eq!(event.payload, Some(serde_json::json!({"a": 1}))); + assert_eq!(event.metadata["k"], "v"); + + let config = EventConfig::default() + .with_max_buffer_size(7) + .with_include_payload_default(true) + .with_max_payload_size_bytes(99) + .with_log_events(true); + assert_eq!(config.max_buffer_size, 7); + assert!(config.include_payload_default && config.log_events); + assert_eq!(config.max_payload_size_bytes, 99); + } } diff --git a/src/job.rs b/src/job.rs index 1299258..34c95fd 100644 --- a/src/job.rs +++ b/src/job.rs @@ -260,6 +260,7 @@ pub enum ResultStorage { /// .with_ttl(Duration::from_secs(3600)); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct ResultConfig { /// Where to store the job results. pub storage: ResultStorage, @@ -407,6 +408,7 @@ impl Default for ResultConfig { /// assert!(job.scheduled_at > job.created_at); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct Job { /// Unique identifier for this job. pub id: JobId, diff --git a/src/lib.rs b/src/lib.rs index d84a95b..b74f5cb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -151,19 +151,14 @@ //! // Set up Kafka streaming for analytics //! let stream_manager = StreamManager::new_default(event_manager.clone()); //! -//! let kafka_stream = StreamConfig { -//! id: uuid::Uuid::new_v4(), -//! name: "analytics_stream".to_string(), -//! backend: StreamBackend::Kafka { +//! let kafka_stream = StreamConfig::new("analytics_stream".to_string(), StreamBackend::Kafka { //! brokers: vec!["localhost:9092".to_string()], //! topic: "job-events".to_string(), //! config: HashMap::new(), -//! }, -//! filter: EventFilter::new().include_payload(), -//! partitioning: PartitioningStrategy::QueueName, -//! enabled: true, -//! ..Default::default() -//! }; +//! }) +//! .with_filter(EventFilter::new().include_payload()) +//! .with_partitioning(PartitioningStrategy::QueueName) +//! .enabled(true); //! //! stream_manager.add_stream(kafka_stream).await?; //! @@ -228,6 +223,9 @@ //! - `encryption` - Enable job payload encryption and PII protection //! - `tracing` - Enable OpenTelemetry distributed tracing +#[macro_use] +mod macros; + pub mod archive; pub mod batch; pub mod config; diff --git a/src/macros.rs b/src/macros.rs new file mode 100644 index 0000000..eeae578 --- /dev/null +++ b/src/macros.rs @@ -0,0 +1,56 @@ +//! Internal macros. + +/// Generate `with_*` builder methods that set one public field each. +/// +/// ```ignore +/// with_setters! { +/// WorkerConfig { +/// with_pool_size(pool_size): usize, +/// with_batch_size(batch_size): Some(usize), // sets `Some(value)` +/// with_user_agent(user_agent): Into(String), // takes `impl Into` +/// } +/// } +/// ``` +/// +/// Configuration structs are `#[non_exhaustive]`, so code outside the crate builds them +/// from `Default` (or a constructor) and these setters instead of struct literals. +macro_rules! with_setters { + ($ty:ty { $($items:tt)* }) => { + impl $ty { + with_setters!(@items $($items)*); + } + }; + (@items) => {}; + (@items $(#[$attr:meta])* $name:ident($field:ident): Some($fty:ty) $(, $($rest:tt)*)?) => { + #[doc = concat!( + "Sets [`", stringify!($field), "`](Self::", stringify!($field), ") to `Some(value)`." + )] + $(#[$attr])* + #[must_use] + pub fn $name(mut self, value: $fty) -> Self { + self.$field = Some(value); + self + } + with_setters!(@items $($($rest)*)?); + }; + (@items $(#[$attr:meta])* $name:ident($field:ident): Into($fty:ty) $(, $($rest:tt)*)?) => { + #[doc = concat!("Sets [`", stringify!($field), "`](Self::", stringify!($field), ").")] + $(#[$attr])* + #[must_use] + pub fn $name(mut self, value: impl Into<$fty>) -> Self { + self.$field = value.into(); + self + } + with_setters!(@items $($($rest)*)?); + }; + (@items $(#[$attr:meta])* $name:ident($field:ident): $fty:ty $(, $($rest:tt)*)?) => { + #[doc = concat!("Sets [`", stringify!($field), "`](Self::", stringify!($field), ").")] + $(#[$attr])* + #[must_use] + pub fn $name(mut self, value: $fty) -> Self { + self.$field = value; + self + } + with_setters!(@items $($($rest)*)?); + }; +} diff --git a/src/metrics.rs b/src/metrics.rs index a73dc7d..91e1902 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -62,6 +62,7 @@ const MIN_UPDATE_INTERVAL: Duration = Duration::from_secs(1); /// Configuration for metrics collection #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct MetricsConfig { /// HTTP server address for metrics exposition (as string) #[serde( diff --git a/src/migrations/mod.rs b/src/migrations/mod.rs index 6996305..8ce1e0c 100644 --- a/src/migrations/mod.rs +++ b/src/migrations/mod.rs @@ -60,6 +60,7 @@ use tracing::info; /// Migration identifier and metadata #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct Migration { /// Unique migration identifier (e.g., "001_initial_schema") pub id: String, @@ -71,8 +72,27 @@ pub struct Migration { pub created_at: DateTime, } +impl Migration { + /// A migration `id` (such as `"021_add_my_table"`) at `version`, created now. + pub fn new(id: impl Into, description: impl Into, version: u32) -> Self { + Self { + id: id.into(), + description: description.into(), + version, + created_at: Utc::now(), + } + } +} + +with_setters! { + Migration { + with_created_at(created_at): DateTime, + } +} + /// Migration execution record #[derive(Debug, Clone)] +#[non_exhaustive] pub struct MigrationRecord { pub migration_id: String, pub executed_at: DateTime, diff --git a/src/priority.rs b/src/priority.rs index 671077b..c6be146 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -460,6 +460,7 @@ pub enum PrioritySelectionStrategy { /// Priority queue statistics #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct PriorityStats { /// Number of jobs per priority level pub job_counts: HashMap, diff --git a/src/queue/lifecycle.rs b/src/queue/lifecycle.rs index 8dbc613..1063311 100644 --- a/src/queue/lifecycle.rs +++ b/src/queue/lifecycle.rs @@ -169,6 +169,7 @@ impl JobOutcome { /// What [`DatabaseQueue::finish_job_run`](super::DatabaseQueue::finish_job_run) (or a /// manual transition) recorded. #[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] pub struct RecordedOutcome { /// The status the job is in now: the terminal status, or `Pending` for a retry or a /// recurring job rescheduled for its next run. diff --git a/src/queue/mod.rs b/src/queue/mod.rs index f82ef03..696f3ab 100644 --- a/src/queue/mod.rs +++ b/src/queue/mod.rs @@ -60,6 +60,7 @@ mod private { /// Information about a queue's pause state #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct QueuePauseInfo { /// Name of the paused queue pub queue_name: String, diff --git a/src/queue/mysql.rs b/src/queue/mysql.rs index aeefefb..2e9ce9b 100644 --- a/src/queue/mysql.rs +++ b/src/queue/mysql.rs @@ -1815,7 +1815,7 @@ impl DatabaseQueue for crate::queue::JobQueue { ) -> Result> { use crate::archive::ArchivedJob; - let mut query = "SELECT id, queue_name, status, created_at, archived_at, archival_reason, original_payload_size, payload_compressed, archived_by FROM hammerwork_jobs_archive".to_string(); + let mut query = "SELECT id, queue_name, status, created_at, archived_at, archival_reason, original_payload_size, payload_compressed, archived_by, workflow_id, workflow_name FROM hammerwork_jobs_archive".to_string(); let mut conditions = Vec::new(); if queue_name.is_some() { @@ -1865,6 +1865,11 @@ impl DatabaseQueue for crate::queue::JobQueue { .transpose()?, payload_compressed: row.try_get("payload_compressed")?, archived_by: row.try_get("archived_by")?, + workflow_id: row + .try_get::, _>("workflow_id")? + .map(|id| uuid::Uuid::parse_str(&id)) + .transpose()?, + workflow_name: row.try_get("workflow_name")?, }) }; Ok(super::decodable_rows( diff --git a/src/queue/postgres.rs b/src/queue/postgres.rs index d91630e..a5260ec 100644 --- a/src/queue/postgres.rs +++ b/src/queue/postgres.rs @@ -1616,7 +1616,7 @@ impl DatabaseQueue for crate::queue::JobQueue { ) -> Result> { use crate::archive::ArchivedJob; - let mut query = "SELECT id, queue_name, status, created_at, archived_at, archival_reason, original_payload_size, payload_compressed, archived_by FROM hammerwork_jobs_archive".to_string(); + let mut query = "SELECT id, queue_name, status, created_at, archived_at, archival_reason, original_payload_size, payload_compressed, archived_by, workflow_id, workflow_name FROM hammerwork_jobs_archive".to_string(); let mut conditions = Vec::new(); if let Some(_queue) = queue_name { @@ -1677,6 +1677,8 @@ impl DatabaseQueue for crate::queue::JobQueue { .transpose()?, payload_compressed: row.try_get("payload_compressed")?, archived_by: row.try_get("archived_by")?, + workflow_id: row.try_get("workflow_id")?, + workflow_name: row.try_get("workflow_name")?, }) }; Ok(super::decodable_rows( diff --git a/src/queue/test.rs b/src/queue/test.rs index 613a679..9785cda 100644 --- a/src/queue/test.rs +++ b/src/queue/test.rs @@ -2858,6 +2858,8 @@ impl DatabaseQueue for TestQueue { original_payload_size: Some(payload_size), payload_compressed: false, // Mock archived_by: Some("test".to_string()), // Mock user + workflow_id: job.workflow_id, + workflow_name: job.workflow_name.clone(), }); } diff --git a/src/rate_limit.rs b/src/rate_limit.rs index b028c84..61770e3 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -76,6 +76,7 @@ impl RateLimit { /// Throttling configuration for queues #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[non_exhaustive] pub struct ThrottleConfig { /// Maximum number of concurrent jobs for this queue pub max_concurrent: Option, diff --git a/src/spawn.rs b/src/spawn.rs index 1e65620..8561148 100644 --- a/src/spawn.rs +++ b/src/spawn.rs @@ -17,6 +17,7 @@ use std::sync::Arc; /// Result of a spawn operation containing information about spawned jobs. #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct SpawnResult { /// The parent job that performed the spawn operation pub parent_job_id: JobId, @@ -54,14 +55,13 @@ pub struct SpawnResult { /// ```rust /// use hammerwork::spawn::SpawnConfig; /// -/// let config = SpawnConfig { -/// max_spawn_count: Some(50), // Limit to 50 files -/// inherit_priority: true, // Inherit parent priority -/// inherit_retry_strategy: true, // Inherit retry settings -/// inherit_timeout: false, // Each file has own timeout -/// inherit_trace_context: true, // Maintain tracing -/// operation_id: Some("file_batch_001".to_string()), -/// }; +/// let config = SpawnConfig::default() +/// .with_max_spawn_count(50) +/// .with_inherit_priority(true) +/// .with_inherit_retry_strategy(true) +/// .with_inherit_timeout(false) +/// .with_inherit_trace_context(true) +/// .with_operation_id("file_batch_001".to_string()); /// ``` /// /// ## Configuration for Large Data Processing @@ -69,16 +69,16 @@ pub struct SpawnResult { /// ```rust /// use hammerwork::spawn::SpawnConfig; /// -/// let config = SpawnConfig { -/// max_spawn_count: Some(1000), // Allow many chunks -/// inherit_priority: false, // Let chunks be normal priority -/// inherit_retry_strategy: true, // Inherit retry logic -/// inherit_timeout: true, // Inherit timeout settings -/// inherit_trace_context: true, // Maintain trace correlation -/// operation_id: Some("data_processing_2024_01".to_string()), -/// }; +/// let config = SpawnConfig::default() +/// .with_max_spawn_count(1000) +/// .with_inherit_priority(false) +/// .with_inherit_retry_strategy(true) +/// .with_inherit_timeout(true) +/// .with_inherit_trace_context(true) +/// .with_operation_id("data_processing_2024_01".to_string()); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct SpawnConfig { /// Maximum number of child jobs that can be spawned by a single parent pub max_spawn_count: Option, @@ -108,6 +108,7 @@ impl Default for SpawnConfig { } /// Context provided to spawn handlers with information about the parent job. +#[non_exhaustive] pub struct SpawnContext { /// The parent job that is spawning child jobs pub parent_job: Job, @@ -117,6 +118,23 @@ pub struct SpawnContext { pub queue: Arc + Send + Sync>, } +impl SpawnContext { + /// The context of `parent_job` spawning on `queue` with `config`. The + /// [`SpawnManager`] builds these; the constructor is for testing a + /// [`SpawnHandler`] directly. + pub fn new( + parent_job: Job, + config: SpawnConfig, + queue: Arc + Send + Sync>, + ) -> Self { + Self { + parent_job, + config, + queue, + } + } +} + /// Error types specific to spawn operations. #[derive(Debug, thiserror::Error)] pub enum SpawnError { @@ -463,11 +481,7 @@ impl SpawnManager { handler.validate_spawn(job, config).await?; // Generate child jobs - let context = SpawnContext { - parent_job: job.clone(), - config: config.clone(), - queue, - }; + let context = SpawnContext::new(job.clone(), config.clone(), queue); let mut child_jobs = handler.spawn_jobs(context).await?; // Check spawn limits @@ -572,14 +586,13 @@ impl Default for SpawnManager { /// use hammerwork::{Job, spawn::{JobSpawnExt, SpawnConfig}}; /// use serde_json::json; /// -/// let spawn_config = SpawnConfig { -/// max_spawn_count: Some(10), -/// inherit_priority: true, -/// inherit_retry_strategy: false, -/// inherit_timeout: true, -/// inherit_trace_context: true, -/// operation_id: Some("batch_001".to_string()), -/// }; +/// let spawn_config = SpawnConfig::default() +/// .with_max_spawn_count(10) +/// .with_inherit_priority(true) +/// .with_inherit_retry_strategy(false) +/// .with_inherit_timeout(true) +/// .with_inherit_trace_context(true) +/// .with_operation_id("batch_001".to_string()); /// /// let job = Job::new("data_processing".to_string(), json!({"records": 5000})) /// .as_high_priority() @@ -708,6 +721,17 @@ pub fn spawn_config_from_payload(payload: &serde_json::Value) -> Result, + event_type: JobEventType, + priority: JobPriority, + ) -> Self { + Self { + job_id, + queue_name: queue_name.into(), + event_type, + priority, + processing_time_ms: None, + error_message: None, + timestamp: Utc::now(), + } + } +} + +with_setters! { + JobEvent { + with_processing_time_ms(processing_time_ms): Some(u64), + with_error_message(error_message): Some(String), + with_timestamp(timestamp): DateTime, + } +} + #[cfg(test)] mod tests { use super::*; @@ -1311,4 +1353,28 @@ mod tests { assert_eq!(stats.error_rate, 0.5); assert_eq!(stats.running, 0); } + + /// #81: `JobEvent` and `StatsConfig` built with constructors and setters. + #[test] + fn test_job_event_and_stats_config_builders() { + let id = uuid::Uuid::new_v4(); + let at = Utc::now() - chrono::Duration::seconds(1); + let event = JobEvent::new(id, "q", JobEventType::Failed, JobPriority::Low) + .with_processing_time_ms(10) + .with_error_message("boom".to_string()) + .with_timestamp(at); + assert_eq!((event.job_id, event.queue_name.as_str()), (id, "q")); + assert_eq!(event.event_type, JobEventType::Failed); + assert_eq!(event.priority, JobPriority::Low); + assert_eq!(event.processing_time_ms, Some(10)); + assert_eq!(event.error_message.as_deref(), Some("boom")); + assert_eq!(event.timestamp, at); + + let config = StatsConfig::default() + .with_max_events(5) + .with_max_event_age_secs(60) + .with_collect_timing(false); + assert_eq!((config.max_events, config.max_event_age_secs), (5, 60)); + assert!(!config.collect_timing); + } } diff --git a/src/streaming.rs b/src/streaming.rs index 167e214..efdeed1 100644 --- a/src/streaming.rs +++ b/src/streaming.rs @@ -44,21 +44,16 @@ //! StreamManagerConfig::default() //! ); //! -//! let stream = StreamConfig { -//! id: uuid::Uuid::new_v4(), -//! name: "job_events_kafka".to_string(), -//! backend: StreamBackend::Kafka { +//! let stream = StreamConfig::new("job_events_kafka".to_string(), StreamBackend::Kafka { //! brokers: vec!["localhost:9092".to_string()], //! topic: "hammerwork-job-events".to_string(), //! config: HashMap::new(), -//! }, -//! filter: EventFilter::new() -//! .with_event_types(vec![JobLifecycleEventType::Completed, JobLifecycleEventType::Failed]), -//! partitioning: PartitioningStrategy::QueueName, -//! serialization: SerializationFormat::Json, -//! enabled: true, -//! ..Default::default() -//! }; +//! }) +//! .with_filter(EventFilter::new() +//! .with_event_types(vec![JobLifecycleEventType::Completed, JobLifecycleEventType::Failed])) +//! .with_partitioning(PartitioningStrategy::QueueName) +//! .with_serialization(SerializationFormat::Json) +//! .enabled(true); //! //! stream_manager.add_stream(stream).await?; //! # Ok(()) @@ -72,25 +67,20 @@ //! use hammerwork::events::EventFilter; //! use std::collections::HashMap; //! -//! let stream = StreamConfig { -//! id: uuid::Uuid::new_v4(), -//! name: "priority_events_kinesis".to_string(), -//! backend: StreamBackend::Kinesis { +//! let stream = StreamConfig::new("priority_events_kinesis".to_string(), StreamBackend::Kinesis { //! region: "us-east-1".to_string(), //! stream_name: "hammerwork-priority-events".to_string(), //! access_key_id: None, // Use IAM roles //! secret_access_key: None, //! config: HashMap::new(), -//! }, -//! filter: EventFilter::new() -//! .with_priorities(vec![hammerwork::priority::JobPriority::High, hammerwork::priority::JobPriority::Critical]), -//! partitioning: PartitioningStrategy::Hash { +//! }) +//! .with_filter(EventFilter::new() +//! .with_priorities(vec![hammerwork::priority::JobPriority::High, hammerwork::priority::JobPriority::Critical])) +//! .with_partitioning(PartitioningStrategy::Hash { //! fields: vec![PartitionField::Priority, PartitionField::QueueName] -//! }, -//! serialization: SerializationFormat::Json, -//! enabled: true, -//! ..Default::default() -//! }; +//! }) +//! .with_serialization(SerializationFormat::Json) +//! .enabled(true); //! ``` //! //! ## Google Cloud Pub/Sub with Buffering @@ -100,25 +90,19 @@ //! use hammerwork::events::EventFilter; //! use std::collections::HashMap; //! -//! let stream = StreamConfig { -//! id: uuid::Uuid::new_v4(), -//! name: "analytics_events_pubsub".to_string(), -//! backend: StreamBackend::PubSub { +//! let stream = StreamConfig::new("analytics_events_pubsub".to_string(), StreamBackend::PubSub { //! project_id: "my-project".to_string(), //! topic_name: "hammerwork-analytics".to_string(), //! service_account_key: None, // Use default credentials //! config: HashMap::new(), -//! }, -//! filter: EventFilter::new().include_payload(), -//! buffer_config: BufferConfig { -//! max_events: 500, -//! max_buffer_time_secs: 10, -//! batch_size: 50, -//! }, -//! serialization: SerializationFormat::Json, -//! enabled: true, -//! ..Default::default() -//! }; +//! }) +//! .with_filter(EventFilter::new().include_payload()) +//! .with_buffer_config(BufferConfig::default() +//! .with_max_events(500) +//! .with_max_buffer_time_secs(10) +//! .with_batch_size(50)) +//! .with_serialization(SerializationFormat::Json) +//! .enabled(true); //! ``` //! //! ## Avro Serialization with Schema Registry @@ -126,17 +110,15 @@ //! ```rust //! use hammerwork::streaming::{StreamConfig, SerializationFormat}; //! -//! let stream = StreamConfig { -//! serialization: SerializationFormat::Avro { +//! let stream = StreamConfig::default() +//! .with_serialization(SerializationFormat::Avro { //! schema_registry_url: "http://localhost:8081".to_string() -//! }, -//! ..Default::default() -//! }; +//! }); //! ``` use crate::{ HammerworkError, - events::{EventFilter, EventManager, JobLifecycleEvent}, + events::{EventFilter, EventManager, EventSubscription, JobLifecycleEvent}, task_tracker::{ListenerHandle, TaskTracker, clamp_permits}, }; @@ -216,42 +198,32 @@ mod uuid_string { /// use std::collections::HashMap; /// /// // Basic Kafka configuration -/// let kafka_stream = StreamConfig { -/// id: Uuid::new_v4(), -/// name: "main_events".to_string(), -/// backend: StreamBackend::Kafka { +/// let kafka_stream = StreamConfig::new("main_events".to_string(), StreamBackend::Kafka { /// brokers: vec!["localhost:9092".to_string()], /// topic: "job-events".to_string(), /// config: HashMap::new(), -/// }, -/// filter: EventFilter::new(), -/// partitioning: PartitioningStrategy::QueueName, -/// serialization: SerializationFormat::Json, -/// enabled: true, -/// ..Default::default() -/// }; +/// }) +/// .with_filter(EventFilter::new()) +/// .with_partitioning(PartitioningStrategy::QueueName) +/// .with_serialization(SerializationFormat::Json) +/// .enabled(true); /// /// // Kinesis with custom partitioning -/// let kinesis_stream = StreamConfig { -/// id: Uuid::new_v4(), -/// name: "analytics_stream".to_string(), -/// backend: StreamBackend::Kinesis { +/// let kinesis_stream = StreamConfig::new("analytics_stream".to_string(), StreamBackend::Kinesis { /// region: "us-west-2".to_string(), /// stream_name: "analytics-events".to_string(), /// access_key_id: None, /// secret_access_key: None, /// config: HashMap::new(), -/// }, -/// partitioning: PartitioningStrategy::JobId, -/// buffer_config: BufferConfig { -/// max_events: 100, -/// max_buffer_time_secs: 5, -/// batch_size: 25, -/// }, -/// ..Default::default() -/// }; +/// }) +/// .with_partitioning(PartitioningStrategy::JobId) +/// .with_buffer_config(BufferConfig::default() +/// .with_max_events(100) +/// .with_max_buffer_time_secs(5) +/// .with_batch_size(25)); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamConfig { /// Unique identifier for this stream #[serde(with = "uuid_string")] @@ -549,24 +521,23 @@ pub enum SerializationFormat { /// let default_policy = StreamRetryPolicy::default(); /// /// // Custom retry policy for critical events -/// let aggressive_policy = StreamRetryPolicy { -/// max_attempts: 10, -/// initial_delay_secs: 1, -/// max_delay_secs: 600, // 10 minutes -/// backoff_multiplier: 2.0, -/// use_jitter: true, -/// }; +/// let aggressive_policy = StreamRetryPolicy::default() +/// .with_max_attempts(10) +/// .with_initial_delay_secs(1) +/// .with_max_delay_secs(600) +/// .with_backoff_multiplier(2.0) +/// .with_use_jitter(true); /// /// // Quick retry policy for non-critical events -/// let fast_policy = StreamRetryPolicy { -/// max_attempts: 3, -/// initial_delay_secs: 1, -/// max_delay_secs: 30, -/// backoff_multiplier: 1.5, -/// use_jitter: false, -/// }; +/// let fast_policy = StreamRetryPolicy::default() +/// .with_max_attempts(3) +/// .with_initial_delay_secs(1) +/// .with_max_delay_secs(30) +/// .with_backoff_multiplier(1.5) +/// .with_use_jitter(false); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamRetryPolicy { /// Maximum number of delivery attempts per event, including the first one. /// `0` is treated as `1` (a single attempt, no retries). @@ -634,27 +605,25 @@ impl StreamRetryPolicy { /// let default_config = BufferConfig::default(); /// /// // High-throughput configuration -/// let high_throughput = BufferConfig { -/// max_events: 5000, -/// max_buffer_time_secs: 10, -/// batch_size: 500, -/// }; +/// let high_throughput = BufferConfig::default() +/// .with_max_events(5000) +/// .with_max_buffer_time_secs(10) +/// .with_batch_size(500); /// /// // Low-latency configuration -/// let low_latency = BufferConfig { -/// max_events: 100, -/// max_buffer_time_secs: 1, -/// batch_size: 10, -/// }; +/// let low_latency = BufferConfig::default() +/// .with_max_events(100) +/// .with_max_buffer_time_secs(1) +/// .with_batch_size(10); /// /// // Memory-constrained configuration -/// let memory_efficient = BufferConfig { -/// max_events: 50, -/// max_buffer_time_secs: 2, -/// batch_size: 5, -/// }; +/// let memory_efficient = BufferConfig::default() +/// .with_max_events(50) +/// .with_max_buffer_time_secs(2) +/// .with_batch_size(5); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct BufferConfig { /// Maximum number of events to buffer pub max_events: usize, @@ -696,6 +665,7 @@ impl Default for StreamConfig { /// A streamed event with routing metadata #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamedEvent { /// The original job lifecycle event pub event: JobLifecycleEvent, @@ -711,6 +681,7 @@ pub struct StreamedEvent { /// Stream delivery attempt result #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamDelivery { /// Unique identifier for this delivery attempt #[serde(with = "uuid_string")] @@ -737,6 +708,7 @@ pub struct StreamDelivery { /// Statistics for a streaming configuration #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamStats { /// Stream configuration ID #[serde(with = "uuid_string")] @@ -772,6 +744,7 @@ pub struct StreamStats { /// Overall stream manager statistics #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct StreamManagerGlobalStats { /// Total number of configured streams pub total_streams: usize, @@ -812,11 +785,10 @@ pub struct StreamManagerGlobalStats { /// let event_manager = Arc::new(EventManager::new_default()); /// let stream_manager = StreamManager::new( /// event_manager.clone(), -/// StreamManagerConfig { -/// max_concurrent_processors: 100, -/// log_operations: true, -/// global_flush_interval_secs: 5, -/// } +/// StreamManagerConfig::default() +/// .with_max_concurrent_processors(100) +/// .with_log_operations(true) +/// .with_global_flush_interval_secs(5) /// ); /// /// // Add streams, start processing, etc. @@ -860,20 +832,19 @@ pub struct StreamManager { /// let default_config = StreamManagerConfig::default(); /// /// // High-throughput configuration -/// let high_throughput = StreamManagerConfig { -/// max_concurrent_processors: 200, -/// log_operations: false, // Reduce logging overhead -/// global_flush_interval_secs: 30, -/// }; +/// let high_throughput = StreamManagerConfig::default() +/// .with_max_concurrent_processors(200) +/// .with_log_operations(false) +/// .with_global_flush_interval_secs(30); /// /// // Development configuration -/// let dev_config = StreamManagerConfig { -/// max_concurrent_processors: 10, -/// log_operations: true, -/// global_flush_interval_secs: 1, // Fast flushing for testing -/// }; +/// let dev_config = StreamManagerConfig::default() +/// .with_max_concurrent_processors(10) +/// .with_log_operations(true) +/// .with_global_flush_interval_secs(1); // Fast flushing for testing /// ``` #[derive(Debug, Clone)] +#[non_exhaustive] pub struct StreamManagerConfig { /// Maximum number of batches being sent at once, across all streams. A batch /// holds a slot only while it is being sent, not while it waits to retry. @@ -1065,11 +1036,10 @@ impl StreamManager { /// use std::sync::Arc; /// /// let event_manager = Arc::new(EventManager::new_default()); - /// let config = StreamManagerConfig { - /// max_concurrent_processors: 50, - /// log_operations: true, - /// global_flush_interval_secs: 10, - /// }; + /// let config = StreamManagerConfig::default() + /// .with_max_concurrent_processors(50) + /// .with_log_operations(true) + /// .with_global_flush_interval_secs(10); /// let stream_manager = StreamManager::new(event_manager, config); /// ``` pub fn new(event_manager: Arc, config: StreamManagerConfig) -> Self { @@ -1200,18 +1170,13 @@ impl StreamManager { /// let event_manager = Arc::new(EventManager::new_default()); /// let stream_manager = StreamManager::new_default(event_manager); /// - /// let stream = StreamConfig { - /// id: uuid::Uuid::new_v4(), - /// name: "kafka-stream".to_string(), - /// backend: StreamBackend::Kafka { + /// let stream = StreamConfig::new("kafka-stream".to_string(), StreamBackend::Kafka { /// brokers: vec!["localhost:9092".to_string()], /// topic: "events".to_string(), /// config: HashMap::new(), - /// }, - /// filter: EventFilter::new(), - /// enabled: true, - /// ..Default::default() - /// }; + /// }) + /// .with_filter(EventFilter::new()) + /// .enabled(true); /// /// stream_manager.add_stream(stream).await?; /// # Ok(()) @@ -1278,7 +1243,7 @@ impl StreamManager { } // Start processing task for this stream - self.start_stream_processing_task(stream_id, subscription.receiver, stop); + self.start_stream_processing_task(stream_id, subscription, stop); if self.config.log_operations { tracing::info!("Added stream: {} ({:?})", stream.name, stream.backend); @@ -1468,7 +1433,9 @@ impl StreamManager { fn start_stream_processing_task( &self, stream_id: Uuid, - mut receiver: broadcast::Receiver, + // The listener holds the whole subscription: dropping it (when the listener + // stops) unregisters the subscription from the event manager. + mut subscription: EventSubscription, mut stop: oneshot::Receiver<()>, ) { let streams = self.streams.clone(); @@ -1575,7 +1542,7 @@ impl StreamManager { let received = tokio::select! { biased; _ = &mut stop => break, - received = receiver.recv() => received, + received = subscription.receiver.recv() => received, _ = flush_due => continue, }; match received { @@ -3154,6 +3121,32 @@ fn fnv1a_64(bytes: &[u8]) -> u64 { hash } +with_setters! { + StreamRetryPolicy { + with_max_attempts(max_attempts): u32, + with_initial_delay_secs(initial_delay_secs): u64, + with_max_delay_secs(max_delay_secs): u64, + with_backoff_multiplier(backoff_multiplier): f64, + with_use_jitter(use_jitter): bool, + } +} + +with_setters! { + BufferConfig { + with_max_events(max_events): usize, + with_max_buffer_time_secs(max_buffer_time_secs): u64, + with_batch_size(batch_size): usize, + } +} + +with_setters! { + StreamManagerConfig { + with_max_concurrent_processors(max_concurrent_processors): usize, + with_log_operations(log_operations): bool, + with_global_flush_interval_secs(global_flush_interval_secs): u64, + } +} + #[cfg(test)] mod tests { use super::*; @@ -5371,4 +5364,46 @@ mod tests { assert_eq!(processor.delivered_ids().len(), 1); manager.shutdown(Duration::from_secs(5)).await; } + + /// #81: stream settings built from their defaults with setters. + #[test] + fn test_stream_settings_builders() { + let retry = StreamRetryPolicy::default() + .with_max_attempts(4) + .with_initial_delay_secs(2) + .with_max_delay_secs(20) + .with_backoff_multiplier(1.5) + .with_use_jitter(false); + assert_eq!( + ( + retry.max_attempts, + retry.initial_delay_secs, + retry.max_delay_secs + ), + (4, 2, 20) + ); + assert_eq!(retry.backoff_multiplier, 1.5); + assert!(!retry.use_jitter); + + let buffer = BufferConfig::default() + .with_max_events(10) + .with_max_buffer_time_secs(3) + .with_batch_size(5); + assert_eq!( + ( + buffer.max_events, + buffer.max_buffer_time_secs, + buffer.batch_size + ), + (10, 3, 5) + ); + + let manager = StreamManagerConfig::default() + .with_max_concurrent_processors(2) + .with_log_operations(false) + .with_global_flush_interval_secs(9); + assert_eq!(manager.max_concurrent_processors, 2); + assert!(!manager.log_operations); + assert_eq!(manager.global_flush_interval_secs, 9); + } } diff --git a/src/tracing.rs b/src/tracing.rs index 6974ce7..a5bc960 100644 --- a/src/tracing.rs +++ b/src/tracing.rs @@ -224,6 +224,7 @@ impl From<&str> for CorrelationId { /// tracing for job processing, including service information and export settings. #[cfg(feature = "tracing")] #[derive(Debug, Clone)] +#[non_exhaustive] pub struct TracingConfig { /// Name of the service for tracing identification pub service_name: String, diff --git a/src/webhooks.rs b/src/webhooks.rs index 62a80d5..ecb3606 100644 --- a/src/webhooks.rs +++ b/src/webhooks.rs @@ -86,16 +86,15 @@ //! "reliable_webhook".to_string(), //! "https://api.example.com/events".to_string(), //! ) -//! .with_retry_policy(RetryPolicy { -//! max_attempts: 5, -//! initial_delay_secs: 2, -//! max_delay_secs: 300, -//! backoff_multiplier: 2.5, -//! retry_on_status_codes: vec![500, 502, 503, 504, 429], -//! }); +//! .with_retry_policy(RetryPolicy::default() +//! .with_max_attempts(5) +//! .with_initial_delay_secs(2) +//! .with_max_delay_secs(300) +//! .with_backoff_multiplier(2.5) +//! .with_retry_on_status_codes(vec![500, 502, 503, 504, 429])); //! ``` -use crate::events::{EventFilter, EventManager, JobLifecycleEvent}; +use crate::events::{EventFilter, EventManager, EventSubscription, JobLifecycleEvent}; use crate::task_tracker::{ListenerHandle, TaskTracker, clamp_permits}; use chrono::{DateTime, Utc}; use reqwest::Client; @@ -172,6 +171,7 @@ mod uuid_string { /// `Debug` never shows the signing secret, header values, credentials, or the path of /// the URL (webhook URLs of chat services are themselves credentials). #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebhookConfig { /// Unique identifier for this webhook #[serde(with = "uuid_string")] @@ -315,6 +315,7 @@ impl std::fmt::Debug for WebhookAuth { /// Retry policy configuration #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct RetryPolicy { /// Maximum number of delivery attempts, including the first (0 is treated as 1: /// every event is attempted at least once) @@ -360,6 +361,7 @@ impl RetryPolicy { /// Webhook delivery attempt result #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebhookDelivery { /// Unique identifier for this delivery attempt #[serde(with = "uuid_string")] @@ -388,6 +390,7 @@ pub struct WebhookDelivery { /// Webhook delivery statistics #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebhookStats { /// Webhook configuration ID #[serde(with = "uuid_string")] @@ -395,6 +398,12 @@ pub struct WebhookStats { /// Total number of HTTP delivery attempts, retries included: one event can take /// several attempts. pub total_attempts: u64, + /// Number of HTTP delivery attempts that failed (an error, a timeout or a non-2xx + /// response), retried ones included. `total_attempts - failed_attempts` attempts + /// succeeded. Compare [`failed_deliveries`](Self::failed_deliveries), which counts + /// events whose delivery failed for good. + #[serde(default)] + pub failed_attempts: u64, /// Number of events delivered successfully (by any attempt) pub successful_deliveries: u64, /// Number of events whose delivery ultimately failed (retries exhausted, or a @@ -419,8 +428,28 @@ pub struct WebhookStats { pub calculated_at: DateTime, } +impl WebhookStats { + /// Statistics of a webhook with no deliveries yet. + pub(crate) fn empty(webhook_id: Uuid) -> Self { + Self { + webhook_id, + total_attempts: 0, + failed_attempts: 0, + successful_deliveries: 0, + failed_deliveries: 0, + success_rate: 0.0, + avg_response_time_ms: 0.0, + last_success_at: None, + last_failure_at: None, + dropped_events: 0, + calculated_at: Utc::now(), + } + } +} + /// Overall webhook manager statistics #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct WebhookManagerStats { /// Total number of configured webhooks pub total_webhooks: usize, @@ -428,6 +457,9 @@ pub struct WebhookManagerStats { pub active_webhooks: usize, /// Total HTTP delivery attempts across all webhooks, retries included pub total_attempts: u64, + /// Total failed HTTP delivery attempts across all webhooks, retries included + #[serde(default)] + pub failed_attempts: u64, /// Total events delivered successfully across all webhooks pub successful_deliveries: u64, /// Total events whose delivery ultimately failed across all webhooks @@ -461,14 +493,13 @@ pub struct WebhookManagerStats { /// # async fn main() -> Result<(), Box> { /// // Create webhook manager /// let event_manager = Arc::new(EventManager::new_default()); -/// let config = WebhookManagerConfig { -/// max_concurrent_deliveries: 20, -/// max_response_body_size: 64 * 1024, -/// log_deliveries: true, -/// default_timeout_secs: 30, -/// max_pending_deliveries: 1_000, -/// user_agent: "MyApp/1.0".to_string(), -/// }; +/// let config = WebhookManagerConfig::default() +/// .with_max_concurrent_deliveries(20) +/// .with_max_response_body_size(64 * 1024) +/// .with_log_deliveries(true) +/// .with_default_timeout_secs(30) +/// .with_max_pending_deliveries(1_000) +/// .with_user_agent("MyApp/1.0".to_string()); /// let webhook_manager = WebhookManager::new(event_manager, config); /// /// // Add a webhook @@ -512,6 +543,7 @@ pub struct WebhookManager { /// Configuration for the webhook manager #[derive(Debug, Clone)] +#[non_exhaustive] pub struct WebhookManagerConfig { /// Maximum number of HTTP requests in flight at once, across all webhooks. /// A delivery holds a slot only while a request is in flight, not while it waits @@ -745,21 +777,7 @@ impl WebhookManager { // Initialize statistics { let mut stats = self.stats.write().await; - stats.insert( - webhook_id, - WebhookStats { - webhook_id, - total_attempts: 0, - successful_deliveries: 0, - failed_deliveries: 0, - success_rate: 0.0, - avg_response_time_ms: 0.0, - last_success_at: None, - last_failure_at: None, - dropped_events: 0, - calculated_at: Utc::now(), - }, - ); + stats.insert(webhook_id, WebhookStats::empty(webhook_id)); } // Replacing the handle of an existing listener stops that listener. @@ -770,7 +788,7 @@ impl WebhookManager { .await?; } - self.start_webhook_delivery_task(webhook_id, subscription.receiver, stop); + self.start_webhook_delivery_task(webhook_id, subscription, stop); if self.config.log_deliveries { // The URL path of chat webhooks (Slack, Discord, Teams) is a credential. @@ -894,6 +912,7 @@ impl WebhookManager { let total_webhooks = webhooks.len(); let active_webhooks = webhooks.values().filter(|w| w.enabled).count(); let total_attempts = stats.values().map(|s| s.total_attempts).sum(); + let failed_attempts = stats.values().map(|s| s.failed_attempts).sum(); let successful_deliveries = stats.values().map(|s| s.successful_deliveries).sum(); let failed_deliveries = stats.values().map(|s| s.failed_deliveries).sum(); @@ -901,6 +920,7 @@ impl WebhookManager { total_webhooks, active_webhooks, total_attempts, + failed_attempts, successful_deliveries, failed_deliveries, } @@ -911,7 +931,9 @@ impl WebhookManager { fn start_webhook_delivery_task( &self, webhook_id: Uuid, - mut receiver: broadcast::Receiver, + // The listener holds the whole subscription: dropping it (when the listener + // stops) unregisters the subscription from the event manager. + mut subscription: EventSubscription, mut stop: oneshot::Receiver<()>, ) { let webhooks = self.webhooks.clone(); @@ -933,7 +955,7 @@ impl WebhookManager { let received = tokio::select! { biased; _ = &mut stop => break, - received = receiver.recv() => received, + received = subscription.receiver.recv() => received, }; let mut event = match received { Ok(event) => event, @@ -1268,7 +1290,7 @@ impl WebhookManager { format!("sha256={}", hex::encode(result.into_bytes())) } - /// Update the per-attempt statistics: the attempts counter, the average response + /// Update the per-attempt statistics: the attempt counters, the average response /// time and the last success and failure timestamps. async fn update_webhook_stats( webhook_id: &Uuid, @@ -1282,6 +1304,7 @@ impl WebhookManager { if delivery.success { webhook_stats.last_success_at = Some(delivery.attempted_at); } else { + webhook_stats.failed_attempts += 1; webhook_stats.last_failure_at = Some(delivery.attempted_at); } @@ -1732,6 +1755,27 @@ pub fn verify_hmac_signature(secret: &str, payload: &[u8], signature: &str) -> b mac.verify_slice(&signature_bytes).is_ok() } +with_setters! { + RetryPolicy { + with_max_attempts(max_attempts): u32, + with_initial_delay_secs(initial_delay_secs): u64, + with_max_delay_secs(max_delay_secs): u64, + with_backoff_multiplier(backoff_multiplier): f64, + with_retry_on_status_codes(retry_on_status_codes): Vec, + } +} + +with_setters! { + WebhookManagerConfig { + with_max_concurrent_deliveries(max_concurrent_deliveries): usize, + with_max_response_body_size(max_response_body_size): usize, + with_log_deliveries(log_deliveries): bool, + with_default_timeout_secs(default_timeout_secs): u64, + with_max_pending_deliveries(max_pending_deliveries): usize, + with_user_agent(user_agent): Into(String), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1932,18 +1976,7 @@ mod tests { #[test] fn test_webhook_stats_calculation() { - let mut stats = WebhookStats { - webhook_id: Uuid::new_v4(), - total_attempts: 0, - successful_deliveries: 0, - failed_deliveries: 0, - success_rate: 0.0, - avg_response_time_ms: 0.0, - last_success_at: None, - last_failure_at: None, - dropped_events: 0, - calculated_at: Utc::now(), - }; + let mut stats = WebhookStats::empty(Uuid::new_v4()); // Simulate successful delivery stats.total_attempts = 1; @@ -2308,6 +2341,7 @@ mod tests { let mut stats = WebhookStats { webhook_id, total_attempts: 10, + failed_attempts: 3, successful_deliveries: 7, failed_deliveries: 3, success_rate: 0.7, @@ -3107,21 +3141,7 @@ mod tests { #[tokio::test] async fn test_stats_count_final_outcomes_not_attempts() { let id = Uuid::new_v4(); - let stats = Arc::new(RwLock::new(HashMap::from([( - id, - WebhookStats { - webhook_id: id, - total_attempts: 0, - successful_deliveries: 0, - failed_deliveries: 0, - success_rate: 0.0, - avg_response_time_ms: 0.0, - last_success_at: None, - last_failure_at: None, - dropped_events: 0, - calculated_at: Utc::now(), - }, - )]))); + let stats = Arc::new(RwLock::new(HashMap::from([(id, WebhookStats::empty(id))]))); let attempt = |success: bool| WebhookDelivery { delivery_id: Uuid::new_v4(), webhook_id: id, @@ -3143,7 +3163,7 @@ mod tests { { let stats = stats.read().await; let s = &stats[&id]; - assert_eq!(s.total_attempts, 3); + assert_eq!((s.total_attempts, s.failed_attempts), (3, 2)); assert_eq!((s.successful_deliveries, s.failed_deliveries), (1, 0)); assert_eq!(s.success_rate, 1.0); assert!(s.last_success_at.is_some() && s.last_failure_at.is_some()); @@ -3156,7 +3176,7 @@ mod tests { WebhookManager::record_delivery_outcome(&id, false, stats.clone()).await; let stats = stats.read().await; let s = &stats[&id]; - assert_eq!(s.total_attempts, 6); + assert_eq!((s.total_attempts, s.failed_attempts), (6, 5)); assert_eq!((s.successful_deliveries, s.failed_deliveries), (1, 1)); assert_eq!(s.success_rate, 0.5); } @@ -3497,4 +3517,39 @@ mod tests { assert_eq!(webhook.retry_policy.max_attempts, 1); assert!(!webhook.enabled); } + + /// #81: webhook settings built from their defaults with setters. + #[test] + fn test_webhook_settings_builders() { + let retry = RetryPolicy::default() + .with_max_attempts(2) + .with_initial_delay_secs(1) + .with_max_delay_secs(5) + .with_backoff_multiplier(3.0) + .with_retry_on_status_codes(vec![503]); + assert_eq!( + ( + retry.max_attempts, + retry.initial_delay_secs, + retry.max_delay_secs + ), + (2, 1, 5) + ); + assert_eq!(retry.backoff_multiplier, 3.0); + assert!(retry.should_retry_status(503) && !retry.should_retry_status(500)); + + let manager = WebhookManagerConfig::default() + .with_max_concurrent_deliveries(3) + .with_max_response_body_size(100) + .with_log_deliveries(false) + .with_default_timeout_secs(4) + .with_max_pending_deliveries(6) + .with_user_agent("acme"); + assert_eq!(manager.max_concurrent_deliveries, 3); + assert_eq!(manager.max_response_body_size, 100); + assert!(!manager.log_deliveries); + assert_eq!(manager.default_timeout_secs, 4); + assert_eq!(manager.max_pending_deliveries, 6); + assert_eq!(manager.user_agent, "acme"); + } } diff --git a/src/worker.rs b/src/worker.rs index bbd3844..515ddcf 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -328,6 +328,7 @@ fn error_backoff(base: Duration, consecutive_errors: u32) -> Duration { /// Statistics for batch job processing by a worker. #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub struct BatchProcessingStats { /// Total number of batch jobs processed pub jobs_processed: u64, @@ -437,6 +438,7 @@ pub type JobHandlerWithResult = Arc< /// Result returned by job handlers, optionally containing result data. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct JobResult { /// Optional result data to store for retrieval pub data: Option, diff --git a/src/worker/autoscale.rs b/src/worker/autoscale.rs index 87108f7..5b8480f 100644 --- a/src/worker/autoscale.rs +++ b/src/worker/autoscale.rs @@ -10,6 +10,7 @@ use super::*; /// enabled, so `with_autoscaling(AutoscaleConfig::default())` turns autoscaling on; see /// [`WorkerPool::with_autoscaling`] for which workers it starts and retires. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct AutoscaleConfig { /// Whether autoscaling is enabled pub enabled: bool, @@ -139,6 +140,7 @@ impl AutoscaleConfig { /// Metrics for autoscaling decisions #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub struct AutoscaleMetrics { /// Current number of active workers: those of the autoscaled queue when /// autoscaling is enabled, otherwise all of the pool's workers diff --git a/src/worker/hooks.rs b/src/worker/hooks.rs index e387e2e..0a2ed1c 100644 --- a/src/worker/hooks.rs +++ b/src/worker/hooks.rs @@ -4,6 +4,7 @@ use super::*; /// Event data for job lifecycle event hooks. #[derive(Debug, Clone)] +#[non_exhaustive] pub struct JobHookEvent { /// The job that triggered the event pub job: Job, @@ -23,6 +24,7 @@ pub type JobHookHandler = Arc; /// Hooks run on the worker's task. A hook that panics is contained: the panic is logged /// at error level, the job's outcome is recorded as usual and the worker keeps polling. #[derive(Clone, Default)] +#[non_exhaustive] pub struct JobEventHooks { /// Called when a job starts processing pub on_job_start: Option, diff --git a/src/workflow.rs b/src/workflow.rs index feb06c4..8b8dfdc 100644 --- a/src/workflow.rs +++ b/src/workflow.rs @@ -180,6 +180,7 @@ impl FailurePolicy { /// .then(final_job); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub struct JobGroup { /// Unique identifier for this workflow pub id: WorkflowId, diff --git a/tests/archive_tests.rs b/tests/archive_tests.rs index 6d0ad80..580960f 100644 --- a/tests/archive_tests.rs +++ b/tests/archive_tests.rs @@ -938,14 +938,16 @@ mod websocket_archive_event_tests { }, ArchiveEvent::BulkArchiveCompleted { operation_id: "op_123".to_string(), - stats: ArchivalStats { - jobs_archived: 1000, - jobs_purged: 0, - bytes_archived: 50000, - bytes_purged: 0, - compression_ratio: 0.7, - operation_duration: std::time::Duration::from_secs(30), - last_run_at: Utc::now(), + 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.7; + value.operation_duration = std::time::Duration::from_secs(30); + value.last_run_at = Utc::now(); + value }, }, ArchiveEvent::JobsPurged { diff --git a/tests/archive_workflow_regression_tests.rs b/tests/archive_workflow_regression_tests.rs index 3a58a0d..f55c582 100644 --- a/tests/archive_workflow_regression_tests.rs +++ b/tests/archive_workflow_regression_tests.rs @@ -268,6 +268,41 @@ where assert_eq!(status.jobs.len(), 2); } +/// #81: `list_archived_jobs` returns the workflow of an archived member (and none for a +/// job outside a workflow). +async fn archived_jobs_list_their_workflow(queue: Arc) +where + Q: DatabaseQueue + Send + Sync + 'static, +{ + let _serial = test_utils::serial().await; + let name = test_utils::unique_queue("listed_workflow"); + let member = Job::new(name.clone(), json!({ "step": "member" })); + let loner = Job::new(name.clone(), json!({ "step": "loner" })); + let (member_id, loner_id) = (member.id, loner.id); + let workflow_id = queue + .enqueue_workflow(JobGroup::new("listed_workflow").add_job(member)) + .await + .unwrap(); + queue.enqueue(loner).await.unwrap(); + queue.complete_job(member_id).await.unwrap(); + queue.complete_job(loner_id).await.unwrap(); + assert_eq!(archive_queue(queue.as_ref(), &name).await, 2); + + let archived = queue + .list_archived_jobs(Some(&name), None, None) + .await + .unwrap(); + assert_eq!(archived.len(), 2, "{archived:?}"); + let member = archived.iter().find(|job| job.id == member_id).unwrap(); + assert_eq!(member.workflow_id, Some(workflow_id)); + assert_eq!(member.workflow_name.as_deref(), Some("listed_workflow")); + let loner = archived.iter().find(|job| job.id == loner_id).unwrap(); + assert_eq!( + (loner.workflow_id, loner.workflow_name.as_deref()), + (None, None) + ); +} + /// #111 (2): an archived failure counts as a failure. async fn archived_failures_fail_their_workflow(queue: Arc) where @@ -648,6 +683,7 @@ crate::test_utils::backend_tests!( archived_jobs_keep_their_times, archiving_uses_the_database_clock, archived_members_count_towards_their_workflow, + archived_jobs_list_their_workflow, archived_failures_fail_their_workflow, spawned_children_raise_workflow_total, dependency_limit_is_enforced, @@ -666,6 +702,7 @@ crate::test_utils::backend_tests!( archived_jobs_keep_their_times, archiving_uses_the_database_clock, archived_members_count_towards_their_workflow, + archived_jobs_list_their_workflow, archived_failures_fail_their_workflow, spawned_children_raise_workflow_total, dependency_limit_is_enforced, @@ -684,6 +721,7 @@ crate::test_utils::backend_tests!( archived_jobs_keep_their_times, archiving_uses_the_database_clock, archived_members_count_towards_their_workflow, + archived_jobs_list_their_workflow, archived_failures_fail_their_workflow, spawned_children_raise_workflow_total, dependency_limit_is_enforced, diff --git a/tests/comprehensive_archive_tests.rs b/tests/comprehensive_archive_tests.rs index 9aea8eb..45873e6 100644 --- a/tests/comprehensive_archive_tests.rs +++ b/tests/comprehensive_archive_tests.rs @@ -45,14 +45,16 @@ async fn test_archive_event_serialization_comprehensive() { }, ArchiveEvent::BulkArchiveCompleted { operation_id: "op_123".to_string(), - stats: hammerwork::archive::ArchivalStats { - jobs_archived: 100, - jobs_purged: 0, - bytes_archived: 1024, - bytes_purged: 0, - compression_ratio: 0.8, - operation_duration: std::time::Duration::from_secs(30), - last_run_at: Utc::now(), + stats: { + let mut value = hammerwork::archive::ArchivalStats::default(); + value.jobs_archived = 100; + value.jobs_purged = 0; + value.bytes_archived = 1024; + 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 { diff --git a/tests/encryption_basic_tests.rs b/tests/encryption_basic_tests.rs index c13fa82..b50d19d 100644 --- a/tests/encryption_basic_tests.rs +++ b/tests/encryption_basic_tests.rs @@ -3,13 +3,12 @@ //! These tests validate the core encryption functionality without requiring //! external database connections, making them suitable for CI/CD environments. -use chrono::{Duration, Utc}; +use chrono::Duration; use hammerwork::encryption::{ - EncryptionAlgorithm, EncryptionKey, ExternalKmsConfig, KeyDerivationConfig, KeyManagerConfig, - KeyManagerStats, KeyPurpose, KeySource, KeyStatus, parse_algorithm, parse_key_source, + EncryptionAlgorithm, ExternalKmsConfig, KeyDerivationConfig, KeyManagerConfig, KeyManagerStats, + KeyPurpose, KeySource, KeyStatus, parse_algorithm, parse_key_source, }; use std::collections::HashMap; -use uuid::Uuid; // Helper function to create test key manager configuration fn create_test_config() -> KeyManagerConfig { @@ -21,32 +20,6 @@ fn create_test_config() -> KeyManagerConfig { .with_audit_enabled(true) } -// Helper function to create test encryption key -fn create_test_encryption_key(key_id: &str) -> EncryptionKey { - EncryptionKey { - id: Uuid::new_v4(), - key_id: key_id.to_string(), - version: 1, - algorithm: EncryptionAlgorithm::AES256GCM, - encrypted_key_material: vec![1, 2, 3, 4, 5, 6, 7, 8], // Mock encrypted data - derivation_salt: Some(vec![9, 10, 11, 12]), - source: KeySource::Generated("test".to_string()), - purpose: KeyPurpose::Encryption, - created_at: Utc::now(), - created_by: Some("test-user".to_string()), - expires_at: Some(Utc::now() + Duration::days(365)), - rotated_at: None, - retired_at: None, - status: KeyStatus::Active, - rotation_interval: Some(Duration::days(90)), - next_rotation_at: Some(Utc::now() + Duration::days(90)), - key_strength: 256, - master_key_id: Some(Uuid::new_v4()), - last_used_at: None, - usage_count: 0, - } -} - #[cfg(test)] mod unit_tests { use super::*; @@ -84,22 +57,6 @@ mod unit_tests { assert!(!config.audit_enabled); } - #[test] - fn test_encryption_key_creation() { - let key = create_test_encryption_key("test-key-1"); - - assert_eq!(key.key_id, "test-key-1"); - assert_eq!(key.version, 1); - assert_eq!(key.algorithm, EncryptionAlgorithm::AES256GCM); - assert_eq!(key.purpose, KeyPurpose::Encryption); - assert_eq!(key.status, KeyStatus::Active); - assert_eq!(key.key_strength, 256); - assert_eq!(key.usage_count, 0); - assert!(key.expires_at.is_some()); - assert!(key.rotation_interval.is_some()); - assert!(key.next_rotation_at.is_some()); - } - #[test] fn test_key_purpose_serialization() { let purposes = vec![KeyPurpose::Encryption, KeyPurpose::MAC, KeyPurpose::KEK]; @@ -136,13 +93,13 @@ mod unit_tests { "test_secret_key".to_string(), ); - let kms_config = ExternalKmsConfig { - service_type: "AWS".to_string(), - endpoint: "https://kms.us-east-1.amazonaws.com".to_string(), - auth_config, - region: Some("us-east-1".to_string()), - namespace: Some("hammerwork-test".to_string()), - }; + let kms_config = ExternalKmsConfig::new( + "AWS".to_string(), + "https://kms.us-east-1.amazonaws.com".to_string(), + ) + .with_auth_config(auth_config) + .with_region("us-east-1".to_string()) + .with_namespace("hammerwork-test".to_string()); assert_eq!(kms_config.service_type, "AWS"); assert_eq!(kms_config.endpoint, "https://kms.us-east-1.amazonaws.com"); @@ -339,13 +296,13 @@ mod aws_kms_tests { auth_config.insert("region".to_string(), "us-east-1".to_string()); auth_config.insert("profile".to_string(), "default".to_string()); - let kms_config = ExternalKmsConfig { - service_type: "AWS_KMS".to_string(), - endpoint: "https://kms.us-east-1.amazonaws.com".to_string(), - auth_config, - region: Some("us-east-1".to_string()), - namespace: Some("hammerwork".to_string()), - }; + let kms_config = ExternalKmsConfig::new( + "AWS_KMS".to_string(), + "https://kms.us-east-1.amazonaws.com".to_string(), + ) + .with_auth_config(auth_config) + .with_region("us-east-1".to_string()) + .with_namespace("hammerwork".to_string()); let serialized = serde_json::to_string(&kms_config).unwrap(); let deserialized: ExternalKmsConfig = serde_json::from_str(&serialized).unwrap(); @@ -356,42 +313,6 @@ mod aws_kms_tests { assert_eq!(kms_config.namespace, deserialized.namespace); assert_eq!(kms_config.auth_config, deserialized.auth_config); } - - #[test] - fn test_aws_kms_key_with_external_source() { - let aws_key = EncryptionKey { - id: Uuid::new_v4(), - key_id: "aws-data-key-1".to_string(), - version: 1, - algorithm: EncryptionAlgorithm::AES256GCM, - encrypted_key_material: vec![1, 2, 3, 4, 5, 6, 7, 8], - derivation_salt: None, - source: KeySource::External( - "aws://alias/hammerwork-data-keys?region=us-east-1".to_string(), - ), - purpose: KeyPurpose::Encryption, - created_at: Utc::now(), - created_by: Some("aws-kms-integration".to_string()), - expires_at: None, // AWS KMS keys don't expire - rotated_at: None, - retired_at: None, - status: KeyStatus::Active, - rotation_interval: Some(Duration::days(30)), - next_rotation_at: Some(Utc::now() + Duration::days(30)), - key_strength: 256, - master_key_id: Some(Uuid::new_v4()), - last_used_at: None, - usage_count: 0, - }; - - assert_eq!(aws_key.key_id, "aws-data-key-1"); - assert!(matches!(aws_key.source, KeySource::External(_))); - assert_eq!(aws_key.purpose, KeyPurpose::Encryption); - assert_eq!(aws_key.status, KeyStatus::Active); - assert_eq!(aws_key.key_strength, 256); - assert!(aws_key.expires_at.is_none()); // AWS KMS keys don't expire - assert!(aws_key.rotation_interval.is_some()); - } } #[cfg(all(test, feature = "aws-kms"))] @@ -510,13 +431,13 @@ mod gcp_kms_tests { auth_config.insert("project_id".to_string(), "my-project".to_string()); auth_config.insert("location".to_string(), "us-central1".to_string()); - let kms_config = ExternalKmsConfig { - service_type: "GCP_KMS".to_string(), - endpoint: "https://cloudkms.googleapis.com".to_string(), - auth_config, - region: Some("us-central1".to_string()), - namespace: Some("hammerwork".to_string()), - }; + let kms_config = ExternalKmsConfig::new( + "GCP_KMS".to_string(), + "https://cloudkms.googleapis.com".to_string(), + ) + .with_auth_config(auth_config) + .with_region("us-central1".to_string()) + .with_namespace("hammerwork".to_string()); let serialized = serde_json::to_string(&kms_config).unwrap(); let deserialized: ExternalKmsConfig = serde_json::from_str(&serialized).unwrap(); @@ -528,50 +449,6 @@ mod gcp_kms_tests { assert_eq!(kms_config.auth_config, deserialized.auth_config); } - #[test] - fn test_gcp_kms_key_with_external_source() { - let gcp_key = EncryptionKey { - id: Uuid::new_v4(), - key_id: "gcp-data-key-1".to_string(), - version: 1, - algorithm: EncryptionAlgorithm::AES256GCM, - encrypted_key_material: vec![1, 2, 3, 4, 5, 6, 7, 8], - derivation_salt: None, - source: KeySource::External( - "gcp://projects/my-project/locations/us-central1/keyRings/hammerwork/cryptoKeys/data-keys".to_string() - ), - purpose: KeyPurpose::Encryption, - created_at: Utc::now(), - created_by: Some("gcp-kms-integration".to_string()), - expires_at: None, // GCP KMS keys don't expire - rotated_at: None, - retired_at: None, - status: KeyStatus::Active, - rotation_interval: Some(Duration::days(30)), - next_rotation_at: Some(Utc::now() + Duration::days(30)), - key_strength: 256, - master_key_id: Some(Uuid::new_v4()), - last_used_at: None, - usage_count: 0, - }; - - assert_eq!(gcp_key.key_id, "gcp-data-key-1"); - assert!(matches!(gcp_key.source, KeySource::External(_))); - assert_eq!(gcp_key.purpose, KeyPurpose::Encryption); - assert_eq!(gcp_key.status, KeyStatus::Active); - assert_eq!(gcp_key.key_strength, 256); - assert!(gcp_key.expires_at.is_none()); // GCP KMS keys don't expire - assert!(gcp_key.rotation_interval.is_some()); - - // Verify the GCP KMS resource path structure - if let KeySource::External(resource) = &gcp_key.source { - assert!(resource.contains("projects/my-project")); - assert!(resource.contains("locations/us-central1")); - assert!(resource.contains("keyRings/hammerwork")); - assert!(resource.contains("cryptoKeys/data-keys")); - } - } - #[test] fn test_gcp_kms_resource_path_parsing() { let valid_paths = vec![ @@ -711,13 +588,12 @@ mod vault_kms_tests { auth_config.insert("addr".to_string(), "https://vault.example.com".to_string()); auth_config.insert("token".to_string(), "hvs.test-token".to_string()); - let kms_config = ExternalKmsConfig { - service_type: "VAULT_KMS".to_string(), - endpoint: "https://vault.example.com".to_string(), - auth_config, - region: None, - namespace: Some("production".to_string()), - }; + let kms_config = ExternalKmsConfig::new( + "VAULT_KMS".to_string(), + "https://vault.example.com".to_string(), + ) + .with_auth_config(auth_config) + .with_namespace("production".to_string()); let serialized = serde_json::to_string(&kms_config).unwrap(); let deserialized: ExternalKmsConfig = serde_json::from_str(&serialized).unwrap(); @@ -729,45 +605,6 @@ mod vault_kms_tests { assert_eq!(kms_config.auth_config, deserialized.auth_config); } - #[test] - fn test_vault_kms_key_with_external_source() { - let vault_key = EncryptionKey { - id: Uuid::new_v4(), - key_id: "vault-data-key-1".to_string(), - version: 1, - algorithm: EncryptionAlgorithm::AES256GCM, - encrypted_key_material: vec![1, 2, 3, 4, 5, 6, 7, 8], - derivation_salt: None, - source: KeySource::External("vault://secret/hammerwork/encryption-key".to_string()), - purpose: KeyPurpose::Encryption, - created_at: Utc::now(), - created_by: Some("vault-kms-integration".to_string()), - expires_at: None, // Vault keys don't expire by default - rotated_at: None, - retired_at: None, - status: KeyStatus::Active, - rotation_interval: Some(Duration::days(30)), - next_rotation_at: Some(Utc::now() + Duration::days(30)), - key_strength: 256, - master_key_id: Some(Uuid::new_v4()), - last_used_at: None, - usage_count: 0, - }; - - assert_eq!(vault_key.key_id, "vault-data-key-1"); - assert!(matches!(vault_key.source, KeySource::External(_))); - assert_eq!(vault_key.purpose, KeyPurpose::Encryption); - assert_eq!(vault_key.status, KeyStatus::Active); - assert_eq!(vault_key.key_strength, 256); - assert!(vault_key.expires_at.is_none()); // Vault keys don't expire by default - assert!(vault_key.rotation_interval.is_some()); - - // Verify the Vault secret path structure - if let KeySource::External(resource) = &vault_key.source { - assert!(resource.contains("secret/hammerwork/encryption-key")); - } - } - #[test] fn test_vault_kms_secret_path_parsing() { let valid_paths = vec![ diff --git a/tests/job_spawning_tests.rs b/tests/job_spawning_tests.rs index 2526cfa..dccdaf8 100644 --- a/tests/job_spawning_tests.rs +++ b/tests/job_spawning_tests.rs @@ -87,10 +87,7 @@ fn children( /// Children keep their own retry strategy, so the injected bad child stays bad. fn spawn_config() -> SpawnConfig { - SpawnConfig { - inherit_retry_strategy: false, - ..SpawnConfig::default() - } + SpawnConfig::default().with_inherit_retry_strategy(false) } /// The parent completes and its children exist, released by the completion. diff --git a/tests/migration_datetime_tests.rs b/tests/migration_datetime_tests.rs index d6391c9..7b69f3d 100644 --- a/tests/migration_datetime_tests.rs +++ b/tests/migration_datetime_tests.rs @@ -124,12 +124,7 @@ async fn test_mysql_migration_021_converts_timestamps_to_datetime() { runner.create_migration_table().await.unwrap(); runner .record_migration( - &Migration { - id: MIGRATION_ID.to_string(), - description: String::new(), - version: 21, - created_at: Utc::now(), - }, + &Migration::new(MIGRATION_ID, String::new(), 21), 0, ) .await diff --git a/tests/migration_lock_tests.rs b/tests/migration_lock_tests.rs index 0acac49..271ca55 100644 --- a/tests/migration_lock_tests.rs +++ b/tests/migration_lock_tests.rs @@ -6,7 +6,6 @@ mod test_utils; -use chrono::Utc; use hammerwork::migrations::{Migration, MigrationManager, MigrationRunner}; /// How many runs race each other. @@ -16,12 +15,11 @@ const RUNS: usize = 6; /// not wait for the others would replay it and fail. fn probe_migration() -> (Migration, String) { let suffix = uuid::Uuid::new_v4().simple().to_string(); - let migration = Migration { - id: format!("900_lock_probe_{suffix}"), - description: "Concurrency probe (test only)".to_string(), - version: 900_000, - created_at: Utc::now(), - }; + let migration = Migration::new( + format!("900_lock_probe_{suffix}"), + "Concurrency probe (test only)", + 900_000, + ); (migration, format!("hw_lock_probe_{suffix}")) } diff --git a/tests/priority_tests.rs b/tests/priority_tests.rs index 702162a..0577b07 100644 --- a/tests/priority_tests.rs +++ b/tests/priority_tests.rs @@ -289,33 +289,27 @@ async fn test_priority_statistics_integration() { // Create events with different priorities let events = vec![ - JobEvent { - job_id: uuid::Uuid::new_v4(), - queue_name: "test_queue".to_string(), - event_type: JobEventType::Completed, - priority: JobPriority::Critical, - processing_time_ms: Some(1000), - error_message: None, - timestamp: chrono::Utc::now(), - }, - JobEvent { - job_id: uuid::Uuid::new_v4(), - queue_name: "test_queue".to_string(), - event_type: JobEventType::Completed, - priority: JobPriority::High, - processing_time_ms: Some(2000), - error_message: None, - timestamp: chrono::Utc::now(), - }, - JobEvent { - job_id: uuid::Uuid::new_v4(), - queue_name: "test_queue".to_string(), - event_type: JobEventType::Completed, - priority: JobPriority::Normal, - processing_time_ms: Some(1500), - error_message: None, - timestamp: chrono::Utc::now(), - }, + JobEvent::new( + uuid::Uuid::new_v4(), + "test_queue".to_string(), + JobEventType::Completed, + JobPriority::Critical, + ) + .with_processing_time_ms(1000), + JobEvent::new( + uuid::Uuid::new_v4(), + "test_queue".to_string(), + JobEventType::Completed, + JobPriority::High, + ) + .with_processing_time_ms(2000), + JobEvent::new( + uuid::Uuid::new_v4(), + "test_queue".to_string(), + JobEventType::Completed, + JobPriority::Normal, + ) + .with_processing_time_ms(1500), ]; // Record events diff --git a/tests/result_config_test.rs b/tests/result_config_test.rs index 1a32992..79857fa 100644 --- a/tests/result_config_test.rs +++ b/tests/result_config_test.rs @@ -16,11 +16,9 @@ async fn test_postgres_result_config_persistence() { let queue = test_utils::setup_postgres_queue().await; // Create a job with result storage configuration - let config = ResultConfig { - storage: ResultStorage::Database, - ttl: Some(Duration::from_secs(3600)), - max_size_bytes: Some(1024), - }; + let config = ResultConfig::new(ResultStorage::Database) + .with_ttl(Duration::from_secs(3600)) + .with_max_size(1024); let queue_name = format!("test_result_config_{}", uuid::Uuid::new_v4()); let _cleanup = test_utils::QueueCleanup::postgres(&queue_name); let job = Job::new(queue_name.clone(), json!({"task": "test"})).with_result_config(config); @@ -49,11 +47,9 @@ async fn test_mysql_result_config_persistence() { let queue = test_utils::setup_mysql_queue().await; // Create a job with result storage configuration - let config = ResultConfig { - storage: ResultStorage::Database, - ttl: Some(Duration::from_secs(7200)), - max_size_bytes: Some(2048), - }; + let config = ResultConfig::new(ResultStorage::Database) + .with_ttl(Duration::from_secs(7200)) + .with_max_size(2048); let queue_name = format!("test_result_config_mysql_{}", uuid::Uuid::new_v4()); let _cleanup = test_utils::QueueCleanup::mysql(&queue_name); let job = Job::new(queue_name.clone(), json!({"task": "test"})).with_result_config(config); diff --git a/tests/result_storage_tests.rs b/tests/result_storage_tests.rs index 0b6f1b1..93ae4a7 100644 --- a/tests/result_storage_tests.rs +++ b/tests/result_storage_tests.rs @@ -560,11 +560,9 @@ async fn test_result_config_builder_methods() { let job2 = Job::new("test".to_string(), json!({})).with_result_ttl(Duration::from_secs(7200)); assert_eq!(job2.result_config.ttl, Some(Duration::from_secs(7200))); - let config = ResultConfig { - storage: ResultStorage::Database, - ttl: Some(Duration::from_secs(3600)), - max_size_bytes: Some(1024 * 1024), // 1MB - }; + let config = ResultConfig::new(ResultStorage::Database) + .with_ttl(Duration::from_secs(3600)) + .with_max_size(1024 * 1024); // 1MB let job3 = Job::new("test".to_string(), json!({})).with_result_config(config.clone()); assert_eq!(job3.result_config.storage, config.storage); assert_eq!(job3.result_config.ttl, config.ttl); diff --git a/tests/worker_batch_tests.rs b/tests/worker_batch_tests.rs index dd85dc5..f8b0389 100644 --- a/tests/worker_batch_tests.rs +++ b/tests/worker_batch_tests.rs @@ -247,16 +247,16 @@ fn test_batch_processing_stats_struct() { fn test_worker_batch_processing_config() { // Test that batch processing configuration works // Test that BatchProcessingStats can be created and manipulated - let stats = BatchProcessingStats { - jobs_processed: 100, - jobs_completed: 95, - jobs_failed: 5, - batches_completed: 10, - batches_successful: 9, - total_processing_time_ms: 5000, - average_processing_time_ms: 52.6, - last_processed_job: Some(chrono::Utc::now()), - }; + // The stats are `#[non_exhaustive]`: start from the default and set the counters. + let mut stats = BatchProcessingStats::default(); + stats.jobs_processed = 100; + stats.jobs_completed = 95; + stats.jobs_failed = 5; + stats.batches_completed = 10; + stats.batches_successful = 9; + stats.total_processing_time_ms = 5000; + stats.average_processing_time_ms = 52.6; + stats.last_processed_job = Some(chrono::Utc::now()); assert_eq!(stats.success_rate(), 0.95); assert_eq!(stats.batch_success_rate(), 0.9); diff --git a/tests/worker_config_tests.rs b/tests/worker_config_tests.rs index 7ec59a1..177ac08 100644 --- a/tests/worker_config_tests.rs +++ b/tests/worker_config_tests.rs @@ -467,13 +467,11 @@ where concurrency.handler(Duration::from_millis(150)), ) .with_poll_interval(Duration::from_millis(20)); - let config = hammerwork::config::WorkerConfig { - pool_size: 1, - autoscaling_enabled: true, - min_workers: 1, - max_workers: 3, - ..Default::default() - }; + let config = hammerwork::config::WorkerConfig::default() + .with_pool_size(1) + .with_autoscaling_enabled(true) + .with_min_workers(1) + .with_max_workers(3); let mut pool = WorkerPool::from_config(worker, &config) .with_autoscaling( config diff --git a/tests/worker_pool_archival_tests.rs b/tests/worker_pool_archival_tests.rs index 59dcc8f..7bf74f7 100644 --- a/tests/worker_pool_archival_tests.rs +++ b/tests/worker_pool_archival_tests.rs @@ -20,15 +20,17 @@ use std::{collections::HashSet, sync::Arc, time::Duration}; /// Archive completed jobs at once; keep archived jobs for an hour. fn policy() -> ArchivalPolicy { - ArchivalPolicy { - archive_completed_after: Some(chrono::Duration::zero()), - archive_failed_after: None, - archive_dead_after: None, - archive_timed_out_after: None, - purge_archived_after: Some(chrono::Duration::hours(1)), - compress_payloads: true, - batch_size: 2, - enabled: true, + { + let mut value = ArchivalPolicy::default(); + value.archive_completed_after = Some(chrono::Duration::zero()); + value.archive_failed_after = None; + value.archive_dead_after = None; + value.archive_timed_out_after = None; + value.purge_archived_after = Some(chrono::Duration::hours(1)); + value.compress_payloads = true; + value.batch_size = 2; + value.enabled = true; + value } } @@ -224,10 +226,11 @@ where let archiver = || { JobArchiver::new(queue.pool.clone()) - .with_default_policy(ArchivalPolicy { - purge_archived_after: None, - batch_size: 5, - ..policy() + .with_default_policy({ + let mut value = policy(); + value.purge_archived_after = None; + value.batch_size = 5; + value }) .with_config(ArchivalConfig::new()) }; From 1940a86e982d00424e99d2a3355d34bb2b63e64e Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Sun, 11 Oct 2026 17:41:19 -0400 Subject: [PATCH 2/2] feat!: mark growing public enums #[non_exhaustive] (#86) Error, event and option enums that keep gaining variants are now #[non_exhaustive], so adding a variant is not a breaking change. JobStatus, JobPriority, the other state enums, AlertSeverity and SmtpTls stay exhaustive. The CLI and dashboard, which match these enums from outside the library, gain wildcard arms: `webhook test` refuses an HTTP method or authentication it does not know, the dashboard shows an unknown job event as `Unknown` and skips unknown archive events. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + cargo-hammerwork/src/commands/webhook.rs | 9 +++++ docs/upgrading-to-3.0.md | 45 ++++++++++++++++++++++++ hammerwork-web/src/live.rs | 2 ++ hammerwork-web/src/websocket.rs | 6 ++++ src/alerting.rs | 3 ++ src/archive.rs | 2 ++ src/batch.rs | 1 + src/config.rs | 1 + src/cron.rs | 1 + src/encryption.rs | 4 +++ src/encryption/key_manager.rs | 2 ++ src/error.rs | 1 + src/events.rs | 1 + src/job.rs | 1 + src/priority.rs | 2 ++ src/queue/lifecycle.rs | 2 ++ src/retry.rs | 2 ++ src/spawn.rs | 1 + src/stats.rs | 1 + src/streaming.rs | 4 +++ src/webhooks.rs | 2 ++ src/worker.rs | 1 + src/workflow.rs | 1 + 24 files changed, 96 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f0bd5f..3458f13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ See [Upgrading from 2.x to 3.0](docs/upgrading-to-3.0.md) for what to change. - **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. - **`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. ### Fixed diff --git a/cargo-hammerwork/src/commands/webhook.rs b/cargo-hammerwork/src/commands/webhook.rs index bde2e9a..e3479ff 100644 --- a/cargo-hammerwork/src/commands/webhook.rs +++ b/cargo-hammerwork/src/commands/webhook.rs @@ -433,6 +433,11 @@ pub async fn send_test_event( HttpMethod::Post => client.post(&webhook.url), HttpMethod::Put => client.put(&webhook.url), HttpMethod::Patch => client.patch(&webhook.url), + // `HttpMethod` is non-exhaustive: a method this CLI does not know yet. + _ => anyhow::bail!( + "This version of the CLI cannot send {:?} requests", + webhook.method + ), }; for (key, value) in &webhook.headers { request = request.header(key, value); @@ -455,6 +460,10 @@ pub async fn send_test_event( request = request.header(key, value); } } + // `WebhookAuth` is non-exhaustive: refuse to send without credentials we cannot apply. + Some(_) => anyhow::bail!( + "This version of the CLI does not support the webhook's authentication method" + ), None => {} } if let Some(secret) = &webhook.secret { diff --git a/docs/upgrading-to-3.0.md b/docs/upgrading-to-3.0.md index fcb3e33..663d8f5 100644 --- a/docs/upgrading-to-3.0.md +++ b/docs/upgrading-to-3.0.md @@ -490,6 +490,51 @@ Small types that are complete by definition stay exhaustive: `queue::StaleJobRec `rate_limit::RateLimit` (`rate`, `per`, `burst_limit`) and the newtypes `tracing::TraceId`, `tracing::CorrelationId` and `config::KeySourceRef`. +### Enums + +Enums that gain variants over time are `#[non_exhaustive]` too +([#86](https://github.com/CodingAnarchy/hammerwork/issues/86)). Constructing their +variants and matching specific ones is unchanged, but a `match` outside Hammerwork must +now end with a wildcard arm, so that a variant added in a minor release does not break +your build: + +```rust +use hammerwork::events::JobLifecycleEventType; + +fn describe(event_type: &JobLifecycleEventType) -> &'static str { + match event_type { + JobLifecycleEventType::Completed => "done", + JobLifecycleEventType::Failed | JobLifecycleEventType::Dead => "failed", + // Before (2.x) the remaining variants could be listed exhaustively. + // After (3.0) a wildcard arm is required: + _ => "other", + } +} +# assert_eq!(describe(&JobLifecycleEventType::Completed), "done"); +``` + +The non-exhaustive enums are: + +- Errors: `HammerworkError`, `encryption::EncryptionError`, `cron::CronError`, + `spawn::SpawnError`, `priority::PriorityError`. +- Events: `events::JobLifecycleEventType`, `stats::JobEventType`, `archive::ArchiveEvent`, + `alerting::AlertType`, `encryption::KeyOperation`. +- Backends and options: `streaming::StreamBackend`, `streaming::SerializationFormat`, + `streaming::PartitioningStrategy`, `streaming::PartitionField`, `alerting::AlertTarget`, + `alerting::SecretSource`, `webhooks::WebhookAuth`, `webhooks::HttpMethod`, + `encryption::KeySource`, `encryption::RetentionPolicy`, + `encryption::EncryptionAlgorithm`, `config::PayloadEncryptionAlgorithm`, + `encryption::KeyPurpose`, `archive::ArchivalReason`, `batch::PartialFailureMode`, + `job::ResultStorage`, `priority::PrioritySelectionStrategy`, `retry::RetryStrategy`, + `retry::JitterType`, `workflow::FailurePolicy`, `worker::JobHandlerType`, + `queue::JobTransition`, `queue::JobOutcome`. + +These stay exhaustive, so matching every variant keeps working: `JobStatus` and +`JobPriority`, the other state enums (`batch::BatchStatus`, `workflow::WorkflowStatus`, +`workflow::DependencyStatus`, `encryption::KeyStatus`), `alerting::AlertSeverity` (a +fixed scale, like `JobPriority`) and `alerting::SmtpTls` (the three ways to connect to an +SMTP server). + ### `ArchivedJob` lists the workflow `ArchivedJob` has two new fields, `workflow_id` and `workflow_name`, filled in by diff --git a/hammerwork-web/src/live.rs b/hammerwork-web/src/live.rs index 1f5cb6f..794fcac 100644 --- a/hammerwork-web/src/live.rs +++ b/hammerwork-web/src/live.rs @@ -318,6 +318,8 @@ pub fn job_update_from_event(event: &JobLifecycleEvent) -> JobUpdate { E::TimedOut => "TimedOut", E::Cancelled => "Cancelled", E::Archived => "Archived", + // `JobLifecycleEventType` is non-exhaustive: an event type added later. + _ => "Unknown", }; let attempts = event .error diff --git a/hammerwork-web/src/websocket.rs b/hammerwork-web/src/websocket.rs index 79e484c..7c17b7a 100644 --- a/hammerwork-web/src/websocket.rs +++ b/hammerwork-web/src/websocket.rs @@ -394,6 +394,12 @@ impl WebSocketState { hammerwork::archive::ArchiveEvent::JobsPurged { count, older_than } => { BroadcastMessage::JobsPurged { count, older_than } } + // `ArchiveEvent` is non-exhaustive: the dashboard has no message for an event + // added later, so it is not forwarded. + other => { + tracing::debug!("Not forwarding archive event {other:?} to dashboard clients"); + return Ok(()); + } }; // Send to the broadcast channel diff --git a/src/alerting.rs b/src/alerting.rs index 1398636..22a7d4b 100644 --- a/src/alerting.rs +++ b/src/alerting.rs @@ -173,6 +173,7 @@ impl AlertingConfig { /// files. The value is read each time it is needed, so rotating the variable takes /// effect on the next alert. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] pub enum SecretSource { /// The secret itself. Only for development and tests. Static(String), @@ -343,6 +344,7 @@ fn single_line(value: &str) -> String { /// `Debug` never shows header values or the path of a webhook or Slack URL (a Slack /// webhook URL is itself a credential). #[derive(Clone, Serialize, Deserialize)] +#[non_exhaustive] pub enum AlertTarget { /// Webhook alert target Webhook { @@ -413,6 +415,7 @@ impl std::fmt::Display for AlertSeverity { /// Alert types that can be triggered #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] pub enum AlertType { HighErrorRate, QueueDepthExceeded, diff --git a/src/archive.rs b/src/archive.rs index bae734d..ded7d45 100644 --- a/src/archive.rs +++ b/src/archive.rs @@ -67,6 +67,7 @@ pub type ArchivalPolicyId = String; /// assert_eq!(ArchivalReason::default(), ArchivalReason::Automatic); /// ``` #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum ArchivalReason { /// Job was archived due to automatic policy. #[default] @@ -155,6 +156,7 @@ impl std::fmt::Display for ArchivalReason { /// }; /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] +#[non_exhaustive] pub enum ArchiveEvent { /// A job was archived JobArchived { diff --git a/src/batch.rs b/src/batch.rs index f86d19e..fcb17f9 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -24,6 +24,7 @@ pub type BatchId = Uuid; /// Strategies for handling partial failures within a batch. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum PartialFailureMode { /// Continue processing remaining jobs even if some fail. /// Failed jobs are tracked but don't stop batch processing. diff --git a/src/config.rs b/src/config.rs index 31a8440..26ab597 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1089,6 +1089,7 @@ impl Default for LoggingConfig { /// The same names as [`EncryptionAlgorithm`](crate::encryption::EncryptionAlgorithm), /// which is only available with the `encryption` feature. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] pub enum PayloadEncryptionAlgorithm { /// AES-256-GCM #[default] diff --git a/src/cron.rs b/src/cron.rs index ceca3b7..5f8f2e4 100644 --- a/src/cron.rs +++ b/src/cron.rs @@ -6,6 +6,7 @@ use std::str::FromStr; use thiserror::Error; #[derive(Error, Debug)] +#[non_exhaustive] pub enum CronError { #[error("Invalid cron expression: {0}")] InvalidExpression(String), diff --git a/src/encryption.rs b/src/encryption.rs index eb59acb..f678a31 100644 --- a/src/encryption.rs +++ b/src/encryption.rs @@ -84,6 +84,7 @@ pub(crate) type SecretBytes = zeroize::Zeroizing>; /// Errors that can occur during encryption operations. #[derive(Error, Debug)] +#[non_exhaustive] pub enum EncryptionError { /// Key management error (missing, invalid, or rotation failure). #[error("Key management error: {0}")] @@ -127,6 +128,7 @@ pub enum EncryptionError { /// Each algorithm has different characteristics in terms of performance, /// security, and compatibility. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum EncryptionAlgorithm { /// AES-256 in Galois/Counter Mode (AES-256-GCM). /// @@ -150,6 +152,7 @@ pub enum EncryptionAlgorithm { /// /// `Debug` and `Display` never show a `Static` key's material. #[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] +#[non_exhaustive] pub enum KeySource { /// Use a static key provided directly. /// @@ -477,6 +480,7 @@ impl Default for EncryptionConfig { /// automatic cleanup. Different retention policies can be applied /// based on data sensitivity and compliance requirements. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum RetentionPolicy { /// Keep data for a specific duration from job creation. DeleteAfter(Duration), diff --git a/src/encryption/key_manager.rs b/src/encryption/key_manager.rs index 8186ae0..ba134f1 100644 --- a/src/encryption/key_manager.rs +++ b/src/encryption/key_manager.rs @@ -302,6 +302,7 @@ pub struct EncryptionKey { /// Purpose of an encryption key #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[non_exhaustive] pub enum KeyPurpose { /// Data encryption key for encrypting job payloads Encryption, @@ -355,6 +356,7 @@ pub struct KeyAuditRecord { /// Types of key operations that can be audited #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] pub enum KeyOperation { /// Key was created Create, diff --git a/src/error.rs b/src/error.rs index 6e69776..d5259f3 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,7 @@ use thiserror::Error; #[derive(Error, Debug)] +#[non_exhaustive] pub enum HammerworkError { #[error("Database error: {0}")] Database(#[from] sqlx::Error), diff --git a/src/events.rs b/src/events.rs index b88899f..0e4ce02 100644 --- a/src/events.rs +++ b/src/events.rs @@ -200,6 +200,7 @@ pub struct JobLifecycleEvent { /// Types of job lifecycle events #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[non_exhaustive] pub enum JobLifecycleEventType { /// Job was enqueued and is pending execution Enqueued, diff --git a/src/job.rs b/src/job.rs index 34c95fd..a9ee1ed 100644 --- a/src/job.rs +++ b/src/job.rs @@ -230,6 +230,7 @@ impl Decode<'_, MySql> for JobStatus { /// let no_storage = ResultStorage::None; /// ``` #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum ResultStorage { /// Store results in the database (persistent across restarts). Database, diff --git a/src/priority.rs b/src/priority.rs index c6be146..c7d8486 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -428,6 +428,7 @@ impl Default for PriorityWeights { /// Errors related to priority handling #[derive(Error, Debug)] +#[non_exhaustive] pub enum PriorityError { #[error("Invalid priority value: {0}. Must be between 0 and 4")] InvalidPriorityValue(i32), @@ -446,6 +447,7 @@ pub enum PriorityError { /// Priority-aware job selection strategy #[derive(Debug, Clone, Default)] +#[non_exhaustive] pub enum PrioritySelectionStrategy { /// Weighted random selection based on priority weights #[default] diff --git a/src/queue/lifecycle.rs b/src/queue/lifecycle.rs index 1063311..ab79a21 100644 --- a/src/queue/lifecycle.rs +++ b/src/queue/lifecycle.rs @@ -34,6 +34,7 @@ use serde::{Deserialize, Serialize}; /// A manual status transition, as performed by the corresponding /// [`DatabaseQueue`](super::DatabaseQueue) method. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] pub enum JobTransition { /// [`complete_job`](super::DatabaseQueue::complete_job): to `Completed`. Complete, @@ -129,6 +130,7 @@ impl JobTransition { /// How one run of a job ended, as reported by the worker that ran it to /// [`DatabaseQueue::finish_job_run`](super::DatabaseQueue::finish_job_run). #[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] pub enum JobOutcome { /// The handler succeeded. Completed, diff --git a/src/retry.rs b/src/retry.rs index b17e6b2..dcc6f09 100644 --- a/src/retry.rs +++ b/src/retry.rs @@ -72,6 +72,7 @@ use std::time::Duration; /// let multiplicative = JitterType::Multiplicative(0.2); /// ``` #[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] pub enum JitterType { /// Add a random duration between 0 and the specified value. /// @@ -280,6 +281,7 @@ impl<'de> Deserialize<'de> for JitterType { /// jitter: None, /// }; /// ``` +#[non_exhaustive] pub enum RetryStrategy { /// Fixed delay between all retry attempts. /// diff --git a/src/spawn.rs b/src/spawn.rs index 8561148..bbec58b 100644 --- a/src/spawn.rs +++ b/src/spawn.rs @@ -137,6 +137,7 @@ impl SpawnContext { /// Error types specific to spawn operations. #[derive(Debug, thiserror::Error)] +#[non_exhaustive] pub enum SpawnError { #[error("Spawn limit exceeded: attempted to spawn {attempted} jobs, limit is {limit}")] SpawnLimitExceeded { attempted: usize, limit: usize }, diff --git a/src/stats.rs b/src/stats.rs index 54a4ea0..200e22f 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -114,6 +114,7 @@ pub struct JobEvent { } #[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] pub enum JobEventType { Started, Completed, diff --git a/src/streaming.rs b/src/streaming.rs index efdeed1..01a039c 100644 --- a/src/streaming.rs +++ b/src/streaming.rs @@ -297,6 +297,7 @@ pub struct StreamConfig { /// values of the `config` maps (they may hold SASL passwords), only their keys. #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "type")] +#[non_exhaustive] pub enum StreamBackend { /// Apache Kafka backend Kafka { @@ -425,6 +426,7 @@ impl std::fmt::Debug for StreamBackend { /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] +#[non_exhaustive] pub enum PartitioningStrategy { /// No partitioning - all events go to single partition None, @@ -445,6 +447,7 @@ pub enum PartitioningStrategy { /// Fields that can be used for hash-based partitioning #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[non_exhaustive] pub enum PartitionField { JobId, QueueName, @@ -496,6 +499,7 @@ pub enum PartitionField { /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] +#[non_exhaustive] pub enum SerializationFormat { /// JSON serialization Json, diff --git a/src/webhooks.rs b/src/webhooks.rs index ecb3606..c407ed4 100644 --- a/src/webhooks.rs +++ b/src/webhooks.rs @@ -251,6 +251,7 @@ impl std::fmt::Debug for WebhookConfig { /// HTTP methods supported for webhooks #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] +#[non_exhaustive] pub enum HttpMethod { Post, Put, @@ -273,6 +274,7 @@ impl std::fmt::Display for HttpMethod { /// API keys or header values. #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "type")] +#[non_exhaustive] pub enum WebhookAuth { /// Bearer token authentication Bearer { token: String }, diff --git a/src/worker.rs b/src/worker.rs index 515ddcf..50acaa5 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -464,6 +464,7 @@ impl Default for JobResult { /// Enum to support both original and enhanced job handlers #[derive(Clone)] +#[non_exhaustive] pub enum JobHandlerType { /// Original handler type that returns Result<()> Legacy(JobHandler), diff --git a/src/workflow.rs b/src/workflow.rs index 8b8dfdc..f551a94 100644 --- a/src/workflow.rs +++ b/src/workflow.rs @@ -97,6 +97,7 @@ impl WorkflowStatus { /// `TimedOut`), not when a failed run is retried. See /// [`DatabaseQueue::fail_job_dependencies`](crate::queue::DatabaseQueue::fail_job_dependencies). #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[non_exhaustive] pub enum FailurePolicy { /// Stop the entire workflow when any job fails: its `Pending` and `Retrying` jobs /// (and any job depending on the failed one) become `Failed`, and the workflow