turul-a2a 0.2.3

A2A Protocol v1.0 server framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! Push delivery worker.
//!
//! [`PushDeliveryWorker::deliver`] is the per-(event, config) entry
//! point: it claims, POSTs with retries, and records the final
//! outcome. Wiring (event → configs → deliver call) and dispatcher
//! lifecycle (spawn on server start, cancel on shutdown) live in
//! the server integration; this module is the pure delivery logic
//! so it can be exercised against wiremock without standing up the
//! full server.
//!
//! # Per-attempt flow
//!
//! 1. `claim_delivery` — acquire the cross-instance lock.
//! 2. For each retry iteration (up to `max_attempts`):
//!    1. Pre-flight checks: config and task still exist (when the
//!       worker has a [`DeliveryTargetLookup`]; the dispatcher always
//!       installs one), SSRF guard allows the URL. The payload size
//!       cap is checked once, before the claim's first attempt.
//!    2. `record_attempt_started` — advance the counter + set
//!       Attempting, fenced on identity + non-terminal status.
//!    3. POST the payload with `Authorization: {scheme}
//!       {credentials}` (from `Secret`, exposed at the header
//!       build call only) and `X-Turul-Push-Token: {token}`.
//!    4. Classify the response into `DeliveryOutcome::{Succeeded,
//!       Retry, GaveUp, Abandoned}`.
//!    5. `record_delivery_outcome` — idempotent on terminals;
//!       Retry keeps the claim open.
//! 3. Sleep backoff between retries; give up at `max_attempts`.
//!
//! # Scope
//!
//! - Single-config, single-event delivery. The dispatcher chooses
//!   which events trigger which configs; this worker doesn't
//!   enumerate.
//! - No redirect following (`Policy::none`): a redirect target could
//!   be an internal address the SSRF check never saw.
//! - DNS resolved once per attempt via [`PushDnsResolver`]; the
//!   reqwest client is rebuilt per attempt with a `resolve` override
//!   pinning the validated IP, so the TCP connect cannot be swapped
//!   to a different host between validation and dial.

use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

use rand::RngExt;
use url::Url;

use crate::push::claim::{
    A2aPushDeliveryStore, AbandonedReason, DeliveryClaim, DeliveryErrorClass, DeliveryOutcome,
    GaveUpReason,
};
use crate::push::secret::Secret;
use crate::push::ssrf::{
    OutboundUrlValidator, SsrfBlockReason, SsrfDecision, check_url, pick_destination,
};
use crate::storage::{A2aPushNotificationStorage, A2aStorageError, A2aTaskStorage};

/// Longest failed-delivery retention honoured; a longer one (such as
/// `Duration::MAX` meaning "keep") is clamped to it. 1000 years keeps
/// the give-up time plus the retention representable as a `SystemTime`
/// on every platform and as microseconds since the epoch in an `i64`,
/// the storage backends' column type.
pub const MAX_FAILED_DELIVERY_RETENTION: Duration = Duration::from_secs(1000 * 365 * 24 * 60 * 60);

/// Runtime-configurable delivery parameters.
///
/// Defaults: 8 attempts (the first immediate), waits doubling from a
/// 2s base and capped at 60s, ±25% jitter — 2+4+8+16+32+60+60 = 182s,
/// a retry horizon of about 3 minutes. These are also the defaults of
/// the server builders' `push_*` settings.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PushDeliveryConfig {
    pub max_attempts: u32,
    pub backoff_base: Duration,
    pub backoff_cap: Duration,
    pub backoff_jitter: f32,
    /// Bound on the whole POST: connect, send and the full response.
    pub request_timeout: Duration,
    pub connect_timeout: Duration,
    /// Longest the POST waits for the receiver's response with nothing
    /// arriving (status line and headers, then each body read).
    pub read_timeout: Duration,
    pub claim_expiry: Duration,
    pub max_payload_bytes: usize,
    pub allow_insecure_urls: bool,
    /// How long a push config confirmed present by the pre-attempt
    /// check is trusted without re-reading storage. Default `ZERO`:
    /// re-read before every attempt, so a deletion made anywhere stops
    /// the delivery at its next attempt. A non-zero TTL lets a deletion
    /// made outside this worker's server go unseen for up to the TTL.
    pub config_cache_ttl: Duration,
    /// How long a failed-delivery record is kept after the delivery
    /// gives up; see [`DeliveryOutcome::GaveUp`]. Values above
    /// [`MAX_FAILED_DELIVERY_RETENTION`] are clamped to it.
    pub failed_delivery_retention: Duration,
}

impl Default for PushDeliveryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 8,
            backoff_base: Duration::from_secs(2),
            backoff_cap: Duration::from_secs(60),
            backoff_jitter: 0.25,
            request_timeout: Duration::from_secs(30),
            connect_timeout: Duration::from_secs(5),
            read_timeout: Duration::from_secs(30),
            claim_expiry: Duration::from_secs(600),
            max_payload_bytes: 1024 * 1024,
            allow_insecure_urls: false,
            config_cache_ttl: Duration::ZERO,
            failed_delivery_retention: Duration::from_secs(7 * 24 * 60 * 60),
        }
    }
}

