#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use lambda_http::http::{Method, StatusCode, header};
use lambda_http::{Body, Request, Response};
use turul_ai_catalog::identity::{MEDIA_TYPE, WELL_KNOWN_PATH};
use turul_ai_catalog::model::AiCatalog;
use turul_ai_catalog::timestamp::Timestamp;
use turul_ai_catalog::validate::Severity;
use turul_ai_catalog_storage::{
AssembleError, CatalogId, CatalogStore, ImportError, InMemoryCatalogStore, Omission, WriterId,
assemble, import,
};
pub const ALLOW: &str = "GET, HEAD";
pub const ID_VAR: &str = "TURUL_AI_CATALOG_ID";
pub const TABLE_VAR: &str = "TURUL_AI_CATALOG_TABLE";
pub const MAX_AGE_VAR: &str = "TURUL_AI_CATALOG_MAX_AGE_SECS";
const DOCUMENT_WRITER: &str = "from-document";
const DEFAULT_MAX_AGE: Duration = Duration::from_secs(60);
#[derive(Debug)]
#[non_exhaustive]
pub enum ColdStartError {
Assemble(AssembleError),
Import(ImportError),
Config(&'static str),
}
impl fmt::Display for ColdStartError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Assemble(AssembleError::Invalid(report)) => {
f.write_str("assembled catalog is invalid:")?;
for d in report
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Error)
{
write!(f, " {} at '{}';", d.code, d.path)?;
}
Ok(())
}
Self::Assemble(e) => write!(f, "cannot assemble the catalog: {e}"),
Self::Import(e) => write!(f, "cannot import the catalog: {e}"),
Self::Config(message) => f.write_str(message),
}
}
}
impl std::error::Error for ColdStartError {}
impl From<AssembleError> for ColdStartError {
fn from(e: AssembleError) -> Self {
Self::Assemble(e)
}
}
pub fn catalog_id(raw: Option<&str>) -> Result<CatalogId, ColdStartError> {
let raw = raw.ok_or(ColdStartError::Config("TURUL_AI_CATALOG_ID is not set"))?;
CatalogId::new(raw)
.map_err(|_| ColdStartError::Config("TURUL_AI_CATALOG_ID is not a valid catalog id"))
}
#[cfg(feature = "dynamodb")]
pub fn table_name(raw: Option<&str>) -> Result<String, ColdStartError> {
match raw {
Some(name) if !name.is_empty() => Ok(name.to_string()),
_ => Err(ColdStartError::Config("TURUL_AI_CATALOG_TABLE is not set")),
}
}
pub fn max_age(raw: Option<&str>) -> Result<Duration, ColdStartError> {
match raw {
None => Ok(DEFAULT_MAX_AGE),
Some(text) => text.parse().map(Duration::from_secs).map_err(|_| {
ColdStartError::Config("TURUL_AI_CATALOG_MAX_AGE_SECS is not a whole number of seconds")
}),
}
}
#[derive(Debug)]
pub struct ServedCatalog {
bytes: Vec<u8>,
omitted: Vec<Omission>,
next_expiry: Option<Timestamp>,
}
impl ServedCatalog {
pub fn omitted(&self) -> &[Omission] {
&self.omitted
}
pub fn next_expiry(&self) -> Option<Timestamp> {
self.next_expiry
}
pub async fn assemble(
store: &dyn CatalogStore,
catalog: &CatalogId,
now: SystemTime,
) -> Result<Self, ColdStartError> {
let assembled = assemble(store, catalog, now).await?;
Ok(Self {
bytes: assembled.bytes,
omitted: assembled.omitted,
next_expiry: assembled.next_expiry,
})
}
pub async fn from_document(document: &AiCatalog) -> Result<Self, ColdStartError> {
let store = InMemoryCatalogStore::new();
let catalog =
CatalogId::new("default").map_err(|_| ColdStartError::Config("invalid catalog id"))?;
let writer = WriterId::new(DOCUMENT_WRITER)
.map_err(|_| ColdStartError::Config("invalid writer id"))?;
import(&store, &catalog, document, &writer)
.await
.map_err(ColdStartError::Import)?;
Self::assemble(&store, &catalog, SystemTime::now()).await
}
}
pub struct SnapshotCache {
max_age: Duration,
clock: Box<dyn Fn() -> SystemTime + Send + Sync>,
state: Mutex<Snapshot>,
}
struct Snapshot {
served: Arc<ServedCatalog>,
attempted_at: SystemTime,
failed: bool,
}
impl SnapshotCache {
pub fn new(
served: ServedCatalog,
max_age: Duration,
clock: impl Fn() -> SystemTime + Send + Sync + 'static,
) -> Self {
let attempted_at = clock();
Self {
max_age,
clock: Box::new(clock),
state: Mutex::new(Snapshot {
served: Arc::new(served),
attempted_at,
failed: false,
}),
}
}
pub async fn current(
&self,
store: &dyn CatalogStore,
catalog: &CatalogId,
) -> (Arc<ServedCatalog>, Option<ColdStartError>) {
let now = (self.clock)();
let (served, due) = self.read(now);
if !due {
return (served, None);
}
match ServedCatalog::assemble(store, catalog, now).await {
Ok(fresh) => {
let fresh = Arc::new(fresh);
*self.lock() = Snapshot {
served: Arc::clone(&fresh),
attempted_at: now,
failed: false,
};
(fresh, None)
}
Err(e) => {
let mut state = self.lock();
state.attempted_at = now;
state.failed = true;
(served, Some(e))
}
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Snapshot> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
fn read(&self, now: SystemTime) -> (Arc<ServedCatalog>, bool) {
let state = self.lock();
let aged = state
.attempted_at
.checked_add(self.max_age)
.is_some_and(|due| now >= due);
let expired = !state.failed
&& state
.served
.next_expiry
.is_some_and(|e| Timestamp::from_system_time(now) >= e);
(Arc::clone(&state.served), aged || expired)
}
}
fn empty(status: StatusCode) -> lambda_http::http::response::Builder {
Response::builder().status(status)
}
pub fn handle(served: &ServedCatalog, request: &Request) -> Response<Body> {
let built = if request.uri().path() != WELL_KNOWN_PATH {
empty(StatusCode::NOT_FOUND).body(Body::Empty)
} else if request.method() == Method::GET {
empty(StatusCode::OK)
.header(header::CONTENT_TYPE, MEDIA_TYPE)
.body(Body::Binary(served.bytes.clone()))
} else if request.method() == Method::HEAD {
empty(StatusCode::OK)
.header(header::CONTENT_TYPE, MEDIA_TYPE)
.body(Body::Empty)
} else {
empty(StatusCode::METHOD_NOT_ALLOWED)
.header(header::ALLOW, ALLOW)
.body(Body::Empty)
};
built.expect("static response parts are valid")
}