turul-a2a-aws-lambda 0.1.4

AWS Lambda adapter for turul-a2a — thin wrapper over the same axum Router
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Builder wiring tests for ADR-012 same-backend requirements on the
//! Lambda adapter. Proves that:
//!
//! - `.storage()` requires `A2aCancellationSupervisor` on the bundled
//!   backend (bound at the type-system level).
//! - `build()` rejects configurations where the cancellation supervisor
//!   is omitted — no silent fallback to a different backend.
//! - `build()` rejects same-backend mismatches that cross the supervisor
//!   boundary.
//!
//! Without these guarantees a production Lambda deployment would write
//! cancel markers to DynamoDB/Postgres while the supervisor reads from
//! an unrelated in-memory store, silently breaking cross-instance
//! cancellation (ADR-012).

use async_trait::async_trait;

use turul_a2a::error::A2aError;
use turul_a2a::executor::AgentExecutor;
use turul_a2a::storage::{
    A2aAtomicStore, A2aCancellationSupervisor, A2aEventStore, A2aPushNotificationStorage,
    A2aStorageError, A2aTaskStorage, InMemoryA2aStorage,
};
use turul_a2a_types::{Message, Task};

use crate::LambdaA2aHandler;

struct DummyExecutor;

#[async_trait]
impl AgentExecutor for DummyExecutor {
    async fn execute(
        &self,
        _task: &mut Task,
        _msg: &Message,
        _ctx: &turul_a2a::executor::ExecutionContext,
    ) -> Result<(), A2aError> {
        Ok(())
    }
    fn agent_card(&self) -> turul_a2a_proto::AgentCard {
        turul_a2a_proto::AgentCard::default()
    }
}

/// Stand-in second-backend type used to exercise same-backend enforcement.
/// Implements every storage trait so we can plug it into the individual
/// setters while reporting a distinct `backend_name`.
#[derive(Clone, Default)]
struct FakeBackend;

#[async_trait]
impl A2aTaskStorage for FakeBackend {
    fn backend_name(&self) -> &'static str {
        "fake-backend"
    }
    async fn create_task(&self, _t: &str, _o: &str, task: Task) -> Result<Task, A2aStorageError> {
        Ok(task)
    }
    async fn get_task(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
        _h: Option<i32>,
    ) -> Result<Option<Task>, A2aStorageError> {
        Ok(None)
    }
    async fn update_task(&self, _t: &str, _o: &str, _task: Task) -> Result<(), A2aStorageError> {
        Ok(())
    }
    async fn delete_task(&self, _t: &str, _tid: &str, _o: &str) -> Result<bool, A2aStorageError> {
        Ok(false)
    }
    async fn list_tasks(
        &self,
        _f: turul_a2a::storage::TaskFilter,
    ) -> Result<turul_a2a::storage::TaskListPage, A2aStorageError> {
        Ok(turul_a2a::storage::TaskListPage {
            tasks: vec![],
            next_page_token: String::new(),
            page_size: 0,
            total_size: 0,
        })
    }
    async fn update_task_status(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
        _s: turul_a2a_types::TaskStatus,
    ) -> Result<Task, A2aStorageError> {
        unimplemented!()
    }
    async fn append_message(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
        _m: Message,
    ) -> Result<(), A2aStorageError> {
        Ok(())
    }
    async fn append_artifact(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
        _a: turul_a2a_types::Artifact,
        _append: bool,
        _last: bool,
    ) -> Result<(), A2aStorageError> {
        Ok(())
    }
    async fn task_count(&self) -> Result<usize, A2aStorageError> {
        Ok(0)
    }
    async fn maintenance(&self) -> Result<(), A2aStorageError> {
        Ok(())
    }
    async fn set_cancel_requested(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
    ) -> Result<(), A2aStorageError> {
        Ok(())
    }
}

#[async_trait]
impl A2aPushNotificationStorage for FakeBackend {
    fn backend_name(&self) -> &'static str {
        "fake-backend"
    }
    async fn create_config(
        &self,
        _t: &str,
        c: turul_a2a_proto::TaskPushNotificationConfig,
    ) -> Result<turul_a2a_proto::TaskPushNotificationConfig, A2aStorageError> {
        Ok(c)
    }
    async fn get_config(
        &self,
        _t: &str,
        _tid: &str,
        _c: &str,
    ) -> Result<Option<turul_a2a_proto::TaskPushNotificationConfig>, A2aStorageError> {
        Ok(None)
    }
    async fn list_configs(
        &self,
        _t: &str,
        _tid: &str,
        _p: Option<&str>,
        _ps: Option<i32>,
    ) -> Result<turul_a2a::storage::PushConfigListPage, A2aStorageError> {
        Ok(turul_a2a::storage::PushConfigListPage {
            configs: vec![],
            next_page_token: String::new(),
        })
    }
    async fn delete_config(&self, _t: &str, _tid: &str, _c: &str) -> Result<(), A2aStorageError> {
        Ok(())
    }
    async fn list_configs_eligible_at_event(
        &self,
        _t: &str,
        _tid: &str,
        _seq: u64,
        _p: Option<&str>,
        _ps: Option<i32>,
    ) -> Result<turul_a2a::storage::PushConfigListPage, A2aStorageError> {
        Ok(turul_a2a::storage::PushConfigListPage {
            configs: vec![],
            next_page_token: String::new(),
        })
    }
}

