bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::{fmt, future::Future, sync::Arc, time::Instant};

use axum::{
    Json, Router,
    extract::State,
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::post,
};
use serde_json::{Value, json};
use tokio::sync::Mutex;

use super::{
    AppState,
    body::seconds_since,
    handler::{BoxError, BoxFuture, CatchPanic, Failure},
    headers::WARMUP_TYPE,
    serve::AppRuntime,
};
use crate::{Error, ErrorKind};

const MAX_PATH_CHARS: usize = 32;

type Handler = Arc<dyn Fn() -> BoxFuture<Result<(), Failure>> + Send + Sync>;

#[derive(Clone, Copy)]
enum WarmupType {
    Memory,
    Disk,
}

impl WarmupType {
    fn as_str(self) -> &'static str {
        match self {
            Self::Memory => "memory",
            Self::Disk => "disk",
        }
    }
}

/// The build warmup hook of AgentCore Runtime: the path that serves it and a handler
/// for each of its two calls. Give it to [`Builder::warmup_hook`](super::Builder::warmup_hook).
///
/// ```no_run
/// use bedrock_agentcore::runtime::{BedrockAgentCoreApp, WarmupHook};
///
/// async fn invoke(payload: serde_json::Value) -> Result<serde_json::Value, std::convert::Infallible> {
///     Ok(payload)
/// }
///
/// async fn load_model() -> Result<(), std::io::Error> {
///     // Blocking work runs on the blocking thread pool, so `GET /ping` keeps answering.
///     tokio::task::spawn_blocking(|| std::fs::read("/opt/model.bin")).await??;
///     Ok(())
/// }
///
/// # async fn run() -> Result<(), bedrock_agentcore::Error> {
/// BedrockAgentCoreApp::builder()
///     .invocation(invoke)
///     .warmup_hook(WarmupHook::new("/warmup").memory(load_model))
///     .build()?
///     .run()
///     .await
/// # }
/// ```
///
/// # When AgentCore Runtime calls the hook
///
/// The [build warmup hook](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-lifecycle-hooks.html)
/// is available on platform version V2 with the microVM compute type. During
/// `CreateAgentRuntime` and `UpdateAgentRuntime`, after the agent passes its health
/// check and before the runtime is `READY`, the service sends two `POST` requests to
/// the hook path. It takes a snapshot of the agent between them.
///
/// - The [`memory`](Self::memory) call comes first, before the snapshot. What the
///   process holds in memory when the handler returns is the state that every new
///   session starts with. Load models, fill caches and build other shared state here.
/// - The [`disk`](Self::disk) call comes second, after the snapshot. The service
///   records which files the agent reads during this call and makes those files fast
///   to read for new sessions. Read the files that a session needs at its start here.
///   State that this handler puts in memory is not part of what sessions start with.
///
/// The two calls share a limit of 120 seconds, which the service measures. The server
/// adds no timeout of its own. A reply other than 2xx fails the create or update, and
/// the service does not retry. So an `Err` or a panic of a handler fails the create
/// or update.
///
/// # Configuration
///
/// The path given to [`new`](Self::new) must equal
/// `hooksConfiguration.build.warmup.action.httpPost.path` of the agent runtime. The
/// hook is served on the serving port of the app, so `httpPost.port` must be unset or
/// equal to that port.
///
/// # Handlers
///
/// A handler is an async function or closure with no arguments that returns
/// `Result<(), E>`, where `E` converts into a boxed error. The server must keep
/// answering `GET /ping` during a warmup call, so a handler must not block its
/// thread. Run blocking work, such as a model load or file reads, with
/// [`tokio::task::spawn_blocking`] and await it.
///
/// A handler gets no [`RequestContext`](crate::RequestContext), because a hook call
/// belongs to no session.
///
/// The handler futures of one hook never run at the same time: a call waits until
/// the handler of an earlier call has completed, failed, panicked or been dropped.
/// This covers the handler future only. The server drops the future when the client
/// disconnects or the shutdown deadline cancels the request, as
/// [`run`](super::BedrockAgentCoreApp::run) describes. Work that the handler started
/// and that the server does not own, such as a `spawn_blocking` closure or a spawned
/// task, then keeps running until it ends, and a later warmup call can overlap with
/// it.
///
/// # Replies
///
/// The service sends the warmup type in the
/// `X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type` header. The server ignores the case
/// of the value and whitespace around it, and does not read the request body.
///
/// | Request | Reply |
/// | --- | --- |
/// | The type has a handler and it returns `Ok` | `200 {"status": "ok", "type": "memory", "result": "completed"}` |
/// | The type has no handler | `200 {"status": "ok", "type": "memory", "result": "skipped"}` |
/// | The handler returns `Err` | `500 {"error": <Display text of the error>, "type": "memory"}` |
/// | The handler panics | `500 {"error": "Internal error", "type": "memory"}` |
/// | The header is absent, repeated or not a warmup type | `400 {"error": ..}` |
///
/// After an `Err` or a panic the server keeps running, and the next warmup call is
/// handled normally. The panic rule holds for unwinding panics only, not with
/// `panic = "abort"`.
#[must_use]
pub struct WarmupHook {
    path: String,
    memory: Option<Handler>,
    disk: Option<Handler>,
}

