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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,15 @@ 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<Postgres>`, `JobQueue<MySql>` 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<Job>`. The new `#[non_exhaustive]` `queue::DequeueOptions` (also `hammerwork::DequeueOptions`) has `priority_weights: Option<PriorityWeights>`, `lease_duration: Option<Duration>` (`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<Job>`). 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.
- **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

Expand Down
37 changes: 18 additions & 19 deletions cargo-hammerwork/src/commands/archive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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",
Expand Down
79 changes: 37 additions & 42 deletions cargo-hammerwork/src/commands/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -441,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);
Expand All @@ -463,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 {
Expand Down Expand Up @@ -666,29 +667,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<hammerwork::HttpMethod> {
Expand Down
27 changes: 12 additions & 15 deletions docs/job-spawning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -214,30 +212,29 @@ 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;
# #[allow(unused_variables, unused_mut, dead_code, unreachable_code)]
# async fn doc(queue: std::sync::Arc<hammerwork::JobQueue<sqlx::Postgres>>, handler: hammerwork::worker::JobHandler, payload: serde_json::Value, job: hammerwork::Job) -> std::result::Result<(), Box<dyn std::error::Error>> {
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));
# Ok(())
# }
```

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

Expand Down
8 changes: 3 additions & 5 deletions docs/monitoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()?;
```
Expand Down
13 changes: 6 additions & 7 deletions docs/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading