1use std::{future::Future, time::Duration};
8
9use crate::{lsp_types::Url, util::fs::Fs};
10
11pub const CACHE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
13
14pub 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
45pub 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}