impl WarmupHook {
    /// Creates a hook that is served as `POST` on `path`, with no handlers. A warmup
    /// type without a handler gets the `skipped` reply.
    ///
    /// The path follows the rules of the AgentCore Runtime API, and
    /// [`Builder::build`](super::Builder::build) returns
    /// [`ErrorKind::InvalidConfig`] when it breaks one of them:
    ///
    /// - It has 1 to 32 characters.
    /// - It starts with `/` and contains only ASCII letters, digits, `.`, `_`, `~`,
    ///   `/` and `-`.
    /// - It is in canonical form: no `/` at the end except for the path `/`, no `//`,
    ///   and no `.` or `..` segment.
    ///
    /// The path also cannot be `/invocations` or the path of a `POST` route given to
    /// [`Builder::routes`](super::Builder::routes). The path `/ping` is valid, because
    /// the health check is `GET /ping`.
    pub fn new(path: impl Into<String>) -> Self {
        Self { path: path.into(), memory: None, disk: None }
    }

    /// Sets the handler of the `memory` call, which runs before the snapshot. What
    /// the process holds in memory when it returns is the state that every new
    /// session starts with. A later call replaces the handler of an earlier one.
    pub fn memory<F, Fut, E>(mut self, handler: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), E>> + Send + 'static,
        E: Into<BoxError>,
    {
        self.memory = Some(erase(handler));
        self
    }

    /// Sets the handler of the `disk` call, which runs after the snapshot. The files
    /// that the agent reads during this call become fast to read for new sessions.
    /// State that the handler puts in memory is not part of what sessions start
    /// with. A later call replaces the handler of an earlier one.
    pub fn disk<F, Fut, E>(mut self, handler: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), E>> + Send + 'static,
        E: Into<BoxError>,
    {
        self.disk = Some(erase(handler));
        self
    }

    pub(crate) fn validate(&self) -> Result<(), Error> {
        validate_path(&self.path).map_err(|reason| Error::new(ErrorKind::InvalidConfig, reason))
    }

    pub(super) fn add_route(self, router: Router<AppState>) -> Router<AppState> {
        let path = self.path.clone();
        let hook = Arc::new((self, Mutex::new(())));
        router.route(
            &path,
            post(move |State(state): State<AppState>, headers: HeaderMap| async move {
                let (hook, lock) = &*hook;
                hook.respond(lock, &headers, &state.runtime).await
            }),
        )
    }

