bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
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.";

/// The invocations whose reply is not complete, each with its span, which holds the
/// request ID and the session ID. The shutdown names them in the log.
#[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 }
    }

    /// Writes one line for each invocation that the shutdown interrupts. Returns
    /// their number.
    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()
    }
}

/// Keeps one invocation in the [`InFlight`] list until it is dropped.
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()
}

/// A reply that refuses the request. AgentCore Runtime does not relay it to the
/// caller, who is sent to the logs. The reason must therefore be in the logs.
pub(crate) fn refused(status: StatusCode, error: &str, details: Option<String>) -> Response {
    tracing::warn!(error, details, "invocation request refused");
    error_response(status, error, details)
}

/// The reason of a body that does not fit the request type of the handler. Serde
/// quotes the value that it did not expect, and the payload must stay out of the
/// logs. Only the text for a missing field is known to hold no value.
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);
    // The span carries the IDs to every line of the invocation. At the level of the
    // lines that report a failure, a filter such as `RUST_LOG=warn` keeps it.
    // Both IDs are recorded as text: the log shows them in quotes, with the
    // characters of a caller escaped.
    let span = tracing::error_span!("invocation", request_id = request_id.as_str(), session_id = tracing::field::Empty);
    // The session ID of the header is on every line from here on, also for a
    // request that is refused or interrupted before its body is parsed.
    if let Ok(Some(session_id)) = headers::session_id(&headers) {
        span.record("session_id", session_id.as_str());
    }
    // The invocation is in flight from here on. The shutdown names it also while
    // its body is still arriving.
    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;
    // The outcome is logged when the body has been sent, which for a stream is long
    // after this function returns.
    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)))
}

/// Logs an invocation that was dropped before its handler returned, also while its
/// body was still arriving: the client disconnected, or the shutdown deadline
/// passed. The line carries the IDs of the span.
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);
    };
    // Every field value and every member of a list must be `identity`.
    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) => {
            // Several Accept fields mean the same as one field with a comma-separated list.
            let accept: Vec<&str> = headers.get_all(ACCEPT).iter().filter_map(|value| value.to_str().ok()).collect();
            // The conversion can drop the handler's stream, whose destructors may read the context.
            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 })) => {
            // AgentCore Runtime does not relay this reply to the caller, who is sent
            // to the logs instead. The reason must therefore be in the logs.
            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))
}