Skip to main content

bedrock_agentcore/runtime/
extract.rs

1use axum::{
2    extract::{FromRequestParts, Request, State},
3    http::{StatusCode, request::Parts},
4    middleware::Next,
5    response::Response,
6};
7
8use super::{AppState, body::ScopedBody, headers, invocations::error_response, response::ROUTE_HEARTBEAT};
9use crate::{RequestContext, context};
10
11/// Marks a request that runs on a route of the app.
12#[derive(Clone)]
13struct AppRoute;
14
15const MISSING_SESSION: &str = "Missing sessionId. Provide via x-amzn-bedrock-agentcore-runtime-session-id header.";
16const NOT_AN_APP_ROUTE: &str = "RequestContext is available only on routes added with Builder::routes";
17
18/// Runs around the routes given to `Builder::routes`. When the request has a session
19/// header, it builds the request context from the headers, makes it ambient for the
20/// route's handler and for the body of its response, and keeps it for the
21/// `RequestContext` extractor.
22pub(crate) async fn route_context(State(state): State<AppState>, mut request: Request, next: Next) -> Response {
23    request.extensions_mut().insert(AppRoute);
24    // A stream that the route returns uses the heartbeat of the app.
25    let heartbeat = state.stream_heartbeat;
26    let run = move |request: Request| ROUTE_HEARTBEAT.scope(heartbeat, next.run(request));
27    let runtime = state.runtime;
28    let Ok(Some(session_id)) = headers::session_id(request.headers()) else {
29        return runtime.run(run(request)).await.map(|body| runtime.pump(body));
30    };
31    let request_id = headers::request_id(request.headers());
32    let ctx = headers::context(
33        request.headers(),
34        session_id,
35        request_id,
36        state.tasks.clone(),
37        state.workload_identity_contexts.clone(),
38    );
39    request.extensions_mut().insert(ctx.clone());
40    let response = runtime.run(context::scope(ctx.clone(), run(request))).await;
41    // The body can be a stream that is read after the handler has returned.
42    response.map(|body| runtime.pump(ScopedBody::wrap_route(body, ctx)))
43}
44
45/// On a route added with [`Builder::routes`](super::Builder::routes), a handler can
46/// take the request context as an argument.
47///
48/// The context is built from the request headers only, so the session ID must be in
49/// its header: a route that takes this argument replies `400` without it. The
50/// context's [`tasks`](RequestContext::tasks) is the registry of the app.
51///
52/// On any other route the extraction fails with `500`, because the route has no app
53/// whose registry the context could use.
54impl<S: Send + Sync> FromRequestParts<S> for RequestContext {
55    type Rejection = Response;
56
57    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
58        if let Some(ctx) = parts.extensions.get::<RequestContext>() {
59            return Ok(ctx.clone());
60        }
61        Err(match parts.extensions.get::<AppRoute>() {
62            Some(AppRoute) => error_response(StatusCode::BAD_REQUEST, MISSING_SESSION, None),
63            None => error_response(StatusCode::INTERNAL_SERVER_ERROR, NOT_AN_APP_ROUTE, None),
64        })
65    }
66}