use std::{
sync::{Arc, Mutex, PoisonError},
time::Instant,
};
use axum::{
Json,
body::Bytes,
extract::{FromRequest, Request, State, rejection::BytesRejection},
http::{
HeaderMap, StatusCode,
header::{ACCEPT, CONTENT_ENCODING},
},
response::{IntoResponse, Response},
};
use serde_json::{Value, json};
use tracing::Instrument;
use super::{
AppState,
body::{ScopedBody, seconds_since},
handler::{Failure, HandlerError},
headers,
response::StreamFailed,
};
use crate::{RequestContext, context};
const MISSING_SESSION: &str =
"Missing sessionId. Provide via x-amzn-bedrock-agentcore-runtime-session-id header or request body.";
const SESSION_NOT_UTF8: &str =
"Invalid sessionId. The x-amzn-bedrock-agentcore-runtime-session-id header is not UTF-8.";
#[derive(Clone, Default)]
pub(crate) struct InFlight(Arc<Mutex<Flights>>);
#[derive(Default)]
struct Flights {
entered: u64,
spans: Vec<(u64, tracing::Span)>,
}
impl InFlight {
fn enter(&self, span: tracing::Span) -> Entered {
let mut flights = self.0.lock().unwrap_or_else(PoisonError::into_inner);
flights.entered += 1;
let id = flights.entered;
flights.spans.push((id, span));
Entered { in_flight: self.clone(), id }
}
pub(crate) fn log_interrupted(&self) -> usize {
let spans: Vec<tracing::Span> = {
let flights = self.0.lock().unwrap_or_else(PoisonError::into_inner);
flights.spans.iter().map(|(_, span)| span.clone()).collect()
};
for span in &spans {
span.in_scope(|| tracing::warn!("shutdown signal received while this invocation is in flight"));
}
spans.len()
}
}
pub(crate) struct Entered {
in_flight: InFlight,
id: u64,
}
impl Drop for Entered {
fn drop(&mut self) {
let mut flights = self.in_flight.0.lock().unwrap_or_else(PoisonError::into_inner);
flights.spans.retain(|(id, _)| *id != self.id);
}
}
pub(crate) fn error_response(status: StatusCode, error: &str, details: Option<String>) -> Response {
let body = match details {
Some(details) => json!({ "error": error, "details": details }),
None => json!({ "error": error }),
};
(status, Json(body)).into_response()
}
pub(crate) fn refused(status: StatusCode, error: &str, details: Option<String>) -> Response {
tracing::warn!(error, details, "invocation request refused");
error_response(status, error, details)
}
fn decode_reason(error: &serde_json::Error) -> String {
let text = error.to_string();
if error.classify() == serde_json::error::Category::Data && !text.starts_with("missing field") {
return format!("the body does not fit the request type at line {} column {}", error.line(), error.column());
}
text
}
pub(crate) async fn not_found() -> Response {
error_response(StatusCode::NOT_FOUND, "Not found", None)
}
pub(crate) async fn invocations(State(state): State<AppState>, request: Request) -> Response {
let started = Instant::now();
let headers = request.headers().clone();
let request_id = headers::request_id(&headers);
let span = tracing::error_span!("invocation", request_id = request_id.as_str(), session_id = tracing::field::Empty);
if let Ok(Some(session_id)) = headers::session_id(&headers) {
span.record("session_id", session_id.as_str());
}
let entered = state.in_flight.enter(span.clone());
let mut unfinished = Unfinished { span: span.clone(), started, finished: false };
let runtime = state.runtime.clone();
let respond = async {
let body = Bytes::from_request(request, &()).await;
respond(state, &headers, body, request_id).await
};
let (response, ctx) = respond.instrument(span.clone()).await;
unfinished.finished = true;
let status = response.status();
let stream_failed = response.extensions().get::<StreamFailed>().cloned();
response.map(|body| runtime.pump(ScopedBody::wrap(body, ctx, span, status, started, stream_failed, entered)))
}
struct Unfinished {
span: tracing::Span,
started: Instant,
finished: bool,
}
impl Drop for Unfinished {
fn drop(&mut self) {
if !self.finished {
let seconds = seconds_since(self.started);
self.span.in_scope(|| tracing::warn!(seconds, "invocation dropped before its handler returned"));
}
}
}
async fn respond(
state: AppState,
headers: &HeaderMap,
body: Result<Bytes, BytesRejection>,
request_id: String,
) -> (Response, Option<RequestContext>) {
let Ok(header_session) = headers::session_id(headers) else {
return (refused(StatusCode::BAD_REQUEST, SESSION_NOT_UTF8, None), None);
};
let unsupported = headers.get_all(CONTENT_ENCODING).iter().any(|value| {
let codings = value.to_str().unwrap_or("?").split(',').map(str::trim);
codings.filter(|coding| !coding.is_empty()).any(|coding| !coding.eq_ignore_ascii_case("identity"))
});
if unsupported {
return (refused(StatusCode::UNSUPPORTED_MEDIA_TYPE, "Unsupported Content-Encoding", None), None);
}
let body = match body {
Ok(body) => body,
Err(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
let details = format!("The limit is {} bytes. Builder::body_limit changes it.", state.body_limit);
return (refused(StatusCode::PAYLOAD_TOO_LARGE, "Request body is too large", Some(details)), None);
}
Err(rejection) => {
let details = Some(rejection.body_text());
return (refused(StatusCode::BAD_REQUEST, "Failed to read request body", details), None);
}
};
let payload: Value = match serde_json::from_slice(&body) {
Ok(payload) => payload,
Err(error) => {
return (refused(StatusCode::BAD_REQUEST, "Invalid JSON", Some(error.to_string())), None);
}
};
let body_session =
|| payload.get("sessionId").and_then(Value::as_str).filter(|id| !id.is_empty()).map(str::to_owned);
let session_id = match header_session {
Some(session_id) => session_id,
None => {
let Some(session_id) = body_session() else {
return (refused(StatusCode::BAD_REQUEST, MISSING_SESSION, None), None);
};
tracing::Span::current().record("session_id", session_id.as_str());
session_id
}
};
drop(payload);
let ctx = headers::context(
headers,
session_id,
request_id,
state.tasks.clone(),
state.workload_identity_contexts.clone(),
);
let result = state.runtime.run(context::scope(ctx.clone(), state.handler.call(body, ctx.clone()))).await;
let response = match result {
Ok(response) => {
let accept: Vec<&str> = headers.get_all(ACCEPT).iter().filter_map(|value| value.to_str().ok()).collect();
context::sync_scope(ctx.clone(), || response.into_http(Some(&accept.join(",")), state.stream_heartbeat))
}
Err(HandlerError::Decode(error)) => {
tracing::warn!(
error = "Invalid request body format",
details = decode_reason(&error),
"invocation request refused"
);
error_response(StatusCode::BAD_REQUEST, "Invalid request body format", Some(error.to_string()))
}
Err(HandlerError::Failed(Failure { error, causes })) => {
tracing::error!(error, causes, "invocation handler returned an error");
error_response(StatusCode::INTERNAL_SERVER_ERROR, &error, None)
}
Err(HandlerError::Panicked(panic)) => {
tracing::error!(panic, "the invocation handler panicked");
error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal error", None)
}
};
(response, Some(ctx))
}