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",
}
}
}
#[must_use]
pub struct WarmupHook {
path: String,
memory: Option<Handler>,
disk: Option<Handler>,
}
impl WarmupHook {
pub fn new(path: impl Into<String>) -> Self {
Self { path: path.into(), memory: None, disk: None }
}
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
}
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();
Box::pin(async move { handler().await.map_err(|error| Failure::of(error.into())) })
})
}
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));
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}");
}
}
}
}
}