bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
//! Behavior of the routes, driven in process without a socket.

use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use axum::{
    Json, Router,
    body::{Body, Bytes},
    http::{HeaderMap, Request, StatusCode, header::CONTENT_TYPE},
    routing::{get, post},
};
use futures_util::{StreamExt, stream};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::{Barrier, Semaphore, mpsc};
use tower::ServiceExt;

use super::{BedrockAgentCoreApp, Builder, PingStatus, Response, WarmupHook};
use crate::{ErrorKind, RequestContext, context, tasks::AsyncTasks};

const SESSION: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
const REQUEST_ID: &str = "x-amzn-bedrock-agentcore-runtime-request-id";
const WAT: &str = "x-amz-bedrock-agentcore-identity-wat";
const LEGACY_WAT: &str = "workloadaccesstoken";
const CUSTOM: &str = "x-amzn-bedrock-agentcore-runtime-custom-tenant";
const IDENTITY_CONTEXT: &str = "x-amzn-bedrock-agentcore-runtime-encrypted-workload-identity-context";
const MISSING_SESSION: &str =
    "Missing sessionId. Provide via x-amzn-bedrock-agentcore-runtime-session-id header or request body.";

type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// The routes of a built app. Requests go straight to the router.
struct App(Router, AsyncTasks);

impl App {
    fn new(builder: Builder) -> Self {
        let app = builder.build().unwrap();
        Self(app.standalone_router(), app.tasks().clone())
    }

    async fn send(
        &self,
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: impl Into<Body>,
    ) -> axum::response::Response {
        let mut request = Request::builder().method(method).uri(path);
        for (name, value) in headers {
            request = request.header(*name, *value);
        }
        self.0.clone().oneshot(request.body(body.into()).unwrap()).await.unwrap()
    }

    /// Sends a request and collects the reply.
    async fn fetch(
        &self,
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: impl Into<Body>,
    ) -> (u16, HeaderMap, Bytes) {
        let response = self.send(method, path, headers, body).await;
        let (parts, body) = response.into_parts();
        (parts.status.as_u16(), parts.headers, axum::body::to_bytes(body, usize::MAX).await.unwrap())
    }

    /// Posts an invocation and expects a JSON reply.
    async fn invoke(&self, headers: &[(&str, &str)], body: impl Into<Body>) -> (StatusCode, Value) {
        let response = self.send("POST", "/invocations", headers, body).await;
        let status = response.status();
        assert_eq!(response.headers()[CONTENT_TYPE], "application/json", "status {status}");
        let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
        (status, serde_json::from_slice(&body).unwrap())
    }

    async fn ping(&self) -> Value {
        let (status, body) = {
            let response = self.send("GET", "/ping", &[], Body::empty()).await;
            assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
            (response.status(), axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap())
        };
        assert_eq!(status, StatusCode::OK);
        serde_json::from_slice(&body).unwrap()
    }
}

async fn echo(payload: Value, ctx: RequestContext) -> Result<Value, BoxError> {
    Ok(json!({ "echo": payload, "session_id": ctx.session_id(), "request_id": ctx.request_id() }))
}

/// Reports the context from both sources: the handler argument and the ambient accessor.
fn describe(ctx: &RequestContext) -> Value {
    let headers: serde_json::Map<_, _> =
        ctx.headers().iter().map(|(name, value)| (name.to_string(), json!(value.to_str().unwrap()))).collect();
    json!({
        "session_id": ctx.session_id(),
        "request_id": ctx.request_id(),
        "workload_access_token": ctx.workload_access_token().map(|token| token.expose()),
        "oauth2_callback_url": ctx.oauth2_callback_url(),
        "headers": headers,
    })
}

async fn context_report(_payload: Value, ctx: RequestContext) -> Result<Value, BoxError> {
    let ambient = context::current().ok_or("no ambient context in the handler")?;
    assert_eq!(describe(&ambient), describe(&ctx));
    Ok(describe(&ctx))
}

#[derive(Deserialize)]
struct Prompt {
    prompt: String,
}

async fn typed(request: Prompt) -> Result<String, BoxError> {
    match request.prompt.as_str() {
        "fail" => Err("the model is unavailable".into()),
        prompt => Ok(prompt.to_uppercase()),
    }
}

async fn value_or_response(request: Prompt) -> Result<Response, BoxError> {
    Ok(match request.prompt.as_str() {
        "number" => Response::json(7),
        // JSON object keys must be strings, so this map fails to serialize.
        "unserializable" => Response::json(std::collections::BTreeMap::from([((1u8, 2u8), 3u8)])),
        prompt => Response::json(json!({ "text": prompt })),
    })
}

#[tokio::test]
async fn session_and_request_id_reach_the_handler() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo));
    let both = r#"{"sessionId":"from-body","n":1}"#;
    let body_only = r#"{"sessionId":"from-body"}"#;
    // (session header, body, expected session)
    let cases = [
        (Some("from-header"), both, "from-header"),
        (None, body_only, "from-body"),
        (Some(""), body_only, "from-body"),
        // The value is used as given. The server does not trim it or check its length.
        (None, r#"{"sessionId":" "}"#, " "),
        // The API sets no pattern for a session ID.
        (Some("caf\u{e9}-\u{2713}"), body_only, "caf\u{e9}-\u{2713}"),
    ];
    for (header, body, session) in cases {
        let mut headers = vec![(REQUEST_ID, "req-1")];
        headers.extend(header.map(|value| (SESSION, value)));
        let (status, reply) = app.invoke(&headers, body).await;
        assert_eq!(status, StatusCode::OK);
        let echoed: Value = serde_json::from_str(body).unwrap();
        assert_eq!(reply, json!({ "echo": echoed, "session_id": session, "request_id": "req-1" }));
    }
}

#[tokio::test]
async fn missing_or_empty_request_id_is_generated_per_request() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo));
    let mut generated = Vec::new();
    for headers in [vec![(SESSION, "s")], vec![(SESSION, "s"), (REQUEST_ID, "")]] {
        let (_, reply) = app.invoke(&headers, "{}").await;
        let id: uuid::Uuid = reply["request_id"].as_str().unwrap().parse().unwrap();
        assert_eq!(id.get_version_num(), 4);
        generated.push(id);
    }
    assert_ne!(generated[0], generated[1]);
}

#[tokio::test]
async fn rejections_follow_the_documented_order() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(typed).body_limit(64));
    let session = [(SESSION, "s")];
    let at_limit = format!(r#"{{"prompt":"{}"}}"#, "a".repeat(64 - 13));
    let over_limit = format!(r#"{{"prompt":"{}"}}"#, "a".repeat(64 - 12));
    // (headers, body, status, error, has details)
    type Case<'a> = (&'a [(&'a str, &'a str)], &'a str, StatusCode, &'a str, bool);
    let cases: [Case; 13] = [
        (&[], "{not json", StatusCode::BAD_REQUEST, "Invalid JSON", true),
        (&session, "", StatusCode::BAD_REQUEST, "Invalid JSON", true),
        (&[], r#"{"wrong":"shape"}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"{"sessionId":""}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"{"sessionId":42}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"{"sessionId":true}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"{"sessionId":null}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"{"sessionId":{"id":"s"}}"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&[], r#"["sessionId"]"#, StatusCode::BAD_REQUEST, MISSING_SESSION, false),
        (&session, r#"{"wrong":"shape"}"#, StatusCode::BAD_REQUEST, "Invalid request body format", true),
        (&session, r#"{"prompt":"fail"}"#, StatusCode::INTERNAL_SERVER_ERROR, "the model is unavailable", false),
        (&session, &over_limit, StatusCode::PAYLOAD_TOO_LARGE, "Request body is too large", true),
        (&[], &over_limit, StatusCode::PAYLOAD_TOO_LARGE, "Request body is too large", true),
    ];
    for (headers, body, status, error, has_details) in cases {
        let (actual, reply) = app.invoke(headers, body.to_owned()).await;
        assert_eq!((actual, reply["error"].as_str()), (status, Some(error)), "body {body}");
        assert_eq!(reply.get("details").is_some_and(Value::is_string), has_details, "body {body}");
    }

    assert_eq!(at_limit.len(), 64);
    let (status, reply) = app.invoke(&session, at_limit).await;
    assert_eq!((status, reply), (StatusCode::OK, json!("A".repeat(64 - 13))));
}

#[tokio::test]
async fn context_holds_identity_fields_and_only_allowlisted_headers() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(context_report));
    let base = [(SESSION, "s"), (REQUEST_ID, "r")];
    // (identity headers, expected token, expected callback URL)
    type Case<'a> = (&'a [(&'a str, &'a str)], Option<&'a str>, Option<&'a str>);
    let cases: [Case; 5] = [
        (&[(WAT, "preferred"), (LEGACY_WAT, "legacy")], Some("preferred"), None),
        (&[(WAT, ""), (LEGACY_WAT, "legacy")], Some("legacy"), None),
        (
            &[(LEGACY_WAT, "legacy"), ("oauth2callbackurl", "https://example.com/cb")],
            Some("legacy"),
            Some("https://example.com/cb"),
        ),
        (&[(LEGACY_WAT, "")], None, None),
        (&[], None, None),
    ];
    for (identity, token, callback) in cases {
        let (status, reply) = app.invoke(&[&base[..], identity].concat(), "{}").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!((reply["workload_access_token"].as_str(), reply["oauth2_callback_url"].as_str()), (token, callback));
        // Of these headers, only a non-empty preferred token header is forwarded.
        let forwarded = identity.iter().filter(|(name, value)| *name == WAT && !value.is_empty());
        let expected: serde_json::Map<_, _> = forwarded.map(|(name, value)| (name.to_string(), json!(value))).collect();
        assert_eq!(reply["headers"], Value::Object(expected), "{identity:?}");
    }

    let headers = [
        (SESSION, "s"),
        ("authorization", "Bearer abc"),
        (CUSTOM, "a"),
        (CUSTOM, ""),
        (CUSTOM, "b"),
        ("x-amzn-bedrock-agentcore-runtime-other", "no"),
        ("x-amzn-trace-id", "no"),
        ("cookie", "no"),
        ("x-custom", "no"),
        (IDENTITY_CONTEXT, "no"),
    ];
    let (_, reply) = app.invoke(&headers, "{}").await;
    assert_eq!(reply["headers"], json!({ "authorization": "Bearer abc", CUSTOM: "a, b" }));
    // A header that the allowlist of the agent runtime lets through is readable,
    // and it is not among the headers to forward.
    let names = |_payload: Value, ctx: RequestContext| async move {
        Ok::<_, BoxError>(ctx.request_headers().keys().map(|name| name.to_string()).collect::<Vec<_>>())
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(names));
    let (_, received) = app.invoke(&headers, "{}").await;
    let received = received.as_array().unwrap();
    let names = [SESSION, "authorization", CUSTOM, "x-amzn-trace-id", "cookie", "x-custom"];
    assert!(names.iter().all(|name| received.contains(&json!(name))), "{received:?}");
    assert!(!received.contains(&json!(IDENTITY_CONTEXT)), "{received:?}");
}

