From 02210d8da1deef893c53fb562d9a6d2a73b5988c Mon Sep 17 00:00:00 2001 From: Matt Tanous Date: Fri, 9 Oct 2026 19:45:41 -0400 Subject: [PATCH] fix(delivery): bound webhook/stream backlogs, fix duplicate listeners, wire ignored config (#64 W4) - H11: update_webhook swaps the config in place; removing or re-adding a webhook or stream stops its old listener (ListenerHandle drop signal). - H12: at most max_pending_deliveries per webhook and BufferConfig::max_events per stream are pending; listeners wait, overflow is dropped oldest-first and counted in dropped_events. Retry backoff no longer holds a concurrency slot. - H13: the webhook timeout covers the response body, which is read up to max_response_body_size. - M9: subscribe before add_webhook/add_stream return; remove the test sleeps. - M7: InMemoryStatsCollector uses a time-ordered VecDeque, O(1) amortised inserts and in-place window aggregation. - M3: deprecate PriorityWeights::with_fairness_factor (never applied; the weighted pick already prevents starvation). - M4: wire default_timeout_secs, global_flush_interval_secs, MetricsConfig::update_interval, StatsConfig max_event_age_secs and collect_timing, and [logging] (LoggingConfig::try_init); deprecate idle_timeout, cleanup_interval_secs, custom_thresholds and web request_timeout; document JobBatch::with_batch_size. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + Cargo.lock | 13 + Cargo.toml | 2 +- docs/monitoring.md | 41 +- docs/priority-system.md | 26 +- docs/streaming.md | 28 +- docs/webhooks.md | 43 ++ docs/worker-configuration.md | 3 +- examples/autoscaling_example.rs | 3 +- examples/priority_example.rs | 12 +- hammerwork-web/README.md | 5 +- hammerwork-web/src/config.rs | 16 +- hammerwork-web/tests/integration_tests.rs | 2 - src/alerting.rs | 17 +- src/batch.rs | 18 +- src/config.rs | 151 +++- src/metrics.rs | 16 +- src/priority.rs | 71 +- src/stats.rs | 575 +++++++++----- src/streaming.rs | 429 +++++++--- src/task_tracker.rs | 62 ++ src/tracing.rs | 60 +- src/webhooks.rs | 902 ++++++++++++++++------ src/worker.rs | 51 +- tests/priority_tests.rs | 16 +- 25 files changed, 1930 insertions(+), 641 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c86bb7d..e415471 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/Cargo.lock b/Cargo.lock index e57e25c..77fc8ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5133,6 +5133,16 @@ dependencies = [ "web-time", ] +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.23" @@ -5143,12 +5153,15 @@ dependencies = [ "nu-ansi-term", "once_cell", "regex-automata", + "serde", + "serde_json", "sharded-slab", "smallvec", "thread_local", "tracing", "tracing-core", "tracing-log", + "tracing-serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 7e28510..03ef4a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/docs/monitoring.md b/docs/monitoring.md index 5093b6c..3b11790 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -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 diff --git a/docs/priority-system.md b/docs/priority-system.md index 923efc9..69beaba 100644 --- a/docs/priority-system.md +++ b/docs/priority-system.md @@ -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; @@ -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); @@ -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(()) # } ``` @@ -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(()) # } ``` @@ -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(()) # } ``` @@ -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(()) # } @@ -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) @@ -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(()) # } @@ -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 @@ -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::(), - "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) diff --git a/docs/streaming.md b/docs/streaming.md index c270d7f..9d1b67d 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -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 @@ -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 diff --git a/docs/webhooks.md b/docs/webhooks.md index 0dc3271..924beb4 100644 --- a/docs/webhooks.md +++ b/docs/webhooks.md @@ -32,6 +32,49 @@ Without a template, the request body is the `JobLifecycleEvent` as JSON. When a `secret` is set, `X-Hammerwork-Signature: sha256=` 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 diff --git a/docs/worker-configuration.md b/docs/worker-configuration.md index 3da4255..d2e59bf 100644 --- a/docs/worker-configuration.md +++ b/docs/worker-configuration.md @@ -90,8 +90,7 @@ let priority_weights = PriorityWeights::new() .with_weight(JobPriority::High, 20) .with_weight(JobPriority::Normal, 10) .with_weight(JobPriority::Low, 5) - .with_weight(JobPriority::Background, 1) - .with_fairness_factor(0.1); // 10% chance for lower priorities + .with_weight(JobPriority::Background, 1); let worker = Worker::new(queue, "priority_queue".to_string(), handler) .with_priority_weights(priority_weights); diff --git a/examples/autoscaling_example.rs b/examples/autoscaling_example.rs index 706cf10..c2e8452 100644 --- a/examples/autoscaling_example.rs +++ b/examples/autoscaling_example.rs @@ -253,8 +253,7 @@ where .with_scale_down_threshold(1) .with_cooldown_period(Duration::from_secs(45)) .with_scale_step(2) - .with_evaluation_window(Duration::from_secs(20)) - .with_idle_timeout(Duration::from_secs(180)); + .with_evaluation_window(Duration::from_secs(20)); let mut pool = WorkerPool::new() .with_worker_template(worker_template.clone()) diff --git a/examples/priority_example.rs b/examples/priority_example.rs index bb64f00..953cd54 100644 --- a/examples/priority_example.rs +++ b/examples/priority_example.rs @@ -133,8 +133,7 @@ async fn demonstrate_weighted_scheduling( .with_weight(JobPriority::High, 20) // High weight .with_weight(JobPriority::Normal, 5) // Normal weight .with_weight(JobPriority::Low, 2) // Low weight - .with_weight(JobPriority::Background, 1) // Minimal weight - .with_fairness_factor(0.1); // 10% fairness to prevent starvation + .with_weight(JobPriority::Background, 1); // Minimal weight, but never starved info!("🎛️ Priority weights configured:"); info!( @@ -151,10 +150,6 @@ async fn demonstrate_weighted_scheduling( " Background: {}x weight", weights.get_weight(JobPriority::Background) ); - info!( - " Fairness factor: {:.1}%", - weights.fairness_factor() * 100.0 - ); // Create worker with weighted priority let worker = Worker::new( @@ -348,7 +343,7 @@ async fn show_priority_statistics( let starved = priority_stats.check_starvation(5.0); // 5% threshold if !starved.is_empty() { info!(" ⚠️ Potential starvation detected for: {:?}", starved); - info!(" Consider adjusting priority weights or fairness factor"); + info!(" Consider raising the weights of the starved priorities"); } } } @@ -437,8 +432,7 @@ async fn demonstrate_worker_pool_priorities( // Worker 3: Custom weights for specialized tasks let custom_weights = PriorityWeights::new() .with_weight(JobPriority::Critical, 50) - .with_weight(JobPriority::High, 15) - .with_fairness_factor(0.2); + .with_weight(JobPriority::High, 15); let custom_worker = Worker::new(queue.clone(), "cleanup".to_string(), handler) .with_priority_weights(custom_weights) diff --git a/hammerwork-web/README.md b/hammerwork-web/README.md index 63cacd3..e85652c 100644 --- a/hammerwork-web/README.md +++ b/hammerwork-web/README.md @@ -81,7 +81,6 @@ static_dir = "./assets" enable_cors = false # Other origins whose pages may change data / open WebSockets (and, with enable_cors, read the API) allowed_origins = [] -request_timeout = "30s" [auth] enabled = true @@ -130,7 +129,6 @@ hammerwork-web = { version = "1.15", features = ["postgres"] } ```rust use hammerwork_web::{WebDashboard, DashboardConfig}; -use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { @@ -143,7 +141,6 @@ async fn main() -> Result<(), Box> { enable_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()], - request_timeout: Duration::from_secs(30), ..Default::default() }; @@ -490,7 +487,7 @@ server { - **Connection Pooling**: Tune `pool_size` based on concurrent users - **WebSocket Limits**: Configure `max_connections` for your use case -- **Request Timeouts**: Set appropriate `request_timeout` for your network +- **Request Timeouts**: The dashboard applies none of its own (`request_timeout` is deprecated and ignored); set them on a reverse proxy in front of it - **Database Indexes**: Ensure proper indexes on hammerwork_jobs table - **Static Assets**: Use a CDN for production deployments - **Monitoring**: Enable structured logging and metrics collection diff --git a/hammerwork-web/src/config.rs b/hammerwork-web/src/config.rs index 6c6975f..423d105 100644 --- a/hammerwork-web/src/config.rs +++ b/hammerwork-web/src/config.rs @@ -128,11 +128,22 @@ pub struct DashboardConfig { #[serde(default)] pub allowed_origins: Vec, - /// Request timeout duration + /// Unused: the dashboard does not apply a request timeout. Optional in + /// configuration files. + #[deprecated( + since = "1.15.6", + note = "never applied; put a reverse proxy with a timeout in front of the dashboard" + )] + #[serde(default = "default_request_timeout")] pub request_timeout: Duration, } +fn default_request_timeout() -> Duration { + Duration::from_secs(30) +} + impl Default for DashboardConfig { + #[allow(deprecated)] fn default() -> Self { Self { bind_address: "127.0.0.1".to_string(), @@ -144,7 +155,7 @@ impl Default for DashboardConfig { websocket: WebSocketConfig::default(), enable_cors: false, allowed_origins: Vec::new(), - request_timeout: Duration::from_secs(30), + request_timeout: default_request_timeout(), } } } @@ -438,6 +449,7 @@ impl Default for WebSocketConfig { } impl std::fmt::Debug for DashboardConfig { + #[allow(deprecated)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DashboardConfig") .field("bind_address", &self.bind_address) diff --git a/hammerwork-web/tests/integration_tests.rs b/hammerwork-web/tests/integration_tests.rs index 1080605..7882882 100644 --- a/hammerwork-web/tests/integration_tests.rs +++ b/hammerwork-web/tests/integration_tests.rs @@ -62,7 +62,6 @@ mod tests { }, enable_cors: true, allowed_origins: vec!["https://ops.example.com".to_string()], - request_timeout: Duration::from_secs(30), ..Default::default() }; @@ -116,7 +115,6 @@ mod tests { ..Default::default() }, enable_cors: false, - request_timeout: Duration::from_secs(30), ..Default::default() }; diff --git a/src/alerting.rs b/src/alerting.rs index 63eb261..ac597be 100644 --- a/src/alerting.rs +++ b/src/alerting.rs @@ -29,11 +29,18 @@ pub struct AlertingConfig { pub cooldown_period: Duration, /// Whether alerting is enabled pub enabled: bool, - /// Custom alert thresholds + /// Unused: no alert reads these thresholds (there are no named custom metrics to + /// compare them with). Optional in configuration files. + #[deprecated( + since = "1.15.6", + note = "never applied; no alert reads custom thresholds" + )] + #[serde(default)] pub custom_thresholds: HashMap, } impl Default for AlertingConfig { + #[allow(deprecated)] fn default() -> Self { Self { error_rate_threshold: None, @@ -139,7 +146,12 @@ impl AlertingConfig { self } - /// Add custom threshold + /// Unused; see [`AlertingConfig::custom_thresholds`]. + #[deprecated( + since = "1.15.6", + note = "never applied; no alert reads custom thresholds" + )] + #[allow(deprecated)] pub fn with_custom_threshold(mut self, name: String, threshold: f64) -> Self { self.custom_thresholds.insert(name, threshold); self @@ -1167,6 +1179,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn test_custom_thresholds() { let config = AlertingConfig::new() .with_custom_threshold("memory_usage".to_string(), 80.0) diff --git a/src/batch.rs b/src/batch.rs index e5e5ea3..b4e7f96 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -187,7 +187,10 @@ pub struct JobBatch { pub name: String, /// Jobs to be processed in this batch. pub jobs: Vec, - /// Maximum number of jobs to process in a single database operation. + /// Chunk size used by [`into_chunks`](Self::into_chunks) (1000 when unset). + /// + /// It does not change how `enqueue_batch` writes the batch: that always inserts + /// the whole batch in one transaction, in statements sized by the backend. pub batch_size: Option, /// Strategy for handling partial failures. pub failure_mode: PartialFailureMode, @@ -261,10 +264,11 @@ impl JobBatch { self } - /// Sets the maximum batch size for database operations. + /// Sets the chunk size used by [`into_chunks`](Self::into_chunks). /// - /// When enqueueing large batches, they will be split into chunks - /// of this size for optimal database performance. + /// To enqueue a large batch in several transactions, split it with `into_chunks` + /// and enqueue each chunk. `enqueue_batch` itself ignores this value: it always + /// inserts the whole batch in one transaction, in statements sized by the backend. /// /// # Examples /// @@ -368,9 +372,11 @@ impl JobBatch { Ok(()) } - /// Splits the batch into smaller chunks based on the configured batch size. + /// Splits the batch into chunks of [`batch_size`](Self::batch_size) jobs (1000 + /// when unset), each a new batch with its own id. /// - /// This is useful for processing very large batches in manageable chunks. + /// Enqueue the chunks one by one to write a very large batch in several + /// transactions. pub fn into_chunks(self) -> Vec { let chunk_size = self.batch_size.unwrap_or(1000) as usize; diff --git a/src/config.rs b/src/config.rs index 65d0492..2f82b3f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -594,6 +594,26 @@ pub struct WebhookGlobalSettings { /// User agent string for requests pub user_agent: String, + + /// Timeout in seconds for webhooks that do not set `timeout_secs` (or set it to 0). + /// See [`WebhookManagerConfig::default_timeout_secs`](crate::webhooks::WebhookManagerConfig::default_timeout_secs). + #[serde(default = "default_webhook_timeout_secs")] + pub default_timeout_secs: u64, + + /// Maximum deliveries pending per webhook before its listener waits. See + /// [`WebhookManagerConfig::max_pending_deliveries`](crate::webhooks::WebhookManagerConfig::max_pending_deliveries). + #[serde(default = "default_max_pending_deliveries")] + pub max_pending_deliveries: usize, +} + +#[cfg(feature = "webhooks")] +fn default_webhook_timeout_secs() -> u64 { + 30 +} + +#[cfg(feature = "webhooks")] +fn default_max_pending_deliveries() -> usize { + 1_000 } #[cfg(feature = "webhooks")] @@ -604,6 +624,8 @@ impl Default for WebhookGlobalSettings { max_response_body_size: 64 * 1024, // 64KB log_deliveries: true, user_agent: format!("hammerwork-webhooks/{}", env!("CARGO_PKG_VERSION")), + default_timeout_secs: default_webhook_timeout_secs(), + max_pending_deliveries: default_max_pending_deliveries(), } } } @@ -771,10 +793,20 @@ impl RateLimitingConfig { } } -/// Logging and tracing configuration +/// The subscriber [`LoggingConfig`] layers its outputs on: the registry with the level filter. +type LoggingSubscriber = + tracing_subscriber::layer::Layered; + +/// Logging and tracing configuration (`[logging]`). +/// +/// A library does not install a global logger on its own: call +/// [`LoggingConfig::try_init`] (for example `config.logging.try_init()?`) once at +/// startup to apply this section. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LoggingConfig { - /// Log level (trace, debug, info, warn, error) + /// Log filter: a level (trace, debug, info, warn, error) or any + /// [`EnvFilter`](tracing_subscriber::EnvFilter) directive, such as + /// `"info,hammerwork=debug"`. pub level: String, /// Whether to enable structured JSON logging @@ -783,16 +815,87 @@ pub struct LoggingConfig { /// Whether to include file and line information pub include_location: bool, - /// Whether to enable OpenTelemetry tracing + /// Whether to export spans with OpenTelemetry (requires the `tracing` feature) pub enable_tracing: bool, - /// OpenTelemetry endpoint URL + /// OpenTelemetry (OTLP/gRPC) endpoint URL. Without one, spans are not exported. pub tracing_endpoint: Option, /// Service name for tracing pub service_name: String, } +impl LoggingConfig { + /// Install a global `tracing` subscriber configured by this section: log lines on + /// stdout filtered by `level`, as JSON when `json_format` is set and with file and + /// line numbers when `include_location` is set. With `enable_tracing`, spans are + /// also exported over OTLP to `tracing_endpoint` under `service_name` (call + /// [`shutdown_tracing`](crate::tracing::shutdown_tracing) before exiting to flush + /// them); this needs the `tracing` feature and must be called inside a Tokio runtime. + /// + /// Fails with a configuration error for an invalid `level`, or when + /// `enable_tracing` is set in a build without the `tracing` feature, and with a + /// tracing error when a global subscriber is already installed. + pub fn try_init(&self) -> crate::Result<()> { + use tracing_subscriber::util::SubscriberInitExt; + self.subscriber()? + .try_init() + .map_err(|e| crate::HammerworkError::Tracing { + message: format!("Failed to initialize tracing subscriber: {e}"), + }) + } + + /// The subscriber [`try_init`](Self::try_init) installs. + fn subscriber(&self) -> crate::Result { + use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt}; + + let filter = EnvFilter::try_new(&self.level).map_err(|e| { + crate::HammerworkError::Config(format!("invalid logging.level '{}': {e}", self.level)) + })?; + + let mut layers: Vec + Send + Sync>> = Vec::new(); + let fmt = tracing_subscriber::fmt::layer() + .with_file(self.include_location) + .with_line_number(self.include_location); + if self.json_format { + layers.push(fmt.json().boxed()); + } else { + layers.push(fmt.boxed()); + } + if self.enable_tracing { + layers.push(self.telemetry_layer()?); + } + + Ok(tracing_subscriber::registry().with(filter).with(layers)) + } + + #[cfg(feature = "tracing")] + fn telemetry_layer( + &self, + ) -> crate::Result + Send + Sync>> { + use opentelemetry::trace::TracerProvider; + use tracing_subscriber::Layer; + let config = crate::tracing::TracingConfig { + service_name: self.service_name.clone(), + otlp_endpoint: self.tracing_endpoint.clone(), + ..crate::tracing::TracingConfig::new() + }; + let provider = crate::tracing::install_tracer_provider(&config)?; + Ok(tracing_opentelemetry::layer() + .with_tracer(provider.tracer("hammerwork")) + .boxed()) + } + + #[cfg(not(feature = "tracing"))] + fn telemetry_layer( + &self, + ) -> crate::Result + Send + Sync>> { + Err(crate::HammerworkError::Config( + "logging.enable_tracing requires the `tracing` feature".to_string(), + )) + } +} + impl Default for LoggingConfig { fn default() -> Self { Self { @@ -1629,6 +1732,46 @@ service_name = "hammerwork" assert!(!logging_config.json_format); } + /// M4: the `[logging]` section builds a working subscriber (plain or JSON, with or + /// without locations) and rejects what it cannot apply. + #[test] + fn test_logging_config_builds_its_subscriber() { + for (json_format, include_location) in [(false, false), (true, true)] { + let config = LoggingConfig { + level: "warn,hammerwork=debug".to_string(), + json_format, + include_location, + ..Default::default() + }; + let subscriber = config.subscriber().unwrap(); + tracing::subscriber::with_default(subscriber, || { + assert!(tracing::enabled!(target: "hammerwork::worker", tracing::Level::DEBUG)); + assert!(!tracing::enabled!(target: "other", tracing::Level::INFO)); + tracing::warn!("logging config test"); + }); + } + + let invalid = LoggingConfig { + level: "hammerwork=loud".to_string(), + ..Default::default() + }; + let err = invalid.subscriber().err().expect("invalid level"); + assert!(err.to_string().contains("logging.level"), "{err}"); + + #[cfg(not(feature = "tracing"))] + { + let tracing_without_feature = LoggingConfig { + enable_tracing: true, + ..Default::default() + }; + let err = tracing_without_feature + .subscriber() + .err() + .expect("no feature"); + assert!(err.to_string().contains("`tracing` feature"), "{err}"); + } + } + #[test] fn test_database_connection_timeout() { let config = DatabaseConfig { diff --git a/src/metrics.rs b/src/metrics.rs index e42ff2f..211ff13 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -55,6 +55,11 @@ use prometheus::{CounterVec, Encoder, GaugeVec, HistogramVec, Registry, TextEnco #[cfg(feature = "metrics")] use warp::Filter; +/// The shortest monitoring interval [`PrometheusMetricsCollector::update_interval`] +/// returns (a zero interval would make the monitoring task spin). +#[cfg(feature = "metrics")] +const MIN_UPDATE_INTERVAL: Duration = Duration::from_secs(1); + /// Configuration for metrics collection #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MetricsConfig { @@ -76,7 +81,10 @@ pub struct MetricsConfig { pub custom_gauges: Vec, /// Custom histogram metric names to track pub custom_histograms: Vec, - /// Update interval for gauge metrics (in seconds) + /// How often each worker's monitoring task refreshes gauge metrics (queue depth) + /// and runs its queue depth and starvation alert checks (in seconds). Values below + /// one second are raised to one second. Without a metrics collector, workers + /// monitor every 30 seconds. #[serde( serialize_with = "serialize_duration_secs", deserialize_with = "deserialize_duration_secs" @@ -289,6 +297,12 @@ impl PrometheusMetricsCollector { Ok(collector) } + /// How often workers using this collector run their monitoring task: + /// [`MetricsConfig::update_interval`], but at least one second. + pub fn update_interval(&self) -> Duration { + self.config.update_interval.max(MIN_UPDATE_INTERVAL) + } + /// Start the Prometheus HTTP exposition server. /// /// The listening socket is bound before this method returns, so a failure to diff --git a/src/priority.rs b/src/priority.rs index a8cab42..11613ef 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -277,26 +277,34 @@ impl std::str::FromStr for JobPriority { /// // Default weighted configuration /// let weights = PriorityWeights::new(); /// assert!(!weights.is_strict()); -/// assert_eq!(weights.fairness_factor(), 0.1); /// /// // Custom weighted configuration /// let custom_weights = PriorityWeights::new() /// .with_weight(JobPriority::Critical, 50) /// .with_weight(JobPriority::High, 20) -/// .with_weight(JobPriority::Normal, 10) -/// .with_fairness_factor(0.15); +/// .with_weight(JobPriority::Normal, 10); /// /// // Strict priority configuration /// let strict_weights = PriorityWeights::strict(); /// assert!(strict_weights.is_strict()); /// ``` +/// +/// # Starvation +/// +/// Weighted selection cannot starve a priority: each time a worker polls, a +/// priority that has a runnable job is chosen with probability +/// `weight / (sum of the weights of the priorities that have runnable jobs)`, however +/// many jobs of higher priority are queued. To process a priority more often, raise its +/// weight. Only a weight of `0` (or strict mode) lets higher priorities always win. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PriorityWeights { /// Weight for each priority level - higher weight means more likely to be selected weights: HashMap, /// Whether to use strict priority (always process highest priority first) strict_priority: bool, - /// Fairness factor to prevent starvation (0.0 = no fairness, 1.0 = round-robin) + /// Deprecated and ignored (see [`with_fairness_factor`](Self::with_fairness_factor)). + /// Kept, and optional, so existing configuration files still parse. + #[serde(default)] fairness_factor: f32, } @@ -311,8 +319,8 @@ impl PriorityWeights { /// - Low: 2 (2x more likely than background) /// - Background: 1 (baseline) /// - /// A fairness factor of 0.1 (10%) is included to ensure lower priority jobs - /// still get some processing time. + /// Every priority with a non-zero weight keeps being processed while higher + /// priorities have work queued (see [Starvation](PriorityWeights#starvation)). /// /// # Examples /// @@ -323,7 +331,6 @@ impl PriorityWeights { /// assert_eq!(weights.get_weight(JobPriority::Critical), 20); /// assert_eq!(weights.get_weight(JobPriority::Normal), 5); /// assert_eq!(weights.get_weight(JobPriority::Background), 1); - /// assert_eq!(weights.fairness_factor(), 0.1); /// ``` pub fn new() -> Self { let mut weights = HashMap::new(); @@ -336,7 +343,7 @@ impl PriorityWeights { Self { weights, strict_priority: false, - fairness_factor: 0.1, // 10% fairness by default + fairness_factor: 0.1, // deprecated and unused; kept for the getter } } @@ -356,7 +363,6 @@ impl PriorityWeights { /// /// let strict_weights = PriorityWeights::strict(); /// assert!(strict_weights.is_strict()); - /// assert_eq!(strict_weights.fairness_factor(), 0.0); /// ``` pub fn strict() -> Self { Self { @@ -384,7 +390,17 @@ impl PriorityWeights { self } - /// Set the fairness factor (0.0 = no fairness, 1.0 = round-robin) + /// Formerly documented as a fairness factor (0.0 = no fairness, 1.0 = round-robin). + /// + /// It was never applied, and is now deprecated: weighted selection already gives + /// every priority with runnable jobs a share proportional to its weight, so lower + /// priorities are not starved (see [Starvation](PriorityWeights#starvation)). Raise + /// a priority's weight to give it a bigger share. The value is stored (clamped to + /// `0.0..=1.0`) but has no effect. + #[deprecated( + since = "1.15.6", + note = "never applied; weighted selection already prevents starvation, adjust the weights instead" + )] pub fn with_fairness_factor(mut self, factor: f32) -> Self { self.fairness_factor = factor.clamp(0.0, 1.0); self @@ -405,7 +421,12 @@ impl PriorityWeights { self.strict_priority } - /// Get the fairness factor + /// The value set with the deprecated [`with_fairness_factor`](Self::with_fairness_factor). + /// It has no effect on job selection. + #[deprecated( + since = "1.15.6", + note = "the fairness factor is not applied; weighted selection already prevents starvation" + )] pub fn fairness_factor(&self) -> f32 { self.fairness_factor } @@ -582,12 +603,30 @@ mod tests { #[test] fn test_priority_weights_custom() { - let weights = PriorityWeights::new() - .with_weight(JobPriority::High, 15) - .with_fairness_factor(0.2); - + let weights = PriorityWeights::new().with_weight(JobPriority::High, 15); assert_eq!(weights.get_weight(JobPriority::High), 15); - assert_eq!(weights.fairness_factor(), 0.2); + } + + /// M3: the deprecated fairness factor is still accepted (builder and configuration + /// files, with or without the field) but does not change the weights. + #[test] + #[allow(deprecated)] + fn test_deprecated_fairness_factor_is_accepted_and_ignored() { + let weights = PriorityWeights::new().with_fairness_factor(2.0); + assert_eq!(weights.fairness_factor(), 1.0); + assert_eq!(weights.weights(), PriorityWeights::new().weights()); + + let with_field: PriorityWeights = serde_json::from_value(serde_json::json!({ + "weights": {}, "strict_priority": false, "fairness_factor": 0.3 + })) + .unwrap(); + assert_eq!(with_field.fairness_factor(), 0.3); + let without_field: PriorityWeights = serde_json::from_value(serde_json::json!({ + "weights": {}, "strict_priority": true + })) + .unwrap(); + assert!(without_field.is_strict()); + assert_eq!(without_field.fairness_factor(), 0.0); } #[test] diff --git a/src/stats.rs b/src/stats.rs index a42d323..7367b7c 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -1,7 +1,11 @@ use crate::priority::{JobPriority, PriorityStats}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, sync::Arc, time::Duration}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, + time::Duration, +}; /// Statistics for job processing over a time window #[derive(Debug, Clone, Serialize, Deserialize)] @@ -138,26 +142,40 @@ pub trait StatisticsCollector: Send + Sync { async fn cleanup_old_statistics(&self, older_than: Duration) -> crate::Result; } -/// In-memory statistics collector with time-windowed data +/// In-memory statistics collector with time-windowed data. +/// +/// Events are kept in a ring buffer ordered by timestamp, bounded by +/// [`StatsConfig::max_events`] and [`StatsConfig::max_event_age_secs`]. Recording an +/// event is amortised O(1) (events normally arrive in time order, so they are appended +/// and the oldest ones fall off the front). Queries find the start of their window by +/// binary search and aggregate the events in it in one pass, without copying them. pub struct InMemoryStatsCollector { - events: Arc>>, + events: Arc>>, config: StatsConfig, } /// Configuration for statistics collection #[derive(Debug, Clone)] pub struct StatsConfig { - /// Maximum number of events to keep in memory + /// Maximum number of events to keep in memory; the oldest are dropped first. pub max_events: usize, - /// How often to clean up old events (in seconds) + /// Unused: old events are now pruned whenever an event is recorded. + #[deprecated( + since = "1.15.6", + note = "old events are pruned whenever an event is recorded; this value is ignored" + )] pub cleanup_interval_secs: u64, - /// Maximum age of events to keep (in seconds) + /// Maximum age of events to keep (in seconds). Older events are pruned whenever an + /// event is recorded, and events older than this are not recorded at all. pub max_event_age_secs: u64, - /// Whether to collect detailed timing information + /// Whether to keep the processing time of each event. When `false`, processing + /// times are discarded, so the timing fields of [`JobStatistics`] and of the priority + /// breakdown stay at zero. pub collect_timing: bool, } impl Default for StatsConfig { + #[allow(deprecated)] fn default() -> Self { Self { max_events: 100_000, @@ -180,47 +198,58 @@ fn cutoff_before(now: DateTime, age: Duration) -> DateTime { .unwrap_or(DateTime::::MIN_UTC) } -impl InMemoryStatsCollector { - pub fn new(config: StatsConfig) -> Self { - Self { - events: Arc::new(std::sync::RwLock::new(Vec::new())), - config, - } - } - - pub fn new_default() -> Self { - Self::new(StatsConfig::default()) - } +/// Per-priority running totals for [`StatsAccumulator`]. +#[derive(Default)] +struct PriorityTotals { + events: u64, + timed_events: u64, + processing_time_ms: u128, +} - /// Lock the event buffer for reading, recovering from a poisoned lock. - /// - /// The buffer is only ever appended to, drained or filtered, so a panic in - /// another thread cannot leave it in a state that is unsafe to keep using. - fn read_events(&self) -> std::sync::RwLockReadGuard<'_, Vec> { - self.events - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - } +/// Single-pass aggregation of the events of one window into [`JobStatistics`]. +#[derive(Default)] +struct StatsAccumulator { + events: u64, + started: u64, + completed: u64, + failed: u64, + retried: u64, + dead: u64, + timed_out: u64, + timed_events: u64, + processing_time_ms: u128, + min_processing_time_ms: Option, + max_processing_time_ms: u64, + priorities: HashMap, +} - /// Lock the event buffer for writing, recovering from a poisoned lock. - fn write_events(&self) -> std::sync::RwLockWriteGuard<'_, Vec> { - self.events - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) - } +impl StatsAccumulator { + fn add(&mut self, event: &JobEvent) { + self.events += 1; + match event.event_type { + JobEventType::Started => self.started += 1, + JobEventType::Completed => self.completed += 1, + JobEventType::Failed => self.failed += 1, + JobEventType::Retried => self.retried += 1, + JobEventType::Dead => self.dead += 1, + JobEventType::TimedOut => self.timed_out += 1, + } - fn filter_events_by_window(&self, window: Duration) -> Vec { - let cutoff = cutoff_before(Utc::now(), window); - let events = self.read_events(); - events - .iter() - .filter(|event| event.timestamp >= cutoff) - .cloned() - .collect() + let priority = self.priorities.entry(event.priority).or_default(); + priority.events += 1; + if let Some(time) = event.processing_time_ms { + priority.timed_events += 1; + priority.processing_time_ms += u128::from(time); + self.timed_events += 1; + self.processing_time_ms += u128::from(time); + self.min_processing_time_ms = + Some(self.min_processing_time_ms.map_or(time, |m| m.min(time))); + self.max_processing_time_ms = self.max_processing_time_ms.max(time); + } } - fn calculate_statistics(&self, events: &[JobEvent], window: Duration) -> JobStatistics { - if events.is_empty() { + fn finish(self, window: Duration) -> JobStatistics { + if self.events == 0 { return JobStatistics { time_window: window, calculated_at: Utc::now(), @@ -230,51 +259,17 @@ impl InMemoryStatsCollector { // A run is counted once, when it finishes: `Started` marks the beginning of a // run that is counted by its outcome event. - let total_processed = events - .iter() - .filter(|e| e.event_type != JobEventType::Started) - .count() as u64; - let completed = events - .iter() - .filter(|e| e.event_type == JobEventType::Completed) - .count() as u64; - let failed = events - .iter() - .filter(|e| e.event_type == JobEventType::Failed) - .count() as u64; - let dead = events - .iter() - .filter(|e| e.event_type == JobEventType::Dead) - .count() as u64; - let timed_out = events - .iter() - .filter(|e| e.event_type == JobEventType::TimedOut) - .count() as u64; - let retried = events - .iter() - .filter(|e| e.event_type == JobEventType::Retried) - .count() as u64; - let running = events - .iter() - .filter(|e| e.event_type == JobEventType::Started) - .count() as u64; - - let processing_times: Vec = - events.iter().filter_map(|e| e.processing_time_ms).collect(); - - let (avg_processing_time_ms, min_processing_time_ms, max_processing_time_ms) = - if processing_times.is_empty() { - (0.0, 0, 0) - } else { - let sum: u64 = processing_times.iter().sum(); - let avg = sum as f64 / processing_times.len() as f64; - let min = processing_times.iter().copied().min().unwrap_or(0); - let max = processing_times.iter().copied().max().unwrap_or(0); - (avg, min, max) - }; + let total_processed = self.events - self.started; + + let avg_processing_time_ms = if self.timed_events > 0 { + self.processing_time_ms as f64 / self.timed_events as f64 + } else { + 0.0 + }; let error_rate = if total_processed > 0 { - (failed + dead + timed_out + retried) as f64 / total_processed as f64 + (self.failed + self.dead + self.timed_out + self.retried) as f64 + / total_processed as f64 } else { 0.0 }; @@ -285,19 +280,32 @@ impl InMemoryStatsCollector { 0.0 }; - // Calculate priority statistics - let priority_stats = self.calculate_priority_statistics(events); + let mut priority_stats = PriorityStats::new(); + for (priority, totals) in self.priorities { + priority_stats.job_counts.insert(priority, totals.events); + // Every event in the window counts towards the recent throughput. + priority_stats + .recent_throughput + .insert(priority, totals.events); + if totals.timed_events > 0 { + priority_stats.avg_processing_times.insert( + priority, + totals.processing_time_ms as f64 / totals.timed_events as f64, + ); + } + } + priority_stats.calculate_distribution(); JobStatistics { total_processed, - completed, - failed, - dead, - timed_out, - running, + completed: self.completed, + failed: self.failed, + dead: self.dead, + timed_out: self.timed_out, + running: self.started, avg_processing_time_ms, - min_processing_time_ms, - max_processing_time_ms, + min_processing_time_ms: self.min_processing_time_ms.unwrap_or(0), + max_processing_time_ms: self.max_processing_time_ms, throughput_per_minute, error_rate, priority_stats: Some(priority_stats), @@ -305,53 +313,65 @@ impl InMemoryStatsCollector { calculated_at: Utc::now(), } } +} - fn calculate_priority_statistics(&self, events: &[JobEvent]) -> PriorityStats { - let mut priority_stats = PriorityStats::new(); - - // Count jobs by priority - for event in events { - *priority_stats.job_counts.entry(event.priority).or_insert(0) += 1; +impl InMemoryStatsCollector { + pub fn new(config: StatsConfig) -> Self { + Self { + events: Arc::new(std::sync::RwLock::new(VecDeque::new())), + config, } + } - // Calculate average processing times by priority - let mut priority_processing_times: HashMap> = HashMap::new(); - for event in events { - if let Some(processing_time) = event.processing_time_ms { - priority_processing_times - .entry(event.priority) - .or_default() - .push(processing_time); - } - } + pub fn new_default() -> Self { + Self::new(StatsConfig::default()) + } - for (priority, times) in priority_processing_times { - if !times.is_empty() { - let avg = times.iter().sum::() as f64 / times.len() as f64; - priority_stats.avg_processing_times.insert(priority, avg); - } - } + /// Lock the event buffer for reading, recovering from a poisoned lock. + /// + /// The buffer is only ever appended to, drained or filtered, so a panic in + /// another thread cannot leave it in a state that is unsafe to keep using. + fn read_events(&self) -> std::sync::RwLockReadGuard<'_, VecDeque> { + self.events + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } - // Calculate recent throughput (count events in the time window) - for event in events { - *priority_stats - .recent_throughput - .entry(event.priority) - .or_insert(0) += 1; - } + /// Lock the event buffer for writing, recovering from a poisoned lock. + fn write_events(&self) -> std::sync::RwLockWriteGuard<'_, VecDeque> { + self.events + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } - // Calculate priority distribution percentages - priority_stats.calculate_distribution(); + /// The oldest timestamp an event may have and still be kept. + fn retention_cutoff(&self) -> DateTime { + cutoff_before( + Utc::now(), + Duration::from_secs(self.config.max_event_age_secs), + ) + } - priority_stats + /// Aggregate the events of the last `window` that `include` accepts. + fn aggregate_window( + &self, + window: Duration, + mut include: impl FnMut(&JobEvent) -> bool, + ) -> StatsAccumulator { + let cutoff = cutoff_before(Utc::now(), window); + let events = self.read_events(); + // The buffer is ordered by timestamp, so the window is a suffix of it. + let start = events.partition_point(|event| event.timestamp < cutoff); + let mut totals = StatsAccumulator::default(); + for event in events.range(start..).filter(|event| include(event)) { + totals.add(event); + } + totals } /// Clean up events older than max_event_age_secs pub fn cleanup_old_events(&self) -> usize { - let cutoff = cutoff_before( - Utc::now(), - Duration::from_secs(self.config.max_event_age_secs), - ); + let cutoff = self.retention_cutoff(); let mut events = self.write_events(); let original_len = events.len(); events.retain(|event| event.timestamp >= cutoff); @@ -359,24 +379,42 @@ impl InMemoryStatsCollector { // Also limit by max_events if we still have too many if events.len() > self.config.max_events { let excess = events.len() - self.config.max_events; - events.drain(0..excess); - original_len - events.len() - } else { - original_len - events.len() + events.drain(..excess); } + original_len - events.len() } } #[async_trait::async_trait] impl StatisticsCollector for InMemoryStatsCollector { - async fn record_event(&self, event: JobEvent) -> crate::Result<()> { + async fn record_event(&self, mut event: JobEvent) -> crate::Result<()> { + if !self.config.collect_timing { + event.processing_time_ms = None; + } + let cutoff = self.retention_cutoff(); + if event.timestamp < cutoff { + return Ok(()); + } + let mut events = self.write_events(); - events.push(event); + // Keep the buffer ordered by timestamp. Events normally arrive in order, so + // this is an append; a late one is inserted near the back. + if events + .back() + .is_none_or(|last| last.timestamp <= event.timestamp) + { + events.push_back(event); + } else { + let at = events.partition_point(|e| e.timestamp <= event.timestamp); + events.insert(at, event); + } - // Periodic cleanup to prevent memory growth - if events.len() > self.config.max_events { - let excess = events.len() - self.config.max_events; - events.drain(0..excess); + // Prune from the front: expired events, then anything over the size limit. + while events.front().is_some_and(|e| e.timestamp < cutoff) { + events.pop_front(); + } + while events.len() > self.config.max_events { + events.pop_front(); } Ok(()) @@ -387,49 +425,50 @@ impl StatisticsCollector for InMemoryStatsCollector { queue_name: &str, window: Duration, ) -> crate::Result { - let events = self.filter_events_by_window(window); - let queue_events: Vec = events - .into_iter() - .filter(|e| e.queue_name == queue_name) - .collect(); - - Ok(self.calculate_statistics(&queue_events, window)) + Ok(self + .aggregate_window(window, |event| event.queue_name == queue_name) + .finish(window)) } async fn get_all_statistics(&self, window: Duration) -> crate::Result> { - let events = self.filter_events_by_window(window); - let mut queue_events: HashMap> = HashMap::new(); - - for event in events { - queue_events - .entry(event.queue_name.clone()) - .or_default() - .push(event); - } - - let mut results = Vec::new(); - for (queue_name, events) in queue_events { - let statistics = self.calculate_statistics(&events, window); - - // Note: pending/running/dead counts would come from database queries - // This is just for the statistics calculation - results.push(QueueStats { - queue_name, - pending_count: 0, // Would be filled by database implementation - running_count: statistics.running, - dead_count: statistics.dead, - timed_out_count: statistics.timed_out, - completed_count: statistics.completed, - statistics, - }); + let cutoff = cutoff_before(Utc::now(), window); + let mut queues: HashMap = HashMap::new(); + { + let events = self.read_events(); + let start = events.partition_point(|event| event.timestamp < cutoff); + for event in events.range(start..) { + match queues.get_mut(&event.queue_name) { + Some(totals) => totals.add(event), + None => { + let mut totals = StatsAccumulator::default(); + totals.add(event); + queues.insert(event.queue_name.clone(), totals); + } + } + } } - Ok(results) + Ok(queues + .into_iter() + .map(|(queue_name, totals)| { + let statistics = totals.finish(window); + // Note: pending/running/dead counts would come from database queries + // This is just for the statistics calculation + QueueStats { + queue_name, + pending_count: 0, // Would be filled by database implementation + running_count: statistics.running, + dead_count: statistics.dead, + timed_out_count: statistics.timed_out, + completed_count: statistics.completed, + statistics, + } + }) + .collect()) } async fn get_system_statistics(&self, window: Duration) -> crate::Result { - let events = self.filter_events_by_window(window); - Ok(self.calculate_statistics(&events, window)) + Ok(self.aggregate_window(window, |_| true).finish(window)) } async fn cleanup_old_statistics(&self, older_than: Duration) -> crate::Result { @@ -533,6 +572,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn test_stats_config_default() { let config = StatsConfig::default(); assert_eq!(config.max_events, 100_000); @@ -594,7 +634,7 @@ mod tests { // Add events { let mut events = collector.events.write().unwrap(); - events.push(JobEvent { + events.push_back(JobEvent { job_id: uuid::Uuid::new_v4(), queue_name: "test".to_string(), event_type: JobEventType::Completed, @@ -603,7 +643,7 @@ mod tests { error_message: None, timestamp: Utc::now() - chrono::Duration::seconds(2), // Old event }); - events.push(JobEvent { + events.push_back(JobEvent { job_id: uuid::Uuid::new_v4(), queue_name: "test".to_string(), event_type: JobEventType::Completed, @@ -812,7 +852,11 @@ mod tests { #[tokio::test] async fn test_cleanup_old_statistics() { - let collector = InMemoryStatsCollector::new_default(); + // Keep events for 3 hours so the 2-hour-old one is recorded. + let collector = InMemoryStatsCollector::new(StatsConfig { + max_event_age_secs: 3 * 3600, + ..Default::default() + }); // Add an old event let old_event = JobEvent { @@ -1025,4 +1069,177 @@ mod tests { assert_eq!(stats.error_rate, 1.0); assert_eq!(stats.throughput_per_minute, 2.0); } + + fn event_at(queue: &str, seconds_ago: i64, processing_time_ms: Option) -> JobEvent { + JobEvent { + timestamp: Utc::now() - chrono::Duration::seconds(seconds_ago), + ..create_test_job_event( + queue, + JobEventType::Completed, + None, + processing_time_ms, + None, + ) + } + } + + /// M7: at the size limit, recording drops the oldest event instead of shifting the + /// whole buffer, and the buffer never grows past `max_events`. + #[tokio::test] + async fn test_record_event_is_bounded_and_drops_the_oldest() { + let collector = InMemoryStatsCollector::new(StatsConfig { + max_events: 3, + ..Default::default() + }); + for seconds_ago in [50, 40, 30, 20, 10] { + collector + .record_event(event_at("q", seconds_ago, Some(seconds_ago as u64))) + .await + .unwrap(); + } + let times: Vec<_> = collector + .read_events() + .iter() + .map(|e| e.processing_time_ms.unwrap()) + .collect(); + assert_eq!(times, vec![30, 20, 10]); + } + + /// Late events are inserted in timestamp order, so windows stay exact. + #[tokio::test] + async fn test_out_of_order_events_are_kept_in_time_order() { + let collector = InMemoryStatsCollector::new_default(); + for seconds_ago in [10, 500, 5, 120] { + collector + .record_event(event_at("q", seconds_ago, Some(seconds_ago as u64))) + .await + .unwrap(); + } + { + let events = collector.read_events(); + assert!( + events + .iter() + .zip(events.iter().skip(1)) + .all(|(a, b)| a.timestamp <= b.timestamp) + ); + } + + // The last 60 seconds hold the events from 10 s and 5 s ago only. + let stats = collector + .get_queue_statistics("q", Duration::from_secs(60)) + .await + .unwrap(); + assert_eq!(stats.total_processed, 2); + assert_eq!( + (stats.min_processing_time_ms, stats.max_processing_time_ms), + (5, 10) + ); + let all = collector + .get_system_statistics(Duration::from_secs(3600)) + .await + .unwrap(); + assert_eq!(all.total_processed, 4); + } + + /// `max_event_age_secs` is applied when recording, without a cleanup call. + #[tokio::test] + async fn test_expired_events_are_pruned_when_recording() { + let collector = InMemoryStatsCollector::new(StatsConfig { + max_event_age_secs: 60, + ..Default::default() + }); + collector + .record_event(event_at("q", 120, None)) + .await + .unwrap(); + assert_eq!(collector.read_events().len(), 0, "too old to record"); + + // Recorded while fresh, then expired by the time the next event arrives. + collector + .record_event(event_at("q", 59, None)) + .await + .unwrap(); + collector.write_events()[0].timestamp = Utc::now() - chrono::Duration::seconds(61); + collector + .record_event(event_at("q", 0, None)) + .await + .unwrap(); + assert_eq!(collector.read_events().len(), 1); + } + + /// `collect_timing = false` discards processing times. + #[tokio::test] + async fn test_collect_timing_false_discards_processing_times() { + let collector = InMemoryStatsCollector::new(StatsConfig { + collect_timing: false, + ..Default::default() + }); + collector + .record_event(event_at("q", 0, Some(250))) + .await + .unwrap(); + let stats = collector + .get_queue_statistics("q", Duration::from_secs(60)) + .await + .unwrap(); + assert_eq!(stats.total_processed, 1); + assert_eq!(stats.avg_processing_time_ms, 0.0); + assert_eq!(stats.max_processing_time_ms, 0); + assert!( + stats + .priority_stats + .unwrap() + .avg_processing_times + .is_empty() + ); + } + + /// Per-priority and per-queue aggregates match the events. + #[tokio::test] + async fn test_priority_breakdown_and_queue_split() { + let collector = InMemoryStatsCollector::new_default(); + for (queue, priority, time) in [ + ("a", JobPriority::High, Some(10)), + ("a", JobPriority::High, Some(30)), + ("a", JobPriority::Low, None), + ("b", JobPriority::Low, Some(7)), + ] { + collector + .record_event(create_test_job_event( + queue, + JobEventType::Completed, + Some(priority), + time, + None, + )) + .await + .unwrap(); + } + let a = collector + .get_queue_statistics("a", Duration::from_secs(60)) + .await + .unwrap(); + let priorities = a.priority_stats.unwrap(); + assert_eq!(priorities.job_counts[&JobPriority::High], 2); + assert_eq!(priorities.job_counts[&JobPriority::Low], 1); + assert_eq!(priorities.avg_processing_times[&JobPriority::High], 20.0); + assert!( + !priorities + .avg_processing_times + .contains_key(&JobPriority::Low) + ); + assert_eq!(a.avg_processing_time_ms, 20.0); + + let mut all = collector + .get_all_statistics(Duration::from_secs(60)) + .await + .unwrap(); + all.sort_by(|x, y| x.queue_name.cmp(&y.queue_name)); + let counts: Vec<_> = all + .iter() + .map(|q| (q.queue_name.as_str(), q.statistics.total_processed)) + .collect(); + assert_eq!(counts, vec![("a", 3), ("b", 1)]); + } } diff --git a/src/streaming.rs b/src/streaming.rs index e5747fd..6f990a1 100644 --- a/src/streaming.rs +++ b/src/streaming.rs @@ -136,8 +136,8 @@ use crate::{ HammerworkError, - events::{EventFilter, EventManager, EventSubscription, JobLifecycleEvent}, - task_tracker::TaskTracker, + events::{EventFilter, EventManager, JobLifecycleEvent}, + task_tracker::{ListenerHandle, TaskTracker, clamp_permits}, }; #[cfg(feature = "kafka")] @@ -172,7 +172,7 @@ use std::{ sync::Arc, time::Duration, }; -use tokio::sync::{RwLock, Semaphore, broadcast, watch}; +use tokio::sync::{OwnedSemaphorePermit, RwLock, Semaphore, broadcast, oneshot, watch}; use uuid::Uuid; /// Processors by stream id. Processors are reference-counted so a batch can send @@ -760,6 +760,12 @@ pub struct StreamStats { /// Error from the most recent failed delivery (after retries were exhausted) #[serde(default)] pub last_error: Option, + /// Events this stream never processed because its listener fell behind: while + /// [`BufferConfig::max_events`] events are being delivered the listener waits, and + /// events that overflow the event manager's buffer in the meantime are dropped + /// (oldest first). + #[serde(default)] + pub dropped_events: u64, /// Statistics calculation timestamp pub calculated_at: DateTime, } @@ -821,7 +827,7 @@ pub struct StreamManager { /// Active stream configurations streams: Arc>>, /// Active event subscriptions for streams - subscriptions: Arc>>, + subscriptions: Arc>>, /// Event manager for subscribing to events event_manager: Arc, /// Stream processors by stream id @@ -869,11 +875,14 @@ pub struct StreamManager { /// ``` #[derive(Debug, Clone)] pub struct StreamManagerConfig { - /// Maximum number of concurrent stream processors + /// 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. pub max_concurrent_processors: usize, /// Whether to log stream operations pub log_operations: bool, - /// Global buffer flush interval (in seconds) + /// Upper bound, in seconds, on how long any stream buffers an event before + /// flushing it: a stream flushes after + /// `min(buffer_config.max_buffer_time_secs, global_flush_interval_secs)`. pub global_flush_interval_secs: u64, } @@ -995,15 +1004,7 @@ pub trait StreamProcessor { /// `0` permits would make every processing task wait forever and more than /// `Semaphore::MAX_PERMITS` panics inside tokio. fn clamp_processor_permits(configured: usize) -> usize { - let permits = configured.clamp(1, Semaphore::MAX_PERMITS); - if permits != configured { - tracing::warn!( - configured, - effective = permits, - "max_concurrent_processors is out of range, clamping" - ); - } - permits + clamp_permits(configured, "max_concurrent_processors") } /// First four characters of a credential for display, cut on a character @@ -1223,10 +1224,12 @@ impl StreamManager { ) -> crate::Result<()> { let stream_id = stream.id; - // Subscribe to events for this stream + // Subscribe before returning, and hand this receiver to the listener: events + // published from now on are buffered for it even before its task first runs. let subscription = self.event_manager.subscribe(stream.filter.clone()).await?; + let (handle, stop) = ListenerHandle::new(subscription.id); - // Store stream, processor, and subscription + // Store stream and processor { let mut streams = self.streams.write().await; streams.insert(stream_id, stream.clone()); @@ -1237,11 +1240,6 @@ impl StreamManager { processors.insert(stream_id, Arc::from(processor)); } - { - let mut subscriptions = self.subscriptions.write().await; - subscriptions.insert(stream_id, subscription); - } - // Initialize statistics { let mut stats = self.stats.write().await; @@ -1258,13 +1256,22 @@ impl StreamManager { last_success_at: None, last_failure_at: None, last_error: None, + dropped_events: 0, calculated_at: Utc::now(), }, ); } + // Replacing the handle of an existing listener (same stream id) stops it. + let replaced = self.subscriptions.write().await.insert(stream_id, handle); + if let Some(replaced) = replaced { + self.event_manager + .unsubscribe(replaced.subscription_id) + .await?; + } + // Start processing task for this stream - self.start_stream_processing_task(stream_id).await; + self.start_stream_processing_task(stream_id, subscription.receiver, stop); if self.config.log_operations { tracing::info!("Added stream: {} ({:?})", stream.name, stream.backend); @@ -1293,20 +1300,20 @@ impl StreamManager { /// Remove a stream configuration pub async fn remove_stream(&self, stream_id: Uuid) -> crate::Result<()> { + // Stop the listener first (dropping its handle) and remove the subscription + let handle = self.subscriptions.write().await.remove(&stream_id); + if let Some(handle) = handle { + self.event_manager + .unsubscribe(handle.subscription_id) + .await?; + } + // Shutdown processor let processor = self.processors.write().await.remove(&stream_id); if let Some(processor) = processor { processor.shutdown().await?; } - // Remove subscription - { - let mut subscriptions = self.subscriptions.write().await; - if let Some(subscription) = subscriptions.remove(&stream_id) { - self.event_manager.unsubscribe(subscription.id).await?; - } - } - // Remove stream configuration { let mut streams = self.streams.write().await; @@ -1442,32 +1449,37 @@ impl StreamManager { } } - /// Start processing task for a specific stream - async fn start_stream_processing_task(&self, stream_id: Uuid) { + /// Start the listener of a stream: it reads `receiver` until `stop` fires (its + /// [`ListenerHandle`] is dropped), buffers matching events and hands full or + /// expired buffers to batch tasks. + /// + /// A buffer is flushed when it holds `batch_size` or `max_events` events, or when + /// its oldest event has waited [`flush_after`](Self::flush_after). At most + /// `max_events` events are in batches at once (being sent or waiting to retry); + /// beyond that the listener waits, and events that overflow the event manager's + /// buffer meanwhile are dropped and counted in [`StreamStats::dropped_events`]. + fn start_stream_processing_task( + &self, + stream_id: Uuid, + mut receiver: broadcast::Receiver, + mut stop: oneshot::Receiver<()>, + ) { let streams = self.streams.clone(); - let subscriptions = self.subscriptions.clone(); let processors = self.processors.clone(); let stats = self.stats.clone(); let processing_semaphore = self.processing_semaphore.clone(); let config = self.config.clone(); let shutdown_signal = self.shutdown_signal.clone(); - let batches = self.batches.clone(); self.listeners.spawn("listener", async move { let mut event_buffer: Vec = Vec::new(); - let mut last_flush = std::time::Instant::now(); - - // Subscribe once and keep the receiver for the lifetime of the listener. - // Re-subscribing on every iteration would skip every event published - // while the previous one was being handled. - let mut receiver = { - let subscriptions = subscriptions.read().await; - match subscriptions.get(&stream_id) { - Some(subscription) => subscription.receiver.resubscribe(), - None => return, - } - }; + // When the oldest buffered event arrived. + let mut buffered_since: Option = None; + // Events handed to batches and not finished yet. + let mut in_flight_limit: Option<(usize, Arc)> = None; + // Whether the listener is waiting for in-flight batches (logged once per pause). + let mut paused = false; loop { // Get stream configuration @@ -1479,23 +1491,48 @@ impl StreamManager { None => break, } }; + let max_events = clamp_permits(stream.buffer_config.max_events, "max_events"); + let in_flight = match &in_flight_limit { + Some((limit, semaphore)) if *limit == max_events => semaphore.clone(), + _ => { + let semaphore = Arc::new(Semaphore::new(max_events)); + in_flight_limit = Some((max_events, semaphore.clone())); + semaphore + } + }; + let flush_after = Self::flush_after(&stream, &config); + let flush_at = buffered_since.map(|since| since + flush_after); - // Exit once the subscription is removed - if !subscriptions.read().await.contains_key(&stream_id) { - break; - } - - // Check if we should flush the buffer let should_flush = event_buffer.len() >= stream.buffer_config.batch_size - || last_flush.elapsed().as_secs() >= stream.buffer_config.max_buffer_time_secs - || event_buffer.len() >= stream.buffer_config.max_events; + || event_buffer.len() >= max_events + || flush_at.is_some_and(|at| tokio::time::Instant::now() >= at); if should_flush && !event_buffer.is_empty() { - let events_to_process = event_buffer.clone(); - event_buffer.clear(); - last_flush = std::time::Instant::now(); + let events_to_process = std::mem::take(&mut event_buffer); + buffered_since = None; + + // Bound the backlog: wait until these events fit in the in-flight + // limit. While waiting, new events queue up in the broadcast buffer. + let wanted = + u32::try_from(events_to_process.len().min(max_events)).unwrap_or(u32::MAX); + let full = (in_flight.available_permits() as u32) < wanted; + if full && !paused && config.log_operations { + tracing::warn!( + "Stream {} has {} events in flight; pausing its listener", + stream.name, + max_events - in_flight.available_permits() + ); + } + paused = full; + let slots = tokio::select! { + biased; + _ = &mut stop => break, + slots = in_flight.clone().acquire_many_owned(wanted) => match slots { + Ok(slots) => slots, + Err(_) => break, + }, + }; - // Clone necessary data for processing task let stream_clone = stream.clone(); let processors_clone = processors.clone(); let stats_clone = stats.clone(); @@ -1503,13 +1540,7 @@ impl StreamManager { let semaphore_clone = processing_semaphore.clone(); let shutdown = shutdown_signal.subscribe(); - // Spawn a tracked processing task batches.spawn("batch", async move { - // Acquire processing permit inside the task - let Ok(_permit) = semaphore_clone.acquire().await else { - tracing::error!("stream processing semaphore closed"); - return; - }; Self::process_event_batch( stream_id, stream_clone, @@ -1517,15 +1548,30 @@ impl StreamManager { processors_clone, stats_clone, config_clone, + semaphore_clone, shutdown, + slots, ) .await; }); + continue; } - // Try to receive new events (with timeout to allow periodic flushing) - match tokio::time::timeout(Duration::from_secs(1), receiver.recv()).await { - Ok(Ok(event)) => { + // Wait for the next event, or until the buffer is due to be flushed. + let flush_due = async { + match flush_at { + Some(at) => tokio::time::sleep_until(at).await, + None => std::future::pending().await, + } + }; + let received = tokio::select! { + biased; + _ = &mut stop => break, + received = receiver.recv() => received, + _ = flush_due => continue, + }; + match received { + Ok(event) => { // A disabled stream drops events (but keeps listening, so // that enabling it again resumes delivery). Check the current // state: it may have changed while waiting. @@ -1535,36 +1581,54 @@ impl StreamManager { .get(&stream_id) .is_some_and(|stream| stream.enabled); if enabled && stream.filter.matches(&event) { + if event_buffer.is_empty() { + buffered_since = Some(tokio::time::Instant::now()); + } event_buffer.push(event); } } - Ok(Err(broadcast::error::RecvError::Lagged(skipped))) => { + Err(broadcast::error::RecvError::Lagged(skipped)) => { tracing::warn!( - "Stream {} listener fell behind and skipped {} events; \ - consider a larger event buffer", + "Stream {} listener fell behind and dropped {} events; the \ + backend may be slow or down, or the event buffer too small", stream.name, skipped ); + if let Some(stream_stats) = stats.write().await.get_mut(&stream_id) { + stream_stats.dropped_events += skipped; + } } - Ok(Err(broadcast::error::RecvError::Closed)) => { + Err(broadcast::error::RecvError::Closed) => { // Event manager dropped, exit task break; } - Err(_) => { - // Timeout - continue to check for flush conditions - continue; - } } } }); } + /// How long an event may wait in a stream's buffer: the stream's + /// `max_buffer_time_secs`, capped by the manager's `global_flush_interval_secs`. + fn flush_after(stream: &StreamConfig, config: &StreamManagerConfig) -> Duration { + Duration::from_secs( + stream + .buffer_config + .max_buffer_time_secs + .min(config.global_flush_interval_secs), + ) + } + /// Deliver a batch of events through the stream's processor. /// /// Events are serialized, sent with [`StreamProcessor::send_batch`], and every /// event whose delivery failed (or that has no delivery result) is retried /// according to the stream's [`StreamRetryPolicy`]. Statistics are updated from /// the final per-event outcome. + /// + /// `processing_semaphore` limits sends across all streams; a send holds a slot only + /// while it runs, not during the backoff before a retry. `_in_flight` is the + /// stream's in-flight allowance for these events, released when the batch is done. + #[allow(clippy::too_many_arguments)] async fn process_event_batch( stream_id: Uuid, stream: StreamConfig, @@ -1572,9 +1636,11 @@ impl StreamManager { processors: ProcessorMap, stats: Arc>>, config: StreamManagerConfig, + processing_semaphore: Arc, mut shutdown: watch::Receiver, + _in_flight: OwnedSemaphorePermit, ) { - // The stream may have been removed while the batch waited for a permit. + // The stream may have been removed while the batch waited. let Some(processor) = processors.read().await.get(&stream_id).cloned() else { return; }; @@ -1609,6 +1675,7 @@ impl StreamManager { &stream, processor.as_ref(), streamed_events, + &processing_semaphore, &mut shutdown, &config, &mut outcome, @@ -1626,6 +1693,7 @@ impl StreamManager { stream: &StreamConfig, processor: &(dyn StreamProcessor + Send + Sync), mut pending: Vec, + processing_semaphore: &Semaphore, shutdown: &mut watch::Receiver, config: &StreamManagerConfig, outcome: &mut BatchOutcome, @@ -1645,8 +1713,14 @@ impl StreamManager { pending.clone() }; + let Ok(permit) = processing_semaphore.acquire().await else { + tracing::error!("stream processing semaphore closed"); + outcome.failed += event_ids.len() as u64; + return; + }; let started = std::time::Instant::now(); let result = processor.send_batch(batch).await; + drop(permit); let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); let failed_ids: HashSet = match result { @@ -3747,6 +3821,7 @@ mod tests { last_success_at: Some(Utc::now() - chrono::Duration::minutes(2)), last_failure_at: Some(Utc::now() - chrono::Duration::minutes(10)), last_error: None, + dropped_events: 0, calculated_at: Utc::now(), }; @@ -4445,8 +4520,6 @@ mod tests { .await .unwrap(); - // Let the listener task start and subscribe before the event is published. - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); for _ in 0..100 { let processed = manager @@ -4487,8 +4560,6 @@ mod tests { .await .unwrap(); - // Let the listener task start and subscribe before the events are published. - tokio::time::sleep(Duration::from_millis(100)).await; for _ in 0..100 { events.publish_event(completed_event()).await.unwrap(); } @@ -4536,8 +4607,13 @@ mod tests { panic!("expected test panic in a listener task"); }); - // Let the listener task start and subscribe before the event is published. - tokio::time::sleep(Duration::from_millis(100)).await; + // Let both tasks run (and panic) before shutting down. + for _ in 0..200 { + if manager.task_panics() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } manager.shutdown(Duration::from_secs(5)).await; assert_eq!(manager.task_panics(), 2); } @@ -4582,8 +4658,6 @@ mod tests { .await .unwrap(); - // Let the listener task start and subscribe before the events are published. - tokio::time::sleep(Duration::from_millis(100)).await; let mut ids = Vec::new(); for _ in 0..count { let event = completed_event(); @@ -4686,7 +4760,6 @@ mod tests { .add_stream_with_processor(stream, Box::new(processor.clone())) .await .unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; let published: Vec = (0..4).map(|_| completed_event()).collect(); // The second and fourth events are rejected on every attempt. @@ -4762,7 +4835,6 @@ mod tests { .add_stream_with_processor(stream, Box::new(ForgetfulProcessor)) .await .unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); wait_for_total_events(&manager, stream_id, 1).await; manager.shutdown(Duration::from_secs(5)).await; @@ -4793,7 +4865,6 @@ mod tests { .add_stream_with_processor(stream, Box::new(processor.clone())) .await .unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); // Wait for the first attempt; the batch is now sleeping before its retry. @@ -4959,7 +5030,6 @@ mod tests { .add_stream_with_processor(stream, Box::new(processor.clone())) .await .unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; assert_eq!(manager.get_stream(stream_id).await.unwrap().id, stream_id); assert_eq!(manager.list_streams().await.len(), 1); @@ -5052,4 +5122,185 @@ mod tests { "the metadata value is part of the key" ); } + + /// Wait until `condition` holds, polling every 10 ms for up to 10 seconds. + async fn eventually(what: &str, mut condition: F) + where + F: FnMut() -> Fut, + Fut: std::future::Future, + { + for _ in 0..1000 { + if condition().await { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("timed out waiting until {what}"); + } + + /// H11/M9: re-adding a stream under the same id (directly, or after removing it) + /// leaves one listener, and an event published right after `add_stream` returns + /// is streamed exactly once. + #[tokio::test] + async fn test_readding_a_stream_does_not_duplicate_events() { + let processor = InMemoryProcessor::default(); + let events = Arc::new(EventManager::new_default()); + let manager = StreamManager::new_default(events.clone()); + let stream = test_stream(1, immediate_retries(1)); + let stream_id = stream.id; + for _ in 0..3 { + manager + .add_stream_with_processor(stream.clone(), Box::new(processor.clone())) + .await + .unwrap(); + } + manager.remove_stream(stream_id).await.unwrap(); + manager + .add_stream_with_processor(stream, Box::new(processor.clone())) + .await + .unwrap(); + assert_eq!(events.subscription_count().await, 1); + + let event = completed_event(); + events.publish_event(event.clone()).await.unwrap(); + wait_for_total_events(&manager, stream_id, 1).await; + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(processor.delivered_ids(), vec![event.event_id]); + assert_eq!(processor.calls(), 1); + manager.shutdown(Duration::from_secs(5)).await; + } + + /// A processor whose sends wait until `gate` has a permit (one per send). + #[derive(Clone)] + struct GatedProcessor { + gate: Arc, + calls: Arc, + } + + #[async_trait::async_trait] + impl StreamProcessor for GatedProcessor { + async fn send_batch( + &self, + events: Vec, + ) -> crate::Result> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if let Ok(permit) = self.gate.acquire().await { + permit.forget(); + } + Ok(events + .into_iter() + .map(|event| StreamDelivery { + delivery_id: Uuid::new_v4(), + stream_id: Uuid::nil(), + event_id: event.event.event_id, + success: true, + error_message: None, + attempted_at: Utc::now(), + duration_ms: Some(0), + attempt_number: 1, + partition: None, + }) + .collect()) + } + + async fn health_check(&self) -> crate::Result { + Ok(true) + } + + async fn get_stats(&self) -> crate::Result> { + Ok(HashMap::new()) + } + + async fn shutdown(&self) -> crate::Result<()> { + Ok(()) + } + } + + /// H12: with the backend stuck, at most `max_events` events are in batches; the + /// listener waits and the overflow is dropped and counted. + #[tokio::test] + async fn test_in_flight_events_are_bounded() { + use std::sync::atomic::Ordering; + let processor = GatedProcessor { + gate: Arc::new(Semaphore::new(0)), + calls: Default::default(), + }; + let events = Arc::new(EventManager::new(crate::events::EventConfig { + max_buffer_size: 4, + ..Default::default() + })); + let manager = StreamManager::new_default(events.clone()); + let stream = StreamConfig { + buffer_config: BufferConfig { + batch_size: 1, + max_events: 2, + max_buffer_time_secs: 1, + }, + retry_policy: immediate_retries(1), + ..Default::default() + }; + let stream_id = stream.id; + manager + .add_stream_with_processor(stream, Box::new(processor.clone())) + .await + .unwrap(); + + for _ in 0..20 { + events.publish_event(completed_event()).await.unwrap(); + tokio::task::yield_now().await; + } + eventually("two batches are being sent", || async { + processor.calls.load(Ordering::SeqCst) == 2 + }) + .await; + // The listener is waiting: no third batch is started. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(processor.calls.load(Ordering::SeqCst), 2); + assert!(manager.batches.len() <= 2, "{}", manager.batches.len()); + + // Once the backend recovers, the rest is delivered or counted as dropped. + processor.gate.add_permits(1_000); + eventually("every event is delivered or dropped", || async { + let stats = manager.get_stream_stats(stream_id).await.unwrap(); + stats.successful_deliveries + stats.dropped_events == 20 + }) + .await; + let stats = manager.get_stream_stats(stream_id).await.unwrap(); + assert!(stats.dropped_events > 0, "{stats:?}"); + manager.shutdown(Duration::from_secs(5)).await; + } + + /// M4: `global_flush_interval_secs` caps how long a stream buffers an event. + #[tokio::test] + async fn test_global_flush_interval_caps_buffer_time() { + let mut stream = test_stream(100, immediate_retries(1)); + stream.buffer_config.max_buffer_time_secs = 60; + let config = StreamManagerConfig { + global_flush_interval_secs: 1, + ..Default::default() + }; + assert_eq!( + StreamManager::flush_after(&stream, &config), + Duration::from_secs(1) + ); + assert_eq!( + StreamManager::flush_after(&stream, &StreamManagerConfig::default()), + Duration::from_secs(10) + ); + + let processor = InMemoryProcessor::default(); + let events = Arc::new(EventManager::new_default()); + let manager = StreamManager::new(events.clone(), config); + let stream_id = stream.id; + manager + .add_stream_with_processor(stream, Box::new(processor.clone())) + .await + .unwrap(); + let started = std::time::Instant::now(); + events.publish_event(completed_event()).await.unwrap(); + wait_for_total_events(&manager, stream_id, 1).await; + assert!(started.elapsed() < Duration::from_secs(5)); + assert_eq!(processor.delivered_ids().len(), 1); + manager.shutdown(Duration::from_secs(5)).await; + } } diff --git a/src/task_tracker.rs b/src/task_tracker.rs index e82608e..b98d69b 100644 --- a/src/task_tracker.rs +++ b/src/task_tracker.rs @@ -141,9 +141,71 @@ impl TaskTracker { } } +/// The running listener of one webhook or stream. +/// +/// Dropping the handle stops the listener right away, even while it is waiting for +/// an event: the listener selects on the receiver returned by [`ListenerHandle::new`], +/// which completes when the handle is dropped. So removing or re-adding a webhook or +/// stream never leaves an old listener running next to the new one. +pub(crate) struct ListenerHandle { + /// The listener's event manager subscription + pub(crate) subscription_id: uuid::Uuid, + _stop: tokio::sync::oneshot::Sender<()>, +} + +impl ListenerHandle { + /// A handle for the listener of `subscription_id`, and the stop signal the + /// listener must watch. + pub(crate) fn new(subscription_id: uuid::Uuid) -> (Self, tokio::sync::oneshot::Receiver<()>) { + let (stop, stopped) = tokio::sync::oneshot::channel(); + ( + Self { + subscription_id, + _stop: stop, + }, + stopped, + ) + } +} + +/// Clamp a configured limit into `1..=Semaphore::MAX_PERMITS`, warning when it changes. +/// +/// `0` permits would make every waiter wait forever, and more than +/// `Semaphore::MAX_PERMITS` panics inside tokio. +pub(crate) fn clamp_permits(configured: usize, name: &str) -> usize { + let permits = configured.clamp(1, tokio::sync::Semaphore::MAX_PERMITS); + if permits != configured { + tracing::warn!( + configured, + effective = permits, + "{name} is out of range, clamping" + ); + } + permits +} + #[cfg(test)] mod tests { use super::*; + + #[tokio::test] + async fn dropping_a_listener_handle_stops_the_listener() { + let (handle, mut stopped) = ListenerHandle::new(uuid::Uuid::new_v4()); + assert!(stopped.try_recv().is_err()); + drop(handle); + // The receiver completes (with an error) once the handle is gone. + assert!(stopped.await.is_err()); + } + + #[test] + fn clamp_permits_bounds_the_value() { + assert_eq!(clamp_permits(0, "x"), 1); + assert_eq!(clamp_permits(5, "x"), 5); + assert_eq!( + clamp_permits(usize::MAX, "x"), + tokio::sync::Semaphore::MAX_PERMITS + ); + } use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[tokio::test] diff --git a/src/tracing.rs b/src/tracing.rs index d9691ab..6974ce7 100644 --- a/src/tracing.rs +++ b/src/tracing.rs @@ -431,11 +431,45 @@ impl Default for TracingConfig { /// ``` #[cfg(feature = "tracing")] pub async fn init_tracing(config: TracingConfig) -> Result<()> { + use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + + let tracer_provider = install_tracer_provider(&config)?; + + // Create OpenTelemetry layer + let telemetry_layer = OpenTelemetryLayer::new(tracer_provider.tracer("hammerwork")); + + // Initialize tracing subscriber + let subscriber = tracing_subscriber::registry().with(telemetry_layer); + + if config.console_exporter { + // Add console layer for debugging + subscriber + .with(tracing_subscriber::fmt::layer()) + .try_init() + .map_err(|e| crate::HammerworkError::Tracing { + message: format!("Failed to initialize tracing subscriber: {}", e), + })?; + } else { + subscriber + .try_init() + .map_err(|e| crate::HammerworkError::Tracing { + message: format!("Failed to initialize tracing subscriber: {}", e), + })?; + } + + Ok(()) +} + +/// Build the tracer provider described by `config`, keep it for [`shutdown_tracing`] +/// and install it as the global OpenTelemetry tracer provider. +#[cfg(feature = "tracing")] +pub(crate) fn install_tracer_provider( + config: &TracingConfig, +) -> Result { use opentelemetry_sdk::{ Resource, trace::{Sampler, SdkTracerProvider}, }; - use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // Build resource with service information let mut resource = Resource::builder().with_service_name(config.service_name.clone()); @@ -489,29 +523,7 @@ pub async fn init_tracing(config: TracingConfig) -> Result<()> { // Set global tracer provider global::set_tracer_provider(tracer_provider.clone()); - // Create OpenTelemetry layer - let telemetry_layer = OpenTelemetryLayer::new(tracer_provider.tracer("hammerwork")); - - // Initialize tracing subscriber - let subscriber = tracing_subscriber::registry().with(telemetry_layer); - - if config.console_exporter { - // Add console layer for debugging - subscriber - .with(tracing_subscriber::fmt::layer()) - .try_init() - .map_err(|e| crate::HammerworkError::Tracing { - message: format!("Failed to initialize tracing subscriber: {}", e), - })?; - } else { - subscriber - .try_init() - .map_err(|e| crate::HammerworkError::Tracing { - message: format!("Failed to initialize tracing subscriber: {}", e), - })?; - } - - Ok(()) + Ok(tracer_provider) } /// Shutdown the global tracing infrastructure. diff --git a/src/webhooks.rs b/src/webhooks.rs index a29002e..0460323 100644 --- a/src/webhooks.rs +++ b/src/webhooks.rs @@ -95,15 +95,15 @@ //! }); //! ``` -use crate::events::{EventFilter, EventManager, EventSubscription, JobLifecycleEvent}; -use crate::task_tracker::TaskTracker; +use crate::events::{EventFilter, EventManager, JobLifecycleEvent}; +use crate::task_tracker::{ListenerHandle, TaskTracker, clamp_permits}; use chrono::{DateTime, Utc}; use reqwest::Client; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc, time::Duration}; use tokio::{ - sync::{RwLock, Semaphore, broadcast}, - time::{sleep, timeout}, + sync::{OwnedSemaphorePermit, RwLock, Semaphore, broadcast, oneshot}, + time::{Instant, sleep, timeout_at}, }; use uuid::Uuid; @@ -190,7 +190,11 @@ pub struct WebhookConfig { pub retry_policy: RetryPolicy, /// Authentication configuration pub auth: Option, - /// Timeout for HTTP requests + /// Timeout for one delivery attempt, in seconds: sending the request and reading + /// the response, body included. `0` (also the value when a configuration file + /// leaves it out) uses the manager's + /// [`default_timeout_secs`](WebhookManagerConfig::default_timeout_secs). + #[serde(default)] pub timeout_secs: u64, /// Whether this webhook is currently enabled pub enabled: bool, @@ -401,6 +405,12 @@ pub struct WebhookStats { pub last_success_at: Option>, /// Last failure timestamp pub last_failure_at: Option>, + /// Events this webhook never attempted because its listener fell behind: while + /// [`max_pending_deliveries`](WebhookManagerConfig::max_pending_deliveries) + /// deliveries are pending the listener waits, and events that overflow the event + /// manager's buffer in the meantime are dropped (oldest first). + #[serde(default)] + pub dropped_events: u64, /// Time window these statistics cover pub calculated_at: DateTime, } @@ -452,6 +462,7 @@ pub struct WebhookManagerStats { /// 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 webhook_manager = WebhookManager::new(event_manager, config); @@ -479,8 +490,8 @@ pub struct WebhookManager { http_client: Client, /// Active webhook configurations webhooks: Arc>>, - /// Active event subscriptions for webhooks - subscriptions: Arc>>, + /// The running listener of each webhook + subscriptions: Arc>>, /// Event manager for subscribing to events event_manager: Arc, /// Rate limiting semaphore for concurrent deliveries @@ -498,14 +509,29 @@ pub struct WebhookManager { /// Configuration for the webhook manager #[derive(Debug, Clone)] pub struct WebhookManagerConfig { - /// Maximum number of concurrent webhook deliveries + /// 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 + /// to retry. pub max_concurrent_deliveries: usize, - /// Maximum response body size to store (in bytes) + /// Maximum response body size to read and store (in bytes); the rest of a + /// longer body is not read. pub max_response_body_size: usize, /// Whether to log webhook deliveries pub log_deliveries: bool, - /// Default timeout for webhook requests + /// Timeout, in seconds, for webhooks whose + /// [`timeout_secs`](WebhookConfig::timeout_secs) is `0`. pub default_timeout_secs: u64, + /// Maximum number of deliveries pending per webhook: waiting for a request slot, + /// in flight, or waiting to retry. + /// + /// When a webhook reaches it (for example because its endpoint is down and every + /// delivery is retrying), its listener stops taking new events until a delivery + /// finishes. Events keep arriving in the [`EventManager`]'s broadcast buffer + /// (`EventConfig::max_buffer_size`); once that overflows, the oldest events are + /// dropped for this webhook, logged at `warn` and counted in + /// [`WebhookStats::dropped_events`]. Memory use stays bounded however long the + /// endpoint is down. Values below 1 are treated as 1. + pub max_pending_deliveries: usize, /// User agent string for webhook requests pub user_agent: String, } @@ -517,6 +543,7 @@ impl Default for WebhookManagerConfig { max_response_body_size: 64 * 1024, // 64KB log_deliveries: true, default_timeout_secs: 30, + max_pending_deliveries: 1_000, user_agent: format!("hammerwork-webhooks/{}", env!("CARGO_PKG_VERSION")), } } @@ -528,8 +555,9 @@ impl From<&crate::config::WebhookGlobalSettings> for WebhookManagerConfig { max_concurrent_deliveries: settings.max_concurrent_deliveries, max_response_body_size: settings.max_response_body_size, log_deliveries: settings.log_deliveries, + default_timeout_secs: settings.default_timeout_secs, + max_pending_deliveries: settings.max_pending_deliveries, user_agent: settings.user_agent.clone(), - ..Self::default() } } } @@ -539,15 +567,55 @@ impl From<&crate::config::WebhookGlobalSettings> for WebhookManagerConfig { /// `0` permits would deadlock every delivery task, and more than /// `Semaphore::MAX_PERMITS` panics inside tokio. fn clamp_delivery_permits(configured: usize) -> usize { - let permits = configured.clamp(1, Semaphore::MAX_PERMITS); - if permits != configured { - tracing::warn!( - configured, - effective = permits, - "max_concurrent_deliveries is out of range, clamping" - ); + clamp_permits(configured, "max_concurrent_deliveries") +} + +/// The time allowed for one delivery attempt of `webhook`. +fn attempt_timeout(webhook: &WebhookConfig, config: &WebhookManagerConfig) -> Duration { + let secs = if webhook.timeout_secs == 0 { + config.default_timeout_secs + } else { + webhook.timeout_secs + }; + Duration::from_secs(secs) +} + +/// Read at most `max_bytes` of `response`'s body. Stops reading (and drops the +/// connection) once the limit is reached, so a huge or endless body costs nothing more. +async fn read_body_limited( + mut response: reqwest::Response, + max_bytes: usize, +) -> reqwest::Result { + let mut body = Vec::new(); + let mut truncated = false; + while let Some(chunk) = response.chunk().await? { + let room = max_bytes.saturating_sub(body.len()); + if chunk.len() > room { + body.extend_from_slice(&chunk[..room]); + truncated = true; + break; + } + body.extend_from_slice(&chunk); } - permits + Ok(response_body_text(body, truncated)) +} + +/// The response body as text, marked when it was cut off. +/// +/// The cut can fall inside a multi-byte UTF-8 character; the incomplete character is +/// dropped rather than replaced. Invalid UTF-8 elsewhere becomes U+FFFD. +fn response_body_text(mut body: Vec, truncated: bool) -> String { + if truncated + && let Err(e) = std::str::from_utf8(&body) + && e.error_len().is_none() + { + body.truncate(e.valid_up_to()); + } + let mut text = String::from_utf8_lossy(&body).into_owned(); + if truncated { + text.push_str("... [truncated]"); + } + text } impl WebhookManager { @@ -642,26 +710,27 @@ impl WebhookManager { /// Add a new webhook configuration. /// + /// The webhook receives every matching event published after this returns. + /// Adding a webhook with the id of an existing one replaces it (and resets its + /// statistics); use [`update_webhook`](Self::update_webhook) to change a webhook + /// without a gap in delivery. + /// /// Fails with a configuration error when the webhook is invalid (see /// [`WebhookConfig::validate`]), for example an invalid payload template. pub async fn add_webhook(&self, webhook: WebhookConfig) -> crate::Result<()> { webhook.validate()?; let webhook_id = webhook.id; - // Subscribe to events for this webhook + // Subscribe before returning, and hand this receiver to the listener: events + // published from now on are buffered for it even before its task first runs. let subscription = self.event_manager.subscribe(webhook.filter.clone()).await?; + let (handle, stop) = ListenerHandle::new(subscription.id); - // Store webhook and subscription { let mut webhooks = self.webhooks.write().await; webhooks.insert(webhook_id, webhook.clone()); } - { - let mut subscriptions = self.subscriptions.write().await; - subscriptions.insert(webhook_id, subscription); - } - // Initialize statistics { let mut stats = self.stats.write().await; @@ -676,13 +745,21 @@ impl WebhookManager { avg_response_time_ms: 0.0, last_success_at: None, last_failure_at: None, + dropped_events: 0, calculated_at: Utc::now(), }, ); } - // Start delivery task for this webhook - self.start_webhook_delivery_task(webhook_id).await; + // Replacing the handle of an existing listener stops that listener. + let replaced = self.subscriptions.write().await.insert(webhook_id, handle); + if let Some(replaced) = replaced { + self.event_manager + .unsubscribe(replaced.subscription_id) + .await?; + } + + self.start_webhook_delivery_task(webhook_id, subscription.receiver, stop); if self.config.log_deliveries { // The URL path of chat webhooks (Slack, Discord, Teams) is a credential. @@ -696,18 +773,22 @@ impl WebhookManager { Ok(()) } - /// Remove a webhook configuration + /// Remove a webhook configuration. + /// + /// Its listener stops right away. Deliveries already started finish (including + /// their retries). pub async fn remove_webhook(&self, webhook_id: Uuid) -> crate::Result<()> { { let mut webhooks = self.webhooks.write().await; webhooks.remove(&webhook_id); } - { - let mut subscriptions = self.subscriptions.write().await; - if let Some(subscription) = subscriptions.remove(&webhook_id) { - self.event_manager.unsubscribe(subscription.id).await?; - } + // Dropping the handle stops the listener. + let handle = self.subscriptions.write().await.remove(&webhook_id); + if let Some(handle) = handle { + self.event_manager + .unsubscribe(handle.subscription_id) + .await?; } { @@ -760,19 +841,26 @@ impl WebhookManager { } } - /// Update webhook configuration + /// Update a webhook's configuration. + /// + /// The new configuration (URL, filter, method, auth, ...) applies to every event + /// the webhook's listener handles from now on. The listener and the statistics + /// are kept, so no event is missed or delivered twice because of the update. + /// Deliveries already started finish with the configuration they started with. + /// A webhook with an unknown id is added. pub async fn update_webhook(&self, webhook: WebhookConfig) -> crate::Result<()> { - let webhook_id = webhook.id; // Validate first so an invalid update leaves the existing webhook in place. webhook.validate()?; - // Remove existing webhook - self.remove_webhook(webhook_id).await?; - - // Add updated webhook - self.add_webhook(webhook).await?; + { + let mut webhooks = self.webhooks.write().await; + if let Some(existing) = webhooks.get_mut(&webhook.id) { + *existing = webhook; + return Ok(()); + } + } - Ok(()) + self.add_webhook(webhook).await } /// Get webhook statistics @@ -807,106 +895,116 @@ impl WebhookManager { } } - /// Start delivery task for a specific webhook - async fn start_webhook_delivery_task(&self, webhook_id: Uuid) { + /// Start the listener of a webhook: it reads `receiver` until `stop` fires (its + /// [`ListenerHandle`] is dropped) and starts a delivery for every matching event. + fn start_webhook_delivery_task( + &self, + webhook_id: Uuid, + mut receiver: broadcast::Receiver, + mut stop: oneshot::Receiver<()>, + ) { let webhooks = self.webhooks.clone(); - let subscriptions = self.subscriptions.clone(); let http_client = self.http_client.clone(); let stats = self.stats.clone(); let delivery_semaphore = self.delivery_semaphore.clone(); let config = self.config.clone(); - let deliveries = self.deliveries.clone(); + let pending = Arc::new(Semaphore::new(clamp_permits( + config.max_pending_deliveries, + "max_pending_deliveries", + ))); self.listeners.spawn("listener", async move { - // Subscribe once and keep the receiver for the lifetime of the listener. - // Re-subscribing on every iteration would skip every event published - // while the previous one was being handled. - let mut receiver = { - let subscriptions = subscriptions.read().await; - match subscriptions.get(&webhook_id) { - Some(subscription) => subscription.receiver.resubscribe(), - None => return, - } - }; - + // Whether the listener is waiting for pending deliveries (logged once per pause). + let mut paused = false; loop { - // Get webhook configuration - let webhook = { - let webhooks = webhooks.read().await; - match webhooks.get(&webhook_id) { - Some(webhook) => webhook.clone(), - // Webhook removed, exit task - None => break, - } + let received = tokio::select! { + biased; + _ = &mut stop => break, + received = receiver.recv() => received, }; - - // Exit once the subscription is removed - if !subscriptions.read().await.contains_key(&webhook_id) { - break; - } - - // Wait for events - match receiver.recv().await { - Ok(event) => { - // A disabled webhook drops events but keeps listening, so that - // enabling it again resumes delivery. Check the current state: - // it may have changed while waiting for the event. - let webhook = match webhooks.read().await.get(&webhook_id) { - Some(current) => current.clone(), - None => break, - }; - if webhook.enabled && webhook.filter.matches(&event) { - // Clone necessary data for delivery task - let webhook_clone = webhook.clone(); - let event_clone = event.clone(); - let http_client_clone = http_client.clone(); - let stats_clone = stats.clone(); - let config_clone = config.clone(); - let semaphore_clone = delivery_semaphore.clone(); - - // Spawn a tracked delivery task - deliveries.spawn("delivery", async move { - // Acquire delivery permit inside the task - let Ok(_permit) = semaphore_clone.acquire().await else { - tracing::error!("webhook delivery semaphore closed"); - return; - }; - Self::deliver_webhook_event( - webhook_clone, - event_clone, - http_client_clone, - stats_clone, - config_clone, - ) - .await; - }); - } - } + let event = match received { + Ok(event) => event, Err(broadcast::error::RecvError::Lagged(skipped)) => { tracing::warn!( - "Webhook {} listener fell behind and skipped {} events; \ - consider a larger event buffer", - webhook.name, - skipped + "Webhook {webhook_id} listener fell behind and dropped {skipped} \ + events; the endpoint may be slow or down, or the event buffer \ + too small" ); + if let Some(webhook_stats) = stats.write().await.get_mut(&webhook_id) { + webhook_stats.dropped_events += skipped; + } + continue; } - Err(broadcast::error::RecvError::Closed) => { - // Event manager dropped, exit task - break; - } + // Event manager dropped + Err(broadcast::error::RecvError::Closed) => break, + }; + + // Use the current configuration: it may have been updated, enabled or + // disabled while waiting. A disabled webhook drops events but keeps + // listening, so that enabling it again resumes delivery. + let webhook = match webhooks.read().await.get(&webhook_id) { + Some(current) => current.clone(), + None => break, + }; + if !webhook.enabled || !webhook.filter.matches(&event) { + continue; + } + + // Bound the backlog: wait for a pending-delivery slot. While waiting, + // new events queue up in the broadcast buffer (and the oldest are + // dropped once it is full) instead of in unbounded delivery tasks. + let full = pending.available_permits() == 0; + if full && !paused && config.log_deliveries { + tracing::warn!( + "Webhook {} has {} deliveries pending; pausing its listener", + webhook.name, + config.max_pending_deliveries + ); } + paused = full; + let slot = tokio::select! { + biased; + _ = &mut stop => break, + slot = pending.clone().acquire_owned() => match slot { + Ok(slot) => slot, + Err(_) => break, + }, + }; + + let http_client = http_client.clone(); + let stats = stats.clone(); + let config = config.clone(); + let delivery_semaphore = delivery_semaphore.clone(); + deliveries.spawn("delivery", async move { + Self::deliver_webhook_event( + webhook, + event, + http_client, + stats, + config, + delivery_semaphore, + slot, + ) + .await; + }); } }); } - /// Deliver an event to a webhook endpoint with retries + /// Deliver an event to a webhook endpoint with retries. + /// + /// Each attempt holds a slot of `delivery_semaphore` while its request is in + /// flight; the backoff between attempts does not. `_pending` is the webhook's + /// pending-delivery slot, released when the delivery is finished. async fn deliver_webhook_event( webhook: WebhookConfig, event: JobLifecycleEvent, http_client: Client, stats: Arc>>, config: WebhookManagerConfig, + delivery_semaphore: Arc, + _pending: OwnedSemaphorePermit, ) { let mut attempt = 0; let max_attempts = webhook.retry_policy.max_attempts; @@ -914,9 +1012,14 @@ impl WebhookManager { while attempt < max_attempts { attempt += 1; - let delivery_result = + let delivery_result = { + let Ok(_permit) = delivery_semaphore.acquire().await else { + tracing::error!("webhook delivery semaphore closed"); + return; + }; Self::attempt_webhook_delivery(&webhook, &event, &http_client, &config, attempt) - .await; + .await + }; // Update statistics Self::update_webhook_stats(&webhook.id, &delivery_result, stats.clone()).await; @@ -926,7 +1029,7 @@ impl WebhookManager { tracing::debug!( "Webhook delivery successful: {} -> {} (attempt {})", webhook.name, - webhook.url, + crate::config::redact_url_path(&webhook.url), attempt ); } @@ -945,7 +1048,7 @@ impl WebhookManager { "Webhook delivery failed, retrying in {:?}: {} -> {} (attempt {}/{})", delay, webhook.name, - webhook.url, + crate::config::redact_url_path(&webhook.url), attempt, max_attempts ); @@ -957,7 +1060,7 @@ impl WebhookManager { "Webhook delivery failed with non-retryable status {}: {} -> {}", delivery_result.status_code.unwrap_or(0), webhook.name, - webhook.url + crate::config::redact_url_path(&webhook.url) ); } break; @@ -967,13 +1070,18 @@ impl WebhookManager { "Webhook delivery failed after {} attempts: {} -> {}", max_attempts, webhook.name, - webhook.url + crate::config::redact_url_path(&webhook.url) ); } } } - /// Attempt a single webhook delivery + /// Attempt a single webhook delivery. + /// + /// The webhook's timeout covers the whole attempt: connecting, sending, the + /// response headers and reading the response body. When the status arrived but + /// the body did not finish in time, the attempt counts by its status (the endpoint + /// did answer) and the body is not recorded. async fn attempt_webhook_delivery( webhook: &WebhookConfig, event: &JobLifecycleEvent, @@ -983,24 +1091,24 @@ impl WebhookManager { ) -> WebhookDelivery { let delivery_id = Uuid::new_v4(); let start_time = std::time::Instant::now(); + let elapsed_ms = || u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX); + let failure = |status_code: Option, error: String, duration_ms: u64| WebhookDelivery { + delivery_id, + webhook_id: webhook.id, + event_id: event.event_id, + status_code, + response_body: None, + error_message: Some(error), + attempted_at: Utc::now(), + duration_ms: Some(duration_ms), + attempt_number, + success: false, + }; // Prepare payload let payload = match Self::build_payload(webhook, event) { Ok(payload) => payload, - Err(e) => { - return WebhookDelivery { - delivery_id, - webhook_id: webhook.id, - event_id: event.event_id, - status_code: None, - response_body: None, - error_message: Some(format!("failed to build payload: {e}")), - attempted_at: Utc::now(), - duration_ms: Some(0), - attempt_number, - success: false, - }; - } + Err(e) => return failure(None, format!("failed to build payload: {e}"), 0), }; // Build request @@ -1031,73 +1139,55 @@ impl WebhookManager { .header("Content-Type", "application/json") .json(&payload); - // Set timeout - let timeout_duration = Duration::from_secs(webhook.timeout_secs); - - // Make request - match timeout(timeout_duration, request.send()).await { - Ok(Ok(response)) => { - let duration_ms = - u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX); - let status_code = response.status().as_u16(); - let success = response.status().is_success(); - - // Read response body - let response_body = match response.text().await { - Ok(body) => Some(truncate_response_body(body, config.max_response_body_size)), - Err(_) => None, - }; + // One deadline for the whole attempt, body included. + let deadline = Instant::now() + attempt_timeout(webhook, config); - WebhookDelivery { - delivery_id, - webhook_id: webhook.id, - event_id: event.event_id, - status_code: Some(status_code), - response_body, - error_message: if success { - None - } else { - Some(format!("HTTP {}", status_code)) - }, - attempted_at: Utc::now(), - duration_ms: Some(duration_ms), - attempt_number, - success, - } - } - Ok(Err(err)) => { - let duration_ms = - u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX); - WebhookDelivery { - delivery_id, - webhook_id: webhook.id, - event_id: event.event_id, - status_code: None, - response_body: None, - error_message: Some(err.to_string()), - attempted_at: Utc::now(), - duration_ms: Some(duration_ms), - attempt_number, - success: false, - } + let response = match timeout_at(deadline, request.send()).await { + Ok(Ok(response)) => response, + Ok(Err(err)) => return failure(None, err.to_string(), elapsed_ms()), + Err(_) => return failure(Some(408), "Request timeout".to_string(), elapsed_ms()), + }; + + let status_code = response.status().as_u16(); + let success = response.status().is_success(); + let response_body = match timeout_at( + deadline, + read_body_limited(response, config.max_response_body_size), + ) + .await + { + Ok(Ok(body)) => Some(body), + Ok(Err(e)) => { + tracing::debug!( + "Webhook {}: failed to read response body: {e}", + webhook.name + ); + None } Err(_) => { - // Timeout - let duration_ms = - u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX); - WebhookDelivery { - delivery_id, - webhook_id: webhook.id, - event_id: event.event_id, - status_code: Some(408), - response_body: None, - error_message: Some("Request timeout".to_string()), - attempted_at: Utc::now(), - duration_ms: Some(duration_ms), - attempt_number, - success: false, - } + tracing::debug!( + "Webhook {}: timed out reading the response body", + webhook.name + ); + None } + }; + + WebhookDelivery { + delivery_id, + webhook_id: webhook.id, + event_id: event.event_id, + status_code: Some(status_code), + response_body, + error_message: if success { + None + } else { + Some(format!("HTTP {}", status_code)) + }, + attempted_at: Utc::now(), + duration_ms: Some(elapsed_ms()), + attempt_number, + success, } } @@ -1588,22 +1678,6 @@ pub fn verify_hmac_signature(secret: &str, payload: &[u8], signature: &str) -> b && expected.bytes().zip(signature.bytes()).all(|(a, b)| a == b) } -/// Truncate a webhook response body to at most `max_bytes` bytes (plus a marker). -/// -/// The response comes from a remote endpoint, so the cut point can fall inside a -/// multi-byte UTF-8 character. Back up to the nearest character boundary instead of -/// slicing at the raw byte offset, which would panic. -fn truncate_response_body(body: String, max_bytes: usize) -> String { - if body.len() <= max_bytes { - return body; - } - let mut end = max_bytes; - while !body.is_char_boundary(end) { - end -= 1; - } - format!("{}... [truncated]", &body[..end]) -} - #[cfg(test)] mod tests { use super::*; @@ -1790,6 +1864,7 @@ mod tests { avg_response_time_ms: 0.0, last_success_at: None, last_failure_at: None, + dropped_events: 0, calculated_at: Utc::now(), }; @@ -2162,6 +2237,7 @@ mod tests { avg_response_time_ms: 150.5, last_success_at: Some(Utc::now() - chrono::Duration::minutes(5)), last_failure_at: Some(Utc::now() - chrono::Duration::minutes(10)), + dropped_events: 0, calculated_at: Utc::now(), }; @@ -2185,20 +2261,31 @@ mod tests { } #[test] - fn test_truncate_response_body_respects_utf8_boundaries() { + fn test_response_body_text_respects_utf8_boundaries() { + let cut = |body: &str, max: usize| { + let bytes = body.as_bytes(); + let truncated = bytes.len() > max; + response_body_text(bytes[..max.min(bytes.len())].to_vec(), truncated) + }; // Short bodies are returned unchanged. - assert_eq!(truncate_response_body("ok".to_string(), 10), "ok"); + assert_eq!(cut("ok", 10), "ok"); - // "é" is 2 bytes and "😀" is 4; cutting inside either must not panic. - let body = "aé😀b".to_string(); // bytes: a(1) é(2) 😀(4) b(1) = 8 - assert_eq!(truncate_response_body(body.clone(), 2), "a... [truncated]"); - assert_eq!(truncate_response_body(body.clone(), 3), "aé... [truncated]"); + // "é" is 2 bytes and "😀" is 4; a cut inside either drops the partial character. + let body = "aé😀b"; // bytes: a(1) é(2) 😀(4) b(1) = 8 + assert_eq!(cut(body, 2), "a... [truncated]"); + assert_eq!(cut(body, 3), "aé... [truncated]"); for max in 0..body.len() { - let truncated = truncate_response_body(body.clone(), max); + let truncated = cut(body, max); assert!(truncated.ends_with("... [truncated]")); assert!(truncated.len() <= max + "... [truncated]".len()); } - assert_eq!(truncate_response_body(body.clone(), body.len()), body); + assert_eq!(cut(body, body.len()), body); + + // Invalid UTF-8 from the endpoint is replaced, not an error. + assert_eq!( + response_body_text(vec![b'a', 0xff, b'b'], false), + "a\u{fffd}b" + ); } fn completed_event() -> JobLifecycleEvent { @@ -2267,8 +2354,6 @@ mod tests { let webhook_id = webhook.id; manager.add_webhook(webhook).await.unwrap(); - // Let the listener task start and subscribe before the event is published. - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); wait_for(&received, 1).await; @@ -2289,8 +2374,6 @@ mod tests { .await .unwrap(); - // Let the listener task start and subscribe before the event is published. - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); wait_for(&received, 1).await; @@ -2325,8 +2408,6 @@ mod tests { .await .unwrap(); - // Let the listener task start and subscribe before the events are published. - tokio::time::sleep(Duration::from_millis(100)).await; for _ in 0..100 { events.publish_event(completed_event()).await.unwrap(); } @@ -2345,19 +2426,26 @@ mod tests { ..Default::default() })); let manager = WebhookManager::new_default(events.clone()); - manager - .add_webhook(WebhookConfig::new("lagging".to_string(), url)) - .await - .unwrap(); - - // Let the listener task start and subscribe before the events are published. - tokio::time::sleep(Duration::from_millis(100)).await; + let webhook = WebhookConfig::new("lagging".to_string(), url); + let id = webhook.id; + manager.add_webhook(webhook).await.unwrap(); // Overrun the 4-event channel so the listener sees RecvError::Lagged. for _ in 0..50 { events.publish_event(completed_event()).await.unwrap(); } - tokio::time::sleep(Duration::from_millis(300)).await; + // Every event is either delivered or counted as dropped. + let mut accounted = false; + for _ in 0..400 { + let dropped = manager.get_webhook_stats(id).await.unwrap().dropped_events; + let delivered = received.load(std::sync::atomic::Ordering::SeqCst) as u64; + if dropped > 0 && dropped + delivered == 50 { + accounted = true; + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + assert!(accounted, "dropped events are counted"); let before = received.load(std::sync::atomic::Ordering::SeqCst); assert!(before >= 1, "some events from the burst must be delivered"); @@ -2379,8 +2467,13 @@ mod tests { panic!("expected test panic in a listener task"); }); - // Let the listener task start and subscribe before the event is published. - tokio::time::sleep(Duration::from_millis(100)).await; + // Let both tasks run (and panic) before shutting down. + for _ in 0..200 { + if manager.task_panics() == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } manager.shutdown(Duration::from_secs(5)).await; assert_eq!(manager.task_panics(), 2); } @@ -2614,7 +2707,6 @@ mod tests { r#"{"text": "{{event.queue_name}} job {{event.job_id}}", "job_id": "{{event.job_id}}"}"#, ); manager.add_webhook(webhook).await.unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; let event = completed_event(); events.publish_event(event.clone()).await.unwrap(); @@ -2724,7 +2816,6 @@ mod tests { let events = Arc::new(EventManager::new_default()); let manager = WebhookManager::new_default(events.clone()); manager.add_webhook(webhook).await.unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); let recorded = next_recorded(url_rx).await; manager.shutdown(Duration::from_secs(5)).await; @@ -2823,7 +2914,6 @@ mod tests { }); let id = webhook.id; manager.add_webhook(webhook).await.unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); next_recorded(&mut rx).await; tokio::time::sleep(Duration::from_millis(300)).await; @@ -2842,7 +2932,6 @@ mod tests { .with_retry_policy(no_retries()); let id = webhook.id; manager.add_webhook(webhook).await.unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); next_recorded(&mut rx).await; let mut failed = false; @@ -2872,7 +2961,6 @@ mod tests { WebhookConfig::new("toggle".to_string(), url.clone()).with_retry_policy(no_retries()); let id = webhook.id; manager.add_webhook(webhook.clone()).await.unwrap(); - tokio::time::sleep(Duration::from_millis(100)).await; manager.disable_webhook(id).await.unwrap(); assert_eq!(manager.get_stats().await.active_webhooks, 0); @@ -2899,7 +2987,6 @@ mod tests { manager.get_webhook(id).await.unwrap().method, HttpMethod::Put ); - tokio::time::sleep(Duration::from_millis(100)).await; events.publish_event(completed_event()).await.unwrap(); assert!(next_recorded(&mut rx).await.request_line.starts_with("PUT")); @@ -2913,6 +3000,327 @@ mod tests { manager.shutdown(Duration::from_secs(5)).await; } + /// Wait until `condition` holds, polling every 10 ms for up to 10 seconds. + async fn eventually(what: &str, mut condition: F) + where + F: FnMut() -> Fut, + Fut: std::future::Future, + { + for _ in 0..1000 { + if condition().await { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("timed out waiting until {what}"); + } + + /// M9: the subscription exists when `add_webhook` returns, so an event published + /// immediately afterwards (before the listener task has even run) is delivered. + #[tokio::test] + async fn test_event_published_right_after_add_is_delivered() { + let (url, mut rx) = recording_http_server(200, Duration::ZERO).await; + let events = Arc::new(EventManager::new_default()); + let manager = WebhookManager::new_default(events.clone()); + let event = completed_event(); + manager + .add_webhook(WebhookConfig::new("immediate".to_string(), url)) + .await + .unwrap(); + events.publish_event(event.clone()).await.unwrap(); + + let recorded = next_recorded(&mut rx).await; + assert!(recorded.body.contains(&event.event_id.to_string())); + manager.shutdown(Duration::from_secs(5)).await; + } + + /// H11: updating a webhook (or re-adding it under the same id) leaves exactly one + /// listener, so an event is delivered once, not once per update. + #[tokio::test] + async fn test_updates_do_not_duplicate_delivery() { + let (url, mut rx) = recording_http_server(200, Duration::ZERO).await; + let events = Arc::new(EventManager::new_default()); + let manager = WebhookManager::new_default(events.clone()); + let webhook = + WebhookConfig::new("updated".to_string(), url.clone()).with_retry_policy(no_retries()); + let id = webhook.id; + manager.add_webhook(webhook.clone()).await.unwrap(); + + for i in 0..5 { + manager + .update_webhook( + webhook + .clone() + .with_header("X-Version".to_string(), i.to_string()), + ) + .await + .unwrap(); + } + // Re-adding and removing then adding under the same id replace the listener too. + manager.add_webhook(webhook.clone()).await.unwrap(); + manager.remove_webhook(id).await.unwrap(); + manager + .add_webhook(webhook.with_header("X-Version".to_string(), "last".to_string())) + .await + .unwrap(); + assert_eq!(events.subscription_count().await, 1); + + let event = completed_event(); + events.publish_event(event.clone()).await.unwrap(); + let recorded = next_recorded(&mut rx).await; + assert_eq!( + recorded.headers.get("x-version").map(String::as_str), + Some("last") + ); + assert!(recorded.body.contains(&event.event_id.to_string())); + + // No duplicate arrives, and exactly one attempt was made. + tokio::time::sleep(Duration::from_millis(300)).await; + assert!( + rx.try_recv().is_err(), + "the event was delivered more than once" + ); + assert_eq!( + manager.get_webhook_stats(id).await.unwrap().total_attempts, + 1 + ); + manager.shutdown(Duration::from_secs(5)).await; + } + + /// An updated configuration applies to the next event without re-adding. + #[tokio::test] + async fn test_update_keeps_stats_and_applies_new_filter() { + let (url, mut rx) = recording_http_server(200, Duration::ZERO).await; + let events = Arc::new(EventManager::new_default()); + let manager = WebhookManager::new_default(events.clone()); + let webhook = + WebhookConfig::new("filtered".to_string(), url).with_retry_policy(no_retries()); + let id = webhook.id; + manager.add_webhook(webhook.clone()).await.unwrap(); + events.publish_event(completed_event()).await.unwrap(); + next_recorded(&mut rx).await; + eventually("the first delivery is recorded", || async { + manager.get_webhook_stats(id).await.unwrap().total_attempts == 1 + }) + .await; + + // Only failed events from now on. + manager + .update_webhook( + webhook.with_filter( + EventFilter::new() + .with_event_types(vec![crate::events::JobLifecycleEventType::Failed]), + ), + ) + .await + .unwrap(); + events.publish_event(completed_event()).await.unwrap(); + let mut failed = completed_event(); + failed.event_type = crate::events::JobLifecycleEventType::Failed; + events.publish_event(failed.clone()).await.unwrap(); + + let recorded = next_recorded(&mut rx).await; + assert!(recorded.body.contains(&failed.event_id.to_string())); + eventually("the second delivery is recorded", || async { + manager.get_webhook_stats(id).await.unwrap().total_attempts == 2 + }) + .await; + manager.shutdown(Duration::from_secs(5)).await; + } + + /// A local HTTP server that holds every request until `gate` has a permit (one per + /// response), then answers `200 OK`. Returns its URL and a request counter. + async fn gated_http_server( + gate: Arc, + ) -> (String, Arc) { + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/hook", listener.local_addr().unwrap()); + let received = Arc::new(AtomicUsize::new(0)); + let counter = received.clone(); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let counter = counter.clone(); + let gate = gate.clone(); + tokio::spawn(async move { + let mut buf = vec![0u8; 16 * 1024]; + let _ = socket.read(&mut buf).await; + counter.fetch_add(1, Ordering::SeqCst); + if let Ok(permit) = gate.acquire().await { + permit.forget(); + } + let _ = socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await; + }); + } + }); + (url, received) + } + + /// H12: with the endpoint stuck, at most `max_pending_deliveries` deliveries exist + /// for the webhook; the listener waits and the overflow is dropped and counted. + #[tokio::test] + async fn test_pending_deliveries_are_bounded() { + use std::sync::atomic::Ordering; + let gate = Arc::new(Semaphore::new(0)); + let (url, received) = gated_http_server(gate.clone()).await; + let events = Arc::new(EventManager::new(crate::events::EventConfig { + max_buffer_size: 4, + ..Default::default() + })); + let manager = WebhookManager::new( + events.clone(), + WebhookManagerConfig { + max_pending_deliveries: 2, + ..Default::default() + }, + ); + let webhook = WebhookConfig::new("stuck".to_string(), url).with_retry_policy(no_retries()); + let id = webhook.id; + manager.add_webhook(webhook).await.unwrap(); + + for _ in 0..20 { + events.publish_event(completed_event()).await.unwrap(); + tokio::task::yield_now().await; + } + eventually("two requests are in flight", || async { + received.load(Ordering::SeqCst) == 2 + }) + .await; + // The listener is waiting: no third delivery is started. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(received.load(Ordering::SeqCst), 2); + assert!( + manager.deliveries.len() <= 2, + "{}", + manager.deliveries.len() + ); + + // Once the endpoint answers, the rest is delivered or counted as dropped. + gate.add_permits(1_000); + eventually("every event is delivered or dropped", || async { + let stats = manager.get_webhook_stats(id).await.unwrap(); + stats.successful_deliveries + stats.dropped_events == 20 + }) + .await; + let stats = manager.get_webhook_stats(id).await.unwrap(); + assert!(stats.dropped_events > 0, "{stats:?}"); + manager.shutdown(Duration::from_secs(5)).await; + } + + /// H13: an endpoint that sends its headers and then stalls the body cannot hold a + /// delivery longer than the webhook's timeout. + #[tokio::test] + async fn test_timeout_covers_the_response_body() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/hook", listener.local_addr().unwrap()); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + tokio::spawn(async move { + let mut buf = vec![0u8; 16 * 1024]; + let _ = socket.read(&mut buf).await; + let _ = socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\npartial") + .await; + tokio::time::sleep(Duration::from_secs(60)).await; + }); + } + }); + + let events = Arc::new(EventManager::new_default()); + let manager = WebhookManager::new_default(events.clone()); + let webhook = WebhookConfig::new("stalling".to_string(), url) + .with_timeout_secs(1) + .with_retry_policy(no_retries()); + let id = webhook.id; + manager.add_webhook(webhook).await.unwrap(); + let started = std::time::Instant::now(); + events.publish_event(completed_event()).await.unwrap(); + + eventually("the attempt finishes", || async { + manager.get_webhook_stats(id).await.unwrap().total_attempts == 1 + }) + .await; + assert!(started.elapsed() < Duration::from_secs(5)); + // The endpoint did answer 200, so the delivery counts as successful. + let stats = manager.get_webhook_stats(id).await.unwrap(); + assert_eq!(stats.successful_deliveries, 1); + assert_eq!( + manager.shutdown(Duration::ZERO).await, + 0, + "nothing still running" + ); + } + + /// H13: only `max_bytes` of a response body are read, even an endless one. + #[tokio::test] + async fn test_response_body_read_is_bounded() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/", listener.local_addr().unwrap()); + tokio::spawn(async move { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 16 * 1024]; + let _ = socket.read(&mut buf).await; + let _ = socket + .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n") + .await; + // An endless body. + while socket.write_all(b"400\r\n").await.is_ok() + && socket.write_all(&[b'x'; 1024]).await.is_ok() + && socket.write_all(b"\r\n").await.is_ok() + {} + }); + + let response = Client::new().get(&url).send().await.unwrap(); + let body = tokio::time::timeout(Duration::from_secs(5), read_body_limited(response, 10)) + .await + .expect("reading stops at the limit") + .unwrap(); + assert_eq!(body, "xxxxxxxxxx... [truncated]"); + } + + /// M4: `timeout_secs = 0` (or missing in a file) uses the manager's default. + #[test] + fn test_zero_timeout_uses_manager_default() { + let config = WebhookManagerConfig { + default_timeout_secs: 7, + ..Default::default() + }; + let webhook = WebhookConfig::new("w".to_string(), "http://x".to_string()); + assert_eq!( + attempt_timeout(&webhook.clone().with_timeout_secs(3), &config), + Duration::from_secs(3) + ); + assert_eq!( + attempt_timeout(&webhook.clone().with_timeout_secs(0), &config), + Duration::from_secs(7) + ); + + let mut value = serde_json::to_value(&webhook).unwrap(); + value.as_object_mut().unwrap().remove("timeout_secs"); + let parsed: WebhookConfig = serde_json::from_value(value).unwrap(); + assert_eq!(parsed.timeout_secs, 0); + assert_eq!(attempt_timeout(&parsed, &config), Duration::from_secs(7)); + + let settings = crate::config::WebhookGlobalSettings { + default_timeout_secs: 9, + max_pending_deliveries: 5, + ..Default::default() + }; + let from_settings = WebhookManagerConfig::from(&settings); + assert_eq!(from_settings.default_timeout_secs, 9); + assert_eq!(from_settings.max_pending_deliveries, 5); + } + #[test] fn test_webhook_config_builders() { let filter = EventFilter::new().with_queue_names(vec!["q".to_string()]); diff --git a/src/worker.rs b/src/worker.rs index 884596f..b98688c 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -348,11 +348,17 @@ pub struct AutoscaleConfig { pub scale_step: usize, /// Time window for queue depth averaging pub evaluation_window: Duration, - /// Minimum worker idle time before considering scale-down + /// Unused: scale-down is decided from the queue depth averaged over + /// `evaluation_window` and limited by `cooldown_period`. + #[deprecated( + since = "1.15.6", + note = "never applied; use `evaluation_window` and `cooldown_period` to slow scale-down" + )] pub idle_timeout: Duration, } impl Default for AutoscaleConfig { + #[allow(deprecated)] fn default() -> Self { Self { enabled: true, @@ -368,6 +374,7 @@ impl Default for AutoscaleConfig { } } +#[allow(deprecated)] impl AutoscaleConfig { /// Create a new autoscale configuration with default values pub fn new() -> Self { @@ -422,7 +429,11 @@ impl AutoscaleConfig { self } - /// Set the minimum idle time before considering scale-down + /// Unused; see [`AutoscaleConfig::idle_timeout`]. + #[deprecated( + since = "1.15.6", + note = "never applied; use `evaluation_window` and `cooldown_period` to slow scale-down" + )] pub fn with_idle_timeout(mut self, timeout: Duration) -> Self { self.idle_timeout = timeout; self @@ -791,8 +802,9 @@ pub struct Worker { shutdown_grace_period: Duration, /// Lease held on a running job, renewed by heartbeats lease_duration: Duration, - /// How often the monitoring task updates metrics and checks alerts - monitoring_interval: Duration, + /// How often the monitoring task updates metrics and checks alerts, when set + /// explicitly (otherwise the metrics collector's update interval, or 30 seconds) + monitoring_interval: Option, } impl Clone for Worker @@ -915,7 +927,7 @@ where event_manager: None, shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, lease_duration: DEFAULT_LEASE_DURATION, - monitoring_interval: DEFAULT_MONITORING_INTERVAL, + monitoring_interval: None, } } @@ -991,7 +1003,7 @@ where event_manager: None, shutdown_grace_period: DEFAULT_SHUTDOWN_GRACE_PERIOD, lease_duration: DEFAULT_LEASE_DURATION, - monitoring_interval: DEFAULT_MONITORING_INTERVAL, + monitoring_interval: None, } } @@ -1271,8 +1283,10 @@ where self } - /// Set how often the worker's monitoring task runs (default - /// [`DEFAULT_MONITORING_INTERVAL`], 30 seconds). + /// Set how often the worker's monitoring task runs. Without this, it runs at the + /// [metrics collector](Self::with_metrics_collector)'s update interval + /// (`MetricsConfig::update_interval`), or every [`DEFAULT_MONITORING_INTERVAL`] + /// (30 seconds) without one. /// /// With a [metrics collector](Self::with_metrics_collector) or alerting configured, /// a background task updates the queue depth metric and checks the alert thresholds @@ -1281,7 +1295,7 @@ where /// loop, so a slow alert target or the queue depth `COUNT(*)` never delays /// dequeuing. Values below 10ms are raised to 10ms. pub fn with_monitoring_interval(mut self, interval: Duration) -> Self { - self.monitoring_interval = interval; + self.monitoring_interval = Some(interval); self } @@ -2738,7 +2752,6 @@ where #[cfg(any(feature = "metrics", feature = "alerting"))] fn start_monitoring_task(&self) -> tokio::task::JoinHandle<()> { let queue_name = self.queue_name.clone(); - let monitoring_interval = self.monitoring_interval; let queue = Arc::clone(&self.queue); @@ -2754,10 +2767,19 @@ where #[cfg(feature = "alerting")] let stats_collector = self.stats_collector.clone(); + // An explicit interval wins, then the metrics collector's update interval. + #[cfg(feature = "metrics")] + let collector_interval = metrics_collector.as_ref().map(|m| m.update_interval()); + #[cfg(not(feature = "metrics"))] + let collector_interval: Option = None; + let monitor_every = self + .monitoring_interval + .or(collector_interval) + .unwrap_or(DEFAULT_MONITORING_INTERVAL); + tokio::spawn(async move { // `interval` panics on a zero period. - let mut interval = - tokio::time::interval(monitoring_interval.max(MIN_MONITORING_INTERVAL)); + let mut interval = tokio::time::interval(monitor_every.max(MIN_MONITORING_INTERVAL)); loop { interval.tick().await; @@ -3819,7 +3841,6 @@ mod tests { assert_eq!(config.cooldown_period, Duration::from_secs(60)); assert_eq!(config.scale_step, 1); assert_eq!(config.evaluation_window, Duration::from_secs(30)); - assert_eq!(config.idle_timeout, Duration::from_secs(300)); } #[test] @@ -3831,8 +3852,7 @@ mod tests { .with_scale_down_threshold(1) .with_cooldown_period(Duration::from_secs(120)) .with_scale_step(2) - .with_evaluation_window(Duration::from_secs(45)) - .with_idle_timeout(Duration::from_secs(600)); + .with_evaluation_window(Duration::from_secs(45)); assert_eq!(config.min_workers, 2); assert_eq!(config.max_workers, 20); @@ -3841,7 +3861,6 @@ mod tests { assert_eq!(config.cooldown_period, Duration::from_secs(120)); assert_eq!(config.scale_step, 2); assert_eq!(config.evaluation_window, Duration::from_secs(45)); - assert_eq!(config.idle_timeout, Duration::from_secs(600)); } #[test] diff --git a/tests/priority_tests.rs b/tests/priority_tests.rs index 17ef4a3..702162a 100644 --- a/tests/priority_tests.rs +++ b/tests/priority_tests.rs @@ -61,12 +61,10 @@ fn test_priority_weights_configuration() { // Test custom weights let custom_weights = PriorityWeights::new() .with_weight(JobPriority::Critical, 100) - .with_weight(JobPriority::High, 50) - .with_fairness_factor(0.3); + .with_weight(JobPriority::High, 50); assert_eq!(custom_weights.get_weight(JobPriority::Critical), 100); assert_eq!(custom_weights.get_weight(JobPriority::High), 50); - assert_eq!(custom_weights.fairness_factor(), 0.3); } /// Test priority statistics calculation @@ -101,13 +99,10 @@ fn test_priority_statistics() { #[test] fn test_worker_priority_configuration() { // Test that priority configuration works properly - let custom_weights = PriorityWeights::new() - .with_weight(JobPriority::Critical, 50) - .with_fairness_factor(0.2); + let custom_weights = PriorityWeights::new().with_weight(JobPriority::Critical, 50); // Test that worker would be able to use these weights assert_eq!(custom_weights.get_weight(JobPriority::Critical), 50); - assert_eq!(custom_weights.fairness_factor(), 0.2); // Test strict mode configuration let strict_weights = PriorityWeights::strict(); @@ -267,13 +262,6 @@ fn test_priority_weight_edge_cases() { priority ); } - - // Test fairness factor bounds - let clamped_weights = PriorityWeights::new().with_fairness_factor(2.0); // Should clamp to 1.0 - assert_eq!(clamped_weights.fairness_factor(), 1.0); - - let negative_weights = PriorityWeights::new().with_fairness_factor(-0.5); // Should clamp to 0.0 - assert_eq!(negative_weights.fairness_factor(), 0.0); } /// Test that all priority levels are covered