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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
//! A2aServer builder and runtime.
pub mod in_flight;
pub mod obs;
pub(crate) mod orphans;
pub mod spawn;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use crate::error::A2aError;
use crate::executor::AgentExecutor;
use crate::middleware::{A2aMiddleware, MiddlewareStack, SecurityContribution};
use crate::router::{AppState, build_router};
use crate::storage::{
A2aAtomicStore, A2aPushNotificationStorage, A2aTaskStorage, InMemoryA2aStorage,
};
use crate::streaming::TaskEventBroker;
// ---------------------------------------------------------------------------
// Runtime configuration
// ---------------------------------------------------------------------------
/// Runtime tuning knobs for advanced task lifecycle behaviors.
///
/// Groups: blocking-send two-deadline timeouts
/// (`blocking_task_timeout`, `timeout_abort_grace`); cancellation
/// handler grace / poll intervals and cross-instance cancel-marker
/// poll interval (`cancel_handler_*`,
/// `cross_instance_cancel_poll_interval`); push delivery tuning
/// (`push_*`, `allow_insecure_push_urls`).
///
/// Exposed publicly so tests and advanced consumers can construct
/// [`crate::router::AppState`] directly (e.g., router/transport-level
/// integration tests). The `#[non_exhaustive]` marker reserves the right
/// to add fields in patch releases; callers should use
/// [`RuntimeConfig::default()`] as the construction base and modify
/// specific fields rather than struct-literal construction.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RuntimeConfig {
pub blocking_task_timeout: Duration,
pub timeout_abort_grace: Duration,
pub cancel_handler_grace: Duration,
pub cancel_handler_poll_interval: Duration,
pub cross_instance_cancel_poll_interval: Duration,
pub push_max_attempts: usize,
pub push_backoff_base: Duration,
pub push_backoff_cap: Duration,
pub push_backoff_jitter: f32,
pub push_request_timeout: Duration,
pub push_connect_timeout: Duration,
pub push_read_timeout: Duration,
pub push_claim_expiry: Duration,
pub push_config_cache_ttl: Duration,
pub push_failed_delivery_retention: Duration,
pub push_max_payload_bytes: usize,
pub allow_insecure_push_urls: bool,
/// Interval between reclaim-and-redispatch sweeps.
/// The server background task enumerates expired-but-non-terminal
/// claim rows via
/// [`crate::push::A2aPushDeliveryStore::list_reclaimable_claims`]
/// and drives each through
/// [`crate::push::PushDispatcher::redispatch_one`]. Shorter
/// cadence recovers stuck rows faster but increases steady-state
/// load; default 60s balances recovery latency against scan cost.
pub push_reclaim_sweep_interval: Duration,
/// Max reclaimable rows to pull per sweep tick. The sweeper
/// paginates: each tick fetches up to this many rows, redispatches
/// them, and returns. The next tick picks up any remainder.
pub push_reclaim_sweep_batch: usize,
/// Interval for the opt-in retention-maintenance loop, or `None` to
/// disable it. When `Some`, `A2aServer::run` spawns a background
/// task that calls `cleanup_expired` on the event store on this
/// cadence to reap expired events and tasks. `None` (default) means
/// no maintenance loop runs — the server never deletes on a timer.
///
/// Serverless deployments (AWS Lambda) leave this `None`: there is
/// no persistent process to host the loop. They invoke
/// `cleanup_expired` from a discrete scheduled handler instead.
pub maintenance_interval: Option<Duration>,
/// Whether this runtime can honour
/// `SendMessageConfiguration.return_immediately = true`.
///
/// `true` (default) — the runtime keeps the process alive after
/// the HTTP response returns so `tokio::spawn`'d executors run to
/// completion. Every long-lived host (`A2aServer::run`, ECS,
/// Fargate, AppRunner, Kubernetes, bare VM) sets this.
///
/// `false` — the runtime cannot guarantee post-return execution;
/// `core_send_message` rejects `return_immediately = true` with
/// `A2aError::UnsupportedOperation` before any storage write. The
/// AWS Lambda adapter sets this.
///
/// # Override policy
///
/// This field is an escape hatch for tests and advanced internal
/// consumers that construct [`crate::router::AppState`] directly.
/// **It is not an adopter surface.** Do not set it to `true` on a
/// runtime that cannot actually guarantee post-return execution —
/// the guard exists to prevent silent executor orphaning.
///
/// Adopters who need fire-and-forget-style work on Lambda today
/// should invoke their durable mechanism (Step Functions, SQS,
/// EventBridge, etc.) from inside their `AgentExecutor::execute`
/// body. The executor returns synchronously once the workflow is
/// accepted; the A2A task is Completed for "workflow accepted /
/// started", not "workflow finished". If the A2A task is meant to
/// track the full workflow lifecycle, the workflow itself must
/// later call back into turul-a2a storage to update task state.
///
/// A future capability-taking `LambdaA2aServerBuilder` method
/// (shape: `with_durable_return_immediately(handler)`) will accept
/// a durable continuation mechanism as an argument and flip this
/// flag as a side effect. Even then, the flag SHOULD NOT be flipped
/// directly — reach for the builder method.
pub supports_return_immediately: bool,
}
impl Default for RuntimeConfig {
/// Push delivery defaults are those of
/// [`crate::push::delivery::PushDeliveryConfig::default`].
fn default() -> Self {
let push = crate::push::delivery::PushDeliveryConfig::default();
Self {
blocking_task_timeout: Duration::from_secs(30),
timeout_abort_grace: Duration::from_secs(5),
cancel_handler_grace: Duration::from_secs(5),
cancel_handler_poll_interval: Duration::from_millis(100),
cross_instance_cancel_poll_interval: Duration::from_secs(1),
push_max_attempts: push.max_attempts as usize,
push_backoff_base: push.backoff_base,
push_backoff_cap: push.backoff_cap,
push_backoff_jitter: push.backoff_jitter,
push_request_timeout: push.request_timeout,
push_connect_timeout: push.connect_timeout,
push_read_timeout: push.read_timeout,
push_claim_expiry: push.claim_expiry,
push_config_cache_ttl: push.config_cache_ttl,
push_failed_delivery_retention: push.failed_delivery_retention,
push_max_payload_bytes: push.max_payload_bytes,
allow_insecure_push_urls: push.allow_insecure_urls,
push_reclaim_sweep_interval: Duration::from_secs(60),
push_reclaim_sweep_batch: 64,
maintenance_interval: None,
supports_return_immediately: true,
}
}
}
/// Builder for configuring and running an A2A server.
pub struct A2aServerBuilder {
executor: Option<Arc<dyn AgentExecutor>>,
task_storage: Option<Arc<dyn A2aTaskStorage>>,
push_storage: Option<Arc<dyn A2aPushNotificationStorage>>,
event_store: Option<Arc<dyn crate::storage::A2aEventStore>>,
atomic_store: Option<Arc<dyn A2aAtomicStore>>,
cancellation_supervisor: Option<Arc<dyn crate::storage::A2aCancellationSupervisor>>,
push_delivery_store: Option<Arc<dyn crate::push::A2aPushDeliveryStore>>,
bind_addr: SocketAddr,
middleware: Vec<Arc<dyn A2aMiddleware>>,
runtime_config: RuntimeConfig,
outbound_url_validator: Option<crate::push::ssrf::OutboundUrlValidator>,
fail_orphans_on_start: bool,
}
impl A2aServerBuilder {
pub fn new() -> Self {
Self {
executor: None,
task_storage: None,
push_storage: None,
event_store: None,
atomic_store: None,
cancellation_supervisor: None,
push_delivery_store: None,
bind_addr: ([0, 0, 0, 0], 3000).into(),
middleware: vec![],
runtime_config: RuntimeConfig::default(),
outbound_url_validator: None,
fail_orphans_on_start: false,
}
}
// -----------------------------------------------------------------
// Runtime-config setters.
//
// Each setter updates the internal [`RuntimeConfig`] and returns
// `self`. Defaults are in [`RuntimeConfig::default`].
// -----------------------------------------------------------------
/// Soft timeout for blocking `SendMessage` requests. On expiry the
/// framework trips the executor's cancellation token and waits up to
/// [`Self::timeout_abort_grace`] for cooperative exit.
pub fn blocking_task_timeout(mut self, d: Duration) -> Self {
self.runtime_config.blocking_task_timeout = d;
self
}
/// Grace window between soft cancellation and hard `JoinHandle::abort()`.
///
pub fn timeout_abort_grace(mut self, d: Duration) -> Self {
self.runtime_config.timeout_abort_grace = d;
self
}
/// How long the `CancelTask` handler waits for cancellation to resolve
/// before force-committing CANCELED itself. It is also the abort
/// deadline: an executor that has not committed its own terminal by
/// then is aborted.
pub fn cancel_handler_grace(mut self, d: Duration) -> Self {
self.runtime_config.cancel_handler_grace = d;
self
}
/// Poll interval used inside the `CancelTask` handler's grace window to
/// re-read task state from storage.
pub fn cancel_handler_poll_interval(mut self, d: Duration) -> Self {
self.runtime_config.cancel_handler_poll_interval = d;
self
}
/// How often the in-flight supervisor batch-polls the cancel marker
/// across in-flight tasks for cross-instance cancel propagation.
///
pub fn cross_instance_cancel_poll_interval(mut self, d: Duration) -> Self {
self.runtime_config.cross_instance_cancel_poll_interval = d;
self
}
/// Maximum retry attempts (including first) per push delivery.
///
pub fn push_max_attempts(mut self, n: usize) -> Self {
self.runtime_config.push_max_attempts = n;
self
}
/// Base delay before the second push attempt; doubles up to
/// [`Self::push_backoff_cap`].
pub fn push_backoff_base(mut self, d: Duration) -> Self {
self.runtime_config.push_backoff_base = d;
self
}
/// Maximum single-wait in the push retry schedule.
pub fn push_backoff_cap(mut self, d: Duration) -> Self {
self.runtime_config.push_backoff_cap = d;
self
}
/// Jitter fraction applied to push retry waits.
pub fn push_backoff_jitter(mut self, j: f32) -> Self {
self.runtime_config.push_backoff_jitter = j;
self
}
/// Total per-request timeout for a push POST: connect, send and
/// the full response.
pub fn push_request_timeout(mut self, d: Duration) -> Self {
self.runtime_config.push_request_timeout = d;
self
}
/// Connect-phase timeout for a push POST.
pub fn push_connect_timeout(mut self, d: Duration) -> Self {
self.runtime_config.push_connect_timeout = d;
self
}
/// Longest the push POST waits for the receiver's response with
/// nothing arriving — the status line and headers, then each read
/// of the body. A receiver that accepts the connection and stalls
/// fails the attempt with a `Timeout` error class after this long,
/// independent of [`Self::push_connect_timeout`]; the attempt as a
/// whole stays bounded by [`Self::push_request_timeout`].
pub fn push_read_timeout(mut self, d: Duration) -> Self {
self.runtime_config.push_read_timeout = d;
self
}
/// Claim expiry for the push delivery claim table. Must exceed the
/// retry horizon implied by `push_max_attempts` + `push_backoff_cap`;
/// the push-delivery builder validates this on `build()`.
pub fn push_claim_expiry(mut self, d: Duration) -> Self {
self.runtime_config.push_claim_expiry = d;
self
}
/// How long the delivery worker trusts that a push config still
/// exists without re-reading storage. Before each POST attempt the
/// worker checks that the config and task still exist and abandons
/// the delivery if either is gone; a config found present is
/// trusted for this long. Default `Duration::ZERO`: re-read before
/// every attempt, so a deletion made anywhere stops delivery at the
/// next attempt.
///
/// With a non-zero TTL, deleting a push config through this server
/// drops the cached entries for its task at once, but a deletion
/// made through another instance (or another Lambda function) can
/// be followed by POSTs for up to the TTL, which A2A v1.0.1 §3.1.10
/// ("No further notifications will be sent to the configured
/// webhook after deletion") does not allow. Only set it for a
/// single-instance deployment.
pub fn push_config_cache_ttl(mut self, d: Duration) -> Self {
self.runtime_config.push_config_cache_ttl = d;
self
}
/// The minimum time a failed push delivery stays listed by
/// `list_failed_deliveries` after it gives up. Default 7 days;
/// values above
/// [`MAX_FAILED_DELIVERY_RETENTION`](crate::push::delivery::MAX_FAILED_DELIVERY_RETENTION)
/// (1000 years) are
/// clamped to it.
///
/// On the SQL and in-memory backends the record is removed only
/// when the storage cleanup entry point (`cleanup_expired`, run by
/// [`Self::maintenance`] or a scheduled handler) runs after the
/// retention has passed; without it the record is kept. On DynamoDB
/// `cleanup_expired` does not remove it: the record's `ttl`
/// attribute is set to the end of the retention and the table's TTL
/// expires it.
pub fn push_failed_delivery_retention(mut self, d: Duration) -> Self {
self.runtime_config.push_failed_delivery_retention = d;
self
}
/// Maximum serialized Task body size for a push POST.
pub fn push_max_payload_bytes(mut self, bytes: usize) -> Self {
self.runtime_config.push_max_payload_bytes = bytes;
self
}
/// Dev-only escape hatch: permit `http://` webhook URLs AND bypass the
/// private-IP blocklist. Required for localhost wiremock testing.
/// Default false.
pub fn allow_insecure_push_urls(mut self, allow: bool) -> Self {
self.runtime_config.allow_insecure_push_urls = allow;
self
}
/// Operator allowlist for push webhook URLs.
///
/// Called with each webhook URL on every delivery attempt, before
/// DNS resolution. Returning `Err` refuses the delivery: nothing is
/// resolved or POSTed, and the delivery is recorded as a failed
/// delivery with error class `SSRFBlocked`. The reason string is
/// not persisted. Runs in addition to the built-in scheme and
/// private-address checks, not instead of them. Takes effect only
/// when push delivery is wired (`push_delivery_store`).
pub fn outbound_url_validator(
mut self,
validator: crate::push::ssrf::OutboundUrlValidator,
) -> Self {
self.outbound_url_validator = Some(validator);
self
}
/// Interval between reclaim-and-redispatch sweeps. Default 60s.
pub fn push_reclaim_sweep_interval(mut self, d: Duration) -> Self {
self.runtime_config.push_reclaim_sweep_interval = d;
self
}
/// Max rows pulled per reclaim sweep tick. Default 64.
pub fn push_reclaim_sweep_batch(mut self, n: usize) -> Self {
self.runtime_config.push_reclaim_sweep_batch = n;
self
}
/// Enable the opt-in retention-maintenance loop.
///
/// `A2aServer::run` spawns a background task that calls
/// `cleanup_expired` on the storage backend every `interval`. Each
/// call also removes failed push-delivery records past
/// [`Self::push_failed_delivery_retention`].
/// Disabled by default — without this call the server never deletes
/// on a timer.
///
/// The TTL window is configured on the storage backend itself (its
/// retention config); this method only sets the cadence at which the
/// backend's reaper is invoked. A backend with no retention configured
/// reaps nothing even when this loop runs.
///
/// Expiry is age-based and state-independent: a non-zero task TTL
/// can reap long-running live tasks. Choose `interval` and TTLs that
/// suit the deployment's task lifetimes.
pub fn maintenance(mut self, interval: Duration) -> Self {
self.runtime_config.maintenance_interval = Some(interval);
self
}
pub fn executor(mut self, executor: impl AgentExecutor + 'static) -> Self {
self.executor = Some(Arc::new(executor));
self
}
/// Set all storage from a single backend instance.
///
/// This is the **preferred** method — a single struct implementing all storage
/// traits guarantees the same-backend requirement. Works with any
/// backend: `InMemoryA2aStorage`, `SqliteA2aStorage`, `PostgresA2aStorage`,
/// `DynamoDbA2aStorage`, etc.
///
/// errata: `.storage()` wires storage traits only. It does
/// **not** auto-register the storage as a push-delivery store, even if the
/// backend happens to implement [`crate::push::A2aPushDeliveryStore`]. To
/// opt in to push delivery, call [`Self::push_delivery_store`] explicitly
/// and call `with_push_dispatch_enabled(true)` on the storage instance
/// before passing it here. Non-push deployments need neither.
pub fn storage<S>(mut self, storage: S) -> Self
where
S: A2aTaskStorage
+ A2aPushNotificationStorage
+ crate::storage::A2aEventStore
+ A2aAtomicStore
+ crate::storage::A2aCancellationSupervisor
+ Clone
+ 'static,
{
self.task_storage = Some(Arc::new(storage.clone()));
self.push_storage = Some(Arc::new(storage.clone()));
self.event_store = Some(Arc::new(storage.clone()));
self.atomic_store = Some(Arc::new(storage.clone()));
self.cancellation_supervisor = Some(Arc::new(storage));
self
}
/// Set the cancellation supervisor individually. Prefer `.storage()`
/// so a single backend implements every storage trait. Consumed by
/// the `:cancel` handler for cross-instance marker reads.
pub fn cancellation_supervisor(
mut self,
supervisor: impl crate::storage::A2aCancellationSupervisor + 'static,
) -> Self {
self.cancellation_supervisor = Some(Arc::new(supervisor));
self
}
/// Set task storage individually. Prefer `.storage()` so a single
/// backend implements every storage trait.
pub fn task_storage(mut self, storage: impl A2aTaskStorage + 'static) -> Self {
self.task_storage = Some(Arc::new(storage));
self
}
/// Set push notification storage individually. Prefer `.storage()`
/// so a single backend implements every storage trait.
pub fn push_storage(mut self, storage: impl A2aPushNotificationStorage + 'static) -> Self {
self.push_storage = Some(Arc::new(storage));
self
}
/// Set event store individually. Prefer `.storage()` so a single
/// backend implements every storage trait.
pub fn event_store(mut self, store: impl crate::storage::A2aEventStore + 'static) -> Self {
self.event_store = Some(Arc::new(store));
self
}
/// Set atomic store individually. Prefer `.storage()` so a single
/// backend implements every storage trait.
pub fn atomic_store(mut self, store: impl A2aAtomicStore + 'static) -> Self {
self.atomic_store = Some(Arc::new(store));
self
}
/// Set the push delivery claim store individually.
///
/// Required when push-notification delivery is enabled in the
/// deployment. `.storage()` wires this automatically from a unified
/// backend; use this setter only for mixed-backend tests or when
/// running against an external push-coordination service. The
/// builder rejects split configurations where the atomic store and
/// the push delivery store come from different concrete instances.
pub fn push_delivery_store(
mut self,
store: impl crate::push::A2aPushDeliveryStore + 'static,
) -> Self {
self.push_delivery_store = Some(Arc::new(store));
self
}
pub fn bind(mut self, addr: impl Into<SocketAddr>) -> Self {
self.bind_addr = addr.into();
self
}
/// Fail tasks left `SUBMITTED` or `WORKING` by a previous process
/// before the server serves: [`A2aServer::bind`] (and so `run`)
/// reconciles them first, and `into_router`, `into_routers` and
/// `into_tonic_router` panic unless
/// [`A2aServer::fail_orphaned_tasks`] has completed. Off by default.
///
/// Enable only when exactly one server instance uses the storage;
/// see [`A2aServer::fail_orphaned_tasks`].
pub fn fail_orphaned_tasks_on_start(mut self) -> Self {
self.fail_orphans_on_start = true;
self
}
/// Add auth middleware. Multiple calls stack (AND semantics).
/// Use `AnyOfMiddleware` for OR semantics.
pub fn middleware(mut self, mw: Arc<dyn A2aMiddleware>) -> Self {
self.middleware.push(mw);
self
}
pub fn build(self) -> Result<A2aServer, A2aError> {
let executor = self
.executor
.ok_or(A2aError::Internal("executor is required".into()))?;
let default_storage = InMemoryA2aStorage::new();
let task_storage = self
.task_storage
.unwrap_or_else(|| Arc::new(default_storage.clone()));
let push_storage = self
.push_storage
.unwrap_or_else(|| Arc::new(default_storage.clone()));
let event_store: Arc<dyn crate::storage::A2aEventStore> = self
.event_store
.unwrap_or_else(|| Arc::new(default_storage.clone()));
let atomic_store: Arc<dyn A2aAtomicStore> = self
.atomic_store
.unwrap_or_else(|| Arc::new(default_storage.clone()));
let cancellation_supervisor: Arc<dyn crate::storage::A2aCancellationSupervisor> = self
.cancellation_supervisor
.unwrap_or_else(|| Arc::new(default_storage.clone()));
let push_delivery_store: Option<Arc<dyn crate::push::A2aPushDeliveryStore>> =
self.push_delivery_store;
// Same-backend enforcement: all storage traits must share the same backend.
let task_backend = task_storage.backend_name();
let push_backend = push_storage.backend_name();
let event_backend = event_store.backend_name();
let atomic_backend = atomic_store.backend_name();
let supervisor_backend = cancellation_supervisor.backend_name();
if task_backend != push_backend
|| task_backend != event_backend
|| task_backend != atomic_backend
|| task_backend != supervisor_backend
{
return Err(A2aError::Internal(format!(
"Storage backend mismatch: task={task_backend}, push={push_backend}, \
event={event_backend}, atomic={atomic_backend}, \
cancellation_supervisor={supervisor_backend}. \
All storage traits must share one backend so atomic commits span them."
)));
}
// Push-dispatch consistency: the atomic store's
// opt-in flag and the presence of `push_delivery_store` MUST
// agree. Both-true = push fully wired; both-false = non-push
// deployment. The mixed cases are build errors — one orphans a
// load-bearing marker table without a consumer, the other
// wires a dispatcher that will never receive durable markers.
match (
push_delivery_store.is_some(),
atomic_store.push_dispatch_enabled(),
) {
(true, true) | (false, false) => {}
(true, false) => {
return Err(A2aError::Internal(
"push_delivery_store wired but atomic_store.push_dispatch_enabled() \
is false. Call .with_push_dispatch_enabled(true) on the backend \
storage before passing it to .storage()."
.into(),
));
}
(false, true) => {
return Err(A2aError::Internal(
"atomic_store.push_dispatch_enabled() is true but no \
push_delivery_store is wired. Pending-dispatch markers would be \
written with no consumer, imposing load-bearing infra for no \
benefit. If you need to populate markers for an external \
consumer, open an issue for a distinctly-named opt-in — for now, \
this configuration is rejected."
.into(),
));
}
}
let push_dispatcher: Option<Arc<crate::push::PushDispatcher>> =
if let Some(push_delivery) = push_delivery_store.as_ref() {
let push_delivery_backend = push_delivery.backend_name();
if task_backend != push_delivery_backend {
return Err(A2aError::Internal(format!(
"Storage backend mismatch: task={task_backend}, \
push_delivery={push_delivery_backend}. \
All storage traits must share one backend so atomic commits span them."
)));
}
// claim expiry must exceed the worst-case
// retry horizon so a claim held by a healthy worker is
// never mis-classified as stale mid-retry. Upper bound
// for the horizon is `max_attempts * backoff_cap`
// (every attempt waits the cap), which is conservative
// and independent of jitter.
let retry_horizon = self
.runtime_config
.push_backoff_cap
.saturating_mul(self.runtime_config.push_max_attempts as u32);
if self.runtime_config.push_claim_expiry <= retry_horizon {
return Err(A2aError::Internal(format!(
"push_claim_expiry ({:?}) must be greater than retry horizon \
(push_max_attempts={} * push_backoff_cap={:?} = {:?}). \
Raise push_claim_expiry or lower push_max_attempts/push_backoff_cap.",
self.runtime_config.push_claim_expiry,
self.runtime_config.push_max_attempts,
self.runtime_config.push_backoff_cap,
retry_horizon
)));
}
// Build the push-delivery worker + dispatcher now that
// we've validated the horizon. Runtime config carries
// the full worker tuning; the dispatcher closes the
// commit-to-POST loop so every terminal status commit
// fans out to registered push configs.
let delivery_cfg = crate::push::delivery::PushDeliveryConfig::from_runtime_config(
&self.runtime_config,
);
let instance_id = format!("a2a-server-{}", uuid::Uuid::now_v7());
let worker = crate::push::delivery::PushDeliveryWorker::new(
push_delivery.clone(),
delivery_cfg,
self.outbound_url_validator.clone(),
instance_id,
)
.map_err(|e| A2aError::Internal(format!("push worker build failed: {e}")))?;
Some(Arc::new(crate::push::PushDispatcher::new(
Arc::new(worker),
push_storage.clone(),
task_storage.clone(),
)))
} else {
None
};
// Collect and merge security contributions
let contributions: Vec<SecurityContribution> = self
.middleware
.iter()
.map(|m| m.security_contribution())
.collect();
let merged = merge_stacked_contributions(&contributions)?;
// validate scheme references in every
// build-materializable advertised card surface. The merge
// applied here mirrors `SecurityAugmentedExecutor::agent_card()`
// so validation sees the exact surface clients will receive.
let public_materialized = apply_security_merge(executor.agent_card(), &merged);
validate_card_security_references(&public_materialized, "agent_card")?;
if let Some(extended_raw) = executor.extended_agent_card(None) {
let extended_materialized = apply_security_merge(extended_raw, &merged);
validate_card_security_references(&extended_materialized, "extended_agent_card")?;
}
Ok(A2aServer {
state: AppState {
executor,
task_storage,
push_storage,
event_store,
atomic_store,
event_broker: TaskEventBroker::new(),
middleware_stack: Arc::new(MiddlewareStack::new(self.middleware)),
runtime_config: self.runtime_config,
in_flight: Arc::new(crate::server::in_flight::InFlightRegistry::new()),
cancellation_supervisor,
push_delivery_store,
push_dispatcher,
// long-lived binary server never enqueues;
// `tokio::spawn` is durable in this runtime.
durable_executor_queue: None,
},
merged_security: merged,
bind_addr: self.bind_addr,
fail_orphans_on_start: self.fail_orphans_on_start,
orphans_failed: false,
})
}
}
impl Default for A2aServerBuilder {
fn default() -> Self {
Self::new()
}
}
/// Merge stacked contributions (AND semantics).
///
/// Schemes: union with collision detection (identical = dedup, different = error).
/// Requirements: Cartesian product (AND).
fn merge_stacked_contributions(
contributions: &[SecurityContribution],
) -> Result<SecurityContribution, A2aError> {
let mut merged = SecurityContribution::new();
if contributions.is_empty() {
return Ok(merged);
}
// 1. Collect schemes with collision detection
let mut seen_schemes: std::collections::HashMap<String, turul_a2a_proto::SecurityScheme> =
std::collections::HashMap::new();
for contrib in contributions {
for (name, scheme) in &contrib.schemes {
if let Some(existing) = seen_schemes.get(name) {
// Check semantic equality
if !schemes_equivalent(existing, scheme) {
return Err(A2aError::Internal(format!(
"Security scheme collision: '{}' has conflicting definitions",
name
)));
}
// Identical — skip (dedup)
} else {
seen_schemes.insert(name.clone(), scheme.clone());
merged.schemes.push((name.clone(), scheme.clone()));
}
}
}
// 2. Compute requirements via Cartesian product (AND)
let requirement_sets: Vec<&[turul_a2a_proto::SecurityRequirement]> = contributions
.iter()
.filter(|c| !c.requirements.is_empty())
.map(|c| c.requirements.as_slice())
.collect();
if requirement_sets.is_empty() {
return Ok(merged);
}
let mut combined: Vec<turul_a2a_proto::SecurityRequirement> = requirement_sets[0].to_vec();
for alternatives in &requirement_sets[1..] {
let mut new_combined = Vec::new();
for existing in &combined {
for alt in *alternatives {
let mut merged_schemes = existing.schemes.clone();
for (name, scopes) in &alt.schemes {
merged_schemes
.entry(name.clone())
.and_modify(|existing_scopes| {
// Union scopes, dedup + sort
for s in &scopes.list {
if !existing_scopes.list.contains(s) {
existing_scopes.list.push(s.clone());
}
}
existing_scopes.list.sort();
existing_scopes.list.dedup();
})
.or_insert_with(|| scopes.clone());
}
new_combined.push(turul_a2a_proto::SecurityRequirement {
schemes: merged_schemes,
});
}
}
combined = new_combined;
}
merged.requirements = combined;
Ok(merged)
}
/// Apply a `SecurityContribution` to a raw `AgentCard`, producing the
/// card that clients actually see. Mirrors the per-request merge in
/// `SecurityAugmentedExecutor::agent_card()` so build-time validation
/// and runtime serving agree on the final surface.
fn apply_security_merge(
mut card: turul_a2a_proto::AgentCard,
security: &SecurityContribution,
) -> turul_a2a_proto::AgentCard {
for (name, scheme) in &security.schemes {
card.security_schemes
.entry(name.clone())
.or_insert_with(|| scheme.clone());
}
for req in &security.requirements {
card.security_requirements.push(req.clone());
}
card
}
/// every scheme name referenced by a `SecurityRequirement`
/// on the card MUST appear in `card.security_schemes`. Runs post-merge
/// against the final advertised card (public or extended).
///
/// `surface` is the human-readable surface label (`agent_card` or
/// `extended_agent_card`) — included verbatim in the error so the
/// adopter can tell which card failed.
fn validate_card_security_references(
card: &turul_a2a_proto::AgentCard,
surface: &str,
) -> Result<(), A2aError> {
for req in &card.security_requirements {
for scheme_name in req.schemes.keys() {
if !card.security_schemes.contains_key(scheme_name) {
return Err(A2aError::InvalidRequest {
message: format!(
"{surface}: agent-level security requirement references \
undeclared scheme '{scheme_name}'"
),
});
}
}
}
for skill in &card.skills {
for req in &skill.security_requirements {
for scheme_name in req.schemes.keys() {
if !card.security_schemes.contains_key(scheme_name) {
return Err(A2aError::InvalidRequest {
message: format!(
"{surface}: skill '{skill_id}' references \
undeclared security scheme '{scheme_name}'",
skill_id = skill.id
),
});
}
}
}
}
Ok(())
}
/// Semantic equality for SecurityScheme.
///
/// Uses structural PartialEq on proto types. This is correct for:
/// - ApiKeySecurityScheme (no maps)
/// - HttpAuthSecurityScheme (no maps)
/// - MutualTlsSecurityScheme (no maps)
///
/// Limitation: For OAuth2SecurityScheme and OpenIdConnectSecurityScheme,
/// scope maps (HashMap) have non-deterministic iteration order. PartialEq
/// on HashMap compares by content (not order), so this is correct for
/// HashMap but would need explicit normalization if proto ever uses
/// BTreeMap or sorted structures. Sufficient for the scheme types
/// this workspace supports (API Key + HTTP Bearer); revisit if new
/// scheme types introduce ordering-sensitive fields.
fn schemes_equivalent(
a: &turul_a2a_proto::SecurityScheme,
b: &turul_a2a_proto::SecurityScheme,
) -> bool {
a == b
}
/// A configured A2A server ready to run.
pub struct A2aServer {
state: AppState,
merged_security: SecurityContribution,
bind_addr: SocketAddr,
fail_orphans_on_start: bool,
orphans_failed: bool,
}
impl A2aServer {
pub fn builder() -> A2aServerBuilder {
A2aServerBuilder::new()
}
/// Commit `FAILED` (with a reason message) for every task left
/// `SUBMITTED` or `WORKING` in storage, across all tenants and
/// owners, and return how many were failed. `INPUT_REQUIRED`,
/// `AUTH_REQUIRED` and terminal tasks are untouched. Calling it again
/// returns 0.
///
/// Operator contract: enable this only when exactly one server
/// instance uses the storage. The framework records no per-task
/// executor owner, so on a shared store it would fail tasks that a
/// live peer is still running. That includes the overlap of a rolling
/// or surge deploy, where the new instance starts while the old one
/// still runs executors (use a stop-first rollout), and any other
/// live writer of the same store, such as a Lambda handler.
///
/// Serving consumes the server, so this runs before any request is
/// handled. It does not restart work: a client that wants the work
/// redone sends a new message.
pub async fn fail_orphaned_tasks(&mut self) -> Result<usize, A2aError> {
let failed = crate::server::orphans::fail_orphaned_tasks(&self.state).await?;
self.orphans_failed = true;
Ok(failed)
}
fn assert_orphans_reconciled(&self) {
if self.fail_orphans_on_start && !self.orphans_failed {
panic!(
"fail_orphaned_tasks_on_start is set but orphaned tasks were not reconciled: \
await server.fail_orphaned_tasks() before into_router, into_routers or \
into_tonic_router"
);
}
}
/// Build the axum router — useful for testing.
/// Augments the AgentCard with merged security contributions.
///
/// # Panics
///
/// Panics if the builder set `fail_orphaned_tasks_on_start` and
/// [`A2aServer::fail_orphaned_tasks`] has not completed on this server.
pub fn into_router(self) -> axum::Router {
let (state, had_security) = self.into_augmented_state();
if !had_security {
return build_router(state);
}
build_router(state)
}
/// Build the tonic gRPC router with the Tower auth stack already
/// layered.
///
/// The returned `tonic::transport::server::Router` always applies
/// the same [`MiddlewareStack`] as the HTTP path. A raw
/// unauthenticated service accessor is
/// deliberately not exposed — returning the inner service would
/// permit adopters to compose it into a custom tonic server
/// without the auth layer and silently bypass authentication.
///
/// # Panics
///
/// Panics if the builder set `fail_orphaned_tasks_on_start` and
/// [`A2aServer::fail_orphaned_tasks`] has not completed on this server.
#[cfg(feature = "grpc")]
pub fn into_tonic_router(self) -> crate::grpc::LayeredGrpcRouter {
let (state, _) = self.into_augmented_state();
let middleware_stack = state.middleware_stack.clone();
crate::grpc::make_grpc_router(state, middleware_stack)
}
/// Build the HTTP router and the tonic gRPC router over one shared
/// server state, for serving both transports from one process.
///
/// Both routers share storage, the event broker and the in-flight
/// executor registry, so a turn started on one transport is visible
/// to the other (a follow-up sent over gRPC while an HTTP-started
/// executor is still running is refused). Calling `into_router` and
/// `into_tonic_router` on two separately built servers would give
/// each transport its own registry and broker.
///
/// # Panics
///
/// Panics if the builder set `fail_orphaned_tasks_on_start` and
/// [`A2aServer::fail_orphaned_tasks`] has not completed on this server.
#[cfg(feature = "grpc")]
pub fn into_routers(self) -> (axum::Router, crate::grpc::LayeredGrpcRouter) {
let (state, _) = self.into_augmented_state();
let middleware_stack = state.middleware_stack.clone();
let http = build_router(state.clone());
let grpc = crate::grpc::make_grpc_router(state, middleware_stack);
(http, grpc)
}
/// Produce the `AppState` that `into_router` would mount, plus a flag
/// indicating whether security augmentation was applied. Exposed to
/// tests so they can assert post-augmentation invariants (e.g., that
/// `push_delivery_store` survives the auth rebuild) without going
/// through an HTTP round-trip.
pub(crate) fn into_augmented_state(self) -> (AppState, bool) {
self.assert_orphans_reconciled();
if self.merged_security.is_empty() {
return (self.state, false);
}
let wrapped = SecurityAugmentedExecutor {
inner: self.state.executor.clone(),
security: self.merged_security,
};
let augmented = AppState {
executor: Arc::new(wrapped),
task_storage: self.state.task_storage,
push_storage: self.state.push_storage,
event_store: self.state.event_store,
atomic_store: self.state.atomic_store,
event_broker: self.state.event_broker,
middleware_stack: self.state.middleware_stack,
runtime_config: self.state.runtime_config,
in_flight: self.state.in_flight,
cancellation_supervisor: self.state.cancellation_supervisor,
// Preserve both the push claim store and the dispatcher
// through security augmentation. Dropping either would
// silently disable push delivery for every auth-gated
// deployment.
push_delivery_store: self.state.push_delivery_store,
push_dispatcher: self.state.push_dispatcher,
durable_executor_queue: self.state.durable_executor_queue,
};
(augmented, true)
}
/// Bind the configured address without serving yet.
///
/// The returned [`BoundA2aServer`] holds the listening socket, so
/// [`BoundA2aServer::local_addr`] reports the address actually bound —
/// including the OS-assigned port when the builder was given port 0 —
/// before any request is served. Connections that arrive between
/// `bind` and [`BoundA2aServer::run`] wait in the listen backlog.
///
/// With `fail_orphaned_tasks_on_start` set, orphaned tasks are failed
/// before the socket is bound and an error aborts startup.
pub async fn bind(mut self) -> Result<BoundA2aServer, A2aError> {
if self.fail_orphans_on_start && !self.orphans_failed {
self.fail_orphaned_tasks().await?;
}
let listener = tokio::net::TcpListener::bind(self.bind_addr)
.await
.map_err(|e| A2aError::Internal(format!("Failed to bind: {e}")))?;
let local_addr = listener
.local_addr()
.map_err(|e| A2aError::Internal(format!("Failed to read bound address: {e}")))?;
tracing::info!("A2A server listening on {}", local_addr);
Ok(BoundA2aServer {
server: self,
listener,
local_addr,
})
}
/// Bind the configured address and serve until the server exits.
pub async fn run(self) -> Result<(), A2aError> {
self.bind().await?.run().await
}
/// Serve on an already-bound listener until the server exits.
async fn serve(self, listener: tokio::net::TcpListener) -> Result<(), A2aError> {
// Capture substrate refs for the cross-instance cancel poller
// before `into_router` consumes `self`. The poller uses the same
// Arcs for `in_flight` and `cancellation_supervisor` as the
// router's AppState, so a marker write from any instance is
// observed here within one `cross_instance_cancel_poll_interval`.
let poller_registry = std::sync::Arc::clone(&self.state.in_flight);
let poller_supervisor = std::sync::Arc::clone(&self.state.cancellation_supervisor);
let poller_interval = self
.state
.runtime_config
.cross_instance_cancel_poll_interval;
let poller_abort_grace = self.state.runtime_config.cancel_handler_grace;
let push_delivery_store_for_sweep = self.state.push_delivery_store.clone();
let self_push_dispatcher_for_sweep = self.state.push_dispatcher.clone();
let sweep_interval_for_task = self.state.runtime_config.push_reclaim_sweep_interval;
let sweep_batch_for_task = self.state.runtime_config.push_reclaim_sweep_batch;
let push_claim_expiry_for_sweep = self.state.runtime_config.push_claim_expiry;
let maintenance_event_store = self.state.event_store.clone();
let maintenance_interval = self.state.runtime_config.maintenance_interval;
let app = self.into_router();
// Spawn the supervisor poll loop. A shutdown token lets us stop
// the poller when the server exits; for now axum::serve runs to
// completion so the token is never tripped (server shutdown is
// driven by process exit). Later: wire the token to a graceful
// shutdown signal.
let shutdown = tokio_util::sync::CancellationToken::new();
let poller_shutdown = shutdown.clone();
let poller_handle =
tokio::spawn(crate::server::in_flight::run_cross_instance_cancel_poller(
poller_registry,
poller_supervisor,
poller_interval,
poller_abort_grace,
poller_shutdown,
));
// Push-delivery reclaim loop. Two
// enumerations run per tick:
//
// 1. `list_stale_pending_dispatches` — events whose initial
// fan-out died (e.g. persistent config-store outage)
// before any claim rows were created. The dispatcher
// reloads the task and re-runs the fan-out; each
// per-config delivery then creates or refreshes its
// claim row.
//
// 2. `list_reclaimable_claims` — claim rows that reached a
// non-terminal expired state (worker exhausted its
// bounded persist retry). The dispatcher re-invokes
// `deliver()` which re-claims and re-POSTs.
//
// Staleness threshold for pending dispatches: claim_expiry,
// the same budget the builder already validates must exceed
// the retry horizon. In-progress dispatches stay under this
// threshold; only genuinely stuck markers get picked up.
let sweep_handle = match (
push_delivery_store_for_sweep,
self_push_dispatcher_for_sweep,
) {
(Some(store), Some(dispatcher)) => {
let shutdown = shutdown.clone();
let interval = sweep_interval_for_task;
let batch = sweep_batch_for_task;
let pending_stale_threshold = push_claim_expiry_for_sweep;
Some(tokio::spawn(async move {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
_ = ticker.tick() => {
let cutoff = std::time::SystemTime::now()
.checked_sub(pending_stale_threshold)
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
match store
.list_stale_pending_dispatches(cutoff, batch)
.await
{
Ok(rows) if !rows.is_empty() => {
tracing::warn!(
target: "turul_a2a::push_pending_dispatches_stale",
count = rows.len(),
"reclaim sweep found stale pending-dispatch \
markers; re-running fan-out"
);
for row in rows {
dispatcher.redispatch_pending(row).await;
}
}
Ok(_) => {}
Err(e) => {
tracing::error!(
target: "turul_a2a::push_pending_sweep_error",
error = %e,
"pending-dispatch sweep failed"
);
}
}
match store.list_reclaimable_claims(batch).await {
Ok(rows) if !rows.is_empty() => {
tracing::warn!(
target: "turul_a2a::push_claims_reclaimed",
count = rows.len(),
"reclaim sweep found expired non-terminal \
push claims; redispatching"
);
for row in rows {
dispatcher.redispatch_one(row).await;
}
}
Ok(_) => {}
Err(e) => {
tracing::error!(
target: "turul_a2a::push_sweep_error",
error = %e,
"push claim sweep failed"
);
}
}
}
}
}
}))
}
_ => None,
};
// Opt-in retention-maintenance loop. Reaps expired events and
// tasks on a fixed cadence. Off unless `.maintenance(..)` was
// called on the builder. Each tick calls `cleanup_expired` and
// logs the deleted count; storage errors are logged and the loop
// continues so a transient backend failure does not kill it.
let maintenance_handle = match maintenance_interval {
Some(interval) => {
let shutdown = shutdown.clone();
let event_store = maintenance_event_store;
Some(tokio::spawn(async move {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
// First immediate tick fires at spawn; skip it so the
// first cleanup runs one full interval after startup.
ticker.tick().await;
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
_ = ticker.tick() => {
match event_store.cleanup_expired().await {
Ok(deleted) => {
tracing::info!(
target: "turul_a2a::maintenance_cleanup",
deleted,
"retention maintenance reaped expired rows"
);
}
Err(e) => {
tracing::error!(
target: "turul_a2a::maintenance_cleanup_error",
error = %e,
"retention maintenance cleanup failed; \
will retry next tick"
);
}
}
}
}
}
}))
}
None => None,
};
let serve_result = axum::serve(listener, app).await;
// Gracefully stop background loops — relevant if axum::serve ever returns.
shutdown.cancel();
let _ = poller_handle.await;
if let Some(h) = sweep_handle {
let _ = h.await;
}
if let Some(h) = maintenance_handle {
let _ = h.await;
}
serve_result.map_err(|e| A2aError::Internal(format!("Server error: {e}")))?;
Ok(())
}
}
/// An [`A2aServer`] that holds its listening socket but is not serving
/// yet, returned by [`A2aServer::bind`].
pub struct BoundA2aServer {
server: A2aServer,
listener: tokio::net::TcpListener,
local_addr: SocketAddr,
}
impl BoundA2aServer {
/// The address the listening socket is bound to.
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
/// Serve on the bound socket until the server exits.
pub async fn run(self) -> Result<(), A2aError> {
self.server.serve(self.listener).await
}
}
/// Wraps an executor to augment its agent card with merged security contributions.
struct SecurityAugmentedExecutor {
inner: Arc<dyn AgentExecutor>,
security: SecurityContribution,
}
#[async_trait::async_trait]
impl AgentExecutor for SecurityAugmentedExecutor {
async fn execute(
&self,
task: &mut turul_a2a_types::Task,
msg: &turul_a2a_types::Message,
ctx: &crate::executor::ExecutionContext,
) -> Result<(), A2aError> {
self.inner.execute(task, msg, ctx).await
}
fn agent_card(&self) -> turul_a2a_proto::AgentCard {
apply_security_merge(self.inner.agent_card(), &self.security)
}
fn extended_agent_card(
&self,
claims: Option<&serde_json::Value>,
) -> Option<turul_a2a_proto::AgentCard> {
self.inner
.extended_agent_card(claims)
.map(|card| apply_security_merge(card, &self.security))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::A2aError;
use crate::executor::AgentExecutor;
use turul_a2a_types::{Message, Task};
struct DummyExecutor;
#[async_trait::async_trait]
impl AgentExecutor for DummyExecutor {
async fn execute(
&self,
_task: &mut Task,
_msg: &Message,
_ctx: &crate::executor::ExecutionContext,
) -> Result<(), A2aError> {
Ok(())
}
fn agent_card(&self) -> turul_a2a_proto::AgentCard {
turul_a2a_proto::AgentCard::default()
}
}
#[test]
fn builder_requires_executor() {
let result = A2aServer::builder().build();
assert!(result.is_err());
}
#[test]
fn builder_with_executor_defaults_storage() {
let server = A2aServer::builder()
.executor(DummyExecutor)
.build()
.unwrap();
let _ = server.into_router();
}
#[test]
fn builder_with_explicit_storage() {
// `.storage()` alone wires storage traits only. No push delivery
// is implied — matches the common non-push-consumer deployment.
let storage = InMemoryA2aStorage::new();
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage)
.bind(([127, 0, 0, 1], 8080))
.build()
.unwrap();
let _ = server.into_router();
}
/// Fake event store with a different backend_name for mismatch testing.
struct FakeEventStore;
#[async_trait::async_trait]
impl crate::storage::A2aEventStore for FakeEventStore {
fn backend_name(&self) -> &'static str {
"fake-backend"
}
async fn append_event(
&self,
_t: &str,
_tid: &str,
_e: crate::streaming::StreamEvent,
) -> Result<u64, crate::storage::A2aStorageError> {
Ok(0)
}
async fn get_events_after(
&self,
_t: &str,
_tid: &str,
_s: u64,
) -> Result<Vec<(u64, crate::streaming::StreamEvent)>, crate::storage::A2aStorageError>
{
Ok(vec![])
}
async fn latest_sequence(
&self,
_t: &str,
_tid: &str,
) -> Result<u64, crate::storage::A2aStorageError> {
Ok(0)
}
async fn cleanup_expired(&self) -> Result<u64, crate::storage::A2aStorageError> {
Ok(0)
}
}
#[test]
fn mixed_backend_rejected_at_build() {
// Task + push = in-memory, event = fake-backend → should fail
let result = A2aServer::builder()
.executor(DummyExecutor)
.event_store(FakeEventStore)
.build();
match result {
Err(e) => {
let msg = e.to_string();
assert!(
msg.contains("backend mismatch") || msg.contains("Storage backend mismatch"),
"Error should mention backend mismatch: {msg}"
);
}
Ok(_) => panic!("Mixed backends should be rejected"),
}
}
/// Fake atomic store with a different backend_name for mismatch testing.
struct FakeAtomicStore;
#[async_trait::async_trait]
impl crate::storage::A2aAtomicStore for FakeAtomicStore {
fn backend_name(&self) -> &'static str {
"fake-atomic"
}
async fn create_task_with_events(
&self,
_t: &str,
_o: &str,
task: turul_a2a_types::Task,
_e: Vec<crate::streaming::StreamEvent>,
) -> Result<(turul_a2a_types::Task, Vec<u64>), crate::storage::A2aStorageError> {
Ok((task, vec![]))
}
async fn update_task_status_with_events(
&self,
_t: &str,
_tid: &str,
_o: &str,
_s: turul_a2a_types::TaskStatus,
_e: Vec<crate::streaming::StreamEvent>,
) -> Result<(turul_a2a_types::Task, Vec<u64>), crate::storage::A2aStorageError> {
unimplemented!()
}
async fn update_task_with_events(
&self,
_t: &str,
_o: &str,
_task: turul_a2a_types::Task,
_e: Vec<crate::streaming::StreamEvent>,
) -> Result<Vec<u64>, crate::storage::A2aStorageError> {
Ok(vec![])
}
}
#[test]
fn mixed_atomic_backend_rejected_at_build() {
// Task + push + event = in-memory, atomic = fake-atomic → should fail
let result = A2aServer::builder()
.executor(DummyExecutor)
.atomic_store(FakeAtomicStore)
.build();
match result {
Err(e) => {
let msg = e.to_string();
assert!(
msg.contains("backend mismatch") || msg.contains("Storage backend mismatch"),
"Error should mention backend mismatch: {msg}"
);
}
Ok(_) => panic!("Mixed atomic backend should be rejected"),
}
}
#[test]
fn same_backend_accepted() {
// All four from the same InMemoryA2aStorage — should succeed
let storage = InMemoryA2aStorage::new();
let result = A2aServer::builder()
.executor(DummyExecutor)
.task_storage(storage.clone())
.push_storage(storage.clone())
.event_store(storage.clone())
.atomic_store(storage)
.build();
assert!(result.is_ok(), "Same backend should be accepted");
}
#[test]
fn unified_storage_accepted() {
// Single .storage() call — the preferred path. No push-delivery
// wiring implied.
let result = A2aServer::builder()
.executor(DummyExecutor)
.storage(InMemoryA2aStorage::new())
.build();
assert!(result.is_ok(), "Unified .storage() should be accepted");
}
#[test]
fn runtime_config_setters_survive_build() {
// Invariant: builder setters for runtime-config knobs must propagate
// into the built server's AppState so that handlers can read
// them via `state.runtime_config`. This test exists to prevent the
// regression where setters silently become no-ops.
let server = A2aServer::builder()
.executor(DummyExecutor)
// One representative setter per consumer group.
.blocking_task_timeout(Duration::from_secs(42))
.timeout_abort_grace(Duration::from_secs(7))
.cancel_handler_grace(Duration::from_secs(3))
.cancel_handler_poll_interval(Duration::from_millis(50))
.cross_instance_cancel_poll_interval(Duration::from_secs(2))
.push_max_attempts(17)
.push_backoff_base(Duration::from_millis(500))
.push_backoff_cap(Duration::from_secs(90))
.push_backoff_jitter(0.5)
.push_request_timeout(Duration::from_secs(20))
.push_connect_timeout(Duration::from_secs(3))
.push_read_timeout(Duration::from_secs(15))
.push_claim_expiry(Duration::from_secs(20 * 60))
.push_config_cache_ttl(Duration::from_secs(10))
.push_failed_delivery_retention(Duration::from_secs(48 * 60 * 60))
.push_max_payload_bytes(2 * 1024 * 1024)
.allow_insecure_push_urls(true)
.build()
.expect("build must succeed");
let cfg = &server.state.runtime_config;
assert_eq!(cfg.blocking_task_timeout, Duration::from_secs(42));
assert_eq!(cfg.timeout_abort_grace, Duration::from_secs(7));
assert_eq!(cfg.cancel_handler_grace, Duration::from_secs(3));
assert_eq!(cfg.cancel_handler_poll_interval, Duration::from_millis(50));
assert_eq!(
cfg.cross_instance_cancel_poll_interval,
Duration::from_secs(2)
);
assert_eq!(cfg.push_max_attempts, 17);
assert_eq!(cfg.push_backoff_base, Duration::from_millis(500));
assert_eq!(cfg.push_backoff_cap, Duration::from_secs(90));
assert!((cfg.push_backoff_jitter - 0.5).abs() < f32::EPSILON);
assert_eq!(cfg.push_request_timeout, Duration::from_secs(20));
assert_eq!(cfg.push_connect_timeout, Duration::from_secs(3));
assert_eq!(cfg.push_read_timeout, Duration::from_secs(15));
assert_eq!(cfg.push_claim_expiry, Duration::from_secs(20 * 60));
assert_eq!(cfg.push_config_cache_ttl, Duration::from_secs(10));
assert_eq!(
cfg.push_failed_delivery_retention,
Duration::from_secs(48 * 60 * 60)
);
assert_eq!(cfg.push_max_payload_bytes, 2 * 1024 * 1024);
assert!(cfg.allow_insecure_push_urls);
}
#[test]
fn runtime_config_defaults_reach_built_server() {
// Second half of the contract: when no setters are called, the
// documented defaults land in AppState.
let server = A2aServer::builder()
.executor(DummyExecutor)
.build()
.expect("build must succeed");
let cfg = &server.state.runtime_config;
let defaults = RuntimeConfig::default();
assert_eq!(cfg.blocking_task_timeout, defaults.blocking_task_timeout);
assert_eq!(cfg.push_max_attempts, defaults.push_max_attempts);
assert_eq!(
cfg.allow_insecure_push_urls,
defaults.allow_insecure_push_urls
);
}
// -----------------------------------------------------------------
// Push delivery store wiring
// -----------------------------------------------------------------
#[test]
fn unified_storage_does_not_auto_wire_push_delivery_store() {
// `.storage()` wires storage traits only.
// Implementing the push-delivery trait is not intent to deliver —
// a non-push deployment must be able to pass any all-in-one
// backend without opting in to push semantics.
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(InMemoryA2aStorage::new())
.build()
.expect("build must succeed");
assert!(
server.state.push_delivery_store.is_none(),
".storage() must NOT auto-wire push_delivery_store — push is opt-in via .push_delivery_store()"
);
assert!(
server.state.push_dispatcher.is_none(),
"no delivery store, no dispatcher"
);
}
#[test]
fn default_storage_leaves_push_delivery_store_unset() {
// When no storage is passed at all, push delivery is opt-in —
// push-config CRUD must still work but no worker gets spawned.
let server = A2aServer::builder()
.executor(DummyExecutor)
.build()
.expect("build must succeed");
assert!(
server.state.push_delivery_store.is_none(),
"default build must leave push_delivery_store unset"
);
}
#[test]
fn explicit_push_delivery_store_setter() {
// The individual setter exists for mixed-backend tests. It should
// also satisfy the same-backend check when paired with matching
// storage.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.build()
.expect("build must succeed");
assert!(server.state.push_delivery_store.is_some());
assert!(
server.state.push_dispatcher.is_some(),
"a wired delivery store gets a dispatcher, so terminal commits fan out"
);
}
// -----------------------------------------------------------------
// Push-dispatch consistency: the atomic store's pending-dispatch
// marker must be writable iff a push delivery consumer is wired,
// and the builder rejects inconsistent configurations on both axes.
// -----------------------------------------------------------------
#[test]
fn builder_rejects_push_consumer_without_dispatch_enabled() {
// `push_delivery_store` wired + atomic store's
// `push_dispatch_enabled=false` ⇒ consumer would never receive
// durable markers. Build must fail and cite `with_push_dispatch_enabled`.
let storage = InMemoryA2aStorage::new(); // flag defaults to false
let res = A2aServer::builder()
.executor(DummyExecutor)
.task_storage(storage.clone())
.push_storage(storage.clone())
.event_store(storage.clone())
.atomic_store(storage.clone())
.cancellation_supervisor(storage.clone())
.push_delivery_store(storage)
.build();
let err = match res {
Err(e) => e.to_string(),
Ok(_) => panic!("orphan delivery store must be rejected"),
};
assert!(
err.contains("push_delivery_store wired")
&& err.contains("push_dispatch_enabled")
&& err.contains("with_push_dispatch_enabled(true)"),
"error should name the fix: {err}"
);
}
#[test]
fn builder_rejects_push_dispatch_without_consumer() {
// `push_dispatch_enabled=true` + no `push_delivery_store` ⇒
// markers would accumulate with no reader. Build must fail and
// mention the no-consumer rationale.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let res = A2aServer::builder()
.executor(DummyExecutor)
.task_storage(storage.clone())
.push_storage(storage.clone())
.event_store(storage.clone())
.atomic_store(storage.clone())
.cancellation_supervisor(storage)
// deliberately no .push_delivery_store(...)
.build();
let err = match res {
Err(e) => e.to_string(),
Ok(_) => panic!("orphan dispatch flag must be rejected"),
};
assert!(
err.contains("push_dispatch_enabled() is true") && err.contains("no consumer"),
"error should cite the orphaned-marker rationale: {err}"
);
}
#[test]
fn builder_accepts_push_fully_wired() {
// Positive case: storage opted in via `with_push_dispatch_enabled(true)`
// AND delivery store explicitly wired via `.push_delivery_store(...)`.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let res = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.build();
assert!(res.is_ok(), "push fully wired must build: {:?}", res.err());
}
#[test]
fn builder_accepts_non_push_deployment() {
// Positive case: both flag off and no delivery store.
let storage = InMemoryA2aStorage::new(); // flag defaults to false
let res = A2aServer::builder()
.executor(DummyExecutor)
.task_storage(storage.clone())
.push_storage(storage.clone())
.event_store(storage.clone())
.atomic_store(storage.clone())
.cancellation_supervisor(storage)
.build();
assert!(
res.is_ok(),
"non-push deployment must build: {:?}",
res.err()
);
}
#[test]
fn retry_horizon_violation_rejected() {
// push_claim_expiry <= max_attempts * backoff_cap must fail fast
//. The in-memory delivery store is required to
// trigger the check — so push must be explicitly wired.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let res = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.push_max_attempts(10)
.push_backoff_cap(Duration::from_secs(60))
// 10 * 60s = 600s — equal to claim expiry, which is <=, so rejected.
.push_claim_expiry(Duration::from_secs(600))
.build();
let err = match res {
Err(e) => e,
Ok(_) => panic!("retry horizon violation must be rejected"),
};
let msg = err.to_string();
assert!(
msg.contains("retry horizon") || msg.contains("push_claim_expiry"),
"error should mention retry horizon: {msg}"
);
}
// Test middleware that contributes a non-empty SecurityContribution
// so `into_augmented_state` must rebuild the state. Accepts every
// request — this test is about wiring, not auth behaviour.
struct ContribMiddleware;
#[async_trait::async_trait]
impl A2aMiddleware for ContribMiddleware {
async fn before_request(
&self,
_ctx: &mut crate::middleware::RequestContext,
) -> Result<(), crate::middleware::MiddlewareError> {
Ok(())
}
fn security_contribution(&self) -> SecurityContribution {
SecurityContribution::new().with_scheme(
"TestApiKey",
turul_a2a_proto::SecurityScheme {
scheme: Some(
turul_a2a_proto::security_scheme::Scheme::ApiKeySecurityScheme(
turul_a2a_proto::ApiKeySecurityScheme {
description: "test".into(),
location: "header".into(),
name: "X-Test-Key".into(),
},
),
),
},
vec![],
)
}
}
#[test]
fn push_delivery_store_survives_security_augmentation() {
// Regression: `into_router`'s rebuilt AppState used to hard-code
// push_delivery_store: None, silently disabling push delivery on
// every auth-gated deployment. The augmented state must carry the
// same claim-store Arc the builder installed.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.middleware(Arc::new(ContribMiddleware))
.build()
.expect("build must succeed");
// Sanity: push_delivery_store is wired pre-augmentation.
assert!(server.state.push_delivery_store.is_some());
let (augmented, had_security) = server.into_augmented_state();
assert!(
had_security,
"ContribMiddleware contributed a scheme — augmentation must run"
);
assert!(
augmented.push_delivery_store.is_some(),
"push_delivery_store must survive security augmentation"
);
}
#[test]
fn push_delivery_store_passthrough_without_security() {
// With no contributing middleware, `into_augmented_state` returns
// the original state unchanged — the store must still be present.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.build()
.expect("build must succeed");
let (state, had_security) = server.into_augmented_state();
assert!(!had_security);
assert!(state.push_delivery_store.is_some());
}
#[test]
fn retry_horizon_satisfied_accepted() {
// push_claim_expiry > max_attempts * backoff_cap succeeds.
let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
let server = A2aServer::builder()
.executor(DummyExecutor)
.storage(storage.clone())
.push_delivery_store(storage)
.push_max_attempts(5)
.push_backoff_cap(Duration::from_secs(60))
.push_claim_expiry(Duration::from_secs(5 * 60 + 1))
.build()
.expect("horizon-satisfying config must build");
assert!(server.state.push_delivery_store.is_some());
}
}