/// Two invocations are inside their handlers at the same time, on one app or on two.
#[tokio::test]
async fn interleaved_invocations_keep_their_own_context() {
    for two_apps in [false, true] {
        let barrier = Arc::new(Barrier::new(2));
        let handler = move |_payload: Value| {
            let barrier = barrier.clone();
            async move {
                barrier.wait().await;
                // Each handler resumes after the other one has entered its own context.
                Ok::<_, BoxError>(describe(&context::current().ok_or("no ambient context")?))
            }
        };
        let first = App::new(BedrockAgentCoreApp::builder().invocation(handler.clone()));
        let second = if two_apps { Some(App::new(BedrockAgentCoreApp::builder().invocation(handler))) } else { None };

        let with_token = [(SESSION, "session-a"), (REQUEST_ID, "request-a"), (WAT, "token-a"), (CUSTOM, "a")];
        let without_token = [(SESSION, "session-b"), (REQUEST_ID, "request-b")];
        let (a, b) = tokio::join!(
            first.invoke(&with_token, "{}"),
            second.as_ref().unwrap_or(&first).invoke(&without_token, "{}")
        );
        let expected_a = json!({
            "session_id": "session-a", "request_id": "request-a", "workload_access_token": "token-a",
            "oauth2_callback_url": null, "headers": { WAT: "token-a", CUSTOM: "a" },
        });
        let expected_b = json!({
            "session_id": "session-b", "request_id": "request-b", "workload_access_token": null,
            "oauth2_callback_url": null, "headers": {},
        });
        assert_eq!((a, b), ((StatusCode::OK, expected_a), (StatusCode::OK, expected_b)), "two apps: {two_apps}");
    }
}

#[derive(Deserialize)]
struct Command {
    reply: String,
    #[serde(default)]
    big: u64,
}

/// One handler that produces each kind of reply.
async fn replies(command: Command) -> Result<Response, BoxError> {
    Ok(match command.reply.as_str() {
        "string" => Response::json("line 1\n\"quoted\""),
        "object" => Response::json(json!({ "a": [1, null] })),
        "null" => Response::json(()),
        "created" => Response::with_status(StatusCode::CREATED, json!({ "id": 7 })),
        "unprocessable" => Response::with_status(StatusCode::UNPROCESSABLE_ENTITY, "bad input"),
        "raw" => Response::from_http(
            axum::http::Response::builder()
                .status(StatusCode::ACCEPTED)
                .header("content-type", "application/x-custom")
                .header("x-agent", "raw")
                .body(vec![0u8, 159, 255].into())?,
        ),
        "no-content" => {
            Response::from_http(axum::http::Response::builder().status(StatusCode::NO_CONTENT).body(().into())?)
        }
        // HTTP allows no body for these two statuses.
        "no-content-value" => Response::with_status(StatusCode::NO_CONTENT, json!({ "not": "sent" })),
        "not-modified-value" => Response::with_status(StatusCode::NOT_MODIFIED, "not sent"),
        "big" => Response::json(command.big),
        "panic" => panic!("SECRET panic detail"),
        other => return Err(format!("unknown reply {other}").into()),
    })
}

