bedrock_agentcore/runtime/
handler.rs1use 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 Panicked(String),
24}
25
26pub(crate) struct Failure {
28 pub(crate) error: String,
30 pub(crate) causes: Option<String>,
33}
34
35impl Failure {
36 pub(crate) fn of(error: BoxError) -> Self {
38 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 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
56pub(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
67pub(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 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
91mod 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#[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 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}