Skip to main content

turul_a2a_aws_lambda/
lib.rs

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