#[tokio::test]
async fn replies_are_encoded_by_accept_and_raw_responses_are_not() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(replies));
    const JSON: &str = "application/json";
    const TEXT: &str = "text/plain; charset=utf-8";
    const BINARY: &str = "application/octet-stream";
    let string_json = r#""line 1\n\"quoted\"""#.as_bytes();
    // (reply, Accept, status, content type, body)
    type Case<'a> = (&'a str, Option<&'a str>, u16, &'a str, &'a [u8]);
    let cases: [Case; 16] = [
        ("string", None, 200, JSON, string_json),
        ("string", Some("text/plain"), 200, TEXT, b"line 1\n\"quoted\""),
        ("string", Some("application/octet-stream"), 200, BINARY, string_json),
        ("object", Some("*/*"), 200, JSON, br#"{"a":[1,null]}"#),
        ("object", Some("text/plain"), 200, TEXT, br#"{"a":[1,null]}"#),
        ("object", Some("application/octet-stream"), 200, BINARY, br#"{"a":[1,null]}"#),
        ("object", Some("text/html"), 200, JSON, br#"{"a":[1,null]}"#),
        ("object", Some("application/json;q=0, text/plain"), 200, TEXT, br#"{"a":[1,null]}"#),
        ("null", Some("text/plain"), 200, TEXT, b"null"),
        ("created", None, 201, JSON, br#"{"id":7}"#),
        ("unprocessable", Some("text/plain"), 422, TEXT, b"bad input"),
        ("raw", Some("text/plain"), 202, "application/x-custom", &[0, 159, 255]),
        ("raw", None, 202, "application/x-custom", &[0, 159, 255]),
        ("no-content", Some("application/json"), 204, "", b""),
        ("no-content-value", None, 204, "", b""),
        ("not-modified-value", Some("text/plain"), 304, "", b""),
    ];
    for (reply, accept, status, content_type, body) in cases {
        let mut headers = vec![(SESSION, "s")];
        headers.extend(accept.map(|accept| ("accept", accept)));
        let (actual, headers, bytes) =
            app.fetch("POST", "/invocations", &headers, json!({ "reply": reply }).to_string()).await;
        let actual_type = headers.get(CONTENT_TYPE).map_or("", |value| value.to_str().unwrap());
        assert_eq!((actual, actual_type, &*bytes), (status, content_type, body), "reply {reply}, Accept {accept:?}");
    }
    let (_, headers, _) = app.fetch("POST", "/invocations", &[(SESSION, "s")], r#"{"reply":"raw"}"#).await;
    assert_eq!(headers["x-agent"], "raw");
}

#[tokio::test]
async fn request_bodies_are_decoded_strictly_and_content_type_is_not_checked() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(replies));
    let nested = "[".repeat(200);
    // (headers besides the session, body, status, error)
    type Case<'a> = (&'a [(&'a str, &'a str)], &'a [u8], u16, Option<&'a str>);
    let cases: [Case; 15] = [
        (&[], br#"{"reply":"null"}"#, 200, None),
        (&[("content-type", "application/json; charset=utf-8")], br#"{"reply":"null"}"#, 200, None),
        (&[("content-type", "text/plain")], br#"{"reply":"null"}"#, 200, None),
        (&[("content-encoding", "identity")], br#"{"reply":"null"}"#, 200, None),
        (&[("content-encoding", "Identity")], br#"{"reply":"null"}"#, 200, None),
        (&[("content-encoding", "gzip")], br#"{"reply":"null"}"#, 415, Some("Unsupported Content-Encoding")),
        (&[("content-encoding", "identity, gzip")], br#"{"reply":"null"}"#, 415, Some("Unsupported Content-Encoding")),
        (
            &[("content-encoding", "identity"), ("content-encoding", "gzip")],
            br#"{"reply":"null"}"#,
            415,
            Some("Unsupported Content-Encoding"),
        ),
        // serde ignores unknown fields unless the type opts out.
        (&[], br#"{"reply":"null","extra":true}"#, 200, None),
        (&[], br#"{"big":1}"#, 400, Some("Invalid request body format")),
        (&[], br#"{"reply":"null","reply":"null"}"#, 400, Some("Invalid request body format")),
        (&[], br#"{"reply":"big","big":1.5}"#, 400, Some("Invalid request body format")),
        (&[], b"{\"reply\":\"\xff\"}", 400, Some("Invalid JSON")),
        (&[], nested.as_bytes(), 400, Some("Invalid JSON")),
        (&[], br#"{"reply":"nope"}"#, 500, Some("unknown reply nope")),
    ];
    for (extra, body, status, error) in cases {
        let headers = [&[(SESSION, "s")], extra].concat();
        let (actual, _, bytes) = app.fetch("POST", "/invocations", &headers, body.to_vec()).await;
        let reply: Value = serde_json::from_slice(&bytes).unwrap();
        let body = String::from_utf8_lossy(body);
        assert_eq!((actual, reply.get("error").and_then(Value::as_str)), (status, error), "{extra:?} {body}");
    }

    // The typed field decides the number range: a u64 above i64::MAX survives.
    let (_, big) = app.invoke(&[(SESSION, "s")], r#"{"reply":"big","big":18446744073709551615}"#).await;
    assert_eq!(big, json!(u64::MAX));
}

#[tokio::test]
async fn body_limit_counts_bytes_not_characters() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).body_limit(32));
    let session = [(SESSION, "s")];
    // "é" is two bytes: 24 bytes of JSON syntax and ASCII, then four or five "é".
    let body = |count: usize| format!(r#"{{"text":"{}{}"}}"#, "a".repeat(13), "é".repeat(count));
    assert_eq!((body(4).len(), body(4).chars().count()), (32, 28));
    assert_eq!(app.invoke(&session, body(4)).await.0, StatusCode::OK);
    assert_eq!(app.invoke(&session, body(5)).await.0, StatusCode::PAYLOAD_TOO_LARGE);
}

/// A body that reports the ambient session each time the server polls it and once
/// more when it is dropped.
struct ContextProbe {
    frames: u8,
    seen_on_drop: Arc<std::sync::Mutex<Option<String>>>,
}

fn ambient_session() -> String {
    context::current().map_or("no context".to_owned(), |ctx| ctx.session_id().to_owned())
}

impl axum::body::HttpBody for ContextProbe {
    type Data = Bytes;
    type Error = std::convert::Infallible;

    fn poll_frame(
        mut self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Result<http_body::Frame<Bytes>, Self::Error>>> {
        if self.frames == 0 {
            return std::task::Poll::Ready(None);
        }
        self.frames -= 1;
        std::task::Poll::Ready(Some(Ok(http_body::Frame::data(Bytes::from(format!("[{}]", ambient_session()))))))
    }
}

impl Drop for ContextProbe {
    fn drop(&mut self) {
        *self.seen_on_drop.lock().unwrap() = Some(ambient_session());
    }
}

#[tokio::test]
async fn raw_streaming_body_sees_the_request_context_while_it_is_read_and_dropped() {
    let seen_on_drop = Arc::new(std::sync::Mutex::new(None));
    let probe = seen_on_drop.clone();
    let handler = move |_payload: Value| {
        let body = Body::new(ContextProbe { frames: 2, seen_on_drop: probe.clone() });
        async move { Ok::<_, BoxError>(Response::from_http(axum::http::Response::new(body))) }
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));

    // The handler has returned before the test reads the body.
    let response = app.send("POST", "/invocations", &[(SESSION, "stream-session")], "{}").await;
    assert_eq!(ambient_session(), "no context");
    let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(body, "[stream-session][stream-session]");
    assert_eq!(seen_on_drop.lock().unwrap().as_deref(), Some("stream-session"));
}

/// An error whose text cannot be produced.
#[derive(Debug)]
struct PanicsOnDisplay;

impl std::fmt::Display for PanicsOnDisplay {
    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        panic!("SECRET display panic")
    }
}

impl std::error::Error for PanicsOnDisplay {}

#[tokio::test]
async fn panic_while_formatting_the_handler_error_is_a_sanitized_500() {
    let handler = |_payload: Value| async { Err::<Value, _>(PanicsOnDisplay) };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let reply = app.invoke(&[(SESSION, "s")], "{}").await;
    assert_eq!(reply, (StatusCode::INTERNAL_SERVER_ERROR, json!({ "error": "Internal error" })));
}

type Frames = futures_util::stream::BoxStream<'static, Result<Bytes, axum::Error>>;

impl App {
    /// Starts a streaming invocation and returns the body, one frame for each event.
    async fn stream(&self, session: &str) -> Frames {
        let headers = [(SESSION, session), ("accept", "application/json, text/event-stream")];
        let response = self.send("POST", "/invocations", &headers, "{}").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()[CONTENT_TYPE], "text/event-stream");
        Box::pin(response.into_body().into_data_stream())
    }
}

/// The next event of a streaming reply, or `None` at its end.
async fn next_event(frames: &mut Frames) -> Option<String> {
    let frame = tokio::time::timeout(Duration::from_secs(10), frames.next()).await.expect("no event arrived");
    frame.map(|bytes| String::from_utf8(bytes.unwrap().to_vec()).unwrap())
}

type Sender<T> = mpsc::UnboundedSender<Result<T, BoxError>>;
type Handled = std::future::Ready<Result<Response, BoxError>>;

/// A handler whose stream yields what the test sends. The stream is not `Unpin`.
fn channel_handler<T>() -> (Sender<T>, impl Fn(Value) -> Handled + Clone + Send + Sync + 'static)
where
    T: serde::Serialize + Send + 'static,
{
    let (sender, receiver) = mpsc::unbounded_channel();
    let receiver = Arc::new(std::sync::Mutex::new(Some(receiver)));
    let handler = move |_payload: Value| {
        let receiver = receiver.lock().unwrap().take().expect("one invocation for each channel");
        let items =
            stream::unfold(receiver, |mut receiver| async move { receiver.recv().await.map(|item| (item, receiver)) });
        std::future::ready(Ok(Response::stream(items)))
    };
    (sender, handler)
}

#[tokio::test]
async fn stream_events_arrive_one_at_a_time_as_json_data() {
    let (sender, handler) = channel_handler::<Value>();
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let mut frames = app.stream("s").await;

    // Each event is read before the source yields the next item.
    let cases = [
        (json!({ "n": 1 }), "data: {\"n\":1}\n\n"),
        // Text cannot start a new event: a line break is escaped inside the JSON string.
        (json!("line 1\n\nevent: error"), "data: \"line 1\\n\\nevent: error\"\n\n"),
        // Field names of the item have no meaning for the event.
        (json!({ "data": "x", "event": "y" }), "data: {\"data\":\"x\",\"event\":\"y\"}\n\n"),
        (Value::Null, "data: null\n\n"),
    ];
    for (item, event) in cases {
        sender.send(Ok(item)).unwrap();
        assert_eq!(next_event(&mut frames).await.as_deref(), Some(event));
    }
    drop(sender);
    assert_eq!(next_event(&mut frames).await, None);
}

/// Records the ambient session when it is dropped.
struct ReportOnDrop(Arc<std::sync::Mutex<Vec<String>>>);

impl Drop for ReportOnDrop {
    fn drop(&mut self) {
        self.0.lock().unwrap().push(ambient_session());
    }
}

#[tokio::test]
async fn stream_that_accept_refuses_is_406_and_is_dropped_unpolled_within_the_context() {
    let polled = Arc::new(AtomicBool::new(false));
    let dropped_in = Arc::new(std::sync::Mutex::new(Vec::new()));
    let (flag, report) = (polled.clone(), dropped_in.clone());
    let handler = move |_payload: Value| {
        let (flag, on_drop) = (flag.clone(), ReportOnDrop(report.clone()));
        let items = stream::poll_fn(move |_| {
            let _held = &on_drop;
            flag.store(true, Ordering::SeqCst);
            std::task::Poll::Ready(None::<Result<Value, BoxError>>)
        });
        std::future::ready(Ok::<_, BoxError>(Response::stream(items)))
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let not_acceptable = json!({ "error": "Streaming response requires Accept: text/event-stream header. \
        Please include this header in your request to receive streaming data." });

    let refused = ["application/json", "text/plain, application/*", "text/event-stream;q=0, */*"];
    for accept in refused {
        let headers = [(SESSION, "refused-session"), ("accept", accept)];
        assert_eq!(
            app.invoke(&headers, "{}").await,
            (StatusCode::NOT_ACCEPTABLE, not_acceptable.clone()),
            "{accept:?}"
        );
    }
    assert!(!polled.load(Ordering::SeqCst));
    // The server dropped each stream while the request context was still in place.
    assert_eq!(*dropped_in.lock().unwrap(), ["refused-session"; 3]);

    // A caller that names no type, or allows the type with a wildcard, gets the stream.
    for accept in [None, Some("*/*"), Some("text/*"), Some("application/json, text/event-stream")] {
        let mut headers = vec![(SESSION, "streamed-session")];
        headers.extend(accept.map(|accept| ("accept", accept)));
        let (status, reply_headers, body) = app.fetch("POST", "/invocations", &headers, "{}").await;
        let content_type = reply_headers[CONTENT_TYPE].to_str().unwrap();
        assert_eq!((status, content_type, body.is_empty()), (200, "text/event-stream", true), "{accept:?}");
    }
}

/// An item that fails to serialize when it is `Broken` and whose serializer panics
/// when it is `Panics`.
enum Item {
    Good(u8),
    Broken,
    Panics,
}

impl serde::Serialize for Item {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Good(n) => serializer.serialize_u8(*n),
            Self::Broken => Err(serde::ser::Error::custom("SECRET serializer detail")),
            Self::Panics => panic!("SECRET serializer panic"),
        }
    }
}

#[tokio::test]
async fn stream_failure_sends_one_error_event_and_ends_the_stream() {
    // (items before the failure, the failure, text of the error event)
    type Failure = fn() -> Result<Item, BoxError>;
    let cases: [(u8, Failure, &str); 5] = [
        (0, || Err("the model stopped".into()), "the model stopped"),
        (2, || Err("the model stopped".into()), "the model stopped"),
        (1, || Ok(Item::Broken), "Failed to serialize response"),
        (1, || Ok(Item::Panics), "Internal error"),
        (1, || panic!("SECRET panic detail"), "Internal error"),
    ];
    for (good, failure, error) in cases {
        let dropped = Arc::new(AtomicBool::new(false));
        let on_drop = DropFlag(dropped.clone());
        let handler = move |_payload: Value| {
            let state = (0u8, DropFlag(on_drop.0.clone()));
            let items = stream::unfold(state, move |(sent, on_drop)| async move {
                // The stream never ends by itself: only the failure can end it.
                let item = if sent < good { Ok(Item::Good(sent)) } else { failure() };
                Some((item, (sent + 1, on_drop)))
            });
            std::future::ready(Ok::<_, BoxError>(Response::stream(items)))
        };
        let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
        let mut frames = app.stream("s").await;

        for n in 0..good {
            assert_eq!(next_event(&mut frames).await, Some(format!("data: {n}\n\n")), "{error}");
        }
        let last = format!("event: error\ndata: {{\"error\":\"{error}\"}}\n\n");
        assert_eq!(next_event(&mut frames).await, Some(last), "{error}");
        assert_eq!(next_event(&mut frames).await, None, "{error}");
        assert!(dropped.load(Ordering::SeqCst), "the source was not dropped after: {error}");
    }
}

/// A stream that ends at once and panics when it is dropped.
struct PanicsOnDrop;

impl futures_util::Stream for PanicsOnDrop {
    type Item = Result<Value, BoxError>;

    fn poll_next(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        std::task::Poll::Ready(None)
    }
}

impl Drop for PanicsOnDrop {
    fn drop(&mut self) {
        panic!("SECRET destructor panic");
    }
}

/// The 406 reply drops the stream. A destructor that panics there must not replace the reply.
#[tokio::test]
async fn refused_stream_whose_destructor_panics_still_gets_the_406() {
    let handler = |_payload: Value| async { Ok::<_, BoxError>(Response::stream(PanicsOnDrop)) };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let (status, reply) = app.invoke(&[(SESSION, "s"), ("accept", "application/json")], "{}").await;
    assert_eq!(status, StatusCode::NOT_ACCEPTABLE);
    assert!(reply["error"].as_str().unwrap().starts_with("Streaming response requires"), "{reply}");
}

#[tokio::test]
async fn panic_in_the_destructor_of_an_ended_stream_sends_the_error_event() {
    let handler = |_payload: Value| async { Ok::<_, BoxError>(Response::stream(PanicsOnDrop)) };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let mut frames = app.stream("s").await;
    let error = "event: error\ndata: {\"error\":\"Internal error\"}\n\n";
    assert_eq!(next_event(&mut frames).await.as_deref(), Some(error));
    assert_eq!(next_event(&mut frames).await, None);
}

struct DropFlag(Arc<AtomicBool>);

impl Drop for DropFlag {
    fn drop(&mut self) {
        self.0.store(true, Ordering::SeqCst);
    }
}

#[tokio::test]
async fn quiet_stream_gets_heartbeat_comments_and_an_empty_stream_just_ends() {
    let (sender, handler) = channel_handler::<Value>();
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler).stream_heartbeat(Duration::from_millis(20)));
    let mut frames = app.stream("s").await;

    // Nothing is sent, so the next two frames can only be heartbeats.
    for _ in 0..2 {
        assert_eq!(next_event(&mut frames).await.as_deref(), Some(":\n\n"));
    }
    sender.send(Ok(json!(1))).unwrap();
    let mut events = Vec::new();
    while events.last().map(String::as_str) != Some("data: 1\n\n") {
        events.push(next_event(&mut frames).await.expect("the stream ended before the item"));
    }
    assert!(events[..events.len() - 1].iter().all(|event| event == ":\n\n"), "{events:?}");

    let empty =
        |_payload: Value| async { Ok::<_, BoxError>(Response::stream(stream::empty::<Result<Value, BoxError>>())) };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(empty));
    assert_eq!(next_event(&mut app.stream("s").await).await, None);

    // The longest interval cannot be added to the clock. The stream still sends its item.
    let (sender, handler) = channel_handler::<Value>();
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler).stream_heartbeat(Duration::MAX));
    let mut frames = app.stream("s").await;
    sender.send(Ok(json!(1))).unwrap();
    assert_eq!(next_event(&mut frames).await.as_deref(), Some("data: 1\n\n"));
}

/// A stream that a route of the app returns uses the heartbeat of the app, with or
/// without the session header.
#[tokio::test]
async fn stream_from_a_customer_route_uses_the_heartbeat_of_the_app() {
    let quiet = || async { Response::stream(stream::pending::<Result<Value, BoxError>>()) };
    let builder = BedrockAgentCoreApp::builder()
        .invocation(echo)
        .routes(Router::new().route("/quiet", get(quiet)))
        .stream_heartbeat(Duration::from_millis(20));
    let app = App::new(builder);
    let headers: [&[(&str, &str)]; 2] = [&[], &[(SESSION, "s")]];
    for headers in headers {
        let response = app.send("GET", "/quiet", headers, Body::empty()).await;
        let mut frames: Frames = Box::pin(response.into_body().into_data_stream());
        // The default interval is 30 seconds, longer than `next_event` waits.
        assert_eq!(next_event(&mut frames).await.as_deref(), Some(":\n\n"));
    }
}

/// Two streams are read in turns. Each item reports the session that is ambient while
/// the server polls its stream, and each source reports it once more when it is dropped.
#[tokio::test]
async fn interleaved_streams_keep_their_context_while_polled_and_when_dropped() {
    let dropped_in = Arc::new(std::sync::Mutex::new(Vec::new()));
    let report = dropped_in.clone();
    let (ticks, _) = tokio::sync::broadcast::channel::<()>(8);
    let subscribe = ticks.clone();
    let handler = move |_payload: Value| {
        let state = (subscribe.subscribe(), ReportOnDrop(report.clone()));
        let items = stream::unfold(state, |(mut ticks, on_drop)| async move {
            ticks.recv().await.ok()?;
            Some((Ok::<_, BoxError>(ambient_session()), (ticks, on_drop)))
        });
        std::future::ready(Ok::<_, BoxError>(Response::stream(items)))
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));
    let (mut a, mut b) = (app.stream("session-a").await, app.stream("session-b").await);

    for _ in 0..2 {
        ticks.send(()).unwrap();
        assert_eq!(next_event(&mut a).await.as_deref(), Some("data: \"session-a\"\n\n"));
        assert_eq!(next_event(&mut b).await.as_deref(), Some("data: \"session-b\"\n\n"));
    }
    // The client goes away while each source waits for its next item.
    drop(a);
    drop(b);
    assert_eq!(*dropped_in.lock().unwrap(), ["session-a", "session-b"]);
}

#[tokio::test]
async fn panic_is_a_sanitized_500_and_the_server_keeps_working() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(replies));
    let session = [(SESSION, "s")];
    let panicked = app.invoke(&session, r#"{"reply":"panic"}"#).await;
    assert_eq!(panicked, (StatusCode::INTERNAL_SERVER_ERROR, json!({ "error": "Internal error" })));
    assert_eq!(app.invoke(&session, r#"{"reply":"object"}"#).await.0, StatusCode::OK);
}

#[tokio::test]
async fn routes_match_exact_paths_and_methods() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo));
    let not_found = Some(json!({ "error": "Not found" }));
    // (method, path, status, Allow header, JSON body)
    let cases = [
        ("GET", "/", 404, None, not_found.clone()),
        ("POST", "/invocations/", 404, None, not_found.clone()),
        ("GET", "/ping/", 404, None, not_found.clone()),
        ("POST", "/Invocations", 404, None, not_found),
        ("GET", "/invocations", 405, Some("POST"), None),
        ("OPTIONS", "/invocations", 405, Some("POST"), None),
        ("POST", "/ping", 405, Some("GET,HEAD"), None),
        ("HEAD", "/ping", 200, None, None),
        ("GET", "/ping?verbose=1", 200, None, Some(app.ping().await)),
        // A query parameter does not supply the session.
        ("POST", "/invocations?sessionId=s", 400, None, Some(json!({ "error": MISSING_SESSION }))),
    ];
    for (method, path, status, allow, body) in cases {
        let (actual, headers, bytes) = app.fetch(method, path, &[], "{}").await;
        let actual_allow = headers.get("allow").map(|value| value.to_str().unwrap());
        assert_eq!((actual, actual_allow), (status, allow), "{method} {path}");
        assert_eq!(serde_json::from_slice::<Value>(&bytes).ok(), body, "{method} {path}: {bytes:?}");
    }
}

#[tokio::test]
async fn handler_signatures() {
    let closure = |request: Prompt, ctx: RequestContext| async move {
        Ok::<_, std::convert::Infallible>(format!("{} in {}", request.prompt, ctx.session_id()))
    };
    let cases = [
        (BedrockAgentCoreApp::builder().invocation(typed), "hi", json!("HI")),
        (BedrockAgentCoreApp::builder().invocation(closure), "hi", json!("hi in s")),
        (BedrockAgentCoreApp::builder().invocation(value_or_response), "hi", json!({ "text": "hi" })),
        (BedrockAgentCoreApp::builder().invocation(value_or_response), "number", json!(7)),
    ];
    for (builder, prompt, expected) in cases {
        let app = App::new(builder);
        let (status, reply) = app.invoke(&[(SESSION, "s")], json!({ "prompt": prompt }).to_string()).await;
        assert_eq!((status, reply), (StatusCode::OK, expected));
    }
}

#[tokio::test]
async fn serialization_failure_is_a_json_500_and_the_server_keeps_working() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(value_or_response));
    let invoke = |prompt: &'static str| app.invoke(&[(SESSION, "s")], json!({ "prompt": prompt }).to_string());

    let failed = (StatusCode::INTERNAL_SERVER_ERROR, json!({ "error": "Failed to serialize response" }));
    assert_eq!(invoke("unserializable").await, failed);
    assert_eq!(invoke("hi").await, (StatusCode::OK, json!({ "text": "hi" })));
}

#[tokio::test]
async fn ping_time_changes_only_when_the_status_changes_or_tracked_work_ran() {
    let now = || SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
    let before = now();
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo));
    let time = |ping: &Value| ping["time_of_last_update"].as_u64().unwrap();

    let idle = app.ping().await;
    assert_eq!(idle["status"], "Healthy");
    assert!((before..=now()).contains(&time(&idle)), "{idle} is not Unix seconds near {before}");

    // The clock must move to a new second to show which pings change the time.
    tokio::time::sleep(Duration::from_millis(1100)).await;
    app.invoke(&[(SESSION, "s")], "{}").await;
    assert_eq!(app.ping().await, idle, "an invocation and a later ping do not change an idle status");

    let first = app.1.track("first");
    let second = app.1.track("second");
    let busy = app.ping().await;
    assert_eq!(busy["status"], "HealthyBusy");
    assert!(time(&busy) > time(&idle), "the change to busy did not update the time: {busy}");

    tokio::time::sleep(Duration::from_millis(1100)).await;
    drop(first);
    assert_eq!(app.ping().await, busy, "one of two tasks is still active");

    // The time of the change to idle is the time when the last task ended, not the
    // time of the ping that reports it: the service counts the idle time from it.
    drop(second);
    let ended = now();
    tokio::time::sleep(Duration::from_millis(1100)).await;
    let idle_again = app.ping().await;
    assert_eq!(idle_again["status"], "Healthy");
    assert!(time(&idle_again) > time(&busy), "the change to idle did not update the time: {idle_again}");
    assert!(time(&idle_again) <= ended, "the time is the time of the ping, not of the change: {idle_again}");
    assert_eq!(app.ping().await, idle_again);

    // Work that starts and ends between two pings is seen by no ping. The session
    // was not idle then, so the time moves although the status is the same.
    tokio::time::sleep(Duration::from_millis(1100)).await;
    drop(app.1.track("short"));
    let after_short_work = app.ping().await;
    assert_eq!(after_short_work["status"], "Healthy");
    assert!(time(&after_short_work) > time(&idle_again), "short work did not update the time: {after_short_work}");
}