impl PushDeliveryConfig {
    /// The delivery parameters a server builder's `push_*` settings
    /// select.
    pub fn from_runtime_config(runtime: &crate::server::RuntimeConfig) -> Self {
        Self {
            max_attempts: runtime.push_max_attempts as u32,
            backoff_base: runtime.push_backoff_base,
            backoff_cap: runtime.push_backoff_cap,
            backoff_jitter: runtime.push_backoff_jitter,
            request_timeout: runtime.push_request_timeout,
            connect_timeout: runtime.push_connect_timeout,
            read_timeout: runtime.push_read_timeout,
            claim_expiry: runtime.push_claim_expiry,
            max_payload_bytes: runtime.push_max_payload_bytes,
            allow_insecure_urls: runtime.allow_insecure_push_urls,
            config_cache_ttl: runtime.push_config_cache_ttl,
            failed_delivery_retention: runtime.push_failed_delivery_retention,
        }
    }
}

/// A push notification target as the worker consumes it. The
/// executor-owned `TaskPushNotificationConfig` proto type is
/// translated here into a shape that wraps credentials + token in
/// `Secret`, so formatting paths inside the worker cannot leak.
#[derive(Clone)]
pub struct PushTarget {
    pub tenant: String,
    pub owner: String,
    pub task_id: String,
    pub event_sequence: u64,
    pub config_id: String,
    pub url: Url,
    pub auth_scheme: String,
    pub auth_credentials: Secret,
    pub token: Option<Secret>,
}

/// Injected DNS resolver so the worker's SSRF + connect-by-IP
/// behaviour is testable without a real DNS round-trip. Resolves
/// a hostname + port into a list of resolved IPs. Implementations
/// MUST perform a single resolution per call (no intermediate
/// caching across calls that the worker could re-resolve against).
pub trait PushDnsResolver: Send + Sync {
    fn resolve(
        &self,
        host: &str,
        port: u16,
    ) -> futures::future::BoxFuture<'_, Result<Vec<IpAddr>, String>>;
}

/// Default resolver using `tokio::net::lookup_host`.
pub struct TokioDnsResolver;

impl PushDnsResolver for TokioDnsResolver {
    fn resolve(
        &self,
        host: &str,
        port: u16,
    ) -> futures::future::BoxFuture<'_, Result<Vec<IpAddr>, String>> {
        let host = host.to_string();
        Box::pin(async move {
            let ips: Vec<IpAddr> = tokio::net::lookup_host((host.as_str(), port))
                .await
                .map_err(|e| e.to_string())?
                .map(|sa| sa.ip())
                .collect();
            Ok(ips)
        })
    }
}

/// The config and task stores the worker re-reads before every POST
/// attempt, so a delivery stops once its push config or task is
/// deleted. A2A v1.0.1 §3.1.10: "No further notifications will be sent
/// to the configured webhook after deletion."
///
/// With a non-zero [`PushDeliveryConfig::config_cache_ttl`] a config
/// found present is trusted for the TTL without re-reading. A deletion
/// through the server that owns this worker drops the cached entries
/// for that task at once (see
/// [`PushDeliveryWorker::invalidate_push_configs`]); a deletion made
/// anywhere else is seen within the TTL.
#[derive(Clone)]
#[non_exhaustive]
pub struct DeliveryTargetLookup {
    pub push_storage: Arc<dyn A2aPushNotificationStorage>,
    pub task_storage: Arc<dyn A2aTaskStorage>,
}

impl DeliveryTargetLookup {
    /// Look targets up in `push_storage` (configs) and `task_storage`
    /// (tasks).
    pub fn new(
        push_storage: Arc<dyn A2aPushNotificationStorage>,
        task_storage: Arc<dyn A2aTaskStorage>,
    ) -> Self {
        Self {
            push_storage,
            task_storage,
        }
    }

    /// `Some(reason)` when the config or the task is gone. A read
    /// error is not evidence of deletion: the attempt proceeds and the
    /// next attempt checks again.
    async fn gone(
        &self,
        target: &PushTarget,
        cache: &PushConfigCache,
        ttl: Duration,
    ) -> Option<AbandonedReason> {
        if !cache.is_fresh(target, ttl) {
            let generation = cache.generation();
            match self
                .push_storage
                .get_config(&target.tenant, &target.task_id, &target.config_id)
                .await
            {
                Ok(None) => return Some(AbandonedReason::ConfigDeleted),
                Ok(Some(_)) => cache.record_present(target, ttl, generation),
                Err(_) => {}
            }
        }
        if let Ok(None) = self
            .task_storage
            .get_task(&target.tenant, &target.task_id, &target.owner, Some(0))
            .await
        {
            return Some(AbandonedReason::TaskDeleted);
        }
        None
    }
}

/// Push configs confirmed present, keyed by task then config id, with
/// the time each was confirmed. Only presence is cached — a missing
/// config abandons the delivery, so there is nothing to re-check — and
/// so a config create can never make an entry stale; only a delete can.
#[derive(Default)]
struct PushConfigCache {
    state: Mutex<PushConfigCacheState>,
}

#[derive(Default)]
struct PushConfigCacheState {
    /// Bumped by every invalidation. A storage read that started
    /// before an invalidation may have seen the config before it was
    /// deleted, so its result is not cached.
    generation: u64,
    by_task: HashMap<(String, String), HashMap<String, Instant>>,
}

