Skip to main content

adk_core/
webhook_delivery.rs

1//! Signed outbound webhook delivery with retries, a dead-letter sink, and an egress guard.
2//!
3//! [`WebhookDelivery`] (feature `webhook-delivery`) sends one message to one endpoint:
4//!
5//! | Step | Behaviour |
6//! |------|-----------|
7//! | Egress check | The URL must pass the [`EgressPolicy`] (default [`EgressPolicy::public_only`]: HTTPS, and a host that is not, and does not resolve to, a loopback, private, link-local, cloud metadata or other non-public address). Requests go through a [`GuardedClient`], so the address checked is the address connected to; when that client cannot be built, every delivery is dead-lettered and none is sent |
8//! | Signing | Every attempt is signed with [Standard Webhooks](crate::webhook) under the message's stable `webhook-id` and a fresh `webhook-timestamp` |
9//! | Success | Any `2xx` response |
10//! | Retry | Connection errors, timeouts, `408`, `425`, `429`, and `5xx`, with exponential backoff and full jitter, honouring `Retry-After` up to the backoff cap |
11//! | Dead letter | Any other status, an egress refusal, or the last failed attempt; the message goes to the [`DeadLetterSink`] with its last error |
12//!
13//! Redirects are never followed: a public endpoint could otherwise bounce the request to
14//! an internal one. Logs name the endpoint's origin, never its path or query, which may
15//! carry a token.
16//!
17//! # Example
18//!
19//! ```rust,no_run
20//! use std::sync::Arc;
21//! use adk_core::webhook::WebhookSecret;
22//! use adk_core::webhook_delivery::{
23//!     InMemoryDeadLetterSink, RetryPolicy, WebhookDelivery, WebhookEndpoint, WebhookMessage,
24//! };
25//! use serde_json::json;
26//!
27//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
28//! let dead_letters = Arc::new(InMemoryDeadLetterSink::new());
29//! let delivery = WebhookDelivery::new()
30//!     .with_retry_policy(RetryPolicy::default().with_max_attempts(5))
31//!     .with_dead_letter_sink(dead_letters.clone());
32//!
33//! let endpoint = WebhookEndpoint::new(
34//!     "https://hooks.example.com/runs",
35//!     WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?,
36//! );
37//! let message = WebhookMessage::json("run_42.completed", &json!({"runId": "run_42", "state": "completed"}))?;
38//! let report = delivery.deliver(&endpoint, &message).await;
39//! assert!(report.is_delivered() || !dead_letters.letters().is_empty());
40//! # Ok(())
41//! # }
42//! ```
43
44use std::sync::Arc;
45use std::time::Duration;
46
47use async_trait::async_trait;
48use chrono::{DateTime, Utc};
49use serde::{Deserialize, Serialize};
50
51use crate::egress::{EgressPolicy, GuardedClient, find_denial};
52use crate::webhook::{WebhookSecret, WebhookSigner};
53use crate::{Clock, SystemClock};
54
55/// How many attempts a delivery makes and how long it waits between them.
56///
57/// The wait before attempt `n + 1` is a uniformly random duration in
58/// `[0, min(max_backoff, initial_backoff × 2ⁿ⁻¹)]` ("full jitter"), so many senders
59/// retrying one recovering endpoint spread out instead of arriving together. A
60/// `Retry-After` header raises the wait to the value it names, up to `max_backoff`.
61///
62/// # Example
63///
64/// ```rust
65/// use std::time::Duration;
66/// use adk_core::webhook_delivery::RetryPolicy;
67///
68/// let policy = RetryPolicy::default()
69///     .with_max_attempts(8)
70///     .with_initial_backoff(Duration::from_millis(500))
71///     .with_max_backoff(Duration::from_secs(60));
72/// assert_eq!(policy.backoff_cap(1), Duration::from_millis(500));
73/// assert_eq!(policy.backoff_cap(4), Duration::from_secs(4));
74/// assert_eq!(policy.backoff_cap(20), Duration::from_secs(60));
75/// ```
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct RetryPolicy {
78    /// Attempts before the message is dead-lettered; at least 1.
79    pub max_attempts: u32,
80    /// The backoff cap after the first failed attempt.
81    pub initial_backoff: Duration,
82    /// The largest wait between attempts.
83    pub max_backoff: Duration,
84    /// The bound on one attempt, from connect to response.
85    pub attempt_timeout: Duration,
86}
87
88impl Default for RetryPolicy {
89    fn default() -> Self {
90        Self {
91            max_attempts: 6,
92            initial_backoff: Duration::from_secs(1),
93            max_backoff: Duration::from_secs(300),
94            attempt_timeout: Duration::from_secs(10),
95        }
96    }
97}
98
99impl RetryPolicy {
100    /// Sets the attempts before dead-lettering; values below 1 become 1.
101    pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
102        self.max_attempts = max_attempts.max(1);
103        self
104    }
105
106    /// Sets the backoff cap after the first failed attempt.
107    pub fn with_initial_backoff(mut self, backoff: Duration) -> Self {
108        self.initial_backoff = backoff;
109        self
110    }
111
112    /// Sets the largest wait between attempts.
113    pub fn with_max_backoff(mut self, backoff: Duration) -> Self {
114        self.max_backoff = backoff;
115        self
116    }
117
118    /// Sets the bound on one attempt.
119    pub fn with_attempt_timeout(mut self, timeout: Duration) -> Self {
120        self.attempt_timeout = timeout;
121        self
122    }
123
124    /// The upper bound of the jittered wait after failed attempt `attempt` (1-based).
125    pub fn backoff_cap(&self, attempt: u32) -> Duration {
126        let factor = 2u32.saturating_pow(attempt.saturating_sub(1));
127        self.initial_backoff.saturating_mul(factor).min(self.max_backoff)
128    }
129}
130
131/// One receiver of webhook deliveries.
132#[derive(Debug, Clone)]
133pub struct WebhookEndpoint {
134    /// The URL deliveries are POSTed to.
135    pub url: String,
136    signer: WebhookSigner,
137}
138
139impl WebhookEndpoint {
140    /// Creates an endpoint whose deliveries are signed with `secret`.
141    pub fn new(url: impl Into<String>, secret: WebhookSecret) -> Self {
142        Self { url: url.into(), signer: WebhookSigner::new(secret) }
143    }
144
145    /// Creates an endpoint with a configured signer, for example one carrying two
146    /// secrets during a rotation.
147    pub fn with_signer(url: impl Into<String>, signer: WebhookSigner) -> Self {
148        Self { url: url.into(), signer }
149    }
150}
151
152/// One message to deliver.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct WebhookMessage {
155    /// The `webhook-id`: stable across every retry, so receivers deduplicate on it.
156    pub id: String,
157    /// The raw body.
158    pub body: Vec<u8>,
159    /// The `content-type` header.
160    pub content_type: String,
161}
162
163impl WebhookMessage {
164    /// A message with a JSON body.
165    ///
166    /// # Errors
167    ///
168    /// Returns the serialization error.
169    pub fn json(id: impl Into<String>, body: &impl Serialize) -> serde_json::Result<Self> {
170        Ok(Self {
171            id: id.into(),
172            body: serde_json::to_vec(body)?,
173            content_type: "application/json".to_string(),
174        })
175    }
176}
177
178/// A message that could not be delivered.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(rename_all = "camelCase")]
181pub struct DeadLetter {
182    /// The message's `webhook-id`.
183    pub message_id: String,
184    /// The endpoint URL.
185    pub url: String,
186    /// Attempts made.
187    pub attempts: u32,
188    /// The last HTTP status, when a response arrived.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub last_status: Option<u16>,
191    /// Why the last attempt failed.
192    pub last_error: String,
193    /// The body, for a later redrive.
194    pub body: Vec<u8>,
195    /// When the message was dead-lettered.
196    pub failed_at: DateTime<Utc>,
197}
198
199/// Where undeliverable messages go.
200#[async_trait]
201pub trait DeadLetterSink: Send + Sync {
202    /// Stores `letter`.
203    ///
204    /// # Errors
205    ///
206    /// Returns an error when the sink cannot be written; the delivery logs it.
207    async fn dead_letter(&self, letter: DeadLetter) -> crate::Result<()>;
208}
209
210/// Process-local [`DeadLetterSink`] for tests and single-process deployments.
211#[derive(Debug, Default)]
212pub struct InMemoryDeadLetterSink {
213    letters: std::sync::Mutex<Vec<DeadLetter>>,
214}
215
216impl InMemoryDeadLetterSink {
217    /// Creates an empty sink.
218    pub fn new() -> Self {
219        Self::default()
220    }
221
222    /// The letters received so far, oldest first.
223    pub fn letters(&self) -> Vec<DeadLetter> {
224        self.letters.lock().unwrap_or_else(|e| e.into_inner()).clone()
225    }
226}
227
228#[async_trait]
229impl DeadLetterSink for InMemoryDeadLetterSink {
230    async fn dead_letter(&self, letter: DeadLetter) -> crate::Result<()> {
231        self.letters.lock().unwrap_or_else(|e| e.into_inner()).push(letter);
232        Ok(())
233    }
234}
235
236/// The result of one [`WebhookDelivery::deliver`].
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum DeliveryReport {
239    /// The endpoint answered `2xx`.
240    Delivered {
241        /// Attempts made, including the successful one.
242        attempts: u32,
243        /// The success status.
244        status: u16,
245    },
246    /// The message went to the dead-letter sink.
247    DeadLettered(DeadLetter),
248}
249
250impl DeliveryReport {
251    /// Whether the endpoint accepted the message.
252    pub fn is_delivered(&self) -> bool {
253        matches!(self, Self::Delivered { .. })
254    }
255}
256
257enum Attempt {
258    Delivered(u16),
259    Retry { status: Option<u16>, error: String, retry_after: Option<Duration> },
260    Permanent { status: Option<u16>, error: String },
261}
262
263/// Sends signed webhooks with retries and dead-lettering.
264///
265/// Clones share the HTTP client and the dead-letter sink.
266#[derive(Clone)]
267pub struct WebhookDelivery {
268    /// The client that enforces the egress policy, or why it could not be built.
269    client: Result<GuardedClient, String>,
270    retry: RetryPolicy,
271    egress: EgressPolicy,
272    dead_letters: Option<Arc<dyn DeadLetterSink>>,
273    clock: Arc<dyn Clock>,
274}
275
276impl std::fmt::Debug for WebhookDelivery {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("WebhookDelivery")
279            .field("retry", &self.retry)
280            .field("egress", &self.egress)
281            .field("dead_letters", &self.dead_letters.is_some())
282            .finish()
283    }
284}
285
286impl Default for WebhookDelivery {
287    fn default() -> Self {
288        Self::new()
289    }
290}
291
292impl WebhookDelivery {
293    /// Creates a sender with the default [`RetryPolicy`] and [`EgressPolicy`] and no
294    /// dead-letter sink (undeliverable messages are logged).
295    pub fn new() -> Self {
296        Self::configured(RetryPolicy::default(), EgressPolicy::default())
297    }
298
299    fn configured(retry: RetryPolicy, egress: EgressPolicy) -> Self {
300        // Never a default client in its place: it would skip the egress checks, use the
301        // system proxies and follow redirects.
302        let client = GuardedClient::builder(egress.clone())
303            .timeout(retry.attempt_timeout)
304            .connect_timeout(retry.attempt_timeout.min(Duration::from_secs(5)))
305            .redirects(0)
306            .user_agent(concat!("adk-rust-webhooks/", env!("CARGO_PKG_VERSION")))
307            .build()
308            .map_err(|error| {
309                tracing::error!(error = %error, "webhook client failed to build; every delivery is refused");
310                error.to_string()
311            });
312        Self { client, retry, egress, dead_letters: None, clock: Arc::new(SystemClock) }
313    }
314
315    /// Sets the retry policy.
316    pub fn with_retry_policy(self, retry: RetryPolicy) -> Self {
317        let Self { dead_letters, clock, egress, .. } = self;
318        Self { dead_letters, clock, ..Self::configured(retry, egress) }
319    }
320
321    /// Sets the egress policy.
322    pub fn with_egress_policy(self, egress: EgressPolicy) -> Self {
323        let Self { dead_letters, clock, retry, .. } = self;
324        Self { dead_letters, clock, ..Self::configured(retry, egress) }
325    }
326
327    /// Sets where undeliverable messages go.
328    pub fn with_dead_letter_sink(mut self, sink: Arc<dyn DeadLetterSink>) -> Self {
329        self.dead_letters = Some(sink);
330        self
331    }
332
333    /// Sets the clock that timestamps signatures and dead letters.
334    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
335        self.clock = clock;
336        self
337    }
338
339    /// The retry policy.
340    pub fn retry_policy(&self) -> RetryPolicy {
341        self.retry
342    }
343
344    /// The egress policy.
345    pub fn egress_policy(&self) -> &EgressPolicy {
346        &self.egress
347    }
348
349    /// Delivers `message` to `endpoint`, retrying until it succeeds, fails permanently,
350    /// or runs out of attempts, and dead-letters it in the last two cases.
351    ///
352    /// A sender whose HTTP client could not be built dead-letters every message without an
353    /// attempt.
354    pub async fn deliver(
355        &self,
356        endpoint: &WebhookEndpoint,
357        message: &WebhookMessage,
358    ) -> DeliveryReport {
359        if let Err(denial) = self.egress.check_url(&endpoint.url) {
360            return self.dead_letter(endpoint, message, 0, None, denial.to_string()).await;
361        }
362        let client = match &self.client {
363            Ok(client) => client,
364            Err(reason) => {
365                return self.dead_letter(endpoint, message, 0, None, reason.clone()).await;
366            }
367        };
368        let mut attempt = 0;
369        loop {
370            attempt += 1;
371            let (status, error, retry_after) = match self.attempt(client, endpoint, message).await {
372                Attempt::Delivered(status) => {
373                    tracing::debug!(webhook.id = %message.id, http.status = status, attempt, "webhook delivered");
374                    return DeliveryReport::Delivered { attempts: attempt, status };
375                }
376                Attempt::Permanent { status, error } => {
377                    return self.dead_letter(endpoint, message, attempt, status, error).await;
378                }
379                Attempt::Retry { status, error, retry_after } => (status, error, retry_after),
380            };
381            if attempt >= self.retry.max_attempts {
382                return self.dead_letter(endpoint, message, attempt, status, error).await;
383            }
384            let wait = jittered(self.retry.backoff_cap(attempt))
385                .max(retry_after.unwrap_or_default())
386                .min(self.retry.max_backoff);
387            tracing::debug!(
388                webhook.id = %message.id,
389                attempt,
390                retry.wait_ms = wait.as_millis() as u64,
391                error = %error,
392                "webhook attempt failed; retrying"
393            );
394            tokio::time::sleep(wait).await;
395        }
396    }
397
398    async fn attempt(
399        &self,
400        client: &GuardedClient,
401        endpoint: &WebhookEndpoint,
402        message: &WebhookMessage,
403    ) -> Attempt {
404        let signed = endpoint.signer.sign(&message.id, self.clock.now().timestamp(), &message.body);
405        let mut request = match client.post(&endpoint.url) {
406            Ok(request) => request,
407            Err(denial) => return Attempt::Permanent { status: None, error: denial.to_string() },
408        };
409        request = request
410            .header(reqwest::header::CONTENT_TYPE, &message.content_type)
411            .body(message.body.clone());
412        for (name, value) in signed.header_pairs() {
413            request = request.header(name, value);
414        }
415        let response = match request.send().await {
416            Ok(response) => response,
417            Err(error) => {
418                // The URL's path or query may carry a token; the error is logged and kept.
419                let error = error.without_url();
420                let refused = find_denial(&error).is_some();
421                let text = full_error(&error);
422                return if refused {
423                    Attempt::Permanent { status: None, error: text }
424                } else {
425                    Attempt::Retry { status: None, error: text, retry_after: None }
426                };
427            }
428        };
429        let status = response.status().as_u16();
430        if response.status().is_success() {
431            return Attempt::Delivered(status);
432        }
433        let retry_after = response
434            .headers()
435            .get(reqwest::header::RETRY_AFTER)
436            .and_then(|value| value.to_str().ok())
437            .and_then(|value| value.trim().parse::<u64>().ok())
438            .map(Duration::from_secs);
439        let error = format!("endpoint answered HTTP {status}");
440        match status {
441            408 | 425 | 429 | 500..=599 => {
442                Attempt::Retry { status: Some(status), error, retry_after }
443            }
444            _ => Attempt::Permanent { status: Some(status), error },
445        }
446    }
447
448    async fn dead_letter(
449        &self,
450        endpoint: &WebhookEndpoint,
451        message: &WebhookMessage,
452        attempts: u32,
453        last_status: Option<u16>,
454        last_error: String,
455    ) -> DeliveryReport {
456        let letter = DeadLetter {
457            message_id: message.id.clone(),
458            url: endpoint.url.clone(),
459            attempts,
460            last_status,
461            last_error,
462            body: message.body.clone(),
463            failed_at: self.clock.now(),
464        };
465        // The origin only: the URL's path or query may carry a token.
466        let origin = reqwest::Url::parse(&letter.url)
467            .map(|url| url.origin().ascii_serialization())
468            .unwrap_or_else(|_| "an invalid URL".to_string());
469        tracing::warn!(
470            webhook.id = %letter.message_id,
471            webhook.origin = %origin,
472            attempts,
473            error = %letter.last_error,
474            "webhook dead-lettered"
475        );
476        if let Some(sink) = &self.dead_letters
477            && let Err(error) = sink.dead_letter(letter.clone()).await
478        {
479            tracing::error!(webhook.id = %letter.message_id, error = %error, "dead-letter sink write failed");
480        }
481        DeliveryReport::DeadLettered(letter)
482    }
483}
484
485/// The error and its sources, so a refusal's reason is not hidden behind "error sending request".
486fn full_error(error: &dyn std::error::Error) -> String {
487    let mut text = error.to_string();
488    let mut source = error.source();
489    while let Some(cause) = source {
490        text.push_str(": ");
491        text.push_str(&cause.to_string());
492        source = cause.source();
493    }
494    text
495}
496
497/// A uniformly random duration in `[0, cap]`.
498fn jittered(cap: Duration) -> Duration {
499    // uuid v4 draws from the OS random source; 64 of its random bits are plenty here.
500    let random = uuid::Uuid::new_v4().as_u64_pair().0;
501    let fraction = (random >> 11) as f64 / (1u64 << 53) as f64;
502    cap.mul_f64(fraction)
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    #[test]
510    fn backoff_doubles_up_to_the_cap() {
511        let policy = RetryPolicy::default()
512            .with_initial_backoff(Duration::from_millis(100))
513            .with_max_backoff(Duration::from_millis(500));
514        let caps: Vec<_> = (1..=5).map(|n| policy.backoff_cap(n).as_millis()).collect();
515        assert_eq!(caps, vec![100, 200, 400, 500, 500]);
516        for _ in 0..100 {
517            assert!(jittered(Duration::from_millis(100)) <= Duration::from_millis(100));
518        }
519    }
520
521    /// A name that resolves to an address the policy refuses is dead-lettered after one
522    /// attempt: the refusal is permanent, not retried.
523    #[tokio::test]
524    async fn a_resolution_refusal_is_not_retried() {
525        use crate::egress::StaticResolver;
526        let resolver =
527            StaticResolver::new().with_host("hooks.internal.test", ["10.0.0.9".parse().unwrap()]);
528        let client = GuardedClient::builder(EgressPolicy::public_only())
529            .resolver(Arc::new(resolver))
530            .redirects(0)
531            .build()
532            .unwrap();
533        let sink = Arc::new(InMemoryDeadLetterSink::new());
534        let delivery = WebhookDelivery {
535            client: Ok(client),
536            ..WebhookDelivery::new()
537                .with_retry_policy(RetryPolicy::default().with_max_attempts(5))
538                .with_dead_letter_sink(sink.clone())
539        };
540        let endpoint = WebhookEndpoint::new(
541            "https://hooks.internal.test/runs",
542            WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap(),
543        );
544        let message = WebhookMessage::json("msg_2", &serde_json::json!({ "ok": true })).unwrap();
545
546        let DeliveryReport::DeadLettered(letter) = delivery.deliver(&endpoint, &message).await
547        else {
548            panic!("a refused destination must not be delivered");
549        };
550        assert_eq!(letter.attempts, 1);
551        assert!(letter.last_error.contains("10.0.0.9"), "{}", letter.last_error);
552        assert_eq!(sink.letters().len(), 1);
553    }
554
555    /// A sender whose guarded client did not build sends nothing: no fallback client reaches
556    /// the endpoint, and the message is dead-lettered with the reason.
557    #[tokio::test]
558    async fn a_client_that_did_not_build_refuses_every_delivery() {
559        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
560        let address = listener.local_addr().unwrap();
561        let sink = Arc::new(InMemoryDeadLetterSink::new());
562        let delivery = WebhookDelivery {
563            client: Err("the webhook HTTP client could not be built (no TLS)".to_string()),
564            ..WebhookDelivery::new()
565                .with_egress_policy(EgressPolicy::allow_private_networks())
566                .with_dead_letter_sink(sink.clone())
567        };
568        let endpoint = WebhookEndpoint::new(
569            format!("http://{address}/hook"),
570            WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap(),
571        );
572        let message = WebhookMessage::json("msg_1", &serde_json::json!({ "ok": true })).unwrap();
573
574        let report = delivery.deliver(&endpoint, &message).await;
575
576        let DeliveryReport::DeadLettered(letter) = report else {
577            panic!("a delivery without its guarded client must not succeed: {report:?}");
578        };
579        assert_eq!(letter.attempts, 0);
580        assert_eq!(letter.last_error, "the webhook HTTP client could not be built (no TLS)");
581        assert_eq!(sink.letters(), vec![letter]);
582        let accepted = tokio::time::timeout(Duration::from_millis(200), listener.accept()).await;
583        assert!(accepted.is_err(), "no request reached the endpoint");
584
585        // Under the default, public-only policy too: a public URL gets no attempt.
586        let guarded = WebhookDelivery {
587            client: Err("the webhook HTTP client could not be built (no TLS)".to_string()),
588            ..WebhookDelivery::new()
589        };
590        let public = WebhookEndpoint::new(
591            "https://hooks.example.com/runs",
592            WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap(),
593        );
594        match guarded.deliver(&public, &message).await {
595            DeliveryReport::DeadLettered(letter) => assert_eq!(letter.attempts, 0),
596            other => panic!("a delivery without its guarded client must not succeed: {other:?}"),
597        }
598    }
599}