/// An error of the application whose source is `0`.
#[derive(Debug)]
struct Wrapped(crate::Error);

impl std::fmt::Display for Wrapped {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the tool failed")
    }
}

impl std::error::Error for Wrapped {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

/// The source of an Identity error can hold a credential or the authorization URL,
/// as the error of a function that failed to deliver that URL does.
#[test]
fn logged_causes_of_a_handler_error_end_at_an_identity_error() {
    let error = |kind| crate::Error::new(kind, "the SDK failed").with_source("could not deliver SECRET-URL");
    let causes = |error: BoxError| super::handler::Failure::of(error).causes;
    let identity = ErrorKind::AuthorizationCallbackFailed;

    assert_eq!(causes(Box::new(error(identity))), None);
    // Wrapped by an error of the application: the text of the Identity error is
    // logged, and its source is not.
    assert_eq!(causes(Box::new(Wrapped(error(identity)))).as_deref(), Some("the SDK failed"));
    // The source of any other error is logged.
    let serve = causes(Box::new(Wrapped(error(ErrorKind::Serve))));
    assert_eq!(serve.as_deref(), Some("the SDK failed: could not deliver SECRET-URL"));
}

/// The server reads the body before it calls the handler. The shutdown must name
/// an invocation that it interrupts during that time.
#[tokio::test]
async fn invocation_is_in_flight_while_its_body_is_still_arriving() {
    let app = BedrockAgentCoreApp::builder().invocation(echo).build().unwrap();
    let in_flight = app.state.in_flight.clone();
    let upload = Body::from_stream(stream::pending::<Result<Bytes, BoxError>>());
    let request = Request::post("/invocations").header(SESSION, "s").body(upload).unwrap();
    let reply = tokio::spawn(app.standalone_router().oneshot(request));
    // This runtime has one thread: the request runs until it waits for its body.
    tokio::task::yield_now().await;
    assert_eq!(in_flight.log_interrupted(), 1);

    reply.abort();
    assert!(reply.await.unwrap_err().is_cancelled());
    assert_eq!(in_flight.log_interrupted(), 0);
}

/// The handler returns at once. Its work continues and keeps the app busy.
#[tokio::test]
async fn work_tracked_through_the_context_keeps_the_app_busy_after_the_reply() {
    let (finish, finished) = tokio::sync::watch::channel(false);
    let handler = move |_payload: Value, ctx: RequestContext| {
        let mut finished = finished.clone();
        async move {
            let guard = ctx.tasks().track("background job");
            let job = tokio::spawn(context::scope(ctx.clone(), async move {
                let _guard = guard;
                let _ = finished.wait_for(|finished| *finished).await;
            }));
            Ok::<_, BoxError>(json!({ "started": ctx.tasks().info().running()[0].name(), "done": job.is_finished() }))
        }
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler));