#[async_trait]
impl A2aEventStore for FakeBackend {
    fn backend_name(&self) -> &'static str {
        "fake-backend"
    }
    async fn append_event(
        &self,
        _t: &str,
        _tid: &str,
        _e: turul_a2a::streaming::StreamEvent,
    ) -> Result<u64, A2aStorageError> {
        Ok(0)
    }
    async fn get_events_after(
        &self,
        _t: &str,
        _tid: &str,
        _s: u64,
    ) -> Result<Vec<(u64, turul_a2a::streaming::StreamEvent)>, A2aStorageError> {
        Ok(vec![])
    }
    async fn latest_sequence(&self, _t: &str, _tid: &str) -> Result<u64, A2aStorageError> {
        Ok(0)
    }
    async fn cleanup_expired(&self) -> Result<u64, A2aStorageError> {
        Ok(0)
    }
}

#[async_trait]
impl A2aAtomicStore for FakeBackend {
    fn backend_name(&self) -> &'static str {
        "fake-backend"
    }
    async fn create_task_with_events(
        &self,
        _t: &str,
        _o: &str,
        task: Task,
        _e: Vec<turul_a2a::streaming::StreamEvent>,
    ) -> Result<(Task, Vec<u64>), A2aStorageError> {
        Ok((task, vec![]))
    }
    async fn update_task_status_with_events(
        &self,
        _t: &str,
        _tid: &str,
        _o: &str,
        _s: turul_a2a_types::TaskStatus,
        _e: Vec<turul_a2a::streaming::StreamEvent>,
    ) -> Result<(Task, Vec<u64>), A2aStorageError> {
        unimplemented!()
    }
    async fn update_task_with_events(
        &self,
        _t: &str,
        _o: &str,
        _task: Task,
        _e: Vec<turul_a2a::streaming::StreamEvent>,
    ) -> Result<Vec<u64>, A2aStorageError> {
        Ok(vec![])
    }
}

#[async_trait]
impl A2aCancellationSupervisor for FakeBackend {
    fn backend_name(&self) -> &'static str {
        "fake-backend"
    }
    async fn supervisor_get_cancel_requested(
        &self,
        _t: &str,
        _tid: &str,
    ) -> Result<bool, A2aStorageError> {
        Ok(false)
    }
    async fn supervisor_list_cancel_requested(
        &self,
        _t: &str,
        _tids: &[String],
    ) -> Result<Vec<String>, A2aStorageError> {
        Ok(vec![])
    }
}

// --------------------------------------------------------------------------
// Tests
// --------------------------------------------------------------------------

/// Unified `.storage()` with InMemoryA2aStorage — fully wires the
/// cancellation supervisor from the same backend. Builds cleanly.
#[test]
fn storage_bundle_requires_cancellation_supervisor_trait_bound() {
    // Compile-time check: .storage() accepts InMemoryA2aStorage which now
    // implements A2aCancellationSupervisor. If the trait bound on
    // `.storage()` were relaxed, a backend lacking the supervisor would
    // be accepted and silently wired — the builder test below proves
    // the runtime rejection.
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .storage(InMemoryA2aStorage::new().with_push_dispatch_enabled(true))
        .build();
    assert!(result.is_ok(), "unified storage bundle should build");
}

/// Omitting `cancellation_supervisor` while still supplying all other
/// stores individually MUST fail at build(). No silent in-memory fallback.
#[test]
fn build_rejects_missing_cancellation_supervisor() {
    let storage = InMemoryA2aStorage::new();
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage)
        // NOTE: no .cancellation_supervisor() — this is what we're testing.
        .build();
    match result {
        Err(A2aError::Internal(msg)) => {
            assert!(
                msg.contains("cancellation_supervisor"),
                "error message should mention cancellation_supervisor: {msg}"
            );
        }
        Ok(_) => {
            panic!("expected Internal error about missing cancellation_supervisor, got Ok(handler)")
        }
        Err(other) => panic!("expected Internal error, got different error: {other}"),
    }
}

/// Mismatched backend on cancellation_supervisor MUST be rejected at
/// build() with a message mentioning the mismatch. Prevents the
/// "DynamoDB marker write, in-memory supervisor read" silent failure mode.
#[test]
fn build_rejects_cancellation_supervisor_backend_mismatch() {
    let storage = InMemoryA2aStorage::new();
    let wrong_supervisor = FakeBackend;
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage)
        .cancellation_supervisor(wrong_supervisor)
        .build();
    match result {
        Err(A2aError::Internal(msg)) => {
            assert!(
                msg.contains("backend mismatch") || msg.contains("Storage backend mismatch"),
                "error should mention backend mismatch: {msg}"
            );
            assert!(
                msg.contains("cancellation_supervisor"),
                "error should mention which field mismatched: {msg}"
            );
        }
        Ok(_) => panic!("expected same-backend rejection, got Ok(handler)"),
        Err(other) => panic!("expected Internal mismatch error, got different error: {other}"),
    }
}

