turul_a2a_aws_lambda/lib.rs
1//! AWS Lambda adapter for turul-a2a.
2//!
3//! # Choosing a runner
4//!
5//! A Lambda binary receives raw event JSON; the adapter owns
6//! classifying that JSON and dispatching to the right A2A handler
7//! method. Adopters pick the runner whose name matches the Lambda's
8//! AWS trigger topology and end `main.rs` with one `.await?` call —
9//! `lambda_runtime` / `lambda_http` / event parsing never appear in
10//! adopter code.
11//!
12//! | Lambda triggers | Runner |
13//! |-----------------------------------|------------------------------------------------|
14//! | HTTP only (Function URL / APIGW) | [`LambdaA2aHandler::run_http_only`] |
15//! | SQS only (event source mapping) | `LambdaA2aHandler::run_sqs_only` *(`sqs`)* |
16//! | HTTP **and** SQS on one function | `LambdaA2aHandler::run_http_and_sqs` *(`sqs`)* |
17//! | not sure / just run it | [`LambdaA2aHandler::run`] |
18//!
19//! [`LambdaA2aHandler::run`] is the default "it just works" entry
20//! point: without the `sqs` feature it aliases `run_http_only`; with
21//! `sqs` it aliases `run_http_and_sqs` (permissive, handles either
22//! shape). The explicit runners are **strict** — a non-matching
23//! event shape fails loudly, which is what hardened deployments
24//! and tests want.
25//!
26//! The one-call shortcut is [`LambdaA2aServerBuilder::run`] — it
27//! build-then-runs in a single fluent call. Use `.build()` + a
28//! handler method when the handler is needed for unit tests or
29//! custom middleware.
30//!
31//! ## Composing with non-framework triggers
32//!
33//! Lambdas wired to HTTP **plus** a third trigger the framework does
34//! not know about (EventBridge scheduler, DynamoDB stream, custom
35//! invoke) can't use a named runner directly — the Unknown branch
36//! is adopter-owned. Reach for the public classifier + the HTTP
37//! envelope primitive instead:
38//!
39//! ```ignore
40//! lambda_runtime::run(lambda_runtime::service_fn(
41//! move |event: lambda_runtime::LambdaEvent<serde_json::Value>| {
42//! let handler = handler.clone();
43//! async move {
44//! let (value, _ctx) = event.into_parts();
45//! match turul_a2a_aws_lambda::classify_event(&value) {
46//! turul_a2a_aws_lambda::LambdaEvent::Http => {
47//! handler.handle_http_event_value(value).await
48//! }
49//! turul_a2a_aws_lambda::LambdaEvent::Sqs => {
50//! let sqs = serde_json::from_value(value)?;
51//! Ok(serde_json::to_value(handler.handle_sqs(sqs).await)?)
52//! }
53//! turul_a2a_aws_lambda::LambdaEvent::Unknown => {
54//! // Adopter-owned: run your scheduled sweep,
55//! // DynamoDB stream consumer, etc.
56//! run_adopter_specific_path(value).await
57//! }
58//! }
59//! }
60//! }
61//! )).await
62//! ```
63//!
64//! [`LambdaA2aHandler::handle_http_event_value`] is available without
65//! the `sqs` feature; `handle_sqs` is gated on `sqs`. `classify_event`
66//! + `LambdaEvent` are always available.
67//!
68//! ## API Gateway path prefix
69//!
70//! When Lambda sits behind a REST API Gateway with `AWS_PROXY`
71//! integration, the event carries the full stage + resource tree in
72//! the path (e.g. `/stage/agent/message:send`),
73//! which the root-rooted A2A router would 404. Configure the prefix
74//! to strip via [`LambdaA2aServerBuilder::strip_path_prefix`]:
75//!
76//! ```ignore
77//! LambdaA2aServerBuilder::new()
78//! .executor(my_executor)
79//! .storage(my_storage)
80//! .strip_path_prefix("/stage/agent") // API GW prefix
81//! .run()
82//! .await
83//! ```
84//!
85//! The strip applies to `run_http_only` and `run_http_and_sqs`.
86//! SQS events are unaffected. Non-matching paths pass through
87//! unchanged (router still 404s on genuinely unknown paths —
88//! that's the correct failure mode).
89//!
90//! ```ignore
91//! // HTTP-only Lambda (request Lambda in two-Lambda topology):
92//! LambdaA2aServerBuilder::new()
93//! .executor(my_executor)
94//! .storage(my_storage)
95//! .with_sqs_return_immediately(queue_url, sqs) // enqueues durable jobs
96//! .build()?
97//! .run_http_only()
98//! .await
99//!
100//! // Single-function HTTP+SQS demo:
101//! LambdaA2aServerBuilder::new()
102//! .executor(my_executor)
103//! .storage(my_storage)
104//! .with_sqs_return_immediately(queue_url, sqs)
105//! .run() // builder shortcut; dispatches HTTP + SQS
106//! .await
107//!
108//! // Pure SQS worker — no with_sqs_return_immediately(...) needed
109//! // (it consumes the queue, never enqueues):
110//! LambdaA2aServerBuilder::new()
111//! .executor(my_executor)
112//! .storage(my_storage)
113//! .build()?
114//! .run_sqs_only()
115//! .await
116//! ```
117//!
118//! # Adapter internals
119//!
120//! Thin wrapper: converts Lambda events to axum requests, delegates to
121//! the same Router, converts responses back. Adapter contract:
122//! - Authorizer context mapped via synthetic headers with anti-spoofing.
123//! - SSE responses are buffered: task executes, events are collected,
124//! returned as one response.
125//! - `POST /message:stream` executes the task within the Lambda
126//! invocation and returns all events.
127//! - `GET /tasks/{id}:subscribe` is for tasks that are **not** in a
128//! terminal state. Within one invocation it emits the initial `Task`
129//! snapshot, delivers events committed after it, and closes when the
130//! task reaches a terminal state or INPUT_REQUIRED. Subscribing to an
131//! already-terminal task returns `UnsupportedOperationError` per
132//! A2A v1.0 §3.1.6. For retrieving a terminal task's final state
133//! use `GetTask`.
134//!
135//! # Push-notification delivery — external triggers are mandatory
136//!
137//! Push delivery on Lambda is architecturally different from the
138//! binary server. The request Lambda installed via
139//! [`LambdaA2aServerBuilder`] still constructs a `PushDispatcher`
140//! when `push_delivery_store` is wired, but any `tokio::spawn`
141//! continuation it emits post-return is **opportunistic only** — the
142//! Lambda execution environment may be frozen indefinitely between
143//! invocations, so nothing can depend on that continuation completing.
144//!
145//! Correctness for push delivery on Lambda is carried by:
146//!
147//! 1. The atomic pending-dispatch marker written inside the request
148//! Lambda's commit transaction (opt in via
149//! `StorageImpl::with_push_dispatch_enabled(true)`).
150//! 2. [`LambdaStreamRecoveryHandler`] — DynamoDB Streams trigger on
151//! `a2a_push_pending_dispatches`. DynamoDB backends only.
152//! 3. [`LambdaScheduledRecoveryHandler`] — EventBridge Scheduler
153//! backstop. **Required for all backends**; it is the sole
154//! recovery path for SQLite / PostgreSQL / in-memory deployments.
155//!
156//! Without at least the scheduled worker, push delivery on Lambda is
157//! not durable — a marker written on a cold invocation may never be
158//! consumed. The example wiring lives in
159//! `examples/lambda-stream-worker` and
160//! `examples/lambda-scheduled-worker`.
161//!
162//! Lambda streaming is request-scoped (not persistent SSE connections). The durable
163//! event store ensures events survive across invocations. A client that loses
164//! its stream subscribes again and receives a fresh `Task` snapshot.
165//!
166//! # Cross-instance cancellation
167//!
168//! Lambda invocations are stateless and short-lived, so the Lambda
169//! adapter does **not** run the persistent cross-instance cancel
170//! poller that `A2aServer::run()` spawns. Cancellation behaviour on
171//! the Lambda adapter:
172//!
173//! - **Marker writes** — `CancelTask` on a Lambda invocation writes
174//! the cancel marker to the shared backend (DynamoDB / PostgreSQL).
175//! This works.
176//! - **Propagation to a live executor on the SAME Lambda invocation** —
177//! works via the same-instance token-trip path in `core_cancel_task`.
178//! - **Propagation to a live executor on a DIFFERENT Lambda invocation
179//! (warm container)** — **not currently supported**. There is no
180//! persistent poller to observe markers written by other
181//! invocations. A subsequent invocation whose handler reads the
182//! marker directly may act on it, but that is not a substitute for
183//! the server runtime's live propagation.
184//!
185//! The builder still **requires** an `A2aCancellationSupervisor`
186//! implementation on the same backend so that marker writes reach
187//! the correct backend and a future polling-adapter variant can
188//! consume them. If a deployment passes a non-matching supervisor,
189//! `build()` rejects the configuration.
190
191mod adapter;
192mod auth;
193mod event;
194mod no_streaming;
195mod scheduled_recovery;
196mod stream_recovery;
197
198#[cfg(feature = "sqs")]
199mod durable;
200
201#[cfg(test)]
202mod builder_tests;
203#[cfg(test)]
204mod scheduled_recovery_tests;
205#[cfg(test)]
206mod stream_recovery_tests;
207
208pub use adapter::{axum_to_lambda_response, lambda_to_axum_request};
209pub use auth::{AuthorizerMapping, LambdaAuthorizerMiddleware};
210pub use event::{LambdaEvent, classify_event};
211pub use no_streaming::NoStreamingLayer;
212pub use scheduled_recovery::{
213 LambdaScheduledRecoveryConfig, LambdaScheduledRecoveryHandler, LambdaScheduledRecoveryResponse,
214 handle_maintenance_trigger,
215};
216pub use stream_recovery::LambdaStreamRecoveryHandler;
217
218#[cfg(feature = "sqs")]
219pub use durable::{SqsDurableExecutorQueue, drive_sqs_batch};
220
221use std::sync::Arc;
222
223use turul_a2a::error::A2aError;
224use turul_a2a::executor::AgentExecutor;
225use turul_a2a::middleware::{A2aMiddleware, MiddlewareStack};
226use turul_a2a::push::A2aPushDeliveryStore;
227use turul_a2a::router::{AppState, build_router};
228use turul_a2a::server::RuntimeConfig;
229use turul_a2a::storage::{
230 A2aAtomicStore, A2aCancellationSupervisor, A2aEventStore, A2aPushNotificationStorage,
231 A2aTaskStorage,
232};
233use turul_a2a::streaming::TaskEventBroker;
234
235/// Builder for Lambda A2A handler.
236///
237/// Use `.storage(my_storage)` to supply a single backend implementing all storage traits.
238/// All four storage traits must share the same backend so streaming, push delivery,
239/// and cross-instance cancellation coordinate correctly.
240///
241/// For push-notification delivery, wire `.storage()` with a backend that implements
242/// [`A2aPushDeliveryStore`] (all four first-party backends do). The atomic store
243/// must also opt in via `with_push_dispatch_enabled(true)`; the
244/// builder rejects configurations where the flag and the delivery store disagree.
245pub struct LambdaA2aServerBuilder {
246 executor: Option<Arc<dyn AgentExecutor>>,
247 task_storage: Option<Arc<dyn A2aTaskStorage>>,
248 push_storage: Option<Arc<dyn A2aPushNotificationStorage>>,
249 event_store: Option<Arc<dyn A2aEventStore>>,
250 atomic_store: Option<Arc<dyn A2aAtomicStore>>,
251 cancellation_supervisor: Option<Arc<dyn A2aCancellationSupervisor>>,
252 push_delivery_store: Option<Arc<dyn A2aPushDeliveryStore>>,
253 middleware: Vec<Arc<dyn A2aMiddleware>>,
254 runtime_config: RuntimeConfig,
255 durable_executor_queue: Option<Arc<dyn turul_a2a::durable_executor::DurableExecutorQueue>>,
256 path_prefix: Option<String>,
257 outbound_url_validator: Option<turul_a2a::push::ssrf::OutboundUrlValidator>,
258}
259
260impl LambdaA2aServerBuilder {
261 pub fn new() -> Self {
262 Self {
263 executor: None,
264 task_storage: None,
265 push_storage: None,
266 event_store: None,
267 atomic_store: None,
268 cancellation_supervisor: None,
269 push_delivery_store: None,
270 middleware: vec![],
271 runtime_config: RuntimeConfig::default(),
272 durable_executor_queue: None,
273 path_prefix: None,
274 outbound_url_validator: None,
275 }
276 }
277
278 /// Configure an HTTP path prefix to strip before the A2A router
279 /// sees the request. Needed when Lambda sits behind an API Gateway
280 /// whose stage + resource tree is forwarded into the function
281 /// (e.g. REST API `AWS_PROXY` integrations surface
282 /// `/stage/agent/message:send` where the A2A
283 /// router expects `/message:send`).
284 ///
285 /// The prefix must start with `/` and must not end with `/`
286 /// (unless it is exactly `/`, which is a no-op). Segment boundaries
287 /// are respected — a prefix of `/dev` will not strip `/devs/...`.
288 /// Paths that do not start with the prefix pass through unchanged
289 /// (the router will 404 on a genuinely unknown path, which is the
290 /// correct failure mode). Applies to both
291 /// [`LambdaA2aHandler::run_http_only`] and
292 /// `LambdaA2aHandler::run_http_and_sqs`. SQS events are
293 /// unaffected.
294 pub fn strip_path_prefix(mut self, prefix: impl Into<String>) -> Self {
295 self.path_prefix = Some(prefix.into());
296 self
297 }
298
299 /// Wire a durable executor queue. When set, the
300 /// `return_immediately = true` path in `core_send_message` enqueues
301 /// a [`turul_a2a::durable_executor::QueuedExecutorJob`] on this
302 /// queue instead of spawning the executor locally, and the
303 /// capability flag `RuntimeConfig::supports_return_immediately` is
304 /// turned **back on** as an implementation detail — the capability
305 /// cannot be claimed without supplying the queue.
306 ///
307 /// Adopters should typically reach for the SQS-specific helper
308 /// `Self::with_sqs_return_immediately` instead; this generic
309 /// method exists so adopters can inject in-memory fakes for tests
310 /// or provide non-SQS transports (Kinesis, Step Functions task
311 /// token, self-invoke, etc.).
312 pub fn with_durable_executor(
313 mut self,
314 queue: Arc<dyn turul_a2a::durable_executor::DurableExecutorQueue>,
315 ) -> Self {
316 self.durable_executor_queue = Some(queue);
317 self.runtime_config.supports_return_immediately = true;
318 self
319 }
320
321 /// Wire the AWS SQS durable executor queue. Ergonomic
322 /// helper over [`Self::with_durable_executor`] that constructs a
323 /// [`SqsDurableExecutorQueue`] from a `queue_url` + shared SQS
324 /// client. Requires the `sqs` feature.
325 #[cfg(feature = "sqs")]
326 pub fn with_sqs_return_immediately(
327 self,
328 queue_url: impl Into<String>,
329 sqs_client: Arc<aws_sdk_sqs::Client>,
330 ) -> Self {
331 let queue = Arc::new(SqsDurableExecutorQueue::new(queue_url, sqs_client));
332 self.with_durable_executor(queue)
333 }
334
335 pub fn executor(mut self, exec: impl AgentExecutor + 'static) -> Self {
336 self.executor = Some(Arc::new(exec));
337 self
338 }
339
340 /// Set all storage from a single backend instance.
341 ///
342 /// This is the **preferred** method — a single struct implementing all
343 /// storage traits guarantees the same-backend requirement
344 /// AND ensures the cancellation supervisor reads the same backend
345 /// the cancel marker is written to. A mismatch here (e.g., DynamoDB
346 /// task storage + in-memory cancellation supervisor) silently
347 /// breaks cross-instance cancellation.
348 ///
349 /// errata: `.storage()` wires storage traits only. It does
350 /// **not** auto-register the storage as a push-delivery store, even if
351 /// the backend happens to implement [`A2aPushDeliveryStore`]. To opt in
352 /// to push delivery, call [`Self::push_delivery_store`] explicitly and
353 /// call `with_push_dispatch_enabled(true)` on the storage instance
354 /// before passing it here. Non-push deployments need neither.
355 pub fn storage<S>(mut self, storage: S) -> Self
356 where
357 S: A2aTaskStorage
358 + A2aPushNotificationStorage
359 + A2aEventStore
360 + A2aAtomicStore
361 + A2aCancellationSupervisor
362 + Clone
363 + 'static,
364 {
365 self.task_storage = Some(Arc::new(storage.clone()));
366 self.push_storage = Some(Arc::new(storage.clone()));
367 self.event_store = Some(Arc::new(storage.clone()));
368 self.atomic_store = Some(Arc::new(storage.clone()));
369 self.cancellation_supervisor = Some(Arc::new(storage));
370 self
371 }
372
373 /// Set task storage individually. Must be paired with event_store/atomic_store
374 /// AND `cancellation_supervisor()` for same-backend compliance.
375 pub fn task_storage(mut self, s: impl A2aTaskStorage + 'static) -> Self {
376 self.task_storage = Some(Arc::new(s));
377 self
378 }
379
380 /// Set push notification storage individually.
381 pub fn push_storage(mut self, s: impl A2aPushNotificationStorage + 'static) -> Self {
382 self.push_storage = Some(Arc::new(s));
383 self
384 }
385
386 /// Set event store individually. Must match task_storage backend.
387 pub fn event_store(mut self, s: impl A2aEventStore + 'static) -> Self {
388 self.event_store = Some(Arc::new(s));
389 self
390 }
391
392 /// Set atomic store individually. Must match task_storage backend.
393 pub fn atomic_store(mut self, s: impl A2aAtomicStore + 'static) -> Self {
394 self.atomic_store = Some(Arc::new(s));
395 self
396 }
397
398 /// Set the cancellation supervisor individually. Must match
399 /// task_storage backend — otherwise `:cancel` writes the marker to
400 /// one backend and the supervisor reads from another, silently
401 /// breaking cross-instance cancellation. Prefer `.storage()` for
402 /// unified wiring. Consumed by `core_cancel_task`.
403 pub fn cancellation_supervisor(mut self, s: impl A2aCancellationSupervisor + 'static) -> Self {
404 self.cancellation_supervisor = Some(Arc::new(s));
405 self
406 }
407
408 /// Set the push delivery store individually.
409 ///
410 /// Prefer `.storage()` for unified wiring. The delivery store MUST
411 /// be on the same backend as `.task_storage(...)` — the builder
412 /// rejects mismatches. Passing a delivery store also requires the
413 /// atomic store to have opted in via `with_push_dispatch_enabled(true)`
414 ///.
415 pub fn push_delivery_store(mut self, store: impl A2aPushDeliveryStore + 'static) -> Self {
416 self.push_delivery_store = Some(Arc::new(store));
417 self
418 }
419
420 /// Override the runtime configuration (timeouts, retry budgets,
421 /// push tuning). Defaults to [`RuntimeConfig::default()`]. The
422 /// builder validates push settings (claim expiry vs retry horizon,
423 /// ) when `.push_delivery_store(...)` is wired.
424 pub fn runtime_config(mut self, cfg: RuntimeConfig) -> Self {
425 self.runtime_config = cfg;
426 self
427 }
428
429 pub fn middleware(mut self, mw: Arc<dyn A2aMiddleware>) -> Self {
430 self.middleware.push(mw);
431 self
432 }
433
434 /// Operator allowlist for push webhook URLs.
435 ///
436 /// Called with each webhook URL on every delivery attempt, before
437 /// DNS resolution. Returning `Err` refuses the delivery: nothing is
438 /// resolved or POSTed, and the delivery is recorded as a failed
439 /// delivery with error class `SSRFBlocked`. The reason string is
440 /// not persisted. Runs in addition to the built-in scheme and
441 /// private-address checks, not instead of them. Takes effect only
442 /// when push delivery is wired (`push_delivery_store`).
443 pub fn outbound_url_validator(
444 mut self,
445 validator: turul_a2a::push::ssrf::OutboundUrlValidator,
446 ) -> Self {
447 self.outbound_url_validator = Some(validator);
448 self
449 }
450
451 pub fn build(self) -> Result<LambdaA2aHandler, A2aError> {
452 let executor = self
453 .executor
454 .ok_or(A2aError::Internal("executor is required".into()))?;
455 let task_storage = self.task_storage.ok_or(A2aError::Internal(
456 "task_storage is required for Lambda".into(),
457 ))?;
458 let push_storage = self.push_storage.ok_or(A2aError::Internal(
459 "push_storage is required for Lambda".into(),
460 ))?;
461 let event_store: Arc<dyn A2aEventStore> = self.event_store.ok_or(A2aError::Internal(
462 "event_store is required for Lambda (use .storage() for unified backend)".into(),
463 ))?;
464 let atomic_store: Arc<dyn A2aAtomicStore> = self.atomic_store.ok_or(A2aError::Internal(
465 "atomic_store is required for Lambda (use .storage() for unified backend)".into(),
466 ))?;
467 // the cancellation supervisor MUST be supplied. No
468 // InMemoryA2aStorage fallback: that would silently break
469 // cross-instance cancellation by reading markers from a
470 // different backend than they were written to.
471 let cancellation_supervisor: Arc<dyn A2aCancellationSupervisor> =
472 self.cancellation_supervisor.ok_or(A2aError::Internal(
473 "cancellation_supervisor is required for Lambda. Use .storage() for unified \
474 backend wiring, or .cancellation_supervisor(...) alongside the individual \
475 storage setters. Omitting it silently breaks cross-instance cancellation."
476 .into(),
477 ))?;
478
479 // Same-backend enforcement: all storage traits + the
480 // cancellation supervisor must report the same `backend_name`.
481 let task_backend = task_storage.backend_name();
482 let push_backend = push_storage.backend_name();
483 let event_backend = event_store.backend_name();
484 let atomic_backend = atomic_store.backend_name();
485 let supervisor_backend = cancellation_supervisor.backend_name();
486 if task_backend != push_backend
487 || task_backend != event_backend
488 || task_backend != atomic_backend
489 || task_backend != supervisor_backend
490 {
491 return Err(A2aError::Internal(format!(
492 "Storage backend mismatch: task={task_backend}, push={push_backend}, \
493 event={event_backend}, atomic={atomic_backend}, \
494 cancellation_supervisor={supervisor_backend}. \
495 All storage traits, the cancellation supervisor included, \
496 must share one backend so cross-instance cancel markers \
497 are observable. Use .storage() for unified backend."
498 )));
499 }
500
501 let push_delivery_store = self.push_delivery_store;
502
503 // Push-dispatch consistency: the atomic store's
504 // opt-in flag and the presence of `push_delivery_store` MUST
505 // agree. Both-true = push fully wired; both-false = non-push
506 // deployment. Mixed cases are build errors — this mirrors the
507 // main server builder (server/mod.rs).
508 match (
509 push_delivery_store.is_some(),
510 atomic_store.push_dispatch_enabled(),
511 ) {
512 (true, true) | (false, false) => {}
513 (true, false) => {
514 return Err(A2aError::Internal(
515 "push_delivery_store wired but atomic_store.push_dispatch_enabled() \
516 is false. Call .with_push_dispatch_enabled(true) on the backend \
517 storage before passing it to .storage()."
518 .into(),
519 ));
520 }
521 (false, true) => {
522 return Err(A2aError::Internal(
523 "atomic_store.push_dispatch_enabled() is true but no \
524 push_delivery_store is wired. Pending-dispatch markers would be \
525 written with no consumer, imposing load-bearing infra for no \
526 benefit. If you need to populate markers for an external \
527 consumer, open an issue for a distinctly-named opt-in — for now, \
528 this configuration is rejected."
529 .into(),
530 ));
531 }
532 }
533
534 // The Lambda execution environment can freeze once the HTTP
535 // response is flushed, so a `tokio::spawn`'d executor
536 // continuation is opportunistic only. Refuse
537 // `SendMessageConfiguration.return_immediately = true` at the
538 // `core_send_message` entry point (UnsupportedOperationError —
539 // an aspect of SendMessage this runtime cannot honour, A2A
540 // v1.0.1 §3.3.2) via this capability flag instead of silently
541 // orphaning the executor.
542 //
543 // if a durable executor queue is wired via
544 // [`Self::with_durable_executor`] (or the SQS helper), the
545 // capability is re-enabled because enqueueing is durable
546 // across the Lambda freeze. The explicit re-enable lives in
547 // the builder method so the capability cannot be claimed
548 // without the mechanism.
549 let mut runtime_config = self.runtime_config;
550 if self.durable_executor_queue.is_none() {
551 runtime_config.supports_return_immediately = false;
552 }
553
554 // Push dispatcher wiring. When
555 // `push_delivery_store` is present, validate its backend matches,
556 // validate the retry-horizon invariant, and construct the
557 // `PushDispatcher`. Under Lambda the dispatcher runs
558 // opportunistically post-return; correctness
559 // comes from the atomic marker + stream/scheduler recovery.
560 let push_dispatcher: Option<Arc<turul_a2a::push::PushDispatcher>> = if let Some(delivery) =
561 push_delivery_store.as_ref()
562 {
563 let push_delivery_backend = delivery.backend_name();
564 if task_backend != push_delivery_backend {
565 return Err(A2aError::Internal(format!(
566 "Storage backend mismatch: task={task_backend}, \
567 push_delivery={push_delivery_backend}. \
568 All storage traits must share the same backend."
569 )));
570 }
571
572 // claim expiry must exceed the worst-case
573 // retry horizon so a live claim is not mis-classified as
574 // stale mid-retry.
575 let retry_horizon = runtime_config
576 .push_backoff_cap
577 .saturating_mul(runtime_config.push_max_attempts as u32);
578 if runtime_config.push_claim_expiry <= retry_horizon {
579 return Err(A2aError::Internal(format!(
580 "push_claim_expiry ({:?}) must be greater than retry horizon \
581 (push_max_attempts={} * push_backoff_cap={:?} = {:?}). \
582 Raise push_claim_expiry or lower push_max_attempts/push_backoff_cap.",
583 runtime_config.push_claim_expiry,
584 runtime_config.push_max_attempts,
585 runtime_config.push_backoff_cap,
586 retry_horizon
587 )));
588 }
589
590 let delivery_cfg =
591 turul_a2a::push::delivery::PushDeliveryConfig::from_runtime_config(&runtime_config);
592
593 let instance_id = format!("a2a-lambda-{}", uuid::Uuid::now_v7());
594 let worker = turul_a2a::push::delivery::PushDeliveryWorker::new(
595 delivery.clone(),
596 delivery_cfg,
597 self.outbound_url_validator.clone(),
598 instance_id,
599 )
600 .map_err(|e| A2aError::Internal(format!("push worker build failed: {e}")))?;
601
602 Some(Arc::new(turul_a2a::push::PushDispatcher::new(
603 Arc::new(worker),
604 push_storage.clone(),
605 task_storage.clone(),
606 )))
607 } else {
608 None
609 };
610
611 let state = AppState {
612 executor,
613 task_storage,
614 push_storage,
615 event_store,
616 atomic_store,
617 event_broker: TaskEventBroker::new(),
618 middleware_stack: Arc::new(MiddlewareStack::new(self.middleware)),
619 runtime_config,
620 in_flight: Arc::new(turul_a2a::server::in_flight::InFlightRegistry::new()),
621 cancellation_supervisor,
622 push_delivery_store,
623 push_dispatcher,
624 durable_executor_queue: self.durable_executor_queue,
625 };
626
627 let router = build_router(state.clone());
628
629 let path_prefix = match self.path_prefix {
630 None => None,
631 Some(p) if p.is_empty() || p == "/" => None,
632 Some(p) => {
633 if !p.starts_with('/') {
634 return Err(A2aError::InvalidRequest {
635 message: format!(
636 "LambdaA2aServerBuilder::strip_path_prefix: prefix must start with '/'; got {p:?}"
637 ),
638 });
639 }
640 if p.ends_with('/') {
641 return Err(A2aError::InvalidRequest {
642 message: format!(
643 "LambdaA2aServerBuilder::strip_path_prefix: prefix must not end with '/' (except '/'); got {p:?}"
644 ),
645 });
646 }
647 Some(Arc::from(p))
648 }
649 };
650
651 Ok(LambdaA2aHandler {
652 router,
653 state,
654 path_prefix,
655 })
656 }
657}
658
659impl Default for LambdaA2aServerBuilder {
660 fn default() -> Self {
661 Self::new()
662 }
663}
664
665/// Lambda handler wrapping the axum Router.
666#[derive(Clone)]
667pub struct LambdaA2aHandler {
668 router: axum::Router,
669 /// Held for SQS-event dispatch (`handle_sqs`). Always
670 /// populated — the SQS handler method is gated behind the `sqs`
671 /// feature but the state is carried unconditionally so callers can
672 /// reach it for diagnostics or future non-HTTP / non-SQS handlers.
673 #[cfg_attr(not(feature = "sqs"), allow(dead_code))]
674 state: AppState,
675 /// Leading path segment to strip from each incoming HTTP request
676 /// before the A2A router sees it. `None` = no stripping. Set via
677 /// [`LambdaA2aServerBuilder::strip_path_prefix`].
678 path_prefix: Option<Arc<str>>,
679}
680
681impl LambdaA2aHandler {
682 pub fn builder() -> LambdaA2aServerBuilder {
683 LambdaA2aServerBuilder::new()
684 }
685
686 /// Handle a Lambda HTTP request.
687 pub async fn handle(
688 &self,
689 event: lambda_http::Request,
690 ) -> Result<lambda_http::Response<lambda_http::Body>, lambda_http::Error> {
691 let axum_req = lambda_to_axum_request(event)?;
692 let axum_req = match &self.path_prefix {
693 Some(prefix) => adapter::strip_request_path_prefix(axum_req, prefix),
694 None => axum_req,
695 };
696
697 let axum_resp = tower::ServiceExt::oneshot(self.router.clone(), axum_req)
698 .await
699 .map_err(|e| lambda_http::Error::from(format!("Router error: {e}")))?;
700
701 axum_to_lambda_response(axum_resp).await
702 }
703
704 /// Handle a raw Lambda HTTP event delivered as `serde_json::Value`
705 /// and return a response envelope **matching the inbound event
706 /// shape**:
707 ///
708 /// | Inbound shape detected by `lambda_http::LambdaRequest` | Response envelope |
709 /// |----------------------------------------------------------|------------------------------------|
710 /// | API Gateway v1 (REST) — top-level `httpMethod` + `path` | `ApiGatewayProxyResponse` |
711 /// | API Gateway v2 / Function URL — `requestContext.http` | `ApiGatewayV2httpResponse` |
712 /// | ALB target group — `requestContext.elb` | `AlbTargetGroupResponse` |
713 /// | WebSocket / unrecognised | `Err(...)` |
714 ///
715 /// Mismatching envelopes — most commonly a v2 response sent in
716 /// response to a v1 invocation — cause API Gateway to return
717 /// `502 Bad Gateway` regardless of the body, because the response
718 /// fails the gateway's contract validation. This method ensures
719 /// symmetry: response shape is always picked from the inbound
720 /// shape, never hardcoded.
721 ///
722 /// This is the framework's canonical HTTP envelope conversion
723 /// primitive — useful when a single Lambda function routes among
724 /// HTTP and one or more non-framework triggers (EventBridge,
725 /// DynamoDB streams, custom invoke) and the adopter drives
726 /// [`lambda_runtime::run`] with `serde_json::Value` directly.
727 /// Handles the `LambdaRequest` deserialization, the text-vs-base64
728 /// content-type detection, and the response envelope rebuild.
729 ///
730 /// Body encoding: text for `text/*`, `application/json`,
731 /// `application/xml`, `application/javascript`, any `+json` / `+xml`
732 /// structured-syntax suffix (RFC 6839, e.g. `application/a2a+json`),
733 /// or anything with `charset=`; base64 otherwise.
734 ///
735 /// Path-prefix stripping (see
736 /// [`LambdaA2aServerBuilder::strip_path_prefix`]) is applied
737 /// because dispatch flows through [`Self::handle`]. Adopters who
738 /// only serve HTTP should continue to use [`Self::run_http_only`]
739 /// or [`LambdaA2aServerBuilder::run`]; this entry point exists for
740 /// composition with adopter-owned third triggers.
741 pub async fn handle_http_event_value(
742 &self,
743 value: serde_json::Value,
744 ) -> Result<serde_json::Value, lambda_runtime::Error> {
745 use base64::Engine;
746 use http_body_util::BodyExt;
747
748 let lambda_req: lambda_http::request::LambdaRequest = serde_json::from_value(value)
749 .map_err(|e| lambda_runtime::Error::from(format!("invalid HTTP event: {e}")))?;
750
751 // Capture the inbound shape so we can emit the matching
752 // response envelope. Lost once we convert to `lambda_http::Request`.
753 let shape = match &lambda_req {
754 lambda_http::request::LambdaRequest::ApiGatewayV1(_) => HttpEventShape::ApiGatewayV1,
755 lambda_http::request::LambdaRequest::ApiGatewayV2(_) => HttpEventShape::ApiGatewayV2,
756 lambda_http::request::LambdaRequest::Alb(_) => HttpEventShape::Alb,
757 lambda_http::request::LambdaRequest::WebSocket(_) => {
758 return Err(lambda_runtime::Error::from(
759 "WebSocket Lambda events are not supported by this adapter",
760 ));
761 }
762 _ => {
763 return Err(lambda_runtime::Error::from(
764 "unsupported Lambda HTTP event variant",
765 ));
766 }
767 };
768
769 let req: lambda_http::Request = lambda_req.into();
770
771 let resp = self
772 .handle(req)
773 .await
774 .map_err(|e| lambda_runtime::Error::from(format!("handler error: {e}")))?;
775 let (parts, body) = resp.into_parts();
776
777 let bytes = body
778 .collect()
779 .await
780 .map_err(|e| lambda_runtime::Error::from(format!("body collect: {e}")))?
781 .to_bytes();
782
783 let ct = parts
784 .headers
785 .get(http::header::CONTENT_TYPE)
786 .and_then(|v| v.to_str().ok())
787 .unwrap_or("application/octet-stream")
788 .to_ascii_lowercase();
789 let essence = ct.split(';').next().unwrap_or("").trim();
790 let is_text = essence.starts_with("text/")
791 || matches!(
792 essence,
793 "application/json" | "application/xml" | "application/javascript"
794 )
795 || essence.ends_with("+json")
796 || essence.ends_with("+xml")
797 || ct.contains("charset=");
798
799 let (body_str, is_base64) = if bytes.is_empty() {
800 (None, false)
801 } else if is_text {
802 match std::str::from_utf8(&bytes) {
803 Ok(s) => (Some(s.to_string()), false),
804 Err(_) => (
805 Some(base64::engine::general_purpose::STANDARD.encode(&bytes)),
806 true,
807 ),
808 }
809 } else {
810 (
811 Some(base64::engine::general_purpose::STANDARD.encode(&bytes)),
812 true,
813 )
814 };
815
816 let status = parts.status.as_u16() as i64;
817 let headers = parts.headers;
818 let body_lambda = body_str.map(aws_lambda_events::encodings::Body::Text);
819
820 match shape {
821 HttpEventShape::ApiGatewayV1 => {
822 let mut api_resp = aws_lambda_events::apigw::ApiGatewayProxyResponse::default();
823 api_resp.status_code = status;
824 api_resp.headers = headers;
825 api_resp.body = body_lambda;
826 api_resp.is_base64_encoded = is_base64;
827 serde_json::to_value(api_resp).map_err(|e| {
828 lambda_runtime::Error::from(format!("serialise APIGW v1 response: {e}"))
829 })
830 }
831 HttpEventShape::ApiGatewayV2 => {
832 let mut api_resp = aws_lambda_events::apigw::ApiGatewayV2httpResponse::default();
833 api_resp.status_code = status;
834 api_resp.headers = headers;
835 api_resp.body = body_lambda;
836 api_resp.is_base64_encoded = is_base64;
837 serde_json::to_value(api_resp).map_err(|e| {
838 lambda_runtime::Error::from(format!("serialise APIGW v2 response: {e}"))
839 })
840 }
841 HttpEventShape::Alb => {
842 let mut api_resp = aws_lambda_events::alb::AlbTargetGroupResponse::default();
843 api_resp.status_code = status;
844 api_resp.headers = headers;
845 api_resp.body = body_lambda;
846 api_resp.is_base64_encoded = is_base64;
847 serde_json::to_value(api_resp).map_err(|e| {
848 lambda_runtime::Error::from(format!("serialise ALB response: {e}"))
849 })
850 }
851 }
852 }
853}
854
855/// Inbound HTTP event shape detected by [`LambdaA2aHandler::handle_http_event_value`].
856///
857/// The response envelope must match the inbound shape — see method
858/// docs for the contract.
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
860enum HttpEventShape {
861 ApiGatewayV1,
862 ApiGatewayV2,
863 Alb,
864}
865
866impl LambdaA2aHandler {
867 /// Handle an SQS batch from the durable executor queue.
868 ///
869 /// Returns `SqsBatchResponse` whose `batch_item_failures` list
870 /// tells the event source mapping which records to retry.
871 /// Requires `FunctionResponseTypes: ["ReportBatchItemFailures"]`
872 /// on the mapping.
873 ///
874 /// Each record: deserialize envelope → load task → terminal-no-op
875 /// check → cancel-marker direct-CANCELED commit → run executor.
876 /// See `durable::drive_sqs_batch` for the full semantics.
877 #[cfg(feature = "sqs")]
878 pub async fn handle_sqs(
879 &self,
880 event: aws_lambda_events::event::sqs::SqsEvent,
881 ) -> aws_lambda_events::event::sqs::SqsBatchResponse {
882 durable::drive_sqs_batch(&self.state, event).await
883 }
884
885 /// Run this handler as a pure HTTP Lambda. Strict: any non-HTTP
886 /// event shape (SQS, DynamoDB stream, scheduler, …) causes
887 /// `lambda_http::run` to return a deserialization error on
888 /// invocation.
889 ///
890 /// Appropriate for Lambdas whose only trigger is a Function URL,
891 /// API Gateway, or ALB. The request Lambda in the two-Lambda
892 /// durable-executor topology is the canonical caller.
893 pub async fn run_http_only(self) -> Result<(), lambda_runtime::Error> {
894 let handler = Arc::new(self);
895 lambda_http::run(lambda_http::service_fn(move |event| {
896 let h = Arc::clone(&handler);
897 async move { h.handle(event).await }
898 }))
899 .await
900 }
901}
902
903// Default entrypoint when the `sqs` feature is off — `.run()` aliases
904// the HTTP-only runner. With the `sqs` feature enabled, `.run()` lives
905// in `durable.rs` and routes HTTP+SQS via the classifier.
906#[cfg(not(feature = "sqs"))]
907impl LambdaA2aHandler {
908 /// Default Lambda runner. Dispatches based on the event shape the
909 /// binary receives. Without the `sqs` feature this is HTTP-only
910 /// (equivalent to [`LambdaA2aHandler::run_http_only`]).
911 pub async fn run(self) -> Result<(), lambda_runtime::Error> {
912 self.run_http_only().await
913 }
914}
915
916impl LambdaA2aServerBuilder {
917 /// Build and run in one call. Sugar for
918 /// `self.build()?.run().await`. Hides the handler from the adopter —
919 /// use `.build()` + `handler.run_*()` instead when the handler is
920 /// needed for unit tests, custom middleware, or an explicit
921 /// topology runner.
922 pub async fn run(self) -> Result<(), lambda_runtime::Error> {
923 let handler = self.build().map_err(|e| {
924 lambda_runtime::Error::from(format!("LambdaA2aServerBuilder::run: {e}"))
925 })?;
926 handler.run().await
927 }
928}
929
930#[cfg(test)]
931mod handle_http_event_value_shape_tests {
932 //! Regression tests for the event-shape symmetry contract on
933 //! [`LambdaA2aHandler::handle_http_event_value`]. The wire-shape
934 //! mismatch (v2 response to a v1 invocation) is what causes API
935 //! Gateway REST integrations to return `502 Bad Gateway`. These
936 //! tests pin the contract: response envelope must always match
937 //! the inbound request envelope.
938
939 use super::*;
940 use std::sync::Arc;
941 use turul_a2a::executor::{AgentExecutor, ExecutionContext};
942 use turul_a2a::server::RuntimeConfig;
943 use turul_a2a::server::in_flight::InFlightRegistry;
944 use turul_a2a::storage::InMemoryA2aStorage;
945 use turul_a2a::streaming::TaskEventBroker;
946 use turul_a2a_types::{Message, Task};
947
948 struct NoOpExecutor;
949
950 #[async_trait::async_trait]
951 impl AgentExecutor for NoOpExecutor {
952 async fn execute(
953 &self,
954 task: &mut Task,
955 _msg: &Message,
956 _ctx: &ExecutionContext,
957 ) -> Result<(), turul_a2a::error::A2aError> {
958 let mut proto = task.as_proto().clone();
959 proto.status = Some(turul_a2a_proto::TaskStatus {
960 state: turul_a2a_proto::TaskState::Completed.into(),
961 message: None,
962 timestamp: None,
963 });
964 *task = Task::try_from(proto).unwrap();
965 Ok(())
966 }
967 fn agent_card(&self) -> turul_a2a_proto::AgentCard {
968 turul_a2a_proto::AgentCard {
969 name: "test-agent".to_string(),
970 ..Default::default()
971 }
972 }
973 }
974
975 fn build_handler() -> LambdaA2aHandler {
976 let s = Arc::new(InMemoryA2aStorage::new());
977 let state = AppState {
978 executor: Arc::new(NoOpExecutor),
979 task_storage: s.clone(),
980 push_storage: s.clone(),
981 event_store: s.clone(),
982 atomic_store: s.clone(),
983 event_broker: TaskEventBroker::new(),
984 middleware_stack: Arc::new(MiddlewareStack::new(vec![])),
985 runtime_config: RuntimeConfig::default(),
986 in_flight: Arc::new(InFlightRegistry::new()),
987 cancellation_supervisor: s.clone(),
988 push_delivery_store: None,
989 push_dispatcher: None,
990 durable_executor_queue: None,
991 };
992 let router = build_router(state.clone());
993 LambdaA2aHandler {
994 router,
995 state,
996 path_prefix: None,
997 }
998 }
999
1000 /// API Gateway v2 / Function URL event. `requestContext.http.method`
1001 /// is what `LambdaRequest::ApiGatewayV2` keys off.
1002 fn apigw_v2_agent_card_get() -> serde_json::Value {
1003 serde_json::json!({
1004 "version": "2.0",
1005 "routeKey": "GET /.well-known/agent-card.json",
1006 "rawPath": "/.well-known/agent-card.json",
1007 "rawQueryString": "",
1008 "headers": {"accept": "application/json", "a2a-version": "1.0"},
1009 "requestContext": {
1010 "accountId": "000000000000",
1011 "apiId": "api",
1012 "domainName": "fake.execute-api",
1013 "domainPrefix": "fake",
1014 "http": {
1015 "method": "GET",
1016 "path": "/.well-known/agent-card.json",
1017 "protocol": "HTTP/1.1",
1018 "sourceIp": "127.0.0.1",
1019 "userAgent": "test"
1020 },
1021 "requestId": "rid",
1022 "routeKey": "GET /.well-known/agent-card.json",
1023 "stage": "$default",
1024 "time": "01/Jan/2026:00:00:00 +0000",
1025 "timeEpoch": 1_735_689_600_000i64
1026 },
1027 "isBase64Encoded": false
1028 })
1029 }
1030
1031 /// API Gateway v1 (REST) event. Top-level `httpMethod` + `path` and
1032 /// `requestContext.identity` (no `requestContext.http`) is what
1033 /// `LambdaRequest::ApiGatewayV1` keys off. This is the shape REST
1034 /// API + AWS_PROXY integrations send into the Lambda — the live
1035 /// fleet topology that 502'd against a hardcoded v2 response.
1036 ///
1037 /// `stage` is `$default` here so `lambda_http` does not prepend a
1038 /// stage prefix — this fixture exists to pin the response-shape
1039 /// contract, not the path-rewriting behaviour. See the
1040 /// `strip_path_prefix_*` tests for stage-prefix coverage.
1041 fn apigw_v1_agent_card_get_with_stage(stage: &str, path: &str) -> serde_json::Value {
1042 let request_context_path = if stage == "$default" {
1043 path.to_string()
1044 } else {
1045 format!("/{stage}{path}")
1046 };
1047 serde_json::json!({
1048 "resource": "/{proxy+}",
1049 "path": path,
1050 "httpMethod": "GET",
1051 "headers": {"accept": "application/json", "a2a-version": "1.0"},
1052 "multiValueHeaders": {},
1053 "queryStringParameters": null,
1054 "multiValueQueryStringParameters": null,
1055 "pathParameters": {"proxy": path.trim_start_matches('/').to_string()},
1056 "stageVariables": null,
1057 "requestContext": {
1058 "accountId": "000000000000",
1059 "apiId": "abc123",
1060 "domainName": "fake.execute-api",
1061 "domainPrefix": "fake",
1062 "extendedRequestId": "xrid",
1063 "httpMethod": "GET",
1064 "identity": {
1065 "sourceIp": "127.0.0.1",
1066 "userAgent": "test"
1067 },
1068 "path": request_context_path,
1069 "protocol": "HTTP/1.1",
1070 "requestId": "rid",
1071 "requestTime": "01/Jan/2026:00:00:00 +0000",
1072 "requestTimeEpoch": 1_735_689_600_000i64,
1073 "resourceId": "rsrc",
1074 "resourcePath": "/{proxy+}",
1075 "stage": stage
1076 },
1077 "body": null,
1078 "isBase64Encoded": false
1079 })
1080 }
1081
1082 fn apigw_v1_agent_card_get() -> serde_json::Value {
1083 apigw_v1_agent_card_get_with_stage("$default", "/.well-known/agent-card.json")
1084 }
1085
1086 /// ALB target-group event. `requestContext.elb` is what
1087 /// `LambdaRequest::Alb` keys off.
1088 fn alb_agent_card_get() -> serde_json::Value {
1089 serde_json::json!({
1090 "requestContext": {
1091 "elb": {
1092 "targetGroupArn": "arn:aws:elasticloadbalancing:ap-southeast-2:000:targetgroup/fake/00"
1093 }
1094 },
1095 "httpMethod": "GET",
1096 "path": "/.well-known/agent-card.json",
1097 "queryStringParameters": {},
1098 "headers": {"accept": "application/json", "a2a-version": "1.0"},
1099 "body": "",
1100 "isBase64Encoded": false
1101 })
1102 }
1103
1104 /// REST v1 inbound MUST produce a v1 response shape. This is the
1105 /// regression for the live-fleet 502.
1106 #[tokio::test]
1107 async fn v1_inbound_event_emits_v1_response_envelope() {
1108 let handler = build_handler();
1109 let resp_value = handler
1110 .handle_http_event_value(apigw_v1_agent_card_get())
1111 .await
1112 .expect("handle_http_event_value(v1) must succeed");
1113
1114 // Parses cleanly as v1.
1115 let v1: aws_lambda_events::apigw::ApiGatewayProxyResponse =
1116 serde_json::from_value(resp_value.clone())
1117 .expect("response must deserialize as ApiGatewayProxyResponse (v1)");
1118 assert_eq!(v1.status_code, 200);
1119 match v1.body {
1120 Some(aws_lambda_events::encodings::Body::Text(s)) => {
1121 assert!(s.contains("\"name\""), "v1 body shape: {s}");
1122 }
1123 other => panic!("expected text body, got {other:?}"),
1124 }
1125
1126 // Negative: v1 response JSON must NOT contain the v2-only
1127 // `cookies` field. Presence of `cookies` is API Gateway REST's
1128 // 502 trigger.
1129 assert!(
1130 resp_value.get("cookies").is_none(),
1131 "v1 response must not carry v2-only `cookies` field; payload: {resp_value}"
1132 );
1133 }
1134
1135 /// API Gateway v2 / Function URL inbound MUST produce a v2 response
1136 /// shape (current behaviour, locked in to prevent the inverse
1137 /// regression).
1138 #[tokio::test]
1139 async fn v2_inbound_event_emits_v2_response_envelope() {
1140 let handler = build_handler();
1141 let resp_value = handler
1142 .handle_http_event_value(apigw_v2_agent_card_get())
1143 .await
1144 .expect("handle_http_event_value(v2) must succeed");
1145
1146 let v2: aws_lambda_events::apigw::ApiGatewayV2httpResponse =
1147 serde_json::from_value(resp_value.clone())
1148 .expect("response must deserialize as ApiGatewayV2httpResponse (v2)");
1149 assert_eq!(v2.status_code, 200);
1150 match v2.body {
1151 Some(aws_lambda_events::encodings::Body::Text(s)) => {
1152 assert!(s.contains("\"name\""), "v2 body shape: {s}");
1153 }
1154 other => panic!("expected text body, got {other:?}"),
1155 }
1156 }
1157
1158 /// ALB inbound MUST produce an ALB response shape.
1159 #[tokio::test]
1160 async fn alb_inbound_event_emits_alb_response_envelope() {
1161 let handler = build_handler();
1162 let resp_value = handler
1163 .handle_http_event_value(alb_agent_card_get())
1164 .await
1165 .expect("handle_http_event_value(alb) must succeed");
1166
1167 let alb: aws_lambda_events::alb::AlbTargetGroupResponse =
1168 serde_json::from_value(resp_value)
1169 .expect("response must deserialize as AlbTargetGroupResponse");
1170 assert_eq!(alb.status_code, 200);
1171 }
1172
1173 /// Live-fleet end-to-end regression: REST v1 stage-prefixed event
1174 /// + `strip_path_prefix("/dev")` on the handler routes through
1175 /// the agent-card endpoint AND emits a v1 response envelope. This
1176 /// is the exact scenario the live fleet was 502'ing on.
1177 #[tokio::test]
1178 async fn v1_stage_prefix_inbound_with_strip_emits_v1_response() {
1179 let s = Arc::new(InMemoryA2aStorage::new());
1180 let state = AppState {
1181 executor: Arc::new(NoOpExecutor),
1182 task_storage: s.clone(),
1183 push_storage: s.clone(),
1184 event_store: s.clone(),
1185 atomic_store: s.clone(),
1186 event_broker: TaskEventBroker::new(),
1187 middleware_stack: Arc::new(MiddlewareStack::new(vec![])),
1188 runtime_config: RuntimeConfig::default(),
1189 in_flight: Arc::new(InFlightRegistry::new()),
1190 cancellation_supervisor: s.clone(),
1191 push_delivery_store: None,
1192 push_dispatcher: None,
1193 durable_executor_queue: None,
1194 };
1195 let router = build_router(state.clone());
1196 let handler = LambdaA2aHandler {
1197 router,
1198 state,
1199 path_prefix: Some(Arc::from("/dev")),
1200 };
1201
1202 let event = apigw_v1_agent_card_get_with_stage("dev", "/.well-known/agent-card.json");
1203 let resp_value = handler
1204 .handle_http_event_value(event)
1205 .await
1206 .expect("v1 stage-prefixed event must succeed under strip_path_prefix");
1207
1208 let v1: aws_lambda_events::apigw::ApiGatewayProxyResponse =
1209 serde_json::from_value(resp_value)
1210 .expect("response must deserialize as ApiGatewayProxyResponse");
1211 assert_eq!(v1.status_code, 200);
1212 match v1.body {
1213 Some(aws_lambda_events::encodings::Body::Text(s)) => {
1214 assert!(s.contains("\"name\""), "v1 stage-prefix body: {s}");
1215 }
1216 other => panic!("expected text body, got {other:?}"),
1217 }
1218 }
1219
1220 /// Cross-shape decoding regression: a v1 response JSON carries
1221 /// `multiValueHeaders` (REST shape) but no `cookies`; a v2 response
1222 /// carries `cookies` but no v1-only `multiValueHeaders` semantics.
1223 /// Confirms the two shapes are wire-distinguishable, which is why
1224 /// the gateway 502s on a mismatch.
1225 #[tokio::test]
1226 async fn v1_response_does_not_match_v2_envelope_strictly() {
1227 let handler = build_handler();
1228 let v1_value = handler
1229 .handle_http_event_value(apigw_v1_agent_card_get())
1230 .await
1231 .unwrap();
1232
1233 // Sanity: v1 response JSON has no v2-only `cookies` field.
1234 assert!(v1_value.get("cookies").is_none());
1235
1236 let v2_value = handler
1237 .handle_http_event_value(apigw_v2_agent_card_get())
1238 .await
1239 .unwrap();
1240 // Sanity: v2 response JSON carries the v2 `cookies` field
1241 // (default empty array — still present on the wire).
1242 assert!(
1243 v2_value.get("cookies").is_some(),
1244 "v2 response should carry the v2-only cookies field"
1245 );
1246 }
1247}