impl PushConfigCache {
    fn lock(&self) -> std::sync::MutexGuard<'_, PushConfigCacheState> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    fn is_fresh(&self, target: &PushTarget, ttl: Duration) -> bool {
        self.lock()
            .by_task
            .get(&(target.tenant.clone(), target.task_id.clone()))
            .and_then(|configs| configs.get(&target.config_id))
            .is_some_and(|confirmed| confirmed.elapsed() < ttl)
    }

    /// Read before the storage read whose result is passed to
    /// [`Self::record_present`].
    fn generation(&self) -> u64 {
        self.lock().generation
    }

    /// Cache that `target`'s config was found present by a read that
    /// started at `read_generation`, unless an invalidation has run
    /// since.
    fn record_present(&self, target: &PushTarget, ttl: Duration, read_generation: u64) {
        if ttl.is_zero() {
            return;
        }
        let mut state = self.lock();
        if state.generation != read_generation {
            return;
        }
        // Drop expired entries so the map holds only live deliveries.
        state.by_task.retain(|_, configs| {
            configs.retain(|_, confirmed| confirmed.elapsed() < ttl);
            !configs.is_empty()
        });
        state
            .by_task
            .entry((target.tenant.clone(), target.task_id.clone()))
            .or_default()
            .insert(target.config_id.clone(), Instant::now());
    }

    fn invalidate(&self, tenant: &str, task_id: &str) {
        let mut state = self.lock();
        state.generation = state.generation.wrapping_add(1);
        state
            .by_task
            .remove(&(tenant.to_string(), task_id.to_string()));
    }
}

/// Worker handle, assembled once per instance and cloned into each
/// per-delivery task.
#[derive(Clone)]
pub struct PushDeliveryWorker {
    pub push_delivery_store: Arc<dyn A2aPushDeliveryStore>,
    pub dns_resolver: Arc<dyn PushDnsResolver>,
    pub config: PushDeliveryConfig,
    pub outbound_validator: Option<OutboundUrlValidator>,
    pub instance_id: String,
    /// Pre-attempt existence checks. `None` skips them (a worker
    /// driven directly, without a dispatcher, has no stores to read).
    /// Set through [`Self::with_target_lookup`].
    pub(crate) target_lookup: Option<DeliveryTargetLookup>,
    /// Shared by every clone of this worker.
    config_cache: Arc<PushConfigCache>,
}

impl PushDeliveryWorker {
    /// Construct a worker. HTTP clients are built fresh on every POST
    /// (see [`Self::deliver`]) so each attempt carries its own DNS
    /// override pinning the validated IP. Shared client state would
    /// risk cross-target DNS cache pollution when the worker handles
    /// deliveries to different hosts back-to-back.
    ///
    /// Per-attempt client config:
    /// - Connect timeout: `connect_timeout`.
    /// - Read timeout (receiver silent): `read_timeout`.
    /// - Total timeout: `request_timeout`.
    /// - Redirects: none (HTTP redirects are SSRF risk on push delivery).
    pub fn new(
        push_delivery_store: Arc<dyn A2aPushDeliveryStore>,
        config: PushDeliveryConfig,
        outbound_validator: Option<OutboundUrlValidator>,
        instance_id: String,
    ) -> Result<Self, String> {
        Ok(Self {
            push_delivery_store,
            dns_resolver: Arc::new(TokioDnsResolver),
            config,
            outbound_validator,
            instance_id,
            target_lookup: None,
            config_cache: Arc::default(),
        })
    }

    /// Forget the cached presence of every push config of a task, so
    /// the next attempt of any delivery for it re-reads storage. Call
    /// after deleting one of the task's push configs.
    pub fn invalidate_push_configs(&self, tenant: &str, task_id: &str) {
        self.config_cache.invalidate(tenant, task_id);
    }

    /// Re-read the push config and task before every POST attempt and
    /// abandon the delivery once either is gone.
    pub fn with_target_lookup(mut self, lookup: DeliveryTargetLookup) -> Self {
        self.target_lookup = Some(lookup);
        self
    }

    /// Override the default DNS resolver (tests).
    pub fn with_dns_resolver(mut self, resolver: Arc<dyn PushDnsResolver>) -> Self {
        self.dns_resolver = resolver;
        self
    }

