Skip to main content

bedrock_agentcore/runtime/
handler.rs

1use std::{
2    any::Any,
3    future::Future,
4    panic::{AssertUnwindSafe, catch_unwind},
5    pin::Pin,
6    sync::Arc,
7    task::{Context, Poll},
8};
9
10use axum::body::Bytes;
11use serde::de::DeserializeOwned;
12
13use super::response::{IntoInvocationResponse, Response};
14use crate::RequestContext;
15
16pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync>;
17type HandlerFuture = BoxFuture<Result<Response, HandlerError>>;
18
19pub(crate) enum HandlerError {
20    Decode(serde_json::Error),
21    Failed(Failure),
22    /// The text of the panic.
23    Panicked(String),
24}
25
26/// An error that customer code returned.
27pub(crate) struct Failure {
28    /// The `Display` text of the error. It is the reply to the caller.
29    pub(crate) error: String,
30    /// The `Display` texts of the sources of the error. They go to the log only: an
31    /// AWS SDK error has the text `service error`, and its source names the cause.
32    pub(crate) causes: Option<String>,
33}
34
35impl Failure {
36    /// Runs the `Display` of the error and of its sources, which is customer code.
37    pub(crate) fn of(error: BoxError) -> Self {
38        // The source of an Identity error of this crate can hold a credential or the
39        // authorization URL. The text of that error has what a log needs, so the
40        // walk ends there, also when an error of the application wraps it.
41        let hides_source = |error: &(dyn std::error::Error + 'static)| {
42            error.downcast_ref::<crate::Error>().is_some_and(crate::Error::hides_source)
43        };
44        let mut causes = Vec::new();
45        let mut current: &(dyn std::error::Error + 'static) = error.as_ref();
46        // The limit ends a chain of sources that is a cycle.
47        while causes.len() < 8 && !hides_source(current) {
48            let Some(source) = current.source() else { break };
49            causes.push(source.to_string());
50            current = source;
51        }
52        Self { error: error.to_string(), causes: (!causes.is_empty()).then(|| causes.join(": ")) }
53    }
54}
55
56/// The text of a panic, for the log.
57pub(crate) fn panic_text(panic: &(dyn Any + Send)) -> &str {
58    panic
59        .downcast_ref::<String>()
60        .map(String::as_str)
61        .or_else(|| panic.downcast_ref::<&str>().copied())
62        .unwrap_or("the panic has no text")
63}
64
65pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
66
67/// Resolves to the text of the panic when the wrapped future panics and unwinds.
68pub(crate) struct CatchPanic<T>(pub(crate) Option<BoxFuture<T>>);
69
70impl<T> Future for CatchPanic<T> {
71    type Output = Result<T, String>;
72
73    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
74        let Some(future) = self.0.as_mut() else { return Poll::Ready(Err("polled after its end".to_owned())) };
75        match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
76            Ok(Poll::Pending) => Poll::Pending,
77            Ok(Poll::Ready(output)) => {
78                self.0 = None;
79                Poll::Ready(Ok(output))
80            }
81            Err(panic) => {
82                // Dropping the future can run destructors that panic again.
83                let future = self.0.take();
84                let _ = catch_unwind(AssertUnwindSafe(|| drop(future)));
85                Poll::Ready(Err(panic_text(panic.as_ref()).to_owned()))
86            }
87        }
88    }
89}
90
91/**
92 The items in this module are public so that the public handler trait can refer
93 to them. The module is private, so other crates cannot name them.
94**/
95mod sealed {
96    use super::*;
97
98    #[derive(Clone)]
99    pub struct Erased(pub(super) Arc<dyn Fn(Bytes, RequestContext) -> HandlerFuture + Send + Sync>);
100
101    impl Erased {
102        pub(crate) fn call(&self, body: Bytes, ctx: RequestContext) -> HandlerFuture {
103            (self.0)(body, ctx)
104        }
105    }
106
107    impl std::fmt::Debug for Erased {
108        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109            f.write_str("Erased")
110        }
111    }
112
113    pub trait Sealed<Marker> {
114        fn erase(self) -> Erased;
115    }
116}
117pub(crate) use sealed::{Erased, Sealed};
118
119/// An async function that handles `POST /invocations`.
120///
121/// It is implemented for functions and closures with these signatures:
122///
123/// - `async fn(Req) -> Result<O, E>`
124/// - `async fn(Req, RequestContext) -> Result<O, E>`
125///
126/// `Req` is any [`DeserializeOwned`] type, for example `serde_json::Value` for an
127/// untyped payload. `O` is any [`IntoInvocationResponse`] type. `E` converts into a
128/// boxed error and its `Display` text becomes the `500` error body.
129///
130/// The handler and the future that it returns must be `Send`, and the handler must be
131/// `Sync + 'static`. `Req` must be `Send + 'static`, the boxed error must be
132/// `Send + Sync`, and both arguments are taken by value, in this order.
133///
134/// A handler that panics gets `500 {"error": "Internal error"}` and the server keeps
135/// running. So does a panic in the conversion or the `Display` of the error that the
136/// handler returned. This holds for unwinding panics only, not with `panic = "abort"`.
137///
138/// # Blocking work
139///
140/// A handler must not block its thread, for example with `std::thread::sleep` or
141/// synchronous I/O. Blocking work belongs in `tokio::task::spawn_blocking`.
142/// [`BedrockAgentCoreApp::run`](super::BedrockAgentCoreApp::run) describes what a
143/// handler that blocks delays.
144///
145/// The `Marker` parameter only separates the two signatures. The compiler infers it.
146///
147/// This trait is sealed. Other crates cannot implement it.
148#[diagnostic::on_unimplemented(
149    message = "`{Self}` is not a valid invocation handler",
150    label = "not a valid invocation handler",
151    note = "a handler is an `async fn(Req) -> Result<O, E>` or an `async fn(Req, RequestContext) -> Result<O, E>`",
152    note = "`Req` must implement `serde::de::DeserializeOwned + Send`, and `RequestContext` is taken by value",
153    note = "`O` must implement `serde::Serialize`, or be a `runtime::Response`",
154    note = "`E` must convert into `Box<dyn std::error::Error + Send + Sync>`",
155    note = "the function and its future must be `Send`, and the function must be `Sync + 'static`"
156)]
157pub trait InvocationHandler<Marker>: Sealed<Marker> {}
158
159impl<T: Sealed<Marker>, Marker> InvocationHandler<Marker> for T {}
160
161fn erase<Req, Fut, O, E>(call: impl Fn(Req, RequestContext) -> Fut + Send + Sync + 'static) -> Erased
162where
163    Req: DeserializeOwned + Send + 'static,
164    Fut: Future<Output = Result<O, E>> + Send + 'static,
165    O: IntoInvocationResponse,
166    E: Into<BoxError>,
167{
168    let call = Arc::new(call);
169    Erased(Arc::new(move |body, ctx| {
170        let call = call.clone();
171        let guarded = CatchPanic(Some(Box::pin(async move {
172            let request = serde_json::from_slice(&body).map_err(HandlerError::Decode)?;
173            drop(body);
174            match call(request, ctx).await {
175                Ok(output) => Ok(output.into_invocation_response()),
176                // The error's `Display` is the handler's code. It runs here, inside
177                // the panic boundary.
178                Err(error) => Err(HandlerError::Failed(Failure::of(error.into()))),
179            }
180        })));
181        Box::pin(async move { guarded.await.unwrap_or_else(|panic| Err(HandlerError::Panicked(panic))) })
182    }))
183}
184
185impl<F, Fut, Req, O, E> Sealed<(Req,)> for F
186where
187    F: Fn(Req) -> Fut + Send + Sync + 'static,
188    Fut: Future<Output = Result<O, E>> + Send + 'static,
189    Req: DeserializeOwned + Send + 'static,
190    O: IntoInvocationResponse,
191    E: Into<BoxError>,
192{
193    fn erase(self) -> Erased {
194        erase(move |request, _ctx| self(request))
195    }
196}
197
198impl<F, Fut, Req, O, E> Sealed<(Req, RequestContext)> for F
199where
200    F: Fn(Req, RequestContext) -> Fut + Send + Sync + 'static,
201    Fut: Future<Output = Result<O, E>> + Send + 'static,
202    Req: DeserializeOwned + Send + 'static,
203    O: IntoInvocationResponse,
204    E: Into<BoxError>,
205{
206    fn erase(self) -> Erased {
207        erase(self)
208    }
209}