bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use axum::{
    extract::{FromRequestParts, Request, State},
    http::{StatusCode, request::Parts},
    middleware::Next,
    response::Response,
};

use super::{AppState, body::ScopedBody, headers, invocations::error_response, response::ROUTE_HEARTBEAT};
use crate::{RequestContext, context};

/// Marks a request that runs on a route of the app.
#[derive(Clone)]
struct AppRoute;

const MISSING_SESSION: &str = "Missing sessionId. Provide via x-amzn-bedrock-agentcore-runtime-session-id header.";
const NOT_AN_APP_ROUTE: &str = "RequestContext is available only on routes added with Builder::routes";

/// Runs around the routes given to `Builder::routes`. When the request has a session
/// header, it builds the request context from the headers, makes it ambient for the
/// route's handler and for the body of its response, and keeps it for the
/// `RequestContext` extractor.
pub(crate) async fn route_context(State(state): State<AppState>, mut request: Request, next: Next) -> Response {
    request.extensions_mut().insert(AppRoute);
    // A stream that the route returns uses the heartbeat of the app.
    let heartbeat = state.stream_heartbeat;
    let run = move |request: Request| ROUTE_HEARTBEAT.scope(heartbeat, next.run(request));
    let runtime = state.runtime;
    let Ok(Some(session_id)) = headers::session_id(request.headers()) else {
        return runtime.run(run(request)).await.map(|body| runtime.pump(body));
    };
    let request_id = headers::request_id(request.headers());
    let ctx = headers::context(
        request.headers(),
        session_id,
        request_id,
        state.tasks.clone(),
        state.workload_identity_contexts.clone(),
    );
    request.extensions_mut().insert(ctx.clone());
    let response = runtime.run(context::scope(ctx.clone(), run(request))).await;
    // The body can be a stream that is read after the handler has returned.
    response.map(|body| runtime.pump(ScopedBody::wrap_route(body, ctx)))
}

/// On a route added with [`Builder::routes`](super::Builder::routes), a handler can
/// take the request context as an argument.
///
/// The context is built from the request headers only, so the session ID must be in
/// its header: a route that takes this argument replies `400` without it. The
/// context's [`tasks`](RequestContext::tasks) is the registry of the app.
///
/// On any other route the extraction fails with `500`, because the route has no app
/// whose registry the context could use.
impl<S: Send + Sync> FromRequestParts<S> for RequestContext {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(ctx) = parts.extensions.get::<RequestContext>() {
            return Ok(ctx.clone());
        }
        Err(match parts.extensions.get::<AppRoute>() {
            Some(AppRoute) => error_response(StatusCode::BAD_REQUEST, MISSING_SESSION, None),
            None => error_response(StatusCode::INTERNAL_SERVER_ERROR, NOT_AN_APP_ROUTE, None),
        })
    }
}