    /// Deliver one push notification.
    ///
    /// Blocks through the full retry horizon in the common case.
    /// The caller (the dispatcher) is expected to spawn this on a
    /// tokio task so other (event, config) pairs can proceed in
    /// parallel.
    pub async fn deliver(&self, target: &PushTarget, payload: &[u8]) -> DeliveryReport {
        // Payload size cap. Skip the POST entirely; GaveUp with
        // PayloadTooLarge so operators see it in the failed-delivery list.
        if payload.len() > self.config.max_payload_bytes {
            let claim = match self.claim(target).await {
                Ok(c) => c,
                Err(_e) => return DeliveryReport::UnclaimedSkip,
            };
            return self
                .persist_terminal(
                    target,
                    &claim,
                    self.gave_up(
                        GaveUpReason::PayloadTooLarge,
                        DeliveryErrorClass::PayloadTooLarge,
                        None,
                    ),
                )
                .await;
        }

        let claim = match self.claim(target).await {
            Ok(c) => c,
            Err(ClaimFailure::AlreadyHeld) => return DeliveryReport::ClaimLostOrFinal,
            Err(ClaimFailure::Other(_)) => return DeliveryReport::UnclaimedSkip,
        };

        let mut current_count = claim.delivery_attempt_count;

        loop {
            // Budget check — precise contract: skip and give up
            // when the pre-start count has already reached the
            // ceiling.
            if current_count >= self.config.max_attempts {
                return self
                    .persist_terminal(
                        target,
                        &claim,
                        self.gave_up(
                            GaveUpReason::MaxAttemptsExhausted,
                            DeliveryErrorClass::Timeout,
                            None,
                        ),
                    )
                    .await;
            }

            // Config / task still exist.
            if let Some(lookup) = &self.target_lookup
                && let Some(reason) = lookup
                    .gone(target, &self.config_cache, self.config.config_cache_ttl)
                    .await
            {
                return self
                    .persist_terminal(target, &claim, DeliveryOutcome::Abandoned { reason })
                    .await;
            }

            // SSRF / scheme pre-flight. URL checks first, so a refused
            // URL is never resolved; then one DNS answer per attempt.
            let decision = match check_url(
                &target.url,
                self.config.allow_insecure_urls,
                self.outbound_validator.as_ref(),
            ) {
                Err(reason) => SsrfDecision::Block(reason),
                Ok(()) => {
                    let ips = self.resolve(&target.url).await.unwrap_or_default();
                    pick_destination(&ips, self.config.allow_insecure_urls)
                }
            };
            let resolved_ip = match decision {
                SsrfDecision::Allow { resolved_ip } => resolved_ip,
                SsrfDecision::Block(SsrfBlockReason::InsecureScheme) => {
                    // Not a failure of the receiver: the config can
                    // never be delivered under this deployment's
                    // policy. Logged (by config id — the URL may carry
                    // secrets) and recorded as abandoned, not given up.
                    tracing::warn!(
                        target: "turul_a2a::push_non_https_url",
                        tenant = %target.tenant,
                        task_id = %target.task_id,
                        config_id = %target.config_id,
                        event_sequence = target.event_sequence,
                        "push delivery abandoned: only https:// webhook URLs are \
                         delivered unless allow_insecure_push_urls is set"
                    );
                    return self
                        .persist_terminal(
                            target,
                            &claim,
                            DeliveryOutcome::Abandoned {
                                reason: AbandonedReason::NonHttpsUrlInProduction,
                            },
                        )
                        .await;
                }
                SsrfDecision::Block(_) => {
                    return self
                        .persist_terminal(
                            target,
                            &claim,
                            self.gave_up(
                                GaveUpReason::SsrfBlocked,
                                DeliveryErrorClass::SSRFBlocked,
                                None,
                            ),
                        )
                        .await;
                }
            };

            // Record attempt start — fenced.
            let new_count = match self
                .push_delivery_store
                .record_attempt_started(
                    &target.tenant,
                    &target.task_id,
                    target.event_sequence,
                    &target.config_id,
                    &claim.claimant,
                    claim.generation,
                )
                .await
            {
                Ok(n) => n,
                Err(A2aStorageError::StaleDeliveryClaim { .. }) => {
                    return DeliveryReport::ClaimLostOrFinal;
                }
                Err(_) => return DeliveryReport::TransientStoreError,
            };
            current_count = new_count;

            // Perform the POST.
            let result = self.post(target, payload, resolved_ip).await;

            // Classify.
            let outcome = match &result {
                Ok(status) if (200..400).contains(&status.as_u16()) => DeliveryOutcome::Succeeded {
                    http_status: status.as_u16(),
                },
                Ok(status) if status.as_u16() == 429 => DeliveryOutcome::Retry {
                    next_attempt_at: SystemTime::now() + self.backoff_for(new_count),
                    http_status: Some(status.as_u16()),
                    error_class: DeliveryErrorClass::HttpError429,
                },
                Ok(status) if status.as_u16() == 408 => DeliveryOutcome::Retry {
                    next_attempt_at: SystemTime::now() + self.backoff_for(new_count),
                    http_status: Some(status.as_u16()),
                    error_class: DeliveryErrorClass::Timeout,
                },
                Ok(status) if (500..600).contains(&status.as_u16()) => DeliveryOutcome::Retry {
                    next_attempt_at: SystemTime::now() + self.backoff_for(new_count),
                    http_status: Some(status.as_u16()),
                    error_class: DeliveryErrorClass::HttpError5xx {
                        status: status.as_u16(),
                    },
                },
                Ok(status) => {
                    // 4xx other than 408/429 → permanent failure. Use
                    // `NonRetryableHttpStatus` (not `MaxAttemptsExhausted`)
                    // because the retry budget was never consumed — the
                    // receiver rejected the payload outright.
                    self.gave_up(
                        GaveUpReason::NonRetryableHttpStatus,
                        DeliveryErrorClass::HttpError4xx {
                            status: status.as_u16(),
                        },
                        Some(status.as_u16()),
                    )
                }
                // A TLS handshake failure is a receiver misconfiguration
                // that retrying within the horizon does not fix.
                Err(DeliveryErrorClass::TlsRejected) => self.gave_up(
                    GaveUpReason::TlsRejected,
                    DeliveryErrorClass::TlsRejected,
                    None,
                ),
                Err(err_class) => DeliveryOutcome::Retry {
                    next_attempt_at: SystemTime::now() + self.backoff_for(new_count),
                    http_status: None,
                    error_class: *err_class,
                },
            };

            match outcome {
                DeliveryOutcome::Succeeded { .. }
                | DeliveryOutcome::GaveUp { .. }
                | DeliveryOutcome::Abandoned { .. } => {
                    // Terminal outcome. Persist it and report based on
                    // the durable result: if the store write fails the
                    // worker must NOT claim success, because the claim
                    // row is still non-terminal and a sweeper would
                    // legitimately re-claim and POST again. See
                    // `persist_terminal` for error-class mapping.
                    return self.persist_terminal(target, &claim, outcome).await;
                }
                DeliveryOutcome::Retry {
                    http_status,
                    error_class,
                    ..
                } => {
                    // Non-terminal: record-and-continue. Failure to
                    // persist this Retry row is non-fatal for
                    // correctness — the next attempt's fenced
                    // `record_attempt_started` reconciles via the
                    // claim's (claimant, generation) token.
                    let _ = self
                        .push_delivery_store
                        .record_delivery_outcome(
                            &target.tenant,
                            &target.task_id,
                            target.event_sequence,
                            &target.config_id,
                            &claim.claimant,
                            claim.generation,
                            DeliveryOutcome::Retry {
                                next_attempt_at: SystemTime::now() + self.backoff_for(new_count),
                                http_status,
                                error_class,
                            },
                        )
                        .await;
                    if current_count >= self.config.max_attempts {
                        // Retry budget exhausted. Commit the terminal
                        // GaveUp with the final attempt's classified
                        // error preserved — operators read
                        // `FailedDelivery` rows off the terminal row,
                        // not the intermediate Retry.
                        return self
                            .persist_terminal(
                                target,
                                &claim,
                                self.gave_up(
                                    GaveUpReason::MaxAttemptsExhausted,
                                    error_class,
                                    http_status,
                                ),
                            )
                            .await;
                    }
                    tokio::time::sleep(self.backoff_for(new_count)).await;
                    continue;
                }
            }
        }
    }