    let reply = app.invoke(&[(SESSION, "s")], "{}").await;
    assert_eq!(reply, (StatusCode::OK, json!({ "started": "background job", "done": false })));
    assert_eq!(app.ping().await["status"], "HealthyBusy");
    assert_eq!(app.1.active_count(), 1);

    finish.send(true).unwrap();
    tokio::time::timeout(Duration::from_secs(10), async {
        while app.1.active_count() > 0 {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("the job did not finish");
    assert_eq!(app.ping().await["status"], "Healthy");
}

#[tokio::test]
async fn custom_ping_handler_overrides_tasks_and_a_panic_falls_back_to_them() {
    const BUSY: u8 = 1;
    const PANIC: u8 = 2;
    const AUTOMATIC: u8 = 3;
    let mode = Arc::new(std::sync::atomic::AtomicU8::new(0));
    let read = mode.clone();
    let custom = move || match read.load(Ordering::SeqCst) {
        BUSY => Some(PingStatus::HealthyBusy),
        PANIC => panic!("the custom ping handler failed"),
        AUTOMATIC => None,
        _ => Some(PingStatus::Healthy),
    };
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).ping(custom));
    let status = || async { app.ping().await["status"].as_str().unwrap().to_owned() };

    // The custom result is used whatever the task registry holds.
    let guard = app.1.track("ignored by the custom handler");
    assert_eq!(status().await, "Healthy");
    mode.store(BUSY, Ordering::SeqCst);
    drop(guard);
    let busy = app.ping().await;
    assert_eq!(busy["status"], "HealthyBusy");

    // A failing handler falls back to the task registry, with the same time rule.
    mode.store(PANIC, Ordering::SeqCst);
    let guard = app.1.track("seen by the fallback");
    assert_eq!(app.ping().await, busy, "the fallback status is busy too, so the time stays");
    drop(guard);
    assert_eq!(status().await, "Healthy");

    // A handler that returns `None` leaves the status to the task registry.
    mode.store(AUTOMATIC, Ordering::SeqCst);
    let guard = app.1.track("seen when the handler decides nothing");
    assert_eq!(status().await, "HealthyBusy");
    drop(guard);

    // The last task has ended. The handler then reports busy at one ping and
    // nothing at the next. The service saw busy at the first of them, so the idle
    // time counts from the second, not from the end of the task.
    tokio::time::sleep(Duration::from_millis(1100)).await;
    mode.store(BUSY, Ordering::SeqCst);
    assert_eq!(status().await, "HealthyBusy");
    let seen_busy = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
    tokio::time::sleep(Duration::from_millis(1100)).await;
    mode.store(AUTOMATIC, Ordering::SeqCst);
    let idle = app.ping().await;
    assert_eq!(idle["status"], "Healthy");
    assert!(idle["time_of_last_update"].as_u64().unwrap() > seen_busy, "{idle} is before the busy ping at {seen_busy}");

    // A handler can also return the status itself.
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).ping(|| PingStatus::HealthyBusy));
    assert_eq!(app.ping().await["status"], "HealthyBusy");
}

