Skip to main content

turul_ai_catalog_lambda/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4use std::fmt;
5use std::sync::{Arc, Mutex};
6use std::time::{Duration, SystemTime};
7
8use lambda_http::http::{Method, StatusCode, header};
9use lambda_http::{Body, Request, Response};
10use turul_ai_catalog::identity::{MEDIA_TYPE, WELL_KNOWN_PATH};
11use turul_ai_catalog::model::AiCatalog;
12use turul_ai_catalog::timestamp::Timestamp;
13use turul_ai_catalog::validate::Severity;
14use turul_ai_catalog_storage::{
15    AssembleError, CatalogId, CatalogStore, ImportError, InMemoryCatalogStore, Omission, WriterId,
16    assemble, import,
17};
18
19/// Value of the `Allow` header on a 405 response (RFC 9110 section 15.5.6).
20pub const ALLOW: &str = "GET, HEAD";
21
22/// Environment variable naming the catalog in the store.
23pub const ID_VAR: &str = "TURUL_AI_CATALOG_ID";
24/// Environment variable naming the DynamoDB table.
25pub const TABLE_VAR: &str = "TURUL_AI_CATALOG_TABLE";
26/// Environment variable holding the snapshot refresh interval in seconds.
27pub const MAX_AGE_VAR: &str = "TURUL_AI_CATALOG_MAX_AGE_SECS";
28
29/// The writer of the curated records of [`ServedCatalog::from_document`]'s private store.
30const DOCUMENT_WRITER: &str = "from-document";
31
32const DEFAULT_MAX_AGE: Duration = Duration::from_secs(60);
33
34/// Why the function cannot start or refresh its snapshot.
35#[derive(Debug)]
36#[non_exhaustive]
37pub enum ColdStartError {
38    /// The store could not be read, or the assembled catalog is invalid or not canonicalisable.
39    Assemble(AssembleError),
40    /// A carried document cannot be stored, e.g. it is signed or has catalog-level extensions.
41    Import(ImportError),
42    /// An environment variable is missing or malformed; the message names it.
43    Config(&'static str),
44}
45
46impl fmt::Display for ColdStartError {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::Assemble(AssembleError::Invalid(report)) => {
50                f.write_str("assembled catalog is invalid:")?;
51                for d in report
52                    .diagnostics()
53                    .iter()
54                    .filter(|d| d.severity == Severity::Error)
55                {
56                    write!(f, " {} at '{}';", d.code, d.path)?;
57                }
58                Ok(())
59            }
60            Self::Assemble(e) => write!(f, "cannot assemble the catalog: {e}"),
61            Self::Import(e) => write!(f, "cannot import the catalog: {e}"),
62            Self::Config(message) => f.write_str(message),
63        }
64    }
65}
66
67impl std::error::Error for ColdStartError {}
68
69impl From<AssembleError> for ColdStartError {
70    fn from(e: AssembleError) -> Self {
71        Self::Assemble(e)
72    }
73}
74
75/// Parses the catalog id from the value of [`ID_VAR`]; `raw` is `None` when the variable is unset.
76///
77/// # Errors
78///
79/// Returns [`ColdStartError::Config`] when `raw` is `None` or is not a valid [`CatalogId`].
80///
81/// # Examples
82///
83/// ```
84/// use turul_ai_catalog_lambda::catalog_id;
85///
86/// let id = catalog_id(Some("default"))?;
87/// assert_eq!(id.as_str(), "default");
88/// assert!(catalog_id(None).is_err());
89/// # Ok::<(), Box<dyn std::error::Error>>(())
90/// ```
91pub fn catalog_id(raw: Option<&str>) -> Result<CatalogId, ColdStartError> {
92    let raw = raw.ok_or(ColdStartError::Config("TURUL_AI_CATALOG_ID is not set"))?;
93    CatalogId::new(raw)
94        .map_err(|_| ColdStartError::Config("TURUL_AI_CATALOG_ID is not a valid catalog id"))
95}
96
97/// Parses the DynamoDB table name from the value of [`TABLE_VAR`].
98///
99/// # Errors
100///
101/// Returns [`ColdStartError::Config`] when `raw` is `None` or empty.
102#[cfg(feature = "dynamodb")]
103pub fn table_name(raw: Option<&str>) -> Result<String, ColdStartError> {
104    match raw {
105        Some(name) if !name.is_empty() => Ok(name.to_string()),
106        _ => Err(ColdStartError::Config("TURUL_AI_CATALOG_TABLE is not set")),
107    }
108}
109
110/// Parses the snapshot refresh interval from the value of [`MAX_AGE_VAR`]: whole seconds, 60 when
111/// unset.
112///
113/// # Errors
114///
115/// Returns [`ColdStartError::Config`] when `raw` is not a whole number of seconds.
116///
117/// # Examples
118///
119/// ```
120/// use std::time::Duration;
121/// use turul_ai_catalog_lambda::max_age;
122///
123/// assert_eq!(max_age(None)?, Duration::from_secs(60));
124/// assert_eq!(max_age(Some("5"))?, Duration::from_secs(5));
125/// assert!(max_age(Some("soon")).is_err());
126/// # Ok::<(), Box<dyn std::error::Error>>(())
127/// ```
128pub fn max_age(raw: Option<&str>) -> Result<Duration, ColdStartError> {
129    match raw {
130        None => Ok(DEFAULT_MAX_AGE),
131        Some(text) => text.parse().map(Duration::from_secs).map_err(|_| {
132            ColdStartError::Config("TURUL_AI_CATALOG_MAX_AGE_SECS is not a whole number of seconds")
133        }),
134    }
135}
136
137/// Canonical bytes of an assembled catalog that passed [`validate`](turul_ai_catalog::validate::validate)
138/// with no error diagnostic, with what that assembly left out.
139#[derive(Debug)]
140pub struct ServedCatalog {
141    bytes: Vec<u8>,
142    omitted: Vec<Omission>,
143    next_expiry: Option<Timestamp>,
144}
145
146impl ServedCatalog {
147    /// Every entry record the assembly left out of the served bytes, with its reason.
148    pub fn omitted(&self) -> &[Omission] {
149        &self.omitted
150    }
151
152    /// The earliest expiry among the leases in the served bytes.
153    pub fn next_expiry(&self) -> Option<Timestamp> {
154        self.next_expiry
155    }
156
157    /// Assembles the catalog from the store with [`assemble`] at `now`.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`ColdStartError::Assemble`] for any [`AssembleError`]: a store failure, an error
162    /// diagnostic in the assembled document, or a document that is not canonicalisable.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use turul_ai_catalog_lambda::ServedCatalog;
168    /// use turul_ai_catalog_storage::{CatalogId, InMemoryCatalogStore};
169    ///
170    /// # futures::executor::block_on(async {
171    /// let store = InMemoryCatalogStore::new();
172    /// let catalog = CatalogId::new("default")?;
173    /// let served = ServedCatalog::assemble(&store, &catalog, std::time::SystemTime::now()).await?;
174    /// # let _ = served;
175    /// # Ok::<(), Box<dyn std::error::Error>>(())
176    /// # })?;
177    /// # Ok::<(), Box<dyn std::error::Error>>(())
178    /// ```
179    pub async fn assemble(
180        store: &dyn CatalogStore,
181        catalog: &CatalogId,
182        now: SystemTime,
183    ) -> Result<Self, ColdStartError> {
184        let assembled = assemble(store, catalog, now).await?;
185        Ok(Self {
186            bytes: assembled.bytes,
187            omitted: assembled.omitted,
188            next_expiry: assembled.next_expiry,
189        })
190    }
191
192    /// Builds the served catalog from a caller-supplied document: [`import`] into an in-memory
193    /// store, then [`ServedCatalog::assemble`]. Reads no file and adds nothing to the document, so
194    /// a function that compiles its catalog in and the local server share this one path.
195    ///
196    /// # Errors
197    ///
198    /// Returns [`ColdStartError::Import`] when the document cannot be stored (for example it
199    /// carries a catalog `signature`), and [`ColdStartError::Assemble`] when the assembled
200    /// document has an error diagnostic.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use turul_ai_catalog::parse::parse;
206    /// use turul_ai_catalog_lambda::ServedCatalog;
207    ///
208    /// # futures::executor::block_on(async {
209    /// let document = parse(br#"{"specVersion":"1.0","entries":[{"identifier":"urn:air:example.com:mcp:weather","type":"application/mcp-server-card+json","url":"https://mcp.example.com/server-card.json"}]}"#)?;
210    /// let served = ServedCatalog::from_document(&document).await?;
211    /// # let _ = served;
212    /// # Ok::<(), Box<dyn std::error::Error>>(())
213    /// # })?;
214    /// # Ok::<(), Box<dyn std::error::Error>>(())
215    /// ```
216    pub async fn from_document(document: &AiCatalog) -> Result<Self, ColdStartError> {
217        let store = InMemoryCatalogStore::new();
218        // A fixed, valid id: the store is private to this call, so the id is never observed.
219        let catalog =
220            CatalogId::new("default").map_err(|_| ColdStartError::Config("invalid catalog id"))?;
221        let writer = WriterId::new(DOCUMENT_WRITER)
222            .map_err(|_| ColdStartError::Config("invalid writer id"))?;
223        import(&store, &catalog, document, &writer)
224            .await
225            .map_err(ColdStartError::Import)?;
226        Self::assemble(&store, &catalog, SystemTime::now()).await
227    }
228}
229
230/// The last good [`ServedCatalog`], when it was last assembled or attempted, and the clock that
231/// decides when it is due. The clock lives here, never in [`handle`].
232pub struct SnapshotCache {
233    max_age: Duration,
234    clock: Box<dyn Fn() -> SystemTime + Send + Sync>,
235    state: Mutex<Snapshot>,
236}
237
238struct Snapshot {
239    served: Arc<ServedCatalog>,
240    attempted_at: SystemTime,
241    failed: bool,
242}
243
244impl SnapshotCache {
245    /// Creates a cache holding `served`, assembled at `clock()`. The clock is the one `now` passed
246    /// to every re-assembly; production passes [`SystemTime::now`].
247    pub fn new(
248        served: ServedCatalog,
249        max_age: Duration,
250        clock: impl Fn() -> SystemTime + Send + Sync + 'static,
251    ) -> Self {
252        let attempted_at = clock();
253        Self {
254            max_age,
255            clock: Box::new(clock),
256            state: Mutex::new(Snapshot {
257                served: Arc::new(served),
258                attempted_at,
259                failed: false,
260            }),
261        }
262    }
263
264    /// Returns the snapshot to serve, re-assembled when it is at least `max_age` old or the clock
265    /// has reached its [`next_expiry`](ServedCatalog::next_expiry), so an expired lease is not
266    /// served past its expiry.
267    ///
268    /// When re-assembly fails the last good snapshot is kept, which can hold a lease past its
269    /// expiry, and the failure is returned beside it so the caller can report it; the next
270    /// attempt waits another `max_age`.
271    pub async fn current(
272        &self,
273        store: &dyn CatalogStore,
274        catalog: &CatalogId,
275    ) -> (Arc<ServedCatalog>, Option<ColdStartError>) {
276        let now = (self.clock)();
277        let (served, due) = self.read(now);
278        if !due {
279            return (served, None);
280        }
281        match ServedCatalog::assemble(store, catalog, now).await {
282            Ok(fresh) => {
283                let fresh = Arc::new(fresh);
284                *self.lock() = Snapshot {
285                    served: Arc::clone(&fresh),
286                    attempted_at: now,
287                    failed: false,
288                };
289                (fresh, None)
290            }
291            Err(e) => {
292                // Keep the last good snapshot and restart its age, so a lasting failure is
293                // retried and reported once per `max_age`, not on every request.
294                let mut state = self.lock();
295                state.attempted_at = now;
296                state.failed = true;
297                (served, Some(e))
298            }
299        }
300    }
301
302    fn lock(&self) -> std::sync::MutexGuard<'_, Snapshot> {
303        self.state.lock().unwrap_or_else(|p| p.into_inner())
304    }
305
306    fn read(&self, now: SystemTime) -> (Arc<ServedCatalog>, bool) {
307        let state = self.lock();
308        let aged = state
309            .attempted_at
310            .checked_add(self.max_age)
311            .is_some_and(|due| now >= due);
312        let expired = !state.failed
313            && state
314                .served
315                .next_expiry
316                .is_some_and(|e| Timestamp::from_system_time(now) >= e);
317        (Arc::clone(&state.served), aged || expired)
318    }
319}
320
321fn empty(status: StatusCode) -> lambda_http::http::response::Builder {
322    Response::builder().status(status)
323}
324
325/// Answers a request for the well-known path, routing by path, then method. Pure: no I/O, clock
326/// or state.
327///
328/// `GET` returns the catalog bytes and `HEAD` the same headers with an empty body, both with the
329/// catalog media type; other methods on the path return 405 with `Allow`, and other paths 404.
330///
331/// # Examples
332///
333/// ```
334/// use lambda_http::{Body, http::Request};
335/// use turul_ai_catalog_lambda::{ServedCatalog, handle};
336/// use turul_ai_catalog_storage::{CatalogId, InMemoryCatalogStore};
337///
338/// # futures::executor::block_on(async {
339/// let store = InMemoryCatalogStore::new();
340/// let served = ServedCatalog::assemble(&store, &CatalogId::new("default")?, std::time::SystemTime::now()).await?;
341///
342/// let found = Request::builder().uri("/.well-known/ai-catalog.json").body(Body::Empty)?;
343/// assert_eq!(handle(&served, &found).status(), 200);
344///
345/// let missing = Request::builder().uri("/other").body(Body::Empty)?;
346/// assert_eq!(handle(&served, &missing).status(), 404);
347/// # Ok::<(), Box<dyn std::error::Error>>(())
348/// # })?;
349/// # Ok::<(), Box<dyn std::error::Error>>(())
350/// ```
351pub fn handle(served: &ServedCatalog, request: &Request) -> Response<Body> {
352    let built = if request.uri().path() != WELL_KNOWN_PATH {
353        empty(StatusCode::NOT_FOUND).body(Body::Empty)
354    } else if request.method() == Method::GET {
355        empty(StatusCode::OK)
356            .header(header::CONTENT_TYPE, MEDIA_TYPE)
357            .body(Body::Binary(served.bytes.clone()))
358    } else if request.method() == Method::HEAD {
359        empty(StatusCode::OK)
360            .header(header::CONTENT_TYPE, MEDIA_TYPE)
361            .body(Body::Empty)
362    } else {
363        empty(StatusCode::METHOD_NOT_ALLOWED)
364            .header(header::ALLOW, ALLOW)
365            .body(Body::Empty)
366    };
367    built.expect("static response parts are valid")
368}