    /// A final failure, retained for `failed_delivery_retention` from
    /// now.
    fn gave_up(
        &self,
        reason: GaveUpReason,
        last_error_class: DeliveryErrorClass,
        last_http_status: Option<u16>,
    ) -> DeliveryOutcome {
        DeliveryOutcome::GaveUp {
            reason,
            last_error_class,
            last_http_status,
            retained_until: SystemTime::now()
                + self
                    .config
                    .failed_delivery_retention
                    .min(MAX_FAILED_DELIVERY_RETENTION),
        }
    }

    /// Commit a terminal outcome and return the matching
    /// [`DeliveryReport`], classifying any store error so the caller
    /// never reports success for a row that remained non-terminal.
    ///
    /// The write is retried up to `TERMINAL_PERSIST_MAX_ATTEMPTS`
    /// times with exponential backoff so that transient storage
    /// blips — brief connection drops, conflicting writes that clear
    /// on retry — don't leak up to the dispatcher as
    /// `TransientStoreError`. A truly persistent failure does surface
    /// so the dispatcher / sweeper can react.
    ///
    /// Mapping on the final attempt:
    /// - `Ok(())` → the report matching the outcome variant.
    /// - `Err(StaleDeliveryClaim)` → `ClaimLostOrFinal`. Another
    ///   writer finalised the row under our fencing token, so the
    ///   terminal state IS durable cluster-wide — just not from our
    ///   perspective. Receivers may observe one extra POST in this
    ///   race, which at-least-once delivery semantics already allow.
    /// - `Err(_)` → `TransientStoreError`. The POST happened but the
    ///   row is still non-terminal; operator intervention (or a
    ///   future reclaim-and-redispatch sweeper) is required. The
    ///   worker MUST NOT return `Succeeded` here, because the
    ///   dispatcher would then treat the event as permanently
    ///   resolved while the claim row stays stuck.
    async fn persist_terminal(
        &self,
        target: &PushTarget,
        claim: &DeliveryClaim,
        outcome: DeliveryOutcome,
    ) -> DeliveryReport {
        let success_report = match &outcome {
            DeliveryOutcome::Succeeded { http_status } => DeliveryReport::Succeeded(*http_status),
            DeliveryOutcome::GaveUp { reason, .. } => DeliveryReport::GaveUp(*reason),
            DeliveryOutcome::Abandoned { reason } => DeliveryReport::Abandoned(*reason),
            // Should not happen — caller is responsible for filtering
            // Retry before calling this helper — but if it does we
            // cannot safely claim terminal delivery.
            DeliveryOutcome::Retry { .. } => return DeliveryReport::TransientStoreError,
        };

        // Backoff schedule: 50ms, 150ms, 500ms between attempts.
        // Short enough to stay well inside claim_expiry and to avoid
        // holding the delivery task open for long; bounded so a
        // permanently-down store does surface the error.
        const TERMINAL_PERSIST_MAX_ATTEMPTS: u32 = 3;
        let backoffs = [
            Duration::from_millis(50),
            Duration::from_millis(150),
            Duration::from_millis(500),
        ];

        let mut last_error: Option<A2aStorageError> = None;
        for attempt in 0..TERMINAL_PERSIST_MAX_ATTEMPTS {
            if attempt > 0 {
                // Index is safe: loop bound == slice length.
                tokio::time::sleep(backoffs[(attempt as usize).min(backoffs.len() - 1)]).await;
            }
            match self
                .push_delivery_store
                .record_delivery_outcome(
                    &target.tenant,
                    &target.task_id,
                    target.event_sequence,
                    &target.config_id,
                    &claim.claimant,
                    claim.generation,
                    outcome.clone(),
                )
                .await
            {
                Ok(()) => return success_report,
                Err(A2aStorageError::StaleDeliveryClaim { .. }) => {
                    // Fencing loss is terminal for this claim and not
                    // retryable — another writer holds the row now.
                    return DeliveryReport::ClaimLostOrFinal;
                }
                Err(e) => {
                    last_error = Some(e);
                }
            }
        }
        let _ = last_error; // Reserved for future tracing plumbing.
        DeliveryReport::TransientStoreError
    }

