forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

worker.rs571 lines, 22.5 KiBHistoryRawDownload
1//! The webhook delivery worker: claims due deliveries, sends them with bounded concurrency, and
2//! records each result. A failed attempt is retried on the backoff schedule until the sixth
3//! attempt, after which the delivery is `gave_up`.
4//!
5//! The signature is computed at send time from the decrypted secret, so a rotated secret applies
6//! to retries too. The headers queued at enqueue time never carry a signature or a delivery GUID;
7//! both are added here. After each send, the headers actually sent replace the stored ones, so the
8//! delivery log shows what the receiver got.
9
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use forge_core::Error;
14use forge_core::time::{now_stamp, stamp_after, stamp_ago};
15use forge_core::webhooks::{AttemptOutcome, Delivery};
16use futures_util::StreamExt;
17use serde_json::{Map, Value};
18use time::OffsetDateTime;
19use time::format_description::well_known::Rfc3339;
20use tokio::sync::Notify;
21
22use super::client::{HookClient, SendOutcome, WebhookPolicy, sign, validate_url};
23use crate::live::bump_settings;
24use crate::state::AppState;
25
26/// Handle that wakes the worker. `emit` calls `notify_one` after queueing deliveries.
27pub type WebhookWaker = Arc<Notify>;
28
29/// Deliveries claimed per pass.
30const BATCH: u32 = 16;
31/// Deliveries sent at once.
32const CONCURRENCY: usize = 4;
33/// The shortest sleep, so a due time that has already passed does not spin the loop.
34const MIN_SLEEP: Duration = Duration::from_secs(1);
35/// The longest sleep. It only guards against a missed wake, it is not polling.
36const BACKSTOP: Duration = Duration::from_secs(15 * 60);
37/// Deliveries older than this are purged.
38const RETENTION: Duration = Duration::from_secs(14 * 24 * 60 * 60);
39/// How often the purge runs.
40const PURGE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
41/// Delay before the next attempt, indexed by the attempt that just failed (attempt 1 waits 1m).
42/// After the sixth attempt there is no retry.
43const BACKOFF: [Duration; 5] = [
44 Duration::from_secs(60),
45 Duration::from_secs(5 * 60),
46 Duration::from_secs(30 * 60),
47 Duration::from_secs(2 * 60 * 60),
48 Duration::from_secs(6 * 60 * 60),
49];
50/// Headers the worker owns. Anything stored under these names is replaced at send time.
51const WORKER_HEADERS: [&str; 3] = ["Content-Type", "X-Forge-Delivery", "X-Forge-Signature-256"];
52
53/// Starts the worker task and returns the handle that wakes it. The task runs until the process
54/// exits; it never panics on a bad delivery.
55pub fn spawn(state: AppState) -> WebhookWaker {
56 let waker = Arc::clone(&state.webhook_waker);
57 let task_waker = Arc::clone(&waker);
58 tokio::spawn(run(state, task_waker));
59 waker
60}
61
62async fn run(state: AppState, waker: WebhookWaker) {
63 let policy = match WebhookPolicy::from_config(&state.config.webhooks) {
64 Ok(policy) => policy,
65 Err(e) => {
66 // Fall back to the strictest policy: no internal hosts and no plain HTTP.
67 tracing::error!(error = %e, "webhooks: invalid [webhooks] config, using the default policy");
68 WebhookPolicy {
69 allow_http: false,
70 allowed_hosts: Vec::new(),
71 }
72 }
73 };
74 let client = match HookClient::new(policy.clone()) {
75 Ok(client) => client,
76 Err(e) => {
77 tracing::error!(error = %e, "webhooks: cannot build the HTTP client, deliveries stop");
78 return;
79 }
80 };
81
82 let mut last_purge: Option<Instant> = None;
83 loop {
84 purge_if_due(&state, &mut last_purge).await;
85 let claimed = match process_due(&state, &client, &policy, &now_stamp()).await {
86 Ok(claimed) => claimed,
87 Err(e) => {
88 tracing::error!(error = %e, "webhooks: claiming deliveries failed");
89 0
90 }
91 };
92 // A full batch may mean more is due, so go straight back for it.
93 if claimed < usize::try_from(BATCH).unwrap_or(usize::MAX) {
94 // Wake when the earliest pending delivery is due (a claimed one wakes at its lease
95 // expiry), or at the next purge. With nothing pending, sleep up to `BACKSTOP`.
96 let next = match state.store.next_delivery_due().await {
97 Ok(next) => next,
98 Err(e) => {
99 tracing::error!(error = %e, "webhooks: could not read the next due time");
100 None
101 }
102 };
103 let nap = next
104 .as_deref()
105 .map_or(BACKSTOP, |due| sleep_for(due, OffsetDateTime::now_utc()));
106 let purge_nap = last_purge.map_or(Duration::ZERO, |at| {
107 PURGE_EVERY.saturating_sub(at.elapsed())
108 });
109 tokio::select! {
110 () = waker.notified() => {}
111 () = tokio::time::sleep(nap) => {}
112 () = tokio::time::sleep(purge_nap) => {}
113 }
114 }
115 }
116}
117
118/// How long the worker sleeps until `next_due` (an RFC 3339 stamp, the earliest pending
119/// delivery), clamped to `MIN_SLEEP..=BACKSTOP`. An unparsable stamp gives `MIN_SLEEP`, so it is
120/// retried promptly rather than stalling.
121fn sleep_for(next_due: &str, now: OffsetDateTime) -> Duration {
122 let Ok(due) = OffsetDateTime::parse(next_due, &Rfc3339) else {
123 return MIN_SLEEP;
124 };
125 let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
126 until.clamp(MIN_SLEEP, BACKSTOP)
127}
128
129/// Claims up to [`BATCH`] due deliveries at `now`, sends them, and records each result. Returns
130/// how many were claimed.
131pub async fn process_due(
132 state: &AppState,
133 client: &HookClient,
134 policy: &WebhookPolicy,
135 now: &str,
136) -> forge_core::Result<usize> {
137 let claimed = state.store.claim_due_deliveries(now, BATCH).await?;
138 let count = claimed.len();
139 futures_util::stream::iter(claimed)
140 .for_each_concurrent(CONCURRENCY, |delivery| async move {
141 let outcome = attempt(state, client, policy, &delivery).await;
142 if let Err(e) = state
143 .store
144 .record_delivery_result(&delivery.id, &outcome)
145 .await
146 {
147 tracing::error!(error = %e, delivery_id = %delivery.id, "webhooks: recording the result failed");
148 }
149 // The delivery list of the repo's settings shows the result. A deleted hook has no repo to
150 // wake, and its deliveries are gone with it.
151 match state.store.webhook(&delivery.hook_id).await {
152 Ok(Some(hook)) => bump_settings(&state.live, &hook.repo_id),
153 Ok(None) => {}
154 Err(e) => {
155 tracing::error!(error = %e, delivery_id = %delivery.id, "webhooks: loading the hook to bump failed")
156 }
157 }
158 })
159 .await;
160 Ok(count)
161}
162
163/// One send attempt for a claimed delivery. Never fails: every problem becomes an outcome.
164async fn attempt(
165 state: &AppState,
166 client: &HookClient,
167 policy: &WebhookPolicy,
168 delivery: &Delivery,
169) -> AttemptOutcome {
170 let hook = match state.store.webhook(&delivery.hook_id).await {
171 Ok(Some(hook)) => hook,
172 Ok(None) => return give_up("webhook was deleted"),
173 Err(e) => return retry(delivery, &format!("loading the webhook failed: {e}")),
174 };
175 let secret = match state.store.webhook_secret(&hook.id, &state.key).await {
176 Ok(secret) => secret,
177 Err(Error::NotFound) => return give_up("webhook was deleted"),
178 Err(Error::Crypto(e)) => return give_up(&format!("cannot open the webhook secret: {e}")),
179 Err(e) => return retry(delivery, &format!("loading the webhook secret failed: {e}")),
180 };
181 // Policy can change between save and send, so the URL is checked again here.
182 if let Err(e) = validate_url(&hook.url, policy) {
183 return retry(delivery, &e.to_string());
184 }
185 let body = delivery.request_body.clone().into_bytes();
186 let headers = request_headers(delivery, &secret, &body);
187 let sent = client.send(&hook.url, &headers, body).await;
188 let mut result = outcome(delivery, sent);
189 result.request_headers = Some(headers_json(&headers));
190 result
191}
192
193/// The headers as a JSON object, the form the store keeps. Stored after each send so the delivery
194/// log shows the GUID and signature the receiver got.
195fn headers_json(headers: &[(String, String)]) -> String {
196 let map: Map<String, Value> = headers
197 .iter()
198 .map(|(name, value)| (name.clone(), Value::String(value.clone())))
199 .collect();
200 Value::Object(map).to_string()
201}
202
203/// The stored headers, minus the ones the worker owns, plus the fresh GUID, content type and
204/// signature.
205fn request_headers(delivery: &Delivery, secret: &str, body: &[u8]) -> Vec<(String, String)> {
206 let mut headers: Vec<(String, String)> = match serde_json::from_str::<Map<String, Value>>(
207 &delivery.request_headers,
208 ) {
209 Ok(map) => map
210 .into_iter()
211 .filter_map(|(name, value)| match value {
212 Value::String(value) => Some((name, value)),
213 _ => None,
214 })
215 .collect(),
216 Err(e) => {
217 tracing::error!(error = %e, delivery_id = %delivery.id, "webhooks: stored headers are not a JSON object");
218 Vec::new()
219 }
220 };
221 headers.retain(|(name, _)| {
222 !WORKER_HEADERS
223 .iter()
224 .any(|owned| owned.eq_ignore_ascii_case(name))
225 });
226 headers.push(("Content-Type".to_owned(), "application/json".to_owned()));
227 headers.push(("X-Forge-Delivery".to_owned(), delivery.guid.clone()));
228 headers.push((
229 "X-Forge-Signature-256".to_owned(),
230 sign(secret.as_bytes(), body),
231 ));
232 headers
233}
234
235/// Turns the send result into the outcome to record. Only a 2xx status counts as success.
236fn outcome(delivery: &Delivery, sent: SendOutcome) -> AttemptOutcome {
237 let ok = matches!(sent.status, Some(200..=299));
238 let mut response_map = Map::new();
239 for (name, value) in sent.headers {
240 response_map.insert(name, Value::String(value));
241 }
242 AttemptOutcome {
243 ok,
244 status: sent.status,
245 response_headers: Some(Value::Object(response_map).to_string()),
246 response_body: Some(sent.body),
247 error: sent.error,
248 duration_ms: Some(sent.duration_ms),
249 next_attempt_at: if ok {
250 None
251 } else {
252 next_attempt_at(delivery.attempt)
253 },
254 request_headers: None,
255 }
256}
257
258/// A failed attempt that will be retried, when the schedule has a slot for it.
259fn retry(delivery: &Delivery, error: &str) -> AttemptOutcome {
260 AttemptOutcome {
261 error: Some(error.to_owned()),
262 next_attempt_at: next_attempt_at(delivery.attempt),
263 ..AttemptOutcome::default()
264 }
265}
266
267/// A failure that will not be retried.
268fn give_up(error: &str) -> AttemptOutcome {
269 AttemptOutcome {
270 error: Some(error.to_owned()),
271 ..AttemptOutcome::default()
272 }
273}
274
275/// When the attempt after `attempt` is due, or `None` once the schedule is used up.
276fn next_attempt_at(attempt: u32) -> Option<String> {
277 let index = usize::try_from(attempt.checked_sub(1)?).ok()?;
278 let delay = BACKOFF.get(index)?;
279 Some(stamp_after(*delay))
280}
281
282/// Deletes deliveries older than [`RETENTION`], at most once per [`PURGE_EVERY`].
283async fn purge_if_due(state: &AppState, last: &mut Option<Instant>) {
284 if last.is_some_and(|at| at.elapsed() < PURGE_EVERY) {
285 return;
286 }
287 *last = Some(Instant::now());
288 let cutoff = stamp_ago(RETENTION);
289 match state.store.purge_deliveries_before(&cutoff).await {
290 Ok(0) => {}
291 Ok(removed) => tracing::info!(removed, "webhooks: purged old deliveries"),
292 Err(e) => tracing::error!(error = %e, "webhooks: purging old deliveries failed"),
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use forge_core::Visibility;
299 use forge_core::webhooks::{Delivery, DeliveryState, Webhook, WebhookEvent};
300 use tokio::io::{AsyncReadExt, AsyncWriteExt};
301 use tokio::net::TcpListener;
302 use tokio::sync::mpsc;
303
304 use super::*;
305 use crate::test_support::{KEY, test_state};
306
307 /// A request as the local test server saw it.
308 struct Seen {
309 headers: Vec<(String, String)>,
310 body: Vec<u8>,
311 }
312
313 /// Serves one request per connection, reporting each request on the channel, and answers
314 /// with `status`.
315 async fn server(status: u16) -> (String, mpsc::UnboundedReceiver<Seen>) {
316 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
317 let addr = listener.local_addr().expect("addr");
318 let (tx, rx) = mpsc::unbounded_channel();
319 tokio::spawn(async move {
320 loop {
321 let Ok((mut socket, _)) = listener.accept().await else {
322 return;
323 };
324 let tx = tx.clone();
325 tokio::spawn(async move {
326 let mut buf = Vec::new();
327 let mut chunk = [0u8; 1024];
328 let head_end = loop {
329 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
330 break pos + 4;
331 }
332 match socket.read(&mut chunk).await {
333 Ok(0) | Err(_) => return,
334 Ok(n) => buf.extend_from_slice(&chunk[..n]),
335 }
336 };
337 let head = String::from_utf8_lossy(&buf[..head_end]).into_owned();
338 let headers: Vec<(String, String)> = head
339 .lines()
340 .skip(1)
341 .filter_map(|line| {
342 line.split_once(':')
343 .map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))
344 })
345 .collect();
346 let length: usize = headers
347 .iter()
348 .find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
349 .and_then(|(_, v)| v.parse().ok())
350 .unwrap_or(0);
351 while buf.len() < head_end + length {
352 match socket.read(&mut chunk).await {
353 Ok(0) | Err(_) => break,
354 Ok(n) => buf.extend_from_slice(&chunk[..n]),
355 }
356 }
357 let body = buf[head_end..].to_vec();
358 let _ = tx.send(Seen { headers, body });
359 let reply = format!(
360 "HTTP/1.1 {status} X\r\nContent-Length: 2\r\nConnection: close\r\n\r\nno"
361 );
362 let _ = socket.write_all(reply.as_bytes()).await;
363 let _ = socket.shutdown().await;
364 });
365 }
366 });
367 (format!("http://127.0.0.1:{}/hook", addr.port()), rx)
368 }
369
370 fn local_policy() -> WebhookPolicy {
371 WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
372 allow_http: true,
373 allowed_hosts: vec!["127.0.0.1/32".into()],
374 })
375 .expect("policy")
376 }
377
378 /// A repo with one hook pointing at `url`, subscribed to push, and one queued delivery.
379 async fn queued(state: &AppState, url: &str) -> (Webhook, Delivery, tempfile::TempDir) {
380 let tmp = tempfile::tempdir().expect("tempdir");
381 let owner = state
382 .store
383 .create_user("tahinli", None, "unused", false)
384 .await
385 .expect("user");
386 let repo = state
387 .store
388 .create_repo(&owner.id, "proj", "", Visibility::Public, "main")
389 .await
390 .expect("repo");
391 let sealed = forge_core::secret::seal(&KEY, b"s3cret").expect("seal");
392 let hook = state
393 .store
394 .create_webhook(
395 &repo.id,
396 &owner.id,
397 url,
398 sealed.as_bytes(),
399 &[WebhookEvent::Push],
400 true,
401 )
402 .await
403 .expect("hook");
404 let headers = r#"{"Content-Type":"application/json","X-Forge-Event":"push","X-Forge-Delivery":"stale","X-Forge-Signature-256":"sha256=stale"}"#;
405 let delivery = state
406 .store
407 .enqueue_delivery(
408 &hook.id,
409 WebhookEvent::Push,
410 "",
411 headers,
412 r#"{"ref":"refs/heads/main"}"#,
413 )
414 .await
415 .expect("enqueue");
416 (hook, delivery, tmp)
417 }
418
419 #[tokio::test]
420 async fn delivers_with_fresh_signature_and_headers() {
421 let tmp = tempfile::tempdir().expect("tempdir");
422 let state = test_state(tmp.path()).await;
423 let (url, mut seen) = server(204).await;
424 let (hook, delivery, _dir) = queued(&state, &url).await;
425 let client = HookClient::new(local_policy()).expect("client");
426
427 let claimed = process_due(&state, &client, &local_policy(), &now_stamp())
428 .await
429 .expect("process");
430 assert_eq!(claimed, 1);
431
432 let request = seen.recv().await.expect("request arrives");
433 let header = |name: &str| {
434 request
435 .headers
436 .iter()
437 .find(|(k, _)| k.eq_ignore_ascii_case(name))
438 .map(|(_, v)| v.clone())
439 };
440 assert_eq!(request.body, br#"{"ref":"refs/heads/main"}"#);
441 assert_eq!(
442 header("x-forge-signature-256"),
443 Some(sign(b"s3cret", &request.body))
444 );
445 assert_eq!(header("x-forge-delivery"), Some(delivery.guid.clone()));
446 assert_eq!(header("x-forge-event"), Some("push".into()));
447 assert_eq!(header("content-type"), Some("application/json".into()));
448
449 let done = state
450 .store
451 .delivery(&delivery.id)
452 .await
453 .expect("lookup")
454 .expect("row");
455 assert_eq!(done.state, DeliveryState::Ok);
456 assert_eq!(done.response_status, Some(204));
457 assert!(done.next_attempt_at.is_none());
458 assert_eq!(done.hook_id, hook.id);
459
460 // The stored request headers are what was sent, including the GUID and signature.
461 let stored: Value = serde_json::from_str(&done.request_headers).expect("json");
462 assert_eq!(stored["X-Forge-Delivery"], delivery.guid.as_str());
463 assert_eq!(
464 stored["X-Forge-Signature-256"],
465 sign(b"s3cret", &request.body).as_str()
466 );
467 assert_eq!(stored["X-Forge-Event"], "push");
468 }
469
470 #[tokio::test]
471 async fn failure_schedules_a_retry_and_six_attempts_give_up() {
472 let tmp = tempfile::tempdir().expect("tempdir");
473 let state = test_state(tmp.path()).await;
474 let (url, _seen) = server(500).await;
475 let (_hook, delivery, _dir) = queued(&state, &url).await;
476 let client = HookClient::new(local_policy()).expect("client");
477
478 process_due(&state, &client, &local_policy(), &now_stamp())
479 .await
480 .expect("process");
481 let failed = state
482 .store
483 .delivery(&delivery.id)
484 .await
485 .expect("lookup")
486 .expect("row");
487 assert_eq!(failed.state, DeliveryState::Failed);
488 assert_eq!(failed.response_status, Some(500));
489 let due = failed.next_attempt_at.clone().expect("retry scheduled");
490 let expected = stamp_after(Duration::from_secs(60));
491 // Both stamps are RFC 3339 UTC, so a text comparison orders them; allow a few seconds.
492 let parse = |s: &str| s.parse::<jiff::Timestamp>().expect("stamp").as_second();
493 let drift = parse(&due) - parse(&expected);
494 assert!(
495 drift.abs() <= 5,
496 "retry at {due}, expected about {expected}"
497 );
498
499 // Each later attempt is claimed at its due time. Attempts 2 through 6 all fail.
500 let far_future = stamp_after(Duration::from_secs(10 * 24 * 60 * 60));
501 let mut last = failed;
502 for attempt in 2..=6u32 {
503 process_due(&state, &client, &local_policy(), &far_future)
504 .await
505 .expect("process");
506 last = state
507 .store
508 .delivery(&delivery.id)
509 .await
510 .expect("lookup")
511 .expect("row");
512 assert_eq!(last.attempt, attempt);
513 }
514 assert_eq!(last.state, DeliveryState::GaveUp);
515 assert!(last.next_attempt_at.is_none());
516 }
517
518 #[tokio::test]
519 async fn invalid_url_is_a_failed_attempt_not_a_send() {
520 let tmp = tempfile::tempdir().expect("tempdir");
521 let state = test_state(tmp.path()).await;
522 // Loopback is not in the allow list of this policy, so validation refuses it.
523 let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())
524 .expect("policy");
525 let (_hook, delivery, _dir) = queued(&state, "https://127.0.0.1/hook").await;
526 let client = HookClient::new(strict.clone()).expect("client");
527 assert!(validate_url("https://127.0.0.1/hook", &strict).is_err());
528
529 process_due(&state, &client, &strict, &now_stamp())
530 .await
531 .expect("process");
532 let row = state
533 .store
534 .delivery(&delivery.id)
535 .await
536 .expect("lookup")
537 .expect("row");
538 assert_eq!(row.state, DeliveryState::Failed);
539 assert!(row.error.is_some());
540 assert!(row.next_attempt_at.is_some());
541 }
542
543 #[test]
544 fn sleep_stops_at_the_next_due_time_and_never_spins() {
545 use time::macros::datetime;
546
547 let now = datetime!(2026-10-15 12:00:00 UTC);
548 let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
549 // Due in 10 minutes: sleep until then.
550 let in_10m = stamp(now + time::Duration::minutes(10));
551 assert_eq!(sleep_for(&in_10m, now), Duration::from_secs(600));
552 // Due later than the backstop: wake at the backstop.
553 let in_1h = stamp(now + time::Duration::hours(1));
554 assert_eq!(sleep_for(&in_1h, now), BACKSTOP);
555 // Already due, or a lease that has just passed: wait the minimum.
556 let past = stamp(now - time::Duration::seconds(5));
557 assert_eq!(sleep_for(&past, now), MIN_SLEEP);
558 // A stamp that does not parse also waits the minimum.
559 assert_eq!(sleep_for("soon", now), MIN_SLEEP);
560 }
561
562 #[test]
563 fn backoff_schedule_matches_the_contract() {
564 assert_eq!(next_attempt_at(0), None);
565 assert!(next_attempt_at(1).is_some());
566 assert!(next_attempt_at(5).is_some());
567 assert_eq!(next_attempt_at(6), None);
568 assert_eq!(BACKOFF[0], Duration::from_secs(60));
569 assert_eq!(BACKOFF[4], Duration::from_secs(6 * 60 * 60));
570 }
571}