mod body;
mod extract;
mod handler;
mod headers;
mod invocations;
mod ping;
mod response;
mod serve;
#[cfg(test)]
mod tests;
mod warmup;
use std::{any::Any, convert::Infallible, fmt, net::SocketAddr, time::Duration};
use axum::{
Json, Router,
extract::{DefaultBodyLimit, Request, State},
middleware,
response::IntoResponse,
routing::{Route, get, post},
};
use serde_json::{Value, json};
use tower_layer::Layer;
use tower_service::Service;
pub use self::{
handler::InvocationHandler,
ping::PingStatus,
response::{IntoInvocationResponse, Response},
warmup::WarmupHook,
};
use crate::{Error, ErrorKind, tasks::AsyncTasks};
const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;
#[derive(Clone)]
struct AppState {
handler: handler::Erased,
ping: ping::PingState,
tasks: AsyncTasks,
workload_identity_contexts: crate::context::WorkloadIdentityContexts,
stream_heartbeat: Duration,
body_limit: usize,
in_flight: invocations::InFlight,
runtime: serve::AppRuntime,
}
#[must_use]
pub struct Builder {
handler: Option<handler::Erased>,
ping: Option<ping::PingHandler>,
bind: Option<SocketAddr>,
body_limit: usize,
stream_heartbeat: Duration,
shutdown_grace: Duration,
routes: Vec<Router>,
layers: Vec<Box<dyn Fn(Router) -> Router + Send + Sync>>,
warmup_hook: Option<WarmupHook>,
}
impl Builder {
pub fn invocation<H, M>(mut self, handler: H) -> Self
where
H: InvocationHandler<M>,
{
self.handler = Some(handler.erase());
self
}
pub fn ping<F, S>(mut self, handler: F) -> Self
where
F: Fn() -> S + Send + Sync + 'static,
S: Into<Option<PingStatus>>,
{
self.ping = Some(std::sync::Arc::new(move || handler().into()));
self
}
pub fn bind(mut self, addr: SocketAddr) -> Self {
self.bind = Some(addr);
self
}
pub fn body_limit(mut self, bytes: usize) -> Self {
self.body_limit = bytes;
self
}
pub fn stream_heartbeat(mut self, interval: Duration) -> Self {
self.stream_heartbeat = interval;
self
}
pub fn shutdown_grace(mut self, grace: Duration) -> Self {
self.shutdown_grace = grace;
self
}
pub fn routes(mut self, routes: Router) -> Self {
self.routes.push(routes);
self
}
pub fn layer<L>(mut self, layer: L) -> Self
where
L: Layer<Route> + Clone + Send + Sync + 'static,
L::Service: Service<Request> + Clone + Send + Sync + 'static,
<L::Service as Service<Request>>::Response: IntoResponse + 'static,
<L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
<L::Service as Service<Request>>::Future: Send + 'static,
{
self.layers.push(Box::new(move |router| router.layer(layer.clone())));
self
}
pub fn warmup_hook(mut self, hook: WarmupHook) -> Self {
self.warmup_hook = Some(hook);
self
}
pub fn build(self) -> Result<BedrockAgentCoreApp, Error> {
let handler = self.handler.ok_or_else(|| {
Error::new(ErrorKind::InvalidConfig, "an invocation handler is required: call Builder::invocation")
})?;
if self.stream_heartbeat.is_zero() {
return Err(Error::new(
ErrorKind::InvalidConfig,
"the stream heartbeat interval must be greater than zero",
));
}
if let Some(hook) = &self.warmup_hook {
hook.validate()?;
}
let tasks = AsyncTasks::new();
let state = AppState {
handler,
ping: ping::PingState::new(self.ping, tasks.clone()),
tasks,
workload_identity_contexts: Default::default(),
stream_heartbeat: self.stream_heartbeat,
body_limit: self.body_limit,
in_flight: Default::default(),
runtime: Default::default(),
};
let (body_limit, routes, layers, warmup_hook) = (self.body_limit, self.routes, self.layers, self.warmup_hook);
let has_routes = !routes.is_empty();
let router = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let sdk = Router::new()
.route("/invocations", post(invocations::invocations))
.layer(DefaultBodyLimit::max(body_limit))
.route("/ping", get(ping));
let sdk = match warmup_hook {
Some(hook) => hook.add_route(sdk),
None => sdk,
}
.with_state(state.clone());
match routes.into_iter().reduce(Router::merge) {
Some(routes) => {
sdk.merge(routes.layer(middleware::from_fn_with_state(state.clone(), extract::route_context)))
}
None => sdk,
}
}))
.map_err(|panic| rejected("the routes cannot be combined", panic))?;
let (served, router) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let layered =
|router: Router| layers.iter().fold(router, |router, layer| layer(router)).with_state::<()>(());
if has_routes {
let router = layered(router);
(router.clone(), router)
} else {
(layered(router.clone().fallback(invocations::not_found)), layered(router))
}
}))
.map_err(|panic| rejected("a layer could not be applied", panic))?;
Ok(BedrockAgentCoreApp {
state,
served,
router,
bind: self.bind,
body_limit,
shutdown_grace: self.shutdown_grace,
})
}
}
impl fmt::Debug for Builder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Builder")
.field("handler_set", &self.handler.is_some())
.field("bind", &self.bind)
.field("body_limit", &self.body_limit)
.field("layers", &self.layers.len())
.finish()
}
}
fn rejected(stage: &str, panic: Box<dyn Any + Send>) -> Error {
Error::new(ErrorKind::InvalidConfig, format!("{stage}: {}", handler::panic_text(panic.as_ref())))
}
pub struct BedrockAgentCoreApp {
state: AppState,
served: Router,
router: Router,
bind: Option<SocketAddr>,
body_limit: usize,
shutdown_grace: Duration,
}
impl BedrockAgentCoreApp {
pub fn builder() -> Builder {
Builder {
handler: None,
ping: None,
bind: None,
body_limit: DEFAULT_BODY_LIMIT,
stream_heartbeat: response::DEFAULT_STREAM_HEARTBEAT,
shutdown_grace: Duration::from_secs(8),
routes: Vec::new(),
layers: Vec::new(),
warmup_hook: None,
}
}
pub async fn run(self) -> Result<(), Error> {
let signal = serve::os_shutdown_signal()?;
let listener = serve::bind(self.bind.unwrap_or_else(serve::default_bind_addr)).await?;
self.serve_until(listener, signal).await
}
pub async fn serve(self, listener: tokio::net::TcpListener) -> Result<(), Error> {
let signal = serve::os_shutdown_signal()?;
self.serve_until(listener, signal).await
}
pub async fn serve_with_shutdown(
self,
listener: tokio::net::TcpListener,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), Error> {
self.serve_until(listener, shutdown).await
}
async fn serve_until(
self,
listener: tokio::net::TcpListener,
signal: impl Future<Output = ()> + Send + 'static,
) -> Result<(), Error> {
let router = self.standalone_router();
let AppState { tasks, in_flight, runtime, .. } = self.state;
let shutdown = serve::Shutdown { grace: self.shutdown_grace, tasks, in_flight, runtime };
serve::serve(listener, router, signal, shutdown).await
}
fn standalone_router(&self) -> Router {
self.served.clone()
}
pub fn router(&self) -> Router {
self.router.clone()
}
pub fn tasks(&self) -> &AsyncTasks {
&self.state.tasks
}
}
impl fmt::Debug for BedrockAgentCoreApp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BedrockAgentCoreApp")
.field("bind", &self.bind)
.field("body_limit", &self.body_limit)
.field("shutdown_grace", &self.shutdown_grace)
.finish_non_exhaustive()
}
}
async fn ping(State(state): State<AppState>) -> Json<Value> {
let (status, changed) = state.ping.current();
Json(json!({ "status": status.as_str(), "time_of_last_update": changed }))
}