#[derive(Clone)]
struct Settings {
    name: &'static str,
}

/// A route of the customer with its own state. It reports the context from both sources.
async fn whoami(axum::extract::State(settings): axum::extract::State<Settings>, ctx: RequestContext) -> Json<Value> {
    let guard = ctx.tasks().track("custom route");
    let ambient = context::current().map(|ambient| ambient.session_id().to_owned());
    let reply = json!({
        "name": settings.name,
        "session_id": ctx.session_id(),
        "ambient_session_id": ambient,
        "token": ctx.workload_access_token().map(|token| token.expose()),
        "tasks_of_the_app": ctx.tasks().active_count(),
    });
    drop(guard);
    Json(reply)
}

fn custom_routes() -> Router {
    Router::new()
        .route("/whoami", get(whoami))
        .route("/plain", get(|| async { "no context needed" }))
        .with_state(Settings { name: "custom" })
}

#[tokio::test]
async fn customer_routes_get_the_request_context_and_the_task_registry_of_the_app() {
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).routes(custom_routes()));
    let _held = app.1.track("held by the test");

    let headers = [(SESSION, "custom-session"), (WAT, "token-1")];
    let (status, _, body) = app.fetch("GET", "/whoami", &headers, Body::empty()).await;
    let expected = json!({
        "name": "custom", "session_id": "custom-session", "ambient_session_id": "custom-session",
        "token": "token-1", "tasks_of_the_app": 2,
    });
    assert_eq!((status, serde_json::from_slice::<Value>(&body).unwrap()), (200, expected));

    // The context comes from headers only. A route that takes it needs the session header.
    let (status, _, body) = app.fetch("GET", "/whoami", &[], Body::empty()).await;
    let missing =
        json!({ "error": "Missing sessionId. Provide via x-amzn-bedrock-agentcore-runtime-session-id header." });
    assert_eq!((status, serde_json::from_slice::<Value>(&body).unwrap()), (400, missing));
    // A route that does not take the context has no such requirement.
    assert_eq!(app.fetch("GET", "/plain", &[], Body::empty()).await.2, "no context needed");

    // The routes of the SDK work next to them.
    assert_eq!(app.invoke(&[(SESSION, "s")], r#"{"n":1}"#).await.1["echo"], json!({ "n": 1 }));
    assert_eq!(app.ping().await["status"], "HealthyBusy");
}

#[tokio::test]
async fn streaming_body_of_a_customer_route_sees_the_request_context() {
    let seen_on_drop = Arc::new(std::sync::Mutex::new(None));
    let probe = seen_on_drop.clone();
    let stream = get(move || {
        let body = Body::new(ContextProbe { frames: 2, seen_on_drop: probe.clone() });
        async move { axum::http::Response::new(body) }
    });
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).routes(Router::new().route("/stream", stream)));

    let (status, _, body) = app.fetch("GET", "/stream", &[(SESSION, "route-session")], Body::empty()).await;
    assert_eq!((status, &*body), (200, &b"[route-session][route-session]"[..]));
    assert_eq!(seen_on_drop.lock().unwrap().as_deref(), Some("route-session"));
    // Without the session header there is no context to keep.
    let (_, _, body) = app.fetch("GET", "/stream", &[], Body::empty()).await;
    assert_eq!(&*body, b"[no context][no context]");
}

#[tokio::test]
async fn request_context_outside_the_app_routes_is_a_500_with_guidance() {
    // The route is added to the router after the app was built, not through the builder.
    let app = BedrockAgentCoreApp::builder().invocation(echo).build().unwrap();
    let router = app.router().route("/late", get(|ctx: RequestContext| async move { ctx.session_id().to_owned() }));
    let request = Request::builder().uri("/late").header(SESSION, "s").body(Body::empty()).unwrap();
    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
    let error = json!({ "error": "RequestContext is available only on routes added with Builder::routes" });
    assert_eq!(serde_json::from_slice::<Value>(&body).unwrap(), error);
}

