Skip to main content

swls_core/util/
cache.rs

1//! Freshness policy for the ontology cache (see [`FsTrait`](super::fs::FsTrait)).
2//!
3//! A cached copy younger than [`CACHE_TTL`] is used as is, without touching the
4//! network. An older one is refreshed, and kept when refreshing fails, so the
5//! server keeps working offline with whatever it fetched before.
6
7use std::{future::Future, time::Duration};
8
9use crate::{lsp_types::Url, util::fs::Fs};
10
11/// How long a cached ontology is used before it is fetched again.
12pub const CACHE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
13
14/// Content for the cache entry at `url`, fetching it with `fetch` when the
15/// entry is missing or older than [`CACHE_TTL`].
16///
17/// A successful fetch is written back to the cache. A failed fetch falls back
18/// to the stale entry, if any.
19pub async fn cached<F, Fut>(fs: &Fs, url: &Url, fetch: F) -> Option<String>
20where
21    F: FnOnce() -> Fut,
22    Fut: Future<Output = Option<String>>,
23{
24    let age = fs.0.cache_age(url).await;
25    if age.is_some_and(|age| age < CACHE_TTL) {
26        if let Some(content) = fs.0.read_file(url).await {
27            tracing::debug!("Cache hit {}", url);
28            return Some(content);
29        }
30    }
31
32    match fetch().await {
33        Some(content) => {
34            store(fs, url, &content).await;
35            Some(content)
36        }
37        None if age.is_some() => {
38            tracing::info!("Fetch failed, using stale cache {}", url);
39            fs.0.read_file(url).await
40        }
41        None => None,
42    }
43}
44
45/// Write `content` to the cache entry at `url`, unless it already holds it.
46pub async fn store(fs: &Fs, url: &Url, content: &str) {
47    if fs.0.read_file(url).await.as_deref() == Some(content) {
48        return;
49    }
50    if fs.0.write_cache(url, content).await.is_none() {
51        tracing::warn!("Failed to write cache {}", url);
52    }
53}