    /// Claim a stuck (expired, non-terminal) row purely to record
    /// an [`DeliveryOutcome::Abandoned`]. Used by the reclaim sweeper
    /// when the task or config underlying a stuck claim has been
    /// deleted — we can't POST, but we also don't want the row to
    /// keep appearing in every `list_reclaimable_claims` tick. Moving
    /// it to a terminal `Abandoned` state is the only way to stop
    /// that churn without dropping the audit trail.
    pub async fn abandon_reclaimed(
        &self,
        target: &PushTarget,
        reason: AbandonedReason,
    ) -> DeliveryReport {
        let claim = match self.claim(target).await {
            Ok(c) => c,
            Err(ClaimFailure::AlreadyHeld) => return DeliveryReport::ClaimLostOrFinal,
            Err(ClaimFailure::Other(_)) => return DeliveryReport::UnclaimedSkip,
        };
        self.persist_terminal(target, &claim, DeliveryOutcome::Abandoned { reason })
            .await
    }

    async fn claim(&self, target: &PushTarget) -> Result<DeliveryClaim, ClaimFailure> {
        match self
            .push_delivery_store
            .claim_delivery(
                &target.tenant,
                &target.task_id,
                target.event_sequence,
                &target.config_id,
                &self.instance_id,
                &target.owner,
                self.config.claim_expiry,
            )
            .await
        {
            Ok(c) => Ok(c),
            Err(A2aStorageError::ClaimAlreadyHeld { .. }) => Err(ClaimFailure::AlreadyHeld),
            Err(e) => Err(ClaimFailure::Other(e.to_string())),
        }
    }

    async fn resolve(&self, url: &Url) -> Result<Vec<IpAddr>, String> {
        let host = url
            .host_str()
            .ok_or_else(|| "url has no host".to_string())?;
        let port = url.port_or_known_default().unwrap_or(443);
        self.dns_resolver.resolve(host, port).await
    }

    async fn post(
        &self,
        target: &PushTarget,
        payload: &[u8],
        resolved_ip: IpAddr,
    ) -> Result<reqwest::StatusCode, DeliveryErrorClass> {
        // DNS rebinding defence: the POST MUST connect to the IP we
        // validated against the SSRF guard, not whatever a later DNS
        // lookup might return. `reqwest::ClientBuilder::resolve` installs
        // a host-level DNS override on the client, bypassing the system
        // resolver for that hostname while leaving the `Host` header and
        // SNI name intact (reqwest intercepts only TCP dial resolution —
        // the URL's host string is still used for TLS/Host). Port 0
        // means "use the URL's port", which is what we want.
        //
        // A fresh client per attempt is intentional: deliveries target
        // arbitrary (potentially different) hosts, and mixing DNS
        // overrides on a shared client would risk cross-talk. Per-attempt
        // construction is a few microseconds — negligible next to the
        // retry backoff.
        let host = target
            .url
            .host_str()
            .ok_or(DeliveryErrorClass::NetworkError)?
            .to_string();
        let pinned = SocketAddr::new(resolved_ip, 0);

        let client = reqwest::Client::builder()
            .connect_timeout(self.config.connect_timeout)
            .read_timeout(self.config.read_timeout)
            .timeout(self.config.request_timeout)
            .redirect(reqwest::redirect::Policy::none())
            .resolve(&host, pinned)
            .build()
            .map_err(|_| DeliveryErrorClass::NetworkError)?;

        let mut req = client
            .post(target.url.clone())
            .header(
                "Content-Type",
                turul_a2a_types::wire::protocol::MEDIA_TYPE_A2A_JSON,
            )
            .header(
                "User-Agent",
                format!("turul-a2a/{}", env!("CARGO_PKG_VERSION")),
            )
            .header("X-Turul-Event-Sequence", target.event_sequence.to_string());
        // omit the `Authorization` header entirely when
        // the config has no authentication. Emitting an empty
        // `"{scheme} {creds}"` value — as the earlier implementation
        // did — can be rejected by hardened receivers that refuse
        // malformed auth headers, and it muddies the semantics of
        // "this config is unauthenticated".
        if !target.auth_scheme.is_empty() {
            req = req.header(
                "Authorization",
                format!(
                    "{} {}",
                    target.auth_scheme,
                    target.auth_credentials.expose()
                ),
            );
        }
        if let Some(tok) = &target.token {
            req = req.header("X-Turul-Push-Token", tok.expose());
        }

        let resp = req.body(payload.to_vec()).send().await;

        match resp {
            Ok(r) => Ok(r.status()),
            // TLS first: a handshake failure also reports `is_connect`.
            Err(e) if is_tls_failure(&e) => Err(DeliveryErrorClass::TlsRejected),
            Err(e) if e.is_timeout() => Err(DeliveryErrorClass::Timeout),
            Err(_) => Err(DeliveryErrorClass::NetworkError),
        }
    }