/// The app is mounted in a server of the customer, which has its own state, fallback
/// and middleware.
#[tokio::test]
async fn router_mounts_in_a_customer_server_under_its_middleware_and_fallback() {
    let app = BedrockAgentCoreApp::builder().invocation(echo).routes(custom_routes()).build().unwrap();
    let order = Arc::new(std::sync::Mutex::new(Vec::new()));
    let seen = order.clone();
    let outer = axum::middleware::from_fn(move |request: Request<Body>, next: axum::middleware::Next| {
        let seen = seen.clone();
        async move {
            // The customer's layer runs before the app: no context exists yet.
            seen.lock().unwrap().push(format!("{} {}", request.uri().path(), ambient_session()));
            let mut response = next.run(request).await;
            response.headers_mut().insert("x-outer", "1".parse().unwrap());
            response
        }
    });
    let server = Router::new()
        .route(
            "/home",
            get(|axum::extract::State(greeting): axum::extract::State<&'static str>| async move { greeting }),
        )
        .with_state("welcome")
        .merge(app.router())
        .fallback(|| async { (StatusCode::NOT_FOUND, "customer fallback") })
        .layer(outer);
    let server = App(server, app.tasks().clone());

    // (method, path, status, body)
    let cases = [
        ("GET", "/home", 200, "welcome"),
        ("GET", "/plain", 200, "no context needed"),
        ("GET", "/unknown", 404, "customer fallback"),
        ("POST", "/ping", 405, ""),
    ];
    for (method, path, status, body) in cases {
        let (actual, headers, bytes) = server.fetch(method, path, &[(SESSION, "s")], Body::empty()).await;
        assert_eq!(
            (actual, &*bytes, headers.get("x-outer").is_some()),
            (status, body.as_bytes(), true),
            "{method} {path}"
        );
    }
    assert_eq!(server.invoke(&[(SESSION, "s")], r#"{"n":1}"#).await.1["session_id"], "s");
    assert_eq!(server.ping().await["status"], "Healthy");
    let expected =
        ["/home", "/plain", "/unknown", "/ping", "/invocations", "/ping"].map(|path| format!("{path} no context"));
    assert_eq!(*order.lock().unwrap(), expected);
}

/// A fallback given through `Builder::routes` replaces the JSON 404 and stays in the
/// exported router, where it also answers for a fallback-free router it is merged into.
#[tokio::test]
async fn fallback_of_the_customer_routes_is_kept_when_serving_and_when_exported() {
    let builder = || {
        let routes = custom_routes().fallback(|| async { (StatusCode::NOT_FOUND, "customer fallback") });
        BedrockAgentCoreApp::builder().invocation(echo).routes(routes)
    };
    let standalone = App::new(builder());
    let app = builder().build().unwrap();
    let home = Router::new().route("/home", get(|| async { "home" }));
    let mounted = App(home.merge(app.router()), app.tasks().clone());

    for server in [&standalone, &mounted] {
        let (status, _, body) = server.fetch("GET", "/unknown", &[], Body::empty()).await;
        assert_eq!((status, &*body), (404, &b"customer fallback"[..]));
        assert_eq!(server.ping().await["status"], "Healthy");
    }
    assert_eq!(&*mounted.fetch("GET", "/home", &[], Body::empty()).await.2, b"home");

    // Without a fallback of the customer, the exported router has none: the JSON 404
    // of the SDK is added only when the app serves itself.
    let plain = BedrockAgentCoreApp::builder().invocation(echo).build().unwrap();
    let exported = App(plain.router(), plain.tasks().clone());
    let (status, _, body) = exported.fetch("GET", "/unknown", &[], Body::empty()).await;
    assert_eq!((status, &*body), (404, &b""[..]));
}

type Events = Arc<std::sync::Mutex<Vec<String>>>;

/// Adds a layer that records each request it sees, before it passes the request on.
fn recorded(builder: Builder, name: &'static str, events: &Events) -> Builder {
    let events = events.clone();
    builder.layer(axum::middleware::from_fn(move |request: Request<Body>, next: axum::middleware::Next| {
        events.lock().unwrap().push(format!("{name} {} {}", request.method(), request.uri().path()));
        next.run(request)
    }))
}

#[tokio::test]
async fn layer_sees_every_request_once_when_the_app_serves_and_when_its_router_is_exported() {
    let with_routes = || custom_routes().fallback(|| async { (StatusCode::NOT_FOUND, "customer fallback") });
    let json_404 = r#"{"error":"Not found"}"#;
    // (routes of the customer, exported router, reply of /plain, reply of /unknown)
    let cases = [
        (false, false, (404, json_404), (404, json_404)),
        // The JSON 404 is not part of the exported router.
        (false, true, (404, ""), (404, "")),
        (true, false, (200, "no context needed"), (404, "customer fallback")),
        (true, true, (200, "no context needed"), (404, "customer fallback")),
    ];
    for (routes, exported, plain, unknown) in cases {
        let events = Events::default();
        let builder = recorded(BedrockAgentCoreApp::builder().invocation(echo), "layer", &events);
        let app = if routes { builder.routes(with_routes()) } else { builder }.build().unwrap();
        let router = if exported { app.router() } else { app.standalone_router() };
        let app = App(router, app.tasks().clone());

        // (method, path, status and body. `None` skips the body)
        let requests = [
            ("POST", "/invocations", (200, None)),
            ("GET", "/ping", (200, None)),
            ("POST", "/ping", (405, Some(""))),
            ("GET", "/plain", (plain.0, Some(plain.1))),
            ("GET", "/unknown", (unknown.0, Some(unknown.1))),
        ];
        for (method, path, (status, body)) in requests {
            let (actual, _, bytes) = app.fetch(method, path, &[(SESSION, "s")], "{}").await;
            let case = format!("routes: {routes}, exported: {exported}, {method} {path}");
            assert_eq!(actual, status, "{case}");
            assert!(body.is_none_or(|body| body.as_bytes() == &*bytes), "{case}: {bytes:?}");
        }
        let expected = requests.map(|(method, path, _)| format!("layer {method} {path}"));
        assert_eq!(*events.lock().unwrap(), expected, "routes: {routes}, exported: {exported}");
    }
}

#[tokio::test]
async fn layer_added_last_runs_first_whatever_the_order_of_layer_and_routes_calls() {
    let events = Events::default();
    let builder = || BedrockAgentCoreApp::builder().invocation(echo);
    let layers = |builder| recorded(recorded(builder, "first", &events), "second", &events);
    for builder in [layers(builder().routes(custom_routes())), layers(builder()).routes(custom_routes())] {
        let app = App::new(builder);
        assert_eq!(app.fetch("GET", "/plain", &[], Body::empty()).await.0, 200);
        assert_eq!(std::mem::take(&mut *events.lock().unwrap()), ["second GET /plain", "first GET /plain"]);
    }
}

#[tokio::test]
async fn layer_can_reply_without_calling_the_app() {
    let called = Arc::new(AtomicBool::new(false));
    let flag = called.clone();
    let handler = move |payload: Value| {
        flag.store(true, Ordering::SeqCst);
        std::future::ready(Ok::<_, BoxError>(payload))
    };
    let deny =
        axum::middleware::from_fn(|_: Request<Body>, _: axum::middleware::Next| async { StatusCode::UNAUTHORIZED });
    let app = App::new(BedrockAgentCoreApp::builder().invocation(handler).layer(deny));
    assert_eq!(app.fetch("POST", "/invocations", &[(SESSION, "s")], "{}").await.0, 401);
    assert!(!called.load(Ordering::SeqCst));
}

/// The layer runs after the route is selected and before the app reads the request.
#[tokio::test]
async fn layer_changes_the_headers_the_app_reads_but_not_the_route_and_has_no_context() {
    let seen = Events::default();
    let events = seen.clone();
    let layer = axum::middleware::from_fn(move |mut request: Request<Body>, next: axum::middleware::Next| {
        events.lock().unwrap().push(ambient_session());
        request.headers_mut().insert(SESSION, "from-layer".parse().unwrap());
        *request.uri_mut() = "/unknown".parse().unwrap();
        next.run(request)
    });
    let app = App::new(BedrockAgentCoreApp::builder().invocation(echo).layer(layer));

    assert_eq!(app.invoke(&[(SESSION, "from-client")], "{}").await.1["session_id"], "from-layer");
    assert_eq!(app.ping().await["status"], "Healthy");
    assert_eq!(*seen.lock().unwrap(), ["no context", "no context"]);
}

#[tokio::test]
async fn stream_passes_through_a_layer_one_event_at_a_time() {
    let (sender, handler) = channel_handler::<u8>();
    let app = App::new(recorded(BedrockAgentCoreApp::builder().invocation(handler), "layer", &Events::default()));
    sender.send(Ok(1)).unwrap();
    // A layer that collected the body would wait here for the end of the stream.
    let mut frames = tokio::time::timeout(Duration::from_secs(10), app.stream("s")).await.expect("no reply arrived");
    assert_eq!(next_event(&mut frames).await.as_deref(), Some("data: 1\n\n"));
    sender.send(Ok(2)).unwrap();
    assert_eq!(next_event(&mut frames).await.as_deref(), Some("data: 2\n\n"));
    drop(sender);
    assert_eq!(next_event(&mut frames).await, None);
}

#[derive(Clone)]
struct CountsApplications(Arc<std::sync::atomic::AtomicUsize>);

impl<S> tower::Layer<S> for CountsApplications {
    type Service = S;

    fn layer(&self, inner: S) -> S {
        self.0.fetch_add(1, Ordering::SeqCst);
        inner
    }
}

/// axum constructs the layer of a route without state at each request, unless the
/// router is given its state first. A panic of `Layer::layer` would then leave `build`.
#[tokio::test]
async fn layers_are_constructed_in_build_and_not_when_a_request_arrives() {
    let applied = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let stateless = Router::new().route("/stateless", get(|| async { "mine" }));
    let builder = BedrockAgentCoreApp::builder().invocation(echo).routes(stateless);
    let app = builder.layer(CountsApplications(applied.clone())).build().unwrap();
    let in_build = applied.load(Ordering::SeqCst);
    assert!(in_build > 0);

    for router in [app.standalone_router(), app.router()] {
        let (status, _, body) = App(router, app.tasks().clone()).fetch("GET", "/stateless", &[], Body::empty()).await;
        assert_eq!((status, &*body), (200, &b"mine"[..]));
    }
    assert_eq!(applied.load(Ordering::SeqCst), in_build);
}

#[derive(Clone)]
struct PanicsWhenApplied;

impl<S> tower::Layer<S> for PanicsWhenApplied {
    type Service = S;

    fn layer(&self, _inner: S) -> S {
        panic!("the layer refused")
    }
}

const _: fn() = || {
    fn is_send_and_sync<T: Send + Sync>() {}
    is_send_and_sync::<Builder>();
};

#[test]
fn build_rejects_incomplete_or_invalid_configuration() {
    let no_handler = BedrockAgentCoreApp::builder();
    let zero_heartbeat = BedrockAgentCoreApp::builder().invocation(echo).stream_heartbeat(Duration::ZERO);
    // A route of the customer with the path and method of a route of the SDK.
    let duplicate = Router::new().route("/ping", get(|| async { "mine" }));
    // The routes are combined before the layer is applied, so the routes are reported.
    let duplicate_route = BedrockAgentCoreApp::builder().invocation(echo).routes(duplicate).layer(PanicsWhenApplied);
    let failing_layer = BedrockAgentCoreApp::builder().invocation(echo).layer(PanicsWhenApplied);
    // Two routers that are valid alone and cannot be combined.
    let twice = || Router::new().route("/twice", get(|| async { "mine" }));
    let overlapping_calls = BedrockAgentCoreApp::builder().invocation(echo).routes(twice()).routes(twice());
    let fallback = || Router::new().fallback(|| async { "mine" });
    let two_fallbacks = BedrockAgentCoreApp::builder().invocation(echo).routes(fallback()).routes(fallback());
    let hook = |path| BedrockAgentCoreApp::builder().invocation(echo).warmup_hook(WarmupHook::new(path));
    let hook_on_customer_route = hook("/warmup").routes(Router::new().route("/warmup", post(|| async { "mine" })));
    // (builder, a part of the reason that the error gives)
    let cases = [
        (no_handler, "handler"),
        (zero_heartbeat, "heartbeat"),
        (duplicate_route, "the routes cannot be combined: Overlapping method route. Handler for `GET /ping`"),
        (failing_layer, "a layer could not be applied: the layer refused"),
        (overlapping_calls, "/twice"),
        (two_fallbacks, "both have a fallback"),
        (hook("/warmup/"), "the warmup hook path must be canonical"),
        (hook("/invocations"), "POST /invocations"),
        (hook_on_customer_route, "POST /warmup"),
    ];
    for (builder, reason) in cases {
        let description = format!("{builder:?}");
        let error = builder.build().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidConfig, "{description}");
        assert!(error.to_string().contains(reason), "{error}");
    }
}

const WARMUP_TYPE: &str = "x-amzn-bedrock-agentcore-runtime-warmup-type";

fn warmup_app(hook: WarmupHook) -> App {
    App::new(BedrockAgentCoreApp::builder().invocation(echo).warmup_hook(hook))
}

/// Posts a warmup call with the given values of the warmup type header and no body.
async fn warm(app: &App, path: &str, types: &[&[u8]]) -> (u16, Value) {
    let mut request = Request::builder().method("POST").uri(path);
    for value in types {
        request = request.header(WARMUP_TYPE, *value);
    }
    let response = app.0.clone().oneshot(request.body(Body::empty()).unwrap()).await.unwrap();
    let status = response.status().as_u16();
    let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, serde_json::from_slice(&body).unwrap())
}

fn warmed(warmup_type: &str, result: &str) -> (u16, Value) {
    (200, json!({ "status": "ok", "type": warmup_type, "result": result }))
}

fn count(runs: &Arc<AtomicUsize>) -> impl Fn() -> std::future::Ready<Result<(), BoxError>> + Send + Sync + 'static {
    let runs = runs.clone();
    move || {
        runs.fetch_add(1, Ordering::SeqCst);
        std::future::ready(Ok(()))
    }
}