/// Positive test: individual setters including `.cancellation_supervisor()`
/// on the same backend accept the combination and produce a handler
/// without error.
///
/// Scope: this test proves only what `build()` returns — i.e., that the
/// same-backend check accepts the matching supervisor and that the
/// required-field validation is satisfied. It does NOT inspect
/// `AppState` directly (the `LambdaA2aHandler` wraps the router with no
/// test-only accessor). The corresponding AppState-wiring coverage lives
/// in `crates/turul-a2a/src/server/mod.rs::tests::runtime_config_setters_survive_build`
/// for the main server builder, and in `tests/cancellation_tests.rs`
/// which exercises the supervisor via the full cancel flow.
/// Together those give end-to-end proof that the Arc reaches the
/// router's handler state; this test is the compile-time + build-time
/// slice for the Lambda builder's setter surface.
#[test]
fn build_succeeds_with_explicit_cancellation_supervisor_same_backend() {
    let storage = InMemoryA2aStorage::new();
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage.clone())
        .cancellation_supervisor(storage)
        .build();
    assert!(
        result.is_ok(),
        "same-backend individual setters including cancellation_supervisor should build: {:?}",
        result.err()
    );
}

// ---------------------------------------------------------------------
// ADR-013 §7 / §10.2 Lambda builder mirror of main-server consistency.
// ---------------------------------------------------------------------

#[test]
fn lambda_builder_rejects_push_consumer_without_dispatch_enabled() {
    // push_delivery_store wired + atomic_store.push_dispatch_enabled() = false
    // ⇒ build error with the pinned main-server wording.
    let storage = InMemoryA2aStorage::new(); // flag defaults to false
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage.clone())
        .cancellation_supervisor(storage.clone())
        .push_delivery_store(storage)
        .build();
    let err = match result {
        Err(e) => e.to_string(),
        Ok(_) => panic!("orphan delivery store must be rejected"),
    };
    assert!(
        err.contains("push_delivery_store wired")
            && err.contains("push_dispatch_enabled")
            && err.contains("with_push_dispatch_enabled(true)"),
        "lambda error must mirror main server wording: {err}"
    );
}

#[test]
fn lambda_builder_rejects_push_dispatch_without_consumer() {
    // push_dispatch_enabled=true + no push_delivery_store ⇒ build error.
    let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage.clone())
        .cancellation_supervisor(storage)
        // deliberately no .push_delivery_store(...)
        .build();
    let err = match result {
        Err(e) => e.to_string(),
        Ok(_) => panic!("orphan dispatch flag must be rejected"),
    };
    assert!(
        err.contains("push_dispatch_enabled() is true") && err.contains("no consumer"),
        "lambda error must cite the orphaned-marker rationale: {err}"
    );
}

#[test]
fn lambda_builder_accepts_push_fully_wired() {
    let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .storage(storage)
        .build();
    assert!(
        result.is_ok(),
        "lambda push fully wired must build: {:?}",
        result.err()
    );
}

#[test]
fn lambda_builder_accepts_non_push_deployment() {
    let storage = InMemoryA2aStorage::new(); // flag defaults to false
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .task_storage(storage.clone())
        .push_storage(storage.clone())
        .event_store(storage.clone())
        .atomic_store(storage.clone())
        .cancellation_supervisor(storage)
        .build();
    assert!(
        result.is_ok(),
        "lambda non-push deployment must build: {:?}",
        result.err()
    );
}

#[test]
fn lambda_builder_rejects_retry_horizon_violation() {
    // push_claim_expiry <= max_attempts * backoff_cap must fail fast
    // (ADR-011 §10.3). Mirror of the main server's pinning test.
    use std::time::Duration;
    use turul_a2a::server::RuntimeConfig;

    let storage = InMemoryA2aStorage::new().with_push_dispatch_enabled(true);
    let mut cfg = RuntimeConfig::default();
    cfg.push_max_attempts = 10;
    cfg.push_backoff_cap = Duration::from_secs(60);
    // 10 * 60s = 600s — equal to claim expiry, <= so rejected.
    cfg.push_claim_expiry = Duration::from_secs(600);
    let result = LambdaA2aHandler::builder()
        .executor(DummyExecutor)
        .storage(storage)
        .runtime_config(cfg)
        .build();
    let err = match result {
        Err(e) => e.to_string(),
        Ok(_) => panic!("retry horizon violation must be rejected"),
    };
    assert!(
        err.contains("retry horizon") || err.contains("push_claim_expiry"),
        "lambda error must cite the retry horizon: {err}"
    );
}