    async fn respond(&self, lock: &Mutex<()>, headers: &HeaderMap, runtime: &AppRuntime) -> Response {
        let started = Instant::now();
        let warmup_type = match warmup_type(headers) {
            Ok(warmup_type) => warmup_type,
            Err(received) => {
                tracing::warn!(received, "warmup request with an invalid warmup type header");
                let error = format!(
                    "X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type must be 'memory' or 'disk', got {}",
                    Value::String(received)
                );
                return (StatusCode::BAD_REQUEST, Json(json!({ "error": error }))).into_response();
            }
        };
        let handler = match warmup_type {
            WarmupType::Memory => &self.memory,
            WarmupType::Disk => &self.disk,
        };
        let warmup_type = warmup_type.as_str();
        let seconds = || seconds_since(started);
        let Some(handler) = handler else {
            tracing::info!(warmup_type, seconds = seconds(), "warmup skipped: the type has no handler");
            return Json(json!({ "status": "ok", "type": warmup_type, "result": "skipped" })).into_response();
        };
        let outcome = {
            let _running = lock.lock().await;
            runtime.run(CatchPanic(Some(handler()))).await
        };
        let error = match outcome {
            Ok(Ok(())) => {
                tracing::info!(warmup_type, seconds = seconds(), "warmup completed");
                return Json(json!({ "status": "ok", "type": warmup_type, "result": "completed" })).into_response();
            }
            Ok(Err(Failure { error, causes })) => {
                tracing::error!(warmup_type, seconds = seconds(), error, causes, "warmup handler returned an error");
                error
            }
            Err(panic) => {
                tracing::error!(warmup_type, seconds = seconds(), panic, "the warmup handler panicked");
                "Internal error".to_owned()
            }
        };
        (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": error, "type": warmup_type }))).into_response()
    }
}

impl fmt::Debug for WarmupHook {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WarmupHook")
            .field("path", &self.path)
            .field("memory_set", &self.memory.is_some())
            .field("disk_set", &self.disk.is_some())
            .finish()
    }
}

fn erase<F, Fut, E>(handler: F) -> Handler
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), E>> + Send + 'static,
    E: Into<BoxError>,
{
    let handler = Arc::new(handler);
    Arc::new(move || {
        let handler = handler.clone();
        // The call of the handler and the `Display` of its error are the customer's
        // code. Both run when this future is polled, inside the panic boundary.
        Box::pin(async move { handler().await.map_err(|error| Failure::of(error.into())) })
    })
}

/// The warmup type of a request, or the text that the 400 reply reports as received.
fn warmup_type(headers: &HeaderMap) -> Result<WarmupType, String> {
    let values: Vec<_> =
        headers.get_all(WARMUP_TYPE).iter().map(|value| String::from_utf8_lossy(value.as_bytes())).collect();
    if let [value] = &values[..] {
        let value = value.trim();
        if value.eq_ignore_ascii_case("memory") {
            return Ok(WarmupType::Memory);
        }
        if value.eq_ignore_ascii_case("disk") {
            return Ok(WarmupType::Disk);
        }
    }
    Err(values.join(", "))
}

fn validate_path(path: &str) -> Result<(), String> {
    let length = path.chars().count();
    if !(1..=MAX_PATH_CHARS).contains(&length) {
        return Err(format!("the warmup hook path must have 1 to {MAX_PATH_CHARS} characters, got {path:?}"));
    }
    let allowed = |c: char| c.is_ascii_alphanumeric() || "._~/-".contains(c);
    if !path.starts_with('/') || !path.chars().all(allowed) {
        return Err(format!(
            "the warmup hook path must start with '/' and contain only ASCII letters, digits, '.', '_', '~', '/' \
             and '-', got {path:?}"
        ));
    }
    let canonical = path == "/" || path[1..].split('/').all(|segment| !matches!(segment, "" | "." | ".."));
    if !canonical {
        return Err(format!(
            "the warmup hook path must be canonical: no '/' at the end except for the path '/', no '//', and no \
             '.' or '..' segment, got {path:?}"
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::validate_path;

    #[test]
    fn path_rules_each_have_their_own_message() {
        let longest = format!("/{}", "a".repeat(31));
        let too_long = format!("/{}", "a".repeat(32));
        // (path, a part of the message of the rule that it breaks)
        let cases = [
            ("/", None),
            ("/warmup", None),
            ("/a/b-c_d.e~f", None),
            (longest.as_str(), None),
            ("/a.b", None),
            ("/..a", None),
            ("", Some("1 to 32 characters")),
            (too_long.as_str(), Some("1 to 32 characters")),
            ("warmup", Some("must start with '/'")),
            ("/warm up", Some("must start with '/'")),
            ("/{warmup}", Some("must start with '/'")),
            ("/warmup/", Some("canonical")),
            ("/a//b", Some("canonical")),
            ("/a/./b", Some("canonical")),
            ("/a/..", Some("canonical")),
        ];
        for (path, rule) in cases {
            let error = validate_path(path).err();
            match rule {
                None => assert_eq!(error, None, "{path}"),
                Some(rule) => {
                    let error = error.unwrap_or_else(|| panic!("{path:?} is accepted"));
                    assert!(error.contains(rule) && error.ends_with(&format!("got {path:?}")), "{error}");
                }
            }
        }
    }
}