#[tokio::test]
async fn warmup_runs_the_handler_of_the_requested_type_and_skips_a_type_without_one() {
    let (memory, disk) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
    // A handler that was replaced by a later one. It must not run.
    let replaced = || async { Err::<(), BoxError>("replaced".into()) };
    let both = warmup_app(WarmupHook::new("/warmup").memory(count(&memory)).disk(count(&disk)));
    let memory_only = warmup_app(WarmupHook::new("/").memory(replaced).memory(count(&memory)));
    let disk_only = warmup_app(WarmupHook::new("/ping").disk(replaced).disk(count(&disk)));
    // (app, path, header value, reply, runs of the memory and the disk handler so far)
    let cases = [
        (&both, "/warmup", "memory", warmed("memory", "completed"), (1, 0)),
        (&both, "/warmup", " Disk ", warmed("disk", "completed"), (1, 1)),
        (&both, "/warmup", "MEMORY", warmed("memory", "completed"), (2, 1)),
        (&memory_only, "/", "memory", warmed("memory", "completed"), (3, 1)),
        (&memory_only, "/", "dIsk", warmed("disk", "skipped"), (3, 1)),
        (&disk_only, "/ping", "\tdisk\t", warmed("disk", "completed"), (3, 2)),
        (&disk_only, "/ping", "Memory", warmed("memory", "skipped"), (3, 2)),
    ];
    for (app, path, header, reply, runs) in cases {
        assert_eq!(warm(app, path, &[header.as_bytes()]).await, reply, "{path} {header:?}");
        assert_eq!((memory.load(Ordering::SeqCst), disk.load(Ordering::SeqCst)), runs, "{path} {header:?}");
    }
    // The hook on `POST /ping` leaves the health check on `GET /ping`.
    assert_eq!(disk_only.ping().await["status"], "Healthy");
}

#[tokio::test]
async fn warmup_type_header_errors_report_what_was_received() {
    let runs = Arc::new(AtomicUsize::new(0));
    let app = warmup_app(WarmupHook::new("/warmup").memory(count(&runs)).disk(count(&runs)));
    // (values of the header, the received text as the JSON string in the message)
    let cases: [(&[&[u8]], &str); 8] = [
        (&[], r#""""#),
        (&[b""], r#""""#),
        (&[b" Bogus "], r#"" Bogus ""#),
        (&[b"memory, disk"], r#""memory, disk""#),
        (&[b"memory", b"disk"], r#""memory, disk""#),
        (&[b"memory", b"memory"], r#""memory, memory""#),
        (&[b"say \"disk\""], r#""say \"disk\"""#),
        (&[b"\xffmemory"], "\"\u{fffd}memory\""),
    ];
    for (values, received) in cases {
        let error = format!("X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type must be 'memory' or 'disk', got {received}");
        assert_eq!(warm(&app, "/warmup", values).await, (400, json!({ "error": error })), "{values:?}");
    }
    assert_eq!(runs.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn failed_warmup_is_a_500_with_its_type_and_later_calls_still_run() {
    const FAIL: usize = 1;
    const PANIC: usize = 2;
    let next = Arc::new(AtomicUsize::new(0));
    // Fails once in the way that the test asked for, then succeeds.
    let handler = || {
        let next = next.clone();
        move || {
            let outcome = next.swap(0, Ordering::SeqCst);
            async move {
                match outcome {
                    FAIL => Err(BoxError::from("the model file is missing")),
                    PANIC => panic!("warmup handler panic"),
                    _ => Ok(()),
                }
            }
        }
    };
    let app = warmup_app(WarmupHook::new("/warmup").memory(handler()).disk(handler()));
    // (outcome of the handler, warmup type of the failed call, error of the reply)
    let cases = [
        (FAIL, "memory", "the model file is missing"),
        (FAIL, "disk", "the model file is missing"),
        (PANIC, "memory", "Internal error"),
        (PANIC, "disk", "Internal error"),
    ];
    for (outcome, failed, error) in cases {
        next.store(outcome, Ordering::SeqCst);
        let reply = warm(&app, "/warmup", &[failed.as_bytes()]).await;
        assert_eq!(reply, (500, json!({ "error": error, "type": failed })));
        for warmup_type in ["memory", "disk"] {
            let reply = warm(&app, "/warmup", &[warmup_type.as_bytes()]).await;
            assert_eq!(reply, warmed(warmup_type, "completed"), "after {failed} {error}");
        }
    }
    // The server still serves its other routes.
    assert_eq!(app.invoke(&[(SESSION, "s")], "{}").await.0, StatusCode::OK);
}

/// Subtracts one from the number of running handlers when a handler future ends or is dropped.
struct Running(Arc<AtomicUsize>);

impl Drop for Running {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

#[tokio::test]
async fn warmup_handlers_run_one_at_a_time_and_a_dropped_call_frees_the_next_one() {
    let (running, most) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
    let (entered, mut was_entered) = mpsc::unbounded_channel();
    let release = Arc::new(Semaphore::new(0));
    // Reports that it runs, then waits for a permit of the test.
    let handler = || {
        let (running, most, entered, release) = (running.clone(), most.clone(), entered.clone(), release.clone());
        move || {
            let (running, most, entered, release) = (running.clone(), most.clone(), entered.clone(), release.clone());
            async move {
                most.fetch_max(running.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst);
                let _running = Running(running);
                entered.send(()).unwrap();
                release.acquire().await?.forget();
                Ok::<(), BoxError>(())
            }
        }
    };
    let app = Arc::new(warmup_app(WarmupHook::new("/warmup").memory(handler()).disk(handler())));
    let call = |warmup_type: &'static str| {
        let app = app.clone();
        tokio::spawn(async move { warm(&app, "/warmup", &[warmup_type.as_bytes()]).await })
    };

    let first = call("memory");
    was_entered.recv().await.unwrap();
    let second = call("disk");
    // The second call gets every chance to start its handler while the first one is held.
    for _ in 0..50 {
        tokio::task::yield_now().await;
    }
    assert!(was_entered.try_recv().is_err(), "the second handler started while the first one ran");
    release.add_permits(1);
    assert_eq!(first.await.unwrap(), warmed("memory", "completed"));
    was_entered.recv().await.unwrap();
    release.add_permits(1);
    assert_eq!(second.await.unwrap(), warmed("disk", "completed"));

    // A call whose request is dropped while its handler waits.
    let dropped = call("memory");
    was_entered.recv().await.unwrap();
    dropped.abort();
    assert!(dropped.await.unwrap_err().is_cancelled());
    release.add_permits(1);
    assert_eq!(call("disk").await.unwrap(), warmed("disk", "completed"));
    assert_eq!((running.load(Ordering::SeqCst), most.load(Ordering::SeqCst)), (0, 1));
}

#[tokio::test]
async fn warmup_route_exists_only_with_a_hook_and_unknown_paths_keep_the_json_404() {
    let not_found = (404, json!({ "error": "Not found" }));
    let without_hook = App::new(BedrockAgentCoreApp::builder().invocation(echo));
    assert_eq!(warm(&without_hook, "/warmup", &[b"memory"]).await, not_found);
    let with_hook = warmup_app(WarmupHook::new("/warmup"));
    assert_eq!(warm(&with_hook, "/warmup", &[b"memory"]).await, warmed("memory", "skipped"));
    assert_eq!(warm(&with_hook, "/other", &[b"memory"]).await, not_found);
    // A layer wraps the hook route like every other route of the app.
    let events = Events::default();
    let builder = BedrockAgentCoreApp::builder().invocation(echo).warmup_hook(WarmupHook::new("/warmup"));
    let layered = App::new(recorded(builder, "layer", &events));
    assert_eq!(warm(&layered, "/warmup", &[b"disk"]).await, warmed("disk", "skipped"));
    assert_eq!(*events.lock().unwrap(), ["layer POST /warmup"]);
}