Skip to main content

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, replays stored events via `Last-Event-ID`, and closes
130//!   when the task reaches a terminal state. 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. Clients reconnect with
164//! `Last-Event-ID` for continuation.
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}
258
259impl LambdaA2aServerBuilder {
260    pub fn new() -> Self {
261        Self {
262            executor: None,
263            task_storage: None,
264            push_storage: None,
265            event_store: None,
266            atomic_store: None,
267            cancellation_supervisor: None,
268            push_delivery_store: None,
269            middleware: vec![],
270            runtime_config: RuntimeConfig::default(),
271            durable_executor_queue: None,
272            path_prefix: None,
273        }
274    }
275
276    /// Configure an HTTP path prefix to strip before the A2A router
277    /// sees the request. Needed when Lambda sits behind an API Gateway
278    /// whose stage + resource tree is forwarded into the function
279    /// (e.g. REST API `AWS_PROXY` integrations surface
280    /// `/stage/agent/message:send` where the A2A
281    /// router expects `/message:send`).
282    ///
283    /// The prefix must start with `/` and must not end with `/`
284    /// (unless it is exactly `/`, which is a no-op). Segment boundaries
285    /// are respected — a prefix of `/dev` will not strip `/devs/...`.
286    /// Paths that do not start with the prefix pass through unchanged
287    /// (the router will 404 on a genuinely unknown path, which is the
288    /// correct failure mode). Applies to both
289    /// [`LambdaA2aHandler::run_http_only`] and
290    /// [`LambdaA2aHandler::run_http_and_sqs`]. SQS events are
291    /// unaffected.
292    pub fn strip_path_prefix(mut self, prefix: impl Into<String>) -> Self {
293        self.path_prefix = Some(prefix.into());
294        self
295    }
296
297    /// Wire a durable executor queue. When set, the
298    /// `return_immediately = true` path in `core_send_message` enqueues
299    /// a [`turul_a2a::durable_executor::QueuedExecutorJob`] on this
300    /// queue instead of spawning the executor locally, and the
301    /// capability flag `RuntimeConfig::supports_return_immediately` is
302    /// turned **back on** as an implementation detail — the capability
303    /// cannot be claimed without supplying the queue.
304    ///
305    /// Adopters should typically reach for the SQS-specific helper
306    /// [`Self::with_sqs_return_immediately`] instead; this generic
307    /// method exists so adopters can inject in-memory fakes for tests
308    /// or provide non-SQS transports (Kinesis, Step Functions task
309    /// token, self-invoke, etc.).
310    pub fn with_durable_executor(
311        mut self,
312        queue: Arc<dyn turul_a2a::durable_executor::DurableExecutorQueue>,
313    ) -> Self {
314        self.durable_executor_queue = Some(queue);
315        self.runtime_config.supports_return_immediately = true;
316        self
317    }
318
319    /// Wire the AWS SQS durable executor queue. Ergonomic
320    /// helper over [`Self::with_durable_executor`] that constructs a
321    /// [`SqsDurableExecutorQueue`] from a `queue_url` + shared SQS
322    /// client. Requires the `sqs` feature.
323    #[cfg(feature = "sqs")]
324    pub fn with_sqs_return_immediately(
325        self,
326        queue_url: impl Into<String>,
327        sqs_client: Arc<aws_sdk_sqs::Client>,
328    ) -> Self {
329        let queue = Arc::new(SqsDurableExecutorQueue::new(queue_url, sqs_client));
330        self.with_durable_executor(queue)
331    }
332
333    pub fn executor(mut self, exec: impl AgentExecutor + 'static) -> Self {
334        self.executor = Some(Arc::new(exec));
335        self
336    }
337
338    /// Set all storage from a single backend instance.
339    ///
340    /// This is the **preferred** method — a single struct implementing all
341    /// storage traits guarantees the same-backend requirement
342    /// AND ensures the cancellation supervisor reads the same backend
343    /// the cancel marker is written to. A mismatch here (e.g., DynamoDB
344    /// task storage + in-memory cancellation supervisor) silently
345    /// breaks cross-instance cancellation.
346    ///
347    /// errata: `.storage()` wires storage traits only. It does
348    /// **not** auto-register the storage as a push-delivery store, even if
349    /// the backend happens to implement [`A2aPushDeliveryStore`]. To opt in
350    /// to push delivery, call [`Self::push_delivery_store`] explicitly and
351    /// call `with_push_dispatch_enabled(true)` on the storage instance
352    /// before passing it here. Non-push deployments need neither.
353    pub fn storage<S>(mut self, storage: S) -> Self
354    where
355        S: A2aTaskStorage
356            + A2aPushNotificationStorage
357            + A2aEventStore
358            + A2aAtomicStore
359            + A2aCancellationSupervisor
360            + Clone
361            + 'static,
362    {
363        self.task_storage = Some(Arc::new(storage.clone()));
364        self.push_storage = Some(Arc::new(storage.clone()));
365        self.event_store = Some(Arc::new(storage.clone()));
366        self.atomic_store = Some(Arc::new(storage.clone()));
367        self.cancellation_supervisor = Some(Arc::new(storage));
368        self
369    }
370
371    /// Set task storage individually. Must be paired with event_store/atomic_store
372    /// AND `cancellation_supervisor()` for same-backend compliance.
373    pub fn task_storage(mut self, s: impl A2aTaskStorage + 'static) -> Self {
374        self.task_storage = Some(Arc::new(s));
375        self
376    }
377
378    /// Set push notification storage individually.
379    pub fn push_storage(mut self, s: impl A2aPushNotificationStorage + 'static) -> Self {
380        self.push_storage = Some(Arc::new(s));
381        self
382    }
383
384    /// Set event store individually. Must match task_storage backend.
385    pub fn event_store(mut self, s: impl A2aEventStore + 'static) -> Self {
386        self.event_store = Some(Arc::new(s));
387        self
388    }
389
390    /// Set atomic store individually. Must match task_storage backend.
391    pub fn atomic_store(mut self, s: impl A2aAtomicStore + 'static) -> Self {
392        self.atomic_store = Some(Arc::new(s));
393        self
394    }
395
396    /// Set the cancellation supervisor individually. Must match
397    /// task_storage backend — otherwise `:cancel` writes the marker to
398    /// one backend and the supervisor reads from another, silently
399    /// breaking cross-instance cancellation. Prefer `.storage()` for
400    /// unified wiring. Consumed by `core_cancel_task`.
401    pub fn cancellation_supervisor(mut self, s: impl A2aCancellationSupervisor + 'static) -> Self {
402        self.cancellation_supervisor = Some(Arc::new(s));
403        self
404    }
405
406    /// Set the push delivery store individually.
407    ///
408    /// Prefer `.storage()` for unified wiring. The delivery store MUST
409    /// be on the same backend as `.task_storage(...)` — the builder
410    /// rejects mismatches. Passing a delivery store also requires the
411    /// atomic store to have opted in via `with_push_dispatch_enabled(true)`
412    ///.
413    pub fn push_delivery_store(mut self, store: impl A2aPushDeliveryStore + 'static) -> Self {
414        self.push_delivery_store = Some(Arc::new(store));
415        self
416    }
417
418    /// Override the runtime configuration (timeouts, retry budgets,
419    /// push tuning). Defaults to [`RuntimeConfig::default()`]. The
420    /// builder validates push settings (claim expiry vs retry horizon,
421    /// ) when `.push_delivery_store(...)` is wired.
422    pub fn runtime_config(mut self, cfg: RuntimeConfig) -> Self {
423        self.runtime_config = cfg;
424        self
425    }
426
427    pub fn middleware(mut self, mw: Arc<dyn A2aMiddleware>) -> Self {
428        self.middleware.push(mw);
429        self
430    }
431
432    pub fn build(self) -> Result<LambdaA2aHandler, A2aError> {
433        let executor = self
434            .executor
435            .ok_or(A2aError::Internal("executor is required".into()))?;
436        let task_storage = self.task_storage.ok_or(A2aError::Internal(
437            "task_storage is required for Lambda".into(),
438        ))?;
439        let push_storage = self.push_storage.ok_or(A2aError::Internal(
440            "push_storage is required for Lambda".into(),
441        ))?;
442        let event_store: Arc<dyn A2aEventStore> = self.event_store.ok_or(A2aError::Internal(
443            "event_store is required for Lambda (use .storage() for unified backend)".into(),
444        ))?;
445        let atomic_store: Arc<dyn A2aAtomicStore> = self.atomic_store.ok_or(A2aError::Internal(
446            "atomic_store is required for Lambda (use .storage() for unified backend)".into(),
447        ))?;
448        // the cancellation supervisor MUST be supplied. No
449        // InMemoryA2aStorage fallback: that would silently break
450        // cross-instance cancellation by reading markers from a
451        // different backend than they were written to.
452        let cancellation_supervisor: Arc<dyn A2aCancellationSupervisor> =
453            self.cancellation_supervisor.ok_or(A2aError::Internal(
454                "cancellation_supervisor is required for Lambda. Use .storage() for unified \
455                 backend wiring, or .cancellation_supervisor(...) alongside the individual \
456                 storage setters. Omitting it silently breaks cross-instance cancellation."
457                    .into(),
458            ))?;
459
460        // Same-backend enforcement: all storage traits + the
461        // cancellation supervisor must report the same `backend_name`.
462        let task_backend = task_storage.backend_name();
463        let push_backend = push_storage.backend_name();
464        let event_backend = event_store.backend_name();
465        let atomic_backend = atomic_store.backend_name();
466        let supervisor_backend = cancellation_supervisor.backend_name();
467        if task_backend != push_backend
468            || task_backend != event_backend
469            || task_backend != atomic_backend
470            || task_backend != supervisor_backend
471        {
472            return Err(A2aError::Internal(format!(
473                "Storage backend mismatch: task={task_backend}, push={push_backend}, \
474                 event={event_backend}, atomic={atomic_backend}, \
475                 cancellation_supervisor={supervisor_backend}. \
476  requires all storage traits to share the same backend. \
477  requires the cancellation supervisor on the same backend \
478                 so cross-instance cancel markers are observable. \
479                 Use .storage() for unified backend."
480            )));
481        }
482
483        let push_delivery_store = self.push_delivery_store;
484
485        // Push-dispatch consistency: the atomic store's
486        // opt-in flag and the presence of `push_delivery_store` MUST
487        // agree. Both-true = push fully wired; both-false = non-push
488        // deployment. Mixed cases are build errors — this mirrors the
489        // main server builder (server/mod.rs).
490        match (
491            push_delivery_store.is_some(),
492            atomic_store.push_dispatch_enabled(),
493        ) {
494            (true, true) | (false, false) => {}
495            (true, false) => {
496                return Err(A2aError::Internal(
497                    "push_delivery_store wired but atomic_store.push_dispatch_enabled() \
498                     is false. Call .with_push_dispatch_enabled(true) on the backend \
499                     storage before passing it to .storage()."
500                        .into(),
501                ));
502            }
503            (false, true) => {
504                return Err(A2aError::Internal(
505                    "atomic_store.push_dispatch_enabled() is true but no \
506                     push_delivery_store is wired. Pending-dispatch markers would be \
507                     written with no consumer, imposing load-bearing infra for no \
508                     benefit. If you need to populate markers for an external \
509                     consumer, open an issue for a distinctly-named opt-in — for now, \
510                     this configuration is rejected."
511                        .into(),
512                ));
513            }
514        }
515
516        // §Decision Bug 1: the Lambda execution environment
517        // freezes after the HTTP response is flushed, so any
518        // `tokio::spawn`'d executor continuation is opportunistic only
519        //. Refuse `SendMessageConfiguration.return_immediately
520        // = true` at the `core_send_message` entry point via this
521        // capability flag instead of silently orphaning the executor.
522        //
523        // if a durable executor queue is wired via
524        // [`Self::with_durable_executor`] (or the SQS helper), the
525        // capability is re-enabled because enqueueing is durable
526        // across the Lambda freeze. The explicit re-enable lives in
527        // the builder method so the capability cannot be claimed
528        // without the mechanism.
529        let mut runtime_config = self.runtime_config;
530        if self.durable_executor_queue.is_none() {
531            runtime_config.supports_return_immediately = false;
532        }
533
534        // Push dispatcher wiring. When
535        // `push_delivery_store` is present, validate its backend matches,
536        // validate the retry-horizon invariant, and construct the
537        // `PushDispatcher`. Under Lambda the dispatcher runs
538        // opportunistically post-return; correctness
539        // comes from the atomic marker + stream/scheduler recovery.
540        let push_dispatcher: Option<Arc<turul_a2a::push::PushDispatcher>> =
541            if let Some(delivery) = push_delivery_store.as_ref() {
542                let push_delivery_backend = delivery.backend_name();
543                if task_backend != push_delivery_backend {
544                    return Err(A2aError::Internal(format!(
545                        "Storage backend mismatch: task={task_backend}, \
546                         push_delivery={push_delivery_backend}. \
547  requires all storage traits to share the same backend."
548                    )));
549                }
550
551                // claim expiry must exceed the worst-case
552                // retry horizon so a live claim is not mis-classified as
553                // stale mid-retry.
554                let retry_horizon = runtime_config
555                    .push_backoff_cap
556                    .saturating_mul(runtime_config.push_max_attempts as u32);
557                if runtime_config.push_claim_expiry <= retry_horizon {
558                    return Err(A2aError::Internal(format!(
559                        "push_claim_expiry ({:?}) must be greater than retry horizon \
560                         (push_max_attempts={} * push_backoff_cap={:?} = {:?}). \
561                         Raise push_claim_expiry or lower push_max_attempts/push_backoff_cap.",
562                        runtime_config.push_claim_expiry,
563                        runtime_config.push_max_attempts,
564                        runtime_config.push_backoff_cap,
565                        retry_horizon
566                    )));
567                }
568
569                let mut delivery_cfg = turul_a2a::push::delivery::PushDeliveryConfig::default();
570                delivery_cfg.max_attempts = runtime_config.push_max_attempts as u32;
571                delivery_cfg.backoff_base = runtime_config.push_backoff_base;
572                delivery_cfg.backoff_cap = runtime_config.push_backoff_cap;
573                delivery_cfg.backoff_jitter = runtime_config.push_backoff_jitter;
574                delivery_cfg.request_timeout = runtime_config.push_request_timeout;
575                delivery_cfg.connect_timeout = runtime_config.push_connect_timeout;
576                delivery_cfg.read_timeout = runtime_config.push_read_timeout;
577                delivery_cfg.claim_expiry = runtime_config.push_claim_expiry;
578                delivery_cfg.max_payload_bytes = runtime_config.push_max_payload_bytes;
579                delivery_cfg.allow_insecure_urls = runtime_config.allow_insecure_push_urls;
580
581                let instance_id = format!("a2a-lambda-{}", uuid::Uuid::now_v7());
582                let worker = turul_a2a::push::delivery::PushDeliveryWorker::new(
583                    delivery.clone(),
584                    delivery_cfg,
585                    None,
586                    instance_id,
587                )
588                .map_err(|e| A2aError::Internal(format!("push worker build failed: {e}")))?;
589
590                Some(Arc::new(turul_a2a::push::PushDispatcher::new(
591                    Arc::new(worker),
592                    push_storage.clone(),
593                    task_storage.clone(),
594                )))
595            } else {
596                None
597            };
598
599        let state = AppState {
600            executor,
601            task_storage,
602            push_storage,
603            event_store,
604            atomic_store,
605            event_broker: TaskEventBroker::new(),
606            middleware_stack: Arc::new(MiddlewareStack::new(self.middleware)),
607            runtime_config,
608            in_flight: Arc::new(turul_a2a::server::in_flight::InFlightRegistry::new()),
609            cancellation_supervisor,
610            push_delivery_store,
611            push_dispatcher,
612            durable_executor_queue: self.durable_executor_queue,
613        };
614
615        let router = build_router(state.clone());
616
617        let path_prefix = match self.path_prefix {
618            None => None,
619            Some(p) if p.is_empty() || p == "/" => None,
620            Some(p) => {
621                if !p.starts_with('/') {
622                    return Err(A2aError::InvalidRequest {
623                        message: format!(
624                            "LambdaA2aServerBuilder::strip_path_prefix: prefix must start with '/'; got {p:?}"
625                        ),
626                    });
627                }
628                if p.ends_with('/') {
629                    return Err(A2aError::InvalidRequest {
630                        message: format!(
631                            "LambdaA2aServerBuilder::strip_path_prefix: prefix must not end with '/' (except '/'); got {p:?}"
632                        ),
633                    });
634                }
635                Some(Arc::from(p))
636            }
637        };
638
639        Ok(LambdaA2aHandler {
640            router,
641            state,
642            path_prefix,
643        })
644    }
645}
646
647impl Default for LambdaA2aServerBuilder {
648    fn default() -> Self {
649        Self::new()
650    }
651}
652
653/// Lambda handler wrapping the axum Router.
654#[derive(Clone)]
655pub struct LambdaA2aHandler {
656    router: axum::Router,
657    /// Held for SQS-event dispatch (`handle_sqs`). Always
658    /// populated — the SQS handler method is gated behind the `sqs`
659    /// feature but the state is carried unconditionally so callers can
660    /// reach it for diagnostics or future non-HTTP / non-SQS handlers.
661    #[cfg_attr(not(feature = "sqs"), allow(dead_code))]
662    state: AppState,
663    /// Leading path segment to strip from each incoming HTTP request
664    /// before the A2A router sees it. `None` = no stripping. Set via
665    /// [`LambdaA2aServerBuilder::strip_path_prefix`].
666    path_prefix: Option<Arc<str>>,
667}
668
669impl LambdaA2aHandler {
670    pub fn builder() -> LambdaA2aServerBuilder {
671        LambdaA2aServerBuilder::new()
672    }
673
674    /// Handle a Lambda HTTP request.
675    pub async fn handle(
676        &self,
677        event: lambda_http::Request,
678    ) -> Result<lambda_http::Response<lambda_http::Body>, lambda_http::Error> {
679        let axum_req = lambda_to_axum_request(event)?;
680        let axum_req = match &self.path_prefix {
681            Some(prefix) => adapter::strip_request_path_prefix(axum_req, prefix),
682            None => axum_req,
683        };
684
685        let axum_resp = tower::ServiceExt::oneshot(self.router.clone(), axum_req)
686            .await
687            .map_err(|e| lambda_http::Error::from(format!("Router error: {e}")))?;
688
689        axum_to_lambda_response(axum_resp).await
690    }
691
692    /// Handle a raw Lambda HTTP event delivered as `serde_json::Value`
693    /// and return a response envelope **matching the inbound event
694    /// shape**:
695    ///
696    /// | Inbound shape detected by `lambda_http::LambdaRequest`   | Response envelope                  |
697    /// |----------------------------------------------------------|------------------------------------|
698    /// | API Gateway v1 (REST) — top-level `httpMethod` + `path`  | `ApiGatewayProxyResponse`          |
699    /// | API Gateway v2 / Function URL — `requestContext.http`    | `ApiGatewayV2httpResponse`         |
700    /// | ALB target group — `requestContext.elb`                  | `AlbTargetGroupResponse`           |
701    /// | WebSocket / unrecognised                                  | `Err(...)`                         |
702    ///
703    /// Mismatching envelopes — most commonly a v2 response sent in
704    /// response to a v1 invocation — cause API Gateway to return
705    /// `502 Bad Gateway` regardless of the body, because the response
706    /// fails the gateway's contract validation. This method ensures
707    /// symmetry: response shape is always picked from the inbound
708    /// shape, never hardcoded.
709    ///
710    /// This is the framework's canonical HTTP envelope conversion
711    /// primitive — useful when a single Lambda function routes among
712    /// HTTP and one or more non-framework triggers (EventBridge,
713    /// DynamoDB streams, custom invoke) and the adopter drives
714    /// [`lambda_runtime::run`] with `serde_json::Value` directly.
715    /// Handles the `LambdaRequest` deserialization, the text-vs-base64
716    /// content-type detection, and the response envelope rebuild.
717    ///
718    /// Body encoding: text for `text/*`, `application/json`,
719    /// `application/xml`, `application/javascript`, or anything with
720    /// `charset=`; base64 otherwise.
721    ///
722    /// Path-prefix stripping (see
723    /// [`LambdaA2aServerBuilder::strip_path_prefix`]) is applied
724    /// because dispatch flows through [`Self::handle`]. Adopters who
725    /// only serve HTTP should continue to use [`Self::run_http_only`]
726    /// or [`LambdaA2aServerBuilder::run`]; this entry point exists for
727    /// composition with adopter-owned third triggers.
728    pub async fn handle_http_event_value(
729        &self,
730        value: serde_json::Value,
731    ) -> Result<serde_json::Value, lambda_runtime::Error> {
732        use base64::Engine;
733        use http_body_util::BodyExt;
734
735        let lambda_req: lambda_http::request::LambdaRequest = serde_json::from_value(value)
736            .map_err(|e| lambda_runtime::Error::from(format!("invalid HTTP event: {e}")))?;
737
738        // Capture the inbound shape so we can emit the matching
739        // response envelope. Lost once we convert to `lambda_http::Request`.
740        let shape = match &lambda_req {
741            lambda_http::request::LambdaRequest::ApiGatewayV1(_) => HttpEventShape::ApiGatewayV1,
742            lambda_http::request::LambdaRequest::ApiGatewayV2(_) => HttpEventShape::ApiGatewayV2,
743            lambda_http::request::LambdaRequest::Alb(_) => HttpEventShape::Alb,
744            lambda_http::request::LambdaRequest::WebSocket(_) => {
745                return Err(lambda_runtime::Error::from(
746                    "WebSocket Lambda events are not supported by this adapter",
747                ));
748            }
749            _ => {
750                return Err(lambda_runtime::Error::from(
751                    "unsupported Lambda HTTP event variant",
752                ));
753            }
754        };
755
756        let req: lambda_http::Request = lambda_req.into();
757
758        let resp = self
759            .handle(req)
760            .await
761            .map_err(|e| lambda_runtime::Error::from(format!("handler error: {e}")))?;
762        let (parts, body) = resp.into_parts();
763
764        let bytes = body
765            .collect()
766            .await
767            .map_err(|e| lambda_runtime::Error::from(format!("body collect: {e}")))?
768            .to_bytes();
769
770        let ct = parts
771            .headers
772            .get(http::header::CONTENT_TYPE)
773            .and_then(|v| v.to_str().ok())
774            .unwrap_or("application/octet-stream")
775            .to_ascii_lowercase();
776        let is_text = ct.starts_with("text/")
777            || ct.starts_with("application/json")
778            || ct.starts_with("application/xml")
779            || ct.starts_with("application/javascript")
780            || ct.contains("charset=");
781
782        let (body_str, is_base64) = if bytes.is_empty() {
783            (None, false)
784        } else if is_text {
785            match std::str::from_utf8(&bytes) {
786                Ok(s) => (Some(s.to_string()), false),
787                Err(_) => (
788                    Some(base64::engine::general_purpose::STANDARD.encode(&bytes)),
789                    true,
790                ),
791            }
792        } else {
793            (
794                Some(base64::engine::general_purpose::STANDARD.encode(&bytes)),
795                true,
796            )
797        };
798
799        let status = parts.status.as_u16() as i64;
800        let headers = parts.headers;
801        let body_lambda = body_str.map(aws_lambda_events::encodings::Body::Text);
802
803        match shape {
804            HttpEventShape::ApiGatewayV1 => {
805                let mut api_resp = aws_lambda_events::apigw::ApiGatewayProxyResponse::default();
806                api_resp.status_code = status;
807                api_resp.headers = headers;
808                api_resp.body = body_lambda;
809                api_resp.is_base64_encoded = is_base64;
810                serde_json::to_value(api_resp).map_err(|e| {
811                    lambda_runtime::Error::from(format!("serialise APIGW v1 response: {e}"))
812                })
813            }
814            HttpEventShape::ApiGatewayV2 => {
815                let mut api_resp = aws_lambda_events::apigw::ApiGatewayV2httpResponse::default();
816                api_resp.status_code = status;
817                api_resp.headers = headers;
818                api_resp.body = body_lambda;
819                api_resp.is_base64_encoded = is_base64;
820                serde_json::to_value(api_resp).map_err(|e| {
821                    lambda_runtime::Error::from(format!("serialise APIGW v2 response: {e}"))
822                })
823            }
824            HttpEventShape::Alb => {
825                let mut api_resp = aws_lambda_events::alb::AlbTargetGroupResponse::default();
826                api_resp.status_code = status;
827                api_resp.headers = headers;
828                api_resp.body = body_lambda;
829                api_resp.is_base64_encoded = is_base64;
830                serde_json::to_value(api_resp).map_err(|e| {
831                    lambda_runtime::Error::from(format!("serialise ALB response: {e}"))
832                })
833            }
834        }
835    }
836}
837
838/// Inbound HTTP event shape detected by [`LambdaA2aHandler::handle_http_event_value`].
839///
840/// The response envelope must match the inbound shape — see method
841/// docs for the contract.
842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
843enum HttpEventShape {
844    ApiGatewayV1,
845    ApiGatewayV2,
846    Alb,
847}
848
849impl LambdaA2aHandler {
850    /// Handle an SQS batch from the durable executor queue.
851    ///
852    /// Returns `SqsBatchResponse` whose `batch_item_failures` list
853    /// tells the event source mapping which records to retry.
854    /// Requires `FunctionResponseTypes: ["ReportBatchItemFailures"]`
855    /// on the mapping.
856    ///
857    /// Each record: deserialize envelope → load task → terminal-no-op
858    /// check → cancel-marker direct-CANCELED commit → run executor.
859    /// See `durable::drive_sqs_batch` for the full semantics.
860    #[cfg(feature = "sqs")]
861    pub async fn handle_sqs(
862        &self,
863        event: aws_lambda_events::event::sqs::SqsEvent,
864    ) -> aws_lambda_events::event::sqs::SqsBatchResponse {
865        durable::drive_sqs_batch(&self.state, event).await
866    }
867
868    /// Run this handler as a pure HTTP Lambda. Strict: any non-HTTP
869    /// event shape (SQS, DynamoDB stream, scheduler, …) causes
870    /// `lambda_http::run` to return a deserialization error on
871    /// invocation.
872    ///
873    /// Appropriate for Lambdas whose only trigger is a Function URL,
874    /// API Gateway, or ALB. The request Lambda in the two-Lambda
875    /// durable-executor topology is the canonical caller.
876    pub async fn run_http_only(self) -> Result<(), lambda_runtime::Error> {
877        let handler = Arc::new(self);
878        lambda_http::run(lambda_http::service_fn(move |event| {
879            let h = Arc::clone(&handler);
880            async move { h.handle(event).await }
881        }))
882        .await
883    }
884}
885
886// Default entrypoint when the `sqs` feature is off — `.run()` aliases
887// the HTTP-only runner. With the `sqs` feature enabled, `.run()` lives
888// in `durable.rs` and routes HTTP+SQS via the classifier.
889#[cfg(not(feature = "sqs"))]
890impl LambdaA2aHandler {
891    /// Default Lambda runner. Dispatches based on the event shape the
892    /// binary receives. Without the `sqs` feature this is HTTP-only
893    /// (equivalent to [`LambdaA2aHandler::run_http_only`]).
894    pub async fn run(self) -> Result<(), lambda_runtime::Error> {
895        self.run_http_only().await
896    }
897}
898
899impl LambdaA2aServerBuilder {
900    /// Build and run in one call. Sugar for
901    /// `self.build()?.run().await`. Hides the handler from the adopter —
902    /// use `.build()` + `handler.run_*()` instead when the handler is
903    /// needed for unit tests, custom middleware, or an explicit
904    /// topology runner.
905    pub async fn run(self) -> Result<(), lambda_runtime::Error> {
906        let handler = self.build().map_err(|e| {
907            lambda_runtime::Error::from(format!("LambdaA2aServerBuilder::run: {e}"))
908        })?;
909        handler.run().await
910    }
911}
912
913#[cfg(test)]
914mod handle_http_event_value_shape_tests {
915    //! Regression tests for the event-shape symmetry contract on
916    //! [`LambdaA2aHandler::handle_http_event_value`]. The wire-shape
917    //! mismatch (v2 response to a v1 invocation) is what causes API
918    //! Gateway REST integrations to return `502 Bad Gateway`. These
919    //! tests pin the contract: response envelope must always match
920    //! the inbound request envelope.
921
922    use super::*;
923    use std::sync::Arc;
924    use turul_a2a::executor::{AgentExecutor, ExecutionContext};
925    use turul_a2a::server::RuntimeConfig;
926    use turul_a2a::server::in_flight::InFlightRegistry;
927    use turul_a2a::storage::InMemoryA2aStorage;
928    use turul_a2a::streaming::TaskEventBroker;
929    use turul_a2a_types::{Message, Task};
930
931    struct NoOpExecutor;
932
933    #[async_trait::async_trait]
934    impl AgentExecutor for NoOpExecutor {
935        async fn execute(
936            &self,
937            task: &mut Task,
938            _msg: &Message,
939            _ctx: &ExecutionContext,
940        ) -> Result<(), turul_a2a::error::A2aError> {
941            let mut proto = task.as_proto().clone();
942            proto.status = Some(turul_a2a_proto::TaskStatus {
943                state: turul_a2a_proto::TaskState::Completed.into(),
944                message: None,
945                timestamp: None,
946            });
947            *task = Task::try_from(proto).unwrap();
948            Ok(())
949        }
950        fn agent_card(&self) -> turul_a2a_proto::AgentCard {
951            turul_a2a_proto::AgentCard {
952                name: "test-agent".to_string(),
953                ..Default::default()
954            }
955        }
956    }
957
958    fn build_handler() -> LambdaA2aHandler {
959        let s = Arc::new(InMemoryA2aStorage::new());
960        let state = AppState {
961            executor: Arc::new(NoOpExecutor),
962            task_storage: s.clone(),
963            push_storage: s.clone(),
964            event_store: s.clone(),
965            atomic_store: s.clone(),
966            event_broker: TaskEventBroker::new(),
967            middleware_stack: Arc::new(MiddlewareStack::new(vec![])),
968            runtime_config: RuntimeConfig::default(),
969            in_flight: Arc::new(InFlightRegistry::new()),
970            cancellation_supervisor: s.clone(),
971            push_delivery_store: None,
972            push_dispatcher: None,
973            durable_executor_queue: None,
974        };
975        let router = build_router(state.clone());
976        LambdaA2aHandler {
977            router,
978            state,
979            path_prefix: None,
980        }
981    }
982
983    /// API Gateway v2 / Function URL event. `requestContext.http.method`
984    /// is what `LambdaRequest::ApiGatewayV2` keys off.
985    fn apigw_v2_agent_card_get() -> serde_json::Value {
986        serde_json::json!({
987            "version": "2.0",
988            "routeKey": "GET /.well-known/agent-card.json",
989            "rawPath": "/.well-known/agent-card.json",
990            "rawQueryString": "",
991            "headers": {"accept": "application/json", "a2a-version": "1.0"},
992            "requestContext": {
993                "accountId": "000000000000",
994                "apiId": "api",
995                "domainName": "fake.execute-api",
996                "domainPrefix": "fake",
997                "http": {
998                    "method": "GET",
999                    "path": "/.well-known/agent-card.json",
1000                    "protocol": "HTTP/1.1",
1001                    "sourceIp": "127.0.0.1",
1002                    "userAgent": "test"
1003                },
1004                "requestId": "rid",
1005                "routeKey": "GET /.well-known/agent-card.json",
1006                "stage": "$default",
1007                "time": "01/Jan/2026:00:00:00 +0000",
1008                "timeEpoch": 1_735_689_600_000i64
1009            },
1010            "isBase64Encoded": false
1011        })
1012    }
1013
1014    /// API Gateway v1 (REST) event. Top-level `httpMethod` + `path` and
1015    /// `requestContext.identity` (no `requestContext.http`) is what
1016    /// `LambdaRequest::ApiGatewayV1` keys off. This is the shape REST
1017    /// API + AWS_PROXY integrations send into the Lambda — the live
1018    /// fleet topology that 502'd against a hardcoded v2 response.
1019    ///
1020    /// `stage` is `$default` here so `lambda_http` does not prepend a
1021    /// stage prefix — this fixture exists to pin the response-shape
1022    /// contract, not the path-rewriting behaviour. See the
1023    /// `strip_path_prefix_*` tests for stage-prefix coverage.
1024    fn apigw_v1_agent_card_get_with_stage(stage: &str, path: &str) -> serde_json::Value {
1025        let request_context_path = if stage == "$default" {
1026            path.to_string()
1027        } else {
1028            format!("/{stage}{path}")
1029        };
1030        serde_json::json!({
1031            "resource": "/{proxy+}",
1032            "path": path,
1033            "httpMethod": "GET",
1034            "headers": {"accept": "application/json", "a2a-version": "1.0"},
1035            "multiValueHeaders": {},
1036            "queryStringParameters": null,
1037            "multiValueQueryStringParameters": null,
1038            "pathParameters": {"proxy": path.trim_start_matches('/').to_string()},
1039            "stageVariables": null,
1040            "requestContext": {
1041                "accountId": "000000000000",
1042                "apiId": "abc123",
1043                "domainName": "fake.execute-api",
1044                "domainPrefix": "fake",
1045                "extendedRequestId": "xrid",
1046                "httpMethod": "GET",
1047                "identity": {
1048                    "sourceIp": "127.0.0.1",
1049                    "userAgent": "test"
1050                },
1051                "path": request_context_path,
1052                "protocol": "HTTP/1.1",
1053                "requestId": "rid",
1054                "requestTime": "01/Jan/2026:00:00:00 +0000",
1055                "requestTimeEpoch": 1_735_689_600_000i64,
1056                "resourceId": "rsrc",
1057                "resourcePath": "/{proxy+}",
1058                "stage": stage
1059            },
1060            "body": null,
1061            "isBase64Encoded": false
1062        })
1063    }
1064
1065    fn apigw_v1_agent_card_get() -> serde_json::Value {
1066        apigw_v1_agent_card_get_with_stage("$default", "/.well-known/agent-card.json")
1067    }
1068
1069    /// ALB target-group event. `requestContext.elb` is what
1070    /// `LambdaRequest::Alb` keys off.
1071    fn alb_agent_card_get() -> serde_json::Value {
1072        serde_json::json!({
1073            "requestContext": {
1074                "elb": {
1075                    "targetGroupArn": "arn:aws:elasticloadbalancing:ap-southeast-2:000:targetgroup/fake/00"
1076                }
1077            },
1078            "httpMethod": "GET",
1079            "path": "/.well-known/agent-card.json",
1080            "queryStringParameters": {},
1081            "headers": {"accept": "application/json", "a2a-version": "1.0"},
1082            "body": "",
1083            "isBase64Encoded": false
1084        })
1085    }
1086
1087    /// REST v1 inbound MUST produce a v1 response shape. This is the
1088    /// regression for the live-fleet 502.
1089    #[tokio::test]
1090    async fn v1_inbound_event_emits_v1_response_envelope() {
1091        let handler = build_handler();
1092        let resp_value = handler
1093            .handle_http_event_value(apigw_v1_agent_card_get())
1094            .await
1095            .expect("handle_http_event_value(v1) must succeed");
1096
1097        // Parses cleanly as v1.
1098        let v1: aws_lambda_events::apigw::ApiGatewayProxyResponse =
1099            serde_json::from_value(resp_value.clone())
1100                .expect("response must deserialize as ApiGatewayProxyResponse (v1)");
1101        assert_eq!(v1.status_code, 200);
1102        match v1.body {
1103            Some(aws_lambda_events::encodings::Body::Text(s)) => {
1104                assert!(s.contains("\"name\""), "v1 body shape: {s}");
1105            }
1106            other => panic!("expected text body, got {other:?}"),
1107        }
1108
1109        // Negative: v1 response JSON must NOT contain the v2-only
1110        // `cookies` field. Presence of `cookies` is API Gateway REST's
1111        // 502 trigger.
1112        assert!(
1113            resp_value.get("cookies").is_none(),
1114            "v1 response must not carry v2-only `cookies` field; payload: {resp_value}"
1115        );
1116    }
1117
1118    /// API Gateway v2 / Function URL inbound MUST produce a v2 response
1119    /// shape (current behaviour, locked in to prevent the inverse
1120    /// regression).
1121    #[tokio::test]
1122    async fn v2_inbound_event_emits_v2_response_envelope() {
1123        let handler = build_handler();
1124        let resp_value = handler
1125            .handle_http_event_value(apigw_v2_agent_card_get())
1126            .await
1127            .expect("handle_http_event_value(v2) must succeed");
1128
1129        let v2: aws_lambda_events::apigw::ApiGatewayV2httpResponse =
1130            serde_json::from_value(resp_value.clone())
1131                .expect("response must deserialize as ApiGatewayV2httpResponse (v2)");
1132        assert_eq!(v2.status_code, 200);
1133        match v2.body {
1134            Some(aws_lambda_events::encodings::Body::Text(s)) => {
1135                assert!(s.contains("\"name\""), "v2 body shape: {s}");
1136            }
1137            other => panic!("expected text body, got {other:?}"),
1138        }
1139    }
1140
1141    /// ALB inbound MUST produce an ALB response shape.
1142    #[tokio::test]
1143    async fn alb_inbound_event_emits_alb_response_envelope() {
1144        let handler = build_handler();
1145        let resp_value = handler
1146            .handle_http_event_value(alb_agent_card_get())
1147            .await
1148            .expect("handle_http_event_value(alb) must succeed");
1149
1150        let alb: aws_lambda_events::alb::AlbTargetGroupResponse =
1151            serde_json::from_value(resp_value)
1152                .expect("response must deserialize as AlbTargetGroupResponse");
1153        assert_eq!(alb.status_code, 200);
1154    }
1155
1156    /// Live-fleet end-to-end regression: REST v1 stage-prefixed event
1157    /// + `strip_path_prefix("/dev")` on the handler routes through
1158    /// the agent-card endpoint AND emits a v1 response envelope. This
1159    /// is the exact scenario the live fleet was 502'ing on.
1160    #[tokio::test]
1161    async fn v1_stage_prefix_inbound_with_strip_emits_v1_response() {
1162        let s = Arc::new(InMemoryA2aStorage::new());
1163        let state = AppState {
1164            executor: Arc::new(NoOpExecutor),
1165            task_storage: s.clone(),
1166            push_storage: s.clone(),
1167            event_store: s.clone(),
1168            atomic_store: s.clone(),
1169            event_broker: TaskEventBroker::new(),
1170            middleware_stack: Arc::new(MiddlewareStack::new(vec![])),
1171            runtime_config: RuntimeConfig::default(),
1172            in_flight: Arc::new(InFlightRegistry::new()),
1173            cancellation_supervisor: s.clone(),
1174            push_delivery_store: None,
1175            push_dispatcher: None,
1176            durable_executor_queue: None,
1177        };
1178        let router = build_router(state.clone());
1179        let handler = LambdaA2aHandler {
1180            router,
1181            state,
1182            path_prefix: Some(Arc::from("/dev")),
1183        };
1184
1185        let event = apigw_v1_agent_card_get_with_stage("dev", "/.well-known/agent-card.json");
1186        let resp_value = handler
1187            .handle_http_event_value(event)
1188            .await
1189            .expect("v1 stage-prefixed event must succeed under strip_path_prefix");
1190
1191        let v1: aws_lambda_events::apigw::ApiGatewayProxyResponse =
1192            serde_json::from_value(resp_value)
1193                .expect("response must deserialize as ApiGatewayProxyResponse");
1194        assert_eq!(v1.status_code, 200);
1195        match v1.body {
1196            Some(aws_lambda_events::encodings::Body::Text(s)) => {
1197                assert!(s.contains("\"name\""), "v1 stage-prefix body: {s}");
1198            }
1199            other => panic!("expected text body, got {other:?}"),
1200        }
1201    }
1202
1203    /// Cross-shape decoding regression: a v1 response JSON carries
1204    /// `multiValueHeaders` (REST shape) but no `cookies`; a v2 response
1205    /// carries `cookies` but no v1-only `multiValueHeaders` semantics.
1206    /// Confirms the two shapes are wire-distinguishable, which is why
1207    /// the gateway 502s on a mismatch.
1208    #[tokio::test]
1209    async fn v1_response_does_not_match_v2_envelope_strictly() {
1210        let handler = build_handler();
1211        let v1_value = handler
1212            .handle_http_event_value(apigw_v1_agent_card_get())
1213            .await
1214            .unwrap();
1215
1216        // Sanity: v1 response JSON has no v2-only `cookies` field.
1217        assert!(v1_value.get("cookies").is_none());
1218
1219        let v2_value = handler
1220            .handle_http_event_value(apigw_v2_agent_card_get())
1221            .await
1222            .unwrap();
1223        // Sanity: v2 response JSON carries the v2 `cookies` field
1224        // (default empty array — still present on the wire).
1225        assert!(
1226            v2_value.get("cookies").is_some(),
1227            "v2 response should carry the v2-only cookies field"
1228        );
1229    }
1230}