    fn backoff_for(&self, attempt: u32) -> Duration {
        let base = self.config.backoff_base.as_millis() as u64;
        let cap = self.config.backoff_cap.as_millis() as u64;
        // attempt=1 → base; attempt=2 → 2*base; attempt=N → 2^(N-1)*base capped.
        let raw = base.saturating_mul(1u64 << attempt.min(31).saturating_sub(1));
        let target = raw.min(cap);
        let jitter = self.config.backoff_jitter.max(0.0);
        let delta = (target as f64 * jitter as f64) as i64;
        let offset = if delta == 0 {
            0i64
        } else {
            rand::rng().random_range(-delta..=delta)
        };
        let final_ms = (target as i64).saturating_add(offset).max(0) as u64;
        Duration::from_millis(final_ms)
    }
}

/// Whether `err`, or any error in its source chain, is a TLS handshake
/// failure (certificate rejected, receiver not speaking TLS). The TLS
/// stream reports these as a `rustls::Error` wrapped in one or more
/// `io::Error`s. `io::Error::source` skips the error it wraps, so the
/// walk steps into each `io::Error`'s wrapped error explicitly.
fn is_tls_failure(err: &(dyn std::error::Error + 'static)) -> bool {
    let mut current = Some(err);
    while let Some(e) = current {
        if e.is::<rustls::Error>() {
            return true;
        }
        current = match e.downcast_ref::<std::io::Error>() {
            Some(io) => io
                .get_ref()
                .map(|inner| inner as &(dyn std::error::Error + 'static)),
            None => e.source(),
        };
    }
    false
}

enum ClaimFailure {
    AlreadyHeld,
    // String is retained for future log/trace plumbing; silence the
    // unused-field lint until the worker wires per-failure tracing.
    Other(#[allow(dead_code)] String),
}

/// What `deliver` returns; the dispatcher only logs it — the store
/// already records the definitive outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeliveryReport {
    Succeeded(u16),
    GaveUp(GaveUpReason),
    Abandoned(AbandonedReason),
    /// The claim was not held by this instance (lost race, or the
    /// row had already reached a terminal state by the time we
    /// checked). No POST was attempted by this call.
    ClaimLostOrFinal,
    /// A transient storage error meant we skipped this attempt
    /// without claiming. The dispatcher retries on the next tick.
    UnclaimedSkip,
    /// Storage became unreachable mid-delivery; the row might be in
    /// any state. Worker stops; sweep or next-tick reconciliation
    /// will pick up.
    TransientStoreError,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::InMemoryA2aStorage;

    fn worker_with_store(
        store: Arc<InMemoryA2aStorage>,
        cfg: PushDeliveryConfig,
    ) -> PushDeliveryWorker {
        PushDeliveryWorker::new(store, cfg, None, format!("worker-{}", uuid::Uuid::now_v7()))
            .expect("build")
    }

    fn target(url: &str) -> PushTarget {
        PushTarget {
            tenant: "t".into(),
            owner: "anonymous".into(),
            task_id: format!("task-{}", uuid::Uuid::now_v7()),
            event_sequence: 1,
            config_id: "cfg-A".into(),
            url: Url::parse(url).unwrap(),
            auth_scheme: "Bearer".into(),
            auth_credentials: Secret::new("cred".into()),
            token: None,
        }
    }

    #[test]
    fn backoff_doubles_until_cap() {
        let store = Arc::new(InMemoryA2aStorage::new());
        let cfg = PushDeliveryConfig {
            backoff_base: Duration::from_secs(1),
            backoff_cap: Duration::from_secs(8),
            backoff_jitter: 0.0,
            ..Default::default()
        };
        let w = worker_with_store(store, cfg);
        assert_eq!(w.backoff_for(1), Duration::from_secs(1));
        assert_eq!(w.backoff_for(2), Duration::from_secs(2));
        assert_eq!(w.backoff_for(3), Duration::from_secs(4));
        assert_eq!(w.backoff_for(4), Duration::from_secs(8));
        // Capped — does not grow further.
        assert_eq!(w.backoff_for(5), Duration::from_secs(8));
        assert_eq!(w.backoff_for(10), Duration::from_secs(8));
    }

    /// Rejects a payload that exceeds the configured max and
    /// records `GaveUp(PayloadTooLarge)` without POSTing.
    #[tokio::test]
    async fn payload_too_large_short_circuits_with_gaveup() {
        let store = Arc::new(InMemoryA2aStorage::new());
        let cfg = PushDeliveryConfig {
            max_payload_bytes: 10,
            ..Default::default()
        };
        let w = worker_with_store(store.clone(), cfg);
        let t = target("https://example.com/");
        let payload = vec![0u8; 1024];
        let report = w.deliver(&t, &payload).await;
        assert_eq!(
            report,
            DeliveryReport::GaveUp(GaveUpReason::PayloadTooLarge)
        );

        let failed = store
            .list_failed_deliveries(&t.tenant, SystemTime::UNIX_EPOCH, 10)
            .await
            .unwrap();
        assert_eq!(failed.len(), 1);
        assert!(matches!(
            failed[0].last_error_class,
            DeliveryErrorClass::PayloadTooLarge
        ));
    }

    /// Every push setting of the builders' runtime config reaches the
    /// worker's delivery config.
    #[test]
    fn runtime_config_maps_onto_delivery_config() {
        let runtime = crate::server::RuntimeConfig {
            push_max_attempts: 3,
            push_read_timeout: Duration::from_millis(250),
            push_config_cache_ttl: Duration::from_secs(9),
            push_failed_delivery_retention: Duration::from_secs(60),
            allow_insecure_push_urls: true,
            ..Default::default()
        };
        let cfg = PushDeliveryConfig::from_runtime_config(&runtime);
        assert_eq!(cfg.max_attempts, 3);
        assert_eq!(cfg.read_timeout, Duration::from_millis(250));
        assert_eq!(cfg.config_cache_ttl, Duration::from_secs(9));
        assert_eq!(cfg.failed_delivery_retention, Duration::from_secs(60));
        assert!(cfg.allow_insecure_urls);
    }

    /// The runtime config's push defaults are the delivery config's.
    #[test]
    fn runtime_config_push_defaults_are_delivery_defaults() {
        let from_runtime =
            PushDeliveryConfig::from_runtime_config(&crate::server::RuntimeConfig::default());
        assert_eq!(
            format!("{from_runtime:?}"),
            format!("{:?}", PushDeliveryConfig::default())
        );
    }

    #[test]
    fn certificate_rejection_is_a_tls_failure() {
        // The shape the TLS stream reports: the rustls error inside two
        // layers of `io::Error`.
        let cert = std::io::Error::other(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer),
        ));
        assert!(is_tls_failure(&cert));
        assert!(is_tls_failure(&rustls::Error::InvalidCertificate(
            rustls::CertificateError::Expired
        )));
        let refused = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
        assert!(!is_tls_failure(&refused));
    }

    /// A plain `http://` URL with insecure URLs disallowed is never
    /// POSTed: the delivery is abandoned as `NonHttpsUrlInProduction`
    /// and, being abandoned rather than failed, is not listed as a
    /// failed delivery. `webhook.invalid` cannot resolve, so a POST
    /// attempt would surface as a network-error retry instead.
    #[tokio::test]
    async fn non_https_url_in_production_is_abandoned_without_post() {
        let store = Arc::new(InMemoryA2aStorage::new());
        let cfg = PushDeliveryConfig {
            allow_insecure_urls: false,
            ..Default::default()
        };
        let w = worker_with_store(store.clone(), cfg);
        let t = target("http://webhook.invalid/");
        let report = w.deliver(&t, b"{}").await;
        assert_eq!(
            report,
            DeliveryReport::Abandoned(AbandonedReason::NonHttpsUrlInProduction)
        );
        let failed = store
            .list_failed_deliveries(&t.tenant, SystemTime::UNIX_EPOCH, 10)
            .await
            .unwrap();
        assert!(failed.is_empty(), "abandoned is not a failed delivery");
        // The row is terminal: the delivery cannot be claimed again.
        assert!(matches!(w.claim(&t).await, Err(ClaimFailure::AlreadyHeld)));
    }

    /// A2A v1.0.1 §3.1.10: "No further notifications will be sent to the
    /// configured webhook after deletion." The default re-reads the
    /// config before every attempt, so a deletion made anywhere is seen.
    #[test]
    fn default_config_cache_is_off() {
        assert_eq!(
            PushDeliveryConfig::default().config_cache_ttl,
            Duration::ZERO
        );
    }

    /// A read that started before an invalidation may have seen the
    /// config before it was deleted; its result must not be cached, or
    /// the deleted config would be trusted for a whole TTL.
    #[test]
    fn presence_read_before_invalidation_is_not_cached() {
        let cache = PushConfigCache::default();
        let t = target("https://example.com/hook");
        let ttl = Duration::from_secs(3600);

        let read_generation = cache.generation();
        cache.invalidate(&t.tenant, &t.task_id);
        cache.record_present(&t, ttl, read_generation);
        assert!(!cache.is_fresh(&t, ttl), "stale read was cached");

        let read_generation = cache.generation();
        cache.record_present(&t, ttl, read_generation);
        assert!(cache.is_fresh(&t, ttl), "current read is cached");
        cache.invalidate(&t.tenant, &t.task_id);
        assert!(!cache.is_fresh(&t, ttl), "invalidation drops the entry");
    }

    /// A retention meaning "keep" (`Duration::MAX`) is clamped rather
    /// than overflowing, and the result still fits the backends'
    /// microsecond `i64` columns.
    #[test]
    fn huge_failed_delivery_retention_is_clamped() {
        let cfg = PushDeliveryConfig {
            failed_delivery_retention: Duration::MAX,
            ..Default::default()
        };
        let w = worker_with_store(Arc::new(InMemoryA2aStorage::new()), cfg);
        let before = SystemTime::now();
        let DeliveryOutcome::GaveUp { retained_until, .. } = w.gave_up(
            GaveUpReason::MaxAttemptsExhausted,
            DeliveryErrorClass::Timeout,
            None,
        ) else {
            panic!("gave_up returns GaveUp");
        };
        assert!(retained_until >= before + MAX_FAILED_DELIVERY_RETENTION);
        let micros = retained_until
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_micros();
        assert!(micros <= i64::MAX as u128, "fits an i64 microsecond column");
    }
}