bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::{
    any::Any,
    future::Future,
    panic::{AssertUnwindSafe, catch_unwind},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use axum::body::Bytes;
use serde::de::DeserializeOwned;

use super::response::{IntoInvocationResponse, Response};
use crate::RequestContext;

pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync>;
type HandlerFuture = BoxFuture<Result<Response, HandlerError>>;

pub(crate) enum HandlerError {
    Decode(serde_json::Error),
    Failed(Failure),
    /// The text of the panic.
    Panicked(String),
}

/// An error that customer code returned.
pub(crate) struct Failure {
    /// The `Display` text of the error. It is the reply to the caller.
    pub(crate) error: String,
    /// The `Display` texts of the sources of the error. They go to the log only: an
    /// AWS SDK error has the text `service error`, and its source names the cause.
    pub(crate) causes: Option<String>,
}

impl Failure {
    /// Runs the `Display` of the error and of its sources, which is customer code.
    pub(crate) fn of(error: BoxError) -> Self {
        // The source of an Identity error of this crate can hold a credential or the
        // authorization URL. The text of that error has what a log needs, so the
        // walk ends there, also when an error of the application wraps it.
        let hides_source = |error: &(dyn std::error::Error + 'static)| {
            error.downcast_ref::<crate::Error>().is_some_and(crate::Error::hides_source)
        };
        let mut causes = Vec::new();
        let mut current: &(dyn std::error::Error + 'static) = error.as_ref();
        // The limit ends a chain of sources that is a cycle.
        while causes.len() < 8 && !hides_source(current) {
            let Some(source) = current.source() else { break };
            causes.push(source.to_string());
            current = source;
        }
        Self { error: error.to_string(), causes: (!causes.is_empty()).then(|| causes.join(": ")) }
    }
}

/// The text of a panic, for the log.
pub(crate) fn panic_text(panic: &(dyn Any + Send)) -> &str {
    panic
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| panic.downcast_ref::<&str>().copied())
        .unwrap_or("the panic has no text")
}

pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Resolves to the text of the panic when the wrapped future panics and unwinds.
pub(crate) struct CatchPanic<T>(pub(crate) Option<BoxFuture<T>>);

impl<T> Future for CatchPanic<T> {
    type Output = Result<T, String>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Some(future) = self.0.as_mut() else { return Poll::Ready(Err("polled after its end".to_owned())) };
        match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
            Ok(Poll::Pending) => Poll::Pending,
            Ok(Poll::Ready(output)) => {
                self.0 = None;
                Poll::Ready(Ok(output))
            }
            Err(panic) => {
                // Dropping the future can run destructors that panic again.
                let future = self.0.take();
                let _ = catch_unwind(AssertUnwindSafe(|| drop(future)));
                Poll::Ready(Err(panic_text(panic.as_ref()).to_owned()))
            }
        }
    }
}

/**
 The items in this module are public so that the public handler trait can refer
 to them. The module is private, so other crates cannot name them.
**/
mod sealed {
    use super::*;

    #[derive(Clone)]
    pub struct Erased(pub(super) Arc<dyn Fn(Bytes, RequestContext) -> HandlerFuture + Send + Sync>);

    impl Erased {
        pub(crate) fn call(&self, body: Bytes, ctx: RequestContext) -> HandlerFuture {
            (self.0)(body, ctx)
        }
    }

    impl std::fmt::Debug for Erased {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("Erased")
        }
    }

    pub trait Sealed<Marker> {
        fn erase(self) -> Erased;
    }
}
pub(crate) use sealed::{Erased, Sealed};

/// An async function that handles `POST /invocations`.
///
/// It is implemented for functions and closures with these signatures:
///
/// - `async fn(Req) -> Result<O, E>`
/// - `async fn(Req, RequestContext) -> Result<O, E>`
///
/// `Req` is any [`DeserializeOwned`] type, for example `serde_json::Value` for an
/// untyped payload. `O` is any [`IntoInvocationResponse`] type. `E` converts into a
/// boxed error and its `Display` text becomes the `500` error body.
///
/// The handler and the future that it returns must be `Send`, and the handler must be
/// `Sync + 'static`. `Req` must be `Send + 'static`, the boxed error must be
/// `Send + Sync`, and both arguments are taken by value, in this order.
///
/// A handler that panics gets `500 {"error": "Internal error"}` and the server keeps
/// running. So does a panic in the conversion or the `Display` of the error that the
/// handler returned. This holds for unwinding panics only, not with `panic = "abort"`.
///
/// # Blocking work
///
/// A handler must not block its thread, for example with `std::thread::sleep` or
/// synchronous I/O. Blocking work belongs in `tokio::task::spawn_blocking`.
/// [`BedrockAgentCoreApp::run`](super::BedrockAgentCoreApp::run) describes what a
/// handler that blocks delays.
///
/// The `Marker` parameter only separates the two signatures. The compiler infers it.
///
/// This trait is sealed. Other crates cannot implement it.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a valid invocation handler",
    label = "not a valid invocation handler",
    note = "a handler is an `async fn(Req) -> Result<O, E>` or an `async fn(Req, RequestContext) -> Result<O, E>`",
    note = "`Req` must implement `serde::de::DeserializeOwned + Send`, and `RequestContext` is taken by value",
    note = "`O` must implement `serde::Serialize`, or be a `runtime::Response`",
    note = "`E` must convert into `Box<dyn std::error::Error + Send + Sync>`",
    note = "the function and its future must be `Send`, and the function must be `Sync + 'static`"
)]
pub trait InvocationHandler<Marker>: Sealed<Marker> {}

impl<T: Sealed<Marker>, Marker> InvocationHandler<Marker> for T {}

fn erase<Req, Fut, O, E>(call: impl Fn(Req, RequestContext) -> Fut + Send + Sync + 'static) -> Erased
where
    Req: DeserializeOwned + Send + 'static,
    Fut: Future<Output = Result<O, E>> + Send + 'static,
    O: IntoInvocationResponse,
    E: Into<BoxError>,
{
    let call = Arc::new(call);
    Erased(Arc::new(move |body, ctx| {
        let call = call.clone();
        let guarded = CatchPanic(Some(Box::pin(async move {
            let request = serde_json::from_slice(&body).map_err(HandlerError::Decode)?;
            drop(body);
            match call(request, ctx).await {
                Ok(output) => Ok(output.into_invocation_response()),
                // The error's `Display` is the handler's code. It runs here, inside
                // the panic boundary.
                Err(error) => Err(HandlerError::Failed(Failure::of(error.into()))),
            }
        })));
        Box::pin(async move { guarded.await.unwrap_or_else(|panic| Err(HandlerError::Panicked(panic))) })
    }))
}

impl<F, Fut, Req, O, E> Sealed<(Req,)> for F
where
    F: Fn(Req) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, E>> + Send + 'static,
    Req: DeserializeOwned + Send + 'static,
    O: IntoInvocationResponse,
    E: Into<BoxError>,
{
    fn erase(self) -> Erased {
        erase(move |request, _ctx| self(request))
    }
}

impl<F, Fut, Req, O, E> Sealed<(Req, RequestContext)> for F
where
    F: Fn(Req, RequestContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, E>> + Send + 'static,
    Req: DeserializeOwned + Send + 'static,
    O: IntoInvocationResponse,
    E: Into<BoxError>,
{
    fn erase(self) -> Erased {
        erase(self)
    }
}