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>;
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()
}
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())
}
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() }))
}
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),
"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"}"#;
let cases = [
(Some("from-header"), both, "from-header"),
(None, body_only, "from-body"),
(Some(""), body_only, "from-body"),
(None, r#"{"sessionId":" "}"#, " "),
(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));
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")];
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));
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" }));
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:?}");
}
#[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;
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,
}
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())?)
}
"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();
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);
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"),
),
(&[], 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}");
}
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")];
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);
}
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));
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"));
}
#[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 {
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())
}
}
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>>;
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;
let cases = [
(json!({ "n": 1 }), "data: {\"n\":1}\n\n"),
(json!("line 1\n\nevent: error"), "data: \"line 1\\n\\nevent: error\"\n\n"),
(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);
}
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));
assert_eq!(*dropped_in.lock().unwrap(), ["refused-session"; 3]);
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:?}");
}
}
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() {
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 {
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}");
}
}
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");
}
}
#[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;
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);
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"));
}
#[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());
assert_eq!(next_event(&mut frames).await.as_deref(), Some(":\n\n"));
}
}
#[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"));
}
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" }));
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)),
("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}");
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");
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);
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}");
}
#[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)
}
}
#[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);
assert_eq!(causes(Box::new(Wrapped(error(identity)))).as_deref(), Some("the SDK failed"));
let serve = causes(Box::new(Wrapped(error(ErrorKind::Serve))));
assert_eq!(serve.as_deref(), Some("the SDK failed: could not deliver SECRET-URL"));
}
#[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));
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);
}
#[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() };
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");
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");
mode.store(AUTOMATIC, Ordering::SeqCst);
let guard = app.1.track("seen when the handler decides nothing");
assert_eq!(status().await, "HealthyBusy");
drop(guard);
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}");
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,
}
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));
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));
assert_eq!(app.fetch("GET", "/plain", &[], Body::empty()).await.2, "no context needed");
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"));
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() {
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);
}
#[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 {
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());
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);
}
#[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");
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>>>;
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"}"#;
let cases = [
(false, false, (404, json_404), (404, json_404)),
(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());
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));
}
#[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();
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
}
}
#[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);
let duplicate = Router::new().route("/ping", get(|| async { "mine" }));
let duplicate_route = BedrockAgentCoreApp::builder().invocation(echo).routes(duplicate).layer(PanicsWhenApplied);
let failing_layer = BedrockAgentCoreApp::builder().invocation(echo).layer(PanicsWhenApplied);
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" })));
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))
}
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)));
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)));
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:?}");
}
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)));
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));
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()));
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}");
}
}
assert_eq!(app.invoke(&[(SESSION, "s")], "{}").await.0, StatusCode::OK);
}
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));
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");
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"));
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);
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"]);
}