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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **M8:** a worker with a metrics collector no longer runs `COUNT(*)` for the queue depth on every poll; the monitoring task already updates it.
- **M10:** a worker's monitoring task is aborted however `run` ends (an error, a panic, or the future being dropped), so supervisor restarts no longer leak monitoring loops.
- `TestQueue::mark_job_dead` and `mark_job_timed_out` apply the workflow failure policy and a fail-fast batch's failure like the database backends, `TestQueue::finish_job_run` reports the jobs failed with a run in `RecordedOutcome::cancelled`, and a stale job the `TestQueue` reaper marks `Dead` applies the policy too.
- **Webhook and stream delivery, and config values that were ignored** (part of [#64](https://github.com/CodingAnarchy/hammerwork/issues/64): H11, H12, H13, M3, M4, M7, M9):
- **H11:** `WebhookManager::update_webhook` started a second listener next to the old one, so after N updates every event was POSTed N+1 times. It now swaps the configuration in place (no gap, statistics kept); removing a webhook or stream, or adding one again under the same id, stops the old listener at once.
- **H12:** a webhook or stream whose endpoint was down piled up one task per event without limit. At most `WebhookManagerConfig::max_pending_deliveries` deliveries per webhook (new, default 1000) and `BufferConfig::max_events` events per stream are pending; beyond that the listener waits, and events that overflow the event manager's buffer are dropped oldest-first, logged, and counted in the new `WebhookStats::dropped_events` / `StreamStats::dropped_events`. Retry backoff no longer holds a `max_concurrent_deliveries` / `max_concurrent_processors` slot.
- **H13:** the webhook timeout covered only the response headers, so an endpoint that trickled its body held a delivery slot forever. `timeout_secs` now covers the whole attempt including the body, and at most `max_response_body_size` bytes of the body are read.
- **M9:** webhook and stream listeners subscribed in their own task, so events published right after `add_webhook` / `add_stream` returned were missed. The subscription is now made before those calls return.
- **M7:** `InMemoryStatsCollector` shifted its whole buffer on every event once full and copied up to 100,000 events per statistics query. Recording is now amortised O(1) (a time-ordered ring buffer) and queries aggregate the events in their window in place.
- **M4:** settings that were accepted and never read now work: `WebhookManagerConfig::default_timeout_secs` (used when a webhook's `timeout_secs` is 0 or missing; also `webhooks.global_settings.default_timeout_secs`), `StreamManagerConfig::global_flush_interval_secs` (caps every stream's `max_buffer_time_secs`), `MetricsConfig::update_interval` (the worker monitoring interval when a metrics collector is set; it was fixed at 30 s), `StatsConfig::max_event_age_secs` (applied on every insert) and `StatsConfig::collect_timing`, and `[logging]` through the new `LoggingConfig::try_init()`. `JobBatch::with_batch_size` is documented as what it is: the chunk size of `into_chunks` (`enqueue_batch` always writes the whole batch in one transaction).
- **M3 / M4, deprecated because they have no sound meaning:** `PriorityWeights::with_fairness_factor` / `fairness_factor` (weighted selection already gives every priority with runnable jobs a share proportional to its weight, so nothing starves; raise a weight instead), `AutoscaleConfig::idle_timeout` / `with_idle_timeout`, `StatsConfig::cleanup_interval_secs`, `AlertingConfig::custom_thresholds` / `with_custom_threshold`, and `hammerwork_web::DashboardConfig::request_timeout`. They still compile and still parse from configuration files (now optional there) but have no effect.
- **Behaviour changes:** webhook statistics survive `update_webhook`; an attempt whose status arrived in time but whose body did not counts by its status; a webhook with `timeout_secs = 0` uses the manager's default instead of timing out at once; a stream flushes when its oldest buffered event has waited `max_buffer_time_secs` (it used to flush a lone event after an idle period immediately); with a metrics collector the worker monitoring task runs every `update_interval` (15 s by default) instead of every 30 s; `InMemoryStatsCollector` drops events older than `max_event_age_secs` (1 hour by default) without waiting for `cleanup_old_events`. **Breaking for struct literals:** `WebhookManagerConfig` (`max_pending_deliveries`), `WebhookGlobalSettings` (`default_timeout_secs`, `max_pending_deliveries`), `WebhookStats` and `StreamStats` (`dropped_events`) have new fields; use `..Default::default()` where available. `tracing-subscriber` now enables its `json` feature.
- The CLI no longer hangs when the database is unreachable: connecting gives up after 10 seconds with a clear error. Configure with `connect_timeout_secs` in `config.toml`, `cargo hammerwork config set connect_timeout_secs N`, or `HAMMERWORK_CONNECT_TIMEOUT`.
- **Queue failure semantics are the same on every backend** ([#59](https://github.com/CodingAnarchy/hammerwork/issues/59)):
- PostgreSQL/MySQL `fail_job_dependencies` now applies the workflow's `FailurePolicy`, as documented. It used to fail the failed job's dependents under every policy: under `Manual` it failed jobs that should keep waiting, and under `FailFast` it left the workflow's other pending jobs and its status alone. It now locks the job and its workflow like a terminal transition, applies `FailFast` (the workflow's `Pending`/`Retrying` jobs and all dependents fail, workflow `failed`), `ContinueOnFailure` (only the transitive dependents fail) or `Manual` (nothing changes), and updates the workflow's counters and status.
Expand Down
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
async-trait = "0.1"
tokio-test = "0.4"
rand = "0.8"
Expand Down
41 changes: 40 additions & 1 deletion docs/monitoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,50 @@ check.

Workers automatically start a background monitoring task that:

- Updates queue depth metrics every 30 seconds
- Updates queue depth metrics
- Checks for worker starvation
- Monitors statistical thresholds
- Triggers alerts when thresholds are exceeded

It runs every `MetricsConfig::update_interval` (15 seconds by default, at least one
second) when the worker has a metrics collector, and every 30 seconds otherwise.

## Statistics Collector

`InMemoryStatsCollector` keeps recent job events for the statistics that alert
thresholds and dashboards read. Recording an event is constant time; queries read only
the events inside their window. `StatsConfig` bounds what is kept:

| Field | Default | Meaning |
|-------|---------|---------|
| `max_events` | 100,000 | events kept; the oldest are dropped first |
| `max_event_age_secs` | 3600 | events older than this are pruned whenever an event is recorded (and not recorded at all) |
| `collect_timing` | `true` | keep processing times; when `false`, timing statistics stay at zero |
| `cleanup_interval_secs` | 300 | deprecated and ignored: pruning happens on every insert |

`AlertingConfig::custom_thresholds` (and `with_custom_threshold`) are deprecated: no
alert ever read them. Configuration files that set them still load.

## Logging

The `[logging]` section of `hammerwork.toml` is applied by
`config.logging.try_init()`, which installs a global `tracing` subscriber: `level` is an
`EnvFilter` directive (`"info"`, `"warn,hammerwork=debug"`), `json_format` switches to
JSON lines, and `include_location` adds file and line numbers. With
`enable_tracing = true` (and the `tracing` feature), spans are also exported over OTLP
to `tracing_endpoint` as `service_name`; call `hammerwork::tracing::shutdown_tracing()`
before exiting to flush them.

```rust
let logging = hammerwork::config::LoggingConfig {
level: "warn,hammerwork=debug".to_string(),
json_format: true,
..Default::default()
};
# let _ = &logging;
// logging.try_init()?;
```

## Custom Metrics

```rust
Expand Down
26 changes: 11 additions & 15 deletions docs/priority-system.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ let custom_job = Job::new("custom".to_string(), payload.clone())

Ensures high-priority jobs are processed more frequently while preventing starvation of low-priority jobs.

Each time a worker polls, it picks one of the priorities that currently have a runnable job, with probability `weight / (sum of the weights of those priorities)`, and takes the oldest job of that priority. A priority with a non-zero weight is therefore picked regularly however many higher-priority jobs are queued: with the weights below and Critical, Normal and Background jobs all waiting, Background is picked 1 time in 61. To give a priority a bigger share, raise its weight. A weight of `0` means "only when nothing with a weight is runnable".

`PriorityWeights::with_fairness_factor` is deprecated: it was documented as a fairness knob but never applied, and the weighted pick above already prevents starvation. Configuration files that set `fairness_factor` still load; the value is ignored.

```rust,no_run
# #[allow(unused_imports)] use hammerwork::{*, priority::*, queue::*, worker::*, stats::*};
# #[allow(unused_imports)] use serde_json::json;
Expand All @@ -62,8 +66,7 @@ let priority_weights = PriorityWeights::new()
.with_weight(JobPriority::High, 20) // High jobs are 20x more likely than normal
.with_weight(JobPriority::Normal, 10) // Normal jobs baseline weight
.with_weight(JobPriority::Low, 5) // Low jobs are 2x less likely than normal
.with_weight(JobPriority::Background, 1) // Background jobs are 10x less likely than normal
.with_fairness_factor(0.1); // 10% chance to select from lower priorities
.with_weight(JobPriority::Background, 1); // Background jobs are 10x less likely than normal

let worker = Worker::new(queue, "priority_queue".to_string(), handler)
.with_priority_weights(priority_weights);
Expand Down Expand Up @@ -140,8 +143,7 @@ let high_throughput_weights = PriorityWeights::new()
.with_weight(JobPriority::High, 50) // High weight for important jobs
.with_weight(JobPriority::Normal, 10) // Standard baseline
.with_weight(JobPriority::Low, 2) // Very low weight for analytics
.with_weight(JobPriority::Background, 1) // Minimal background processing
.with_fairness_factor(0.05); // Only 5% fairness to maximize critical job processing
.with_weight(JobPriority::Background, 1); // Minimal background processing
# Ok(())
# }
```
Expand All @@ -163,8 +165,7 @@ let balanced_weights = PriorityWeights::new()
.with_weight(JobPriority::High, 15) // Moderate boost for high
.with_weight(JobPriority::Normal, 10) // Baseline
.with_weight(JobPriority::Low, 7) // Small reduction for low
.with_weight(JobPriority::Background, 3) // Background jobs still get reasonable processing
.with_fairness_factor(0.2); // 20% fairness ensures good coverage
.with_weight(JobPriority::Background, 3); // Background jobs still get reasonable processing
# Ok(())
# }
```
Expand All @@ -186,8 +187,7 @@ let background_heavy_weights = PriorityWeights::new()
.with_weight(JobPriority::High, 15) // High gets some priority
.with_weight(JobPriority::Normal, 10) // Standard baseline
.with_weight(JobPriority::Low, 8) // Low priority gets good processing
.with_weight(JobPriority::Background, 6) // Background jobs get substantial processing time
.with_fairness_factor(0.3); // High fairness ensures background jobs aren't starved
.with_weight(JobPriority::Background, 6); // Background jobs get substantial processing time
# Ok(())
# }
```
Expand Down Expand Up @@ -242,14 +242,13 @@ if !priority_stats.check_starvation(2.0).is_empty() { // 2% threshold
eprintln!("WARNING: Priority starvation detected!");
eprintln!("Lower priority jobs may not be getting processed adequately");

// Consider adjusting weights or fairness factor
// Consider raising the weights of the lower priorities
let adjusted_weights = PriorityWeights::new()
.with_weight(JobPriority::Critical, 30) // Reduce critical weight
.with_weight(JobPriority::High, 15) // Reduce high weight
.with_weight(JobPriority::Normal, 10)
.with_weight(JobPriority::Low, 8)
.with_weight(JobPriority::Background, 5)
.with_fairness_factor(0.25); // Increase fairness
.with_weight(JobPriority::Background, 5);
}
# Ok(())
# }
Expand Down Expand Up @@ -328,7 +327,6 @@ let background_worker = Worker::new(queue.clone(), "maintenance".to_string(), ma
.with_weight(JobPriority::Normal, 2)
.with_weight(JobPriority::Low, 2)
.with_weight(JobPriority::Background, 1)
.with_fairness_factor(0.5) // Very fair processing
);

let email_worker = Worker::new(queue.clone(), "email".to_string(), email_handler)
Expand All @@ -339,7 +337,6 @@ let email_worker = Worker::new(queue.clone(), "email".to_string(), email_handler
.with_weight(JobPriority::Normal, 10)
.with_weight(JobPriority::Low, 5)
.with_weight(JobPriority::Background, 2)
.with_fairness_factor(0.15)
);
# Ok(())
# }
Expand Down Expand Up @@ -403,7 +400,6 @@ let worker = Worker::new(queue, "priority_limited".to_string(), handler)
.with_weight(JobPriority::Normal, 10)
.with_weight(JobPriority::Low, 5)
.with_weight(JobPriority::Background, 1)
.with_fairness_factor(0.1)
)
.with_rate_limit(RateLimit::per_second(10)); // Overall rate limit

Expand Down Expand Up @@ -543,7 +539,7 @@ async fn check_priority_health(
"critical_percentage": stats.priority_distribution.get(&JobPriority::Critical),
"background_percentage": stats.priority_distribution.get(&JobPriority::Background),
"total_jobs": stats.job_counts.values().sum::<u64>(),
"recommendation": "Consider adjusting priority weights or fairness factor"
"recommendation": "Consider raising the weights of the lower priorities"
});

// Send alert via webhook (implement based on your alerting setup)
Expand Down
28 changes: 23 additions & 5 deletions docs/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,28 @@ streams.shutdown(Duration::from_secs(10)).await;
## Delivery

Each stream has a listener that buffers matching events and flushes a batch when it
holds `buffer_config.batch_size` events, when `max_buffer_time_secs` has passed, or when
it holds `max_events`. A batch is serialized with the stream's `serialization` format
and handed to the backend processor's `send_batch`, which reports a result per event.
The bytes produced by the serialization format are what the backend receives, for
every backend.
holds `buffer_config.batch_size` events, when it holds `max_events`, or when its oldest
event has waited `max_buffer_time_secs` (capped by the manager's
`global_flush_interval_secs`, so no stream buffers an event longer than that). A batch
is serialized with the stream's `serialization` format and handed to the backend
processor's `send_batch`, which reports a result per event. The bytes produced by the
serialization format are what the backend receives, for every backend.

The stream subscribes to events before `add_stream` returns, so an event published
right after that call is streamed. Removing a stream, or adding one with the same id
again, stops its previous listener immediately: an event is never streamed twice
because a stream was re-added.

### Backlog limit

At most `buffer_config.max_events` events of a stream are in batches at once (being
sent, or waiting to retry). When a stream reaches that limit, for example because the
backend is down, its listener stops reading events until a batch finishes. Events keep
arriving in the event manager's broadcast buffer (`EventConfig::max_buffer_size`);
once that is full the oldest are dropped for this stream, a warning is logged, and
`dropped_events` counts them. So memory use stays bounded however long the backend is
unavailable. `max_concurrent_processors` limits how many batches are being sent at
once across all streams; a batch waiting out a retry delay does not hold a slot.

### Retries

Expand Down Expand Up @@ -82,6 +99,7 @@ actually happened. They are updated once per batch, after its retries:
| `avg_delivery_time_ms` | average delivery time of acknowledged events |
| `last_success_at`, `last_failure_at` | when the last batch with a success / failure finished |
| `last_error` | the error behind the most recent failure |
| `dropped_events` | events skipped because the listener fell behind (see [Backlog limit](#backlog-limit)) |

## Health checks

Expand Down
43 changes: 43 additions & 0 deletions docs/webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,49 @@ Without a template, the request body is the `JobLifecycleEvent` as JSON. When a
`secret` is set, `X-Hammerwork-Signature: sha256=<hex>` is the HMAC-SHA256 of the body
that was actually sent (the rendered template, if one is configured).

## Delivery

`add_webhook` subscribes before it returns, so an event published right after the
call is delivered. Each webhook has one listener, which starts a delivery (with
retries per its `RetryPolicy`) for every matching event.

- **Updating.** `update_webhook` swaps the configuration in place: the next event
uses the new URL, filter, headers and so on, statistics are kept, and no event is
missed or sent twice. Removing a webhook, or calling `add_webhook` again with the
same id, stops its old listener immediately.
- **Timeout.** `timeout_secs` covers the whole attempt: connecting, sending, the
response headers and the response body. When the status arrived in time but the
body did not, the attempt counts by its status and the body is not recorded.
`timeout_secs = 0` (or leaving it out of a configuration file) uses the manager's
`default_timeout_secs` (30 s by default).
- **Response bodies.** At most `max_response_body_size` bytes are read (64 KiB by
default); the rest of a longer body is not downloaded.
- **Concurrency.** `max_concurrent_deliveries` limits the requests in flight across
all webhooks. A delivery waiting out a retry delay does not hold a slot.
- **Backlog limit.** At most `max_pending_deliveries` deliveries per webhook (1000 by
default) are pending: waiting for a slot, in flight, or waiting to retry. When a
webhook reaches the limit, for example because its endpoint is down, its listener
stops taking events until a delivery finishes. Events keep arriving in the event
manager's broadcast buffer (`EventConfig::max_buffer_size`); once that is full the
oldest are dropped for this webhook, a warning is logged, and
`WebhookStats::dropped_events` counts them. Memory use stays bounded however long
the endpoint is down.

```rust
use hammerwork::webhooks::WebhookManagerConfig;

let config = WebhookManagerConfig {
max_concurrent_deliveries: 50,
default_timeout_secs: 10,
max_pending_deliveries: 500,
..Default::default()
};
assert_eq!(config.max_response_body_size, 64 * 1024);
```

In `hammerwork.toml`, `[webhooks.global_settings]` accepts the same
`default_timeout_secs` and `max_pending_deliveries` keys; both are optional.

## Payload templates

Set `payload_template` (or call `WebhookConfig::with_payload_template`) to send the JSON
Expand Down
Loading
Loading