Cache icons on the client

This should make the vault pages load much faster, and massively reduce the number of requests.
This commit is contained in:
Jake Howard 2021-03-27 13:30:40 +00:00
parent 16eb0a56f9
commit b22564cb00
No known key found for this signature in database
GPG Key ID: 57AFB45680EDD477
2 changed files with 17 additions and 10 deletions

View File

@ -51,7 +51,10 @@ fn icon(domain: String) -> Option<Cached<Content<Vec<u8>>>> {
return None; return None;
} }
get_icon(&domain).map(|icon| Cached::long(Content(ContentType::new("image", "x-icon"), icon))) get_icon(&domain).map(|(icon, cached)| {
let cache_ttl = if cached {CONFIG.icon_cache_ttl()} else {CONFIG.icon_cache_negttl()};
Cached::ttl(Content(ContentType::new("image", "x-icon"), icon), cache_ttl)
})
} }
/// Returns if the domain provided is valid or not. /// Returns if the domain provided is valid or not.
@ -238,7 +241,7 @@ fn is_domain_blacklisted(domain: &str) -> bool {
is_blacklisted is_blacklisted
} }
fn get_icon(domain: &str) -> Option<Vec<u8>> { fn get_icon(domain: &str) -> Option<(Vec<u8>, bool)> {
let path = format!("{}/{}.png", CONFIG.icon_cache_folder(), domain); let path = format!("{}/{}.png", CONFIG.icon_cache_folder(), domain);
// Check for expiration of negatively cached copy // Check for expiration of negatively cached copy
@ -247,7 +250,7 @@ fn get_icon(domain: &str) -> Option<Vec<u8>> {
} }
if let Some(icon) = get_cached_icon(&path) { if let Some(icon) = get_cached_icon(&path) {
return Some(icon); return Some((icon, true));
} }
if CONFIG.disable_icon_download() { if CONFIG.disable_icon_download() {
@ -258,7 +261,7 @@ fn get_icon(domain: &str) -> Option<Vec<u8>> {
match download_icon(&domain) { match download_icon(&domain) {
Ok(icon) => { Ok(icon) => {
save_icon(&path, &icon); save_icon(&path, &icon);
Some(icon) Some((icon, false))
} }
Err(e) => { Err(e) => {
error!("Error downloading icon: {:?}", e); error!("Error downloading icon: {:?}", e);

View File

@ -92,17 +92,21 @@ impl Fairing for CORS {
} }
} }
pub struct Cached<R>(R, &'static str); pub struct Cached<R>(R, String);
impl<R> Cached<R> { impl<R> Cached<R> {
pub const fn long(r: R) -> Cached<R> { pub fn long(r: R) -> Cached<R> {
// 7 days // 7 days
Self(r, "public, max-age=604800") Self(r, String::from("public, max-age=604800"))
} }
pub const fn short(r: R) -> Cached<R> { pub fn short(r: R) -> Cached<R> {
// 10 minutes // 10 minutes
Self(r, "public, max-age=600") Self(r, String::from("public, max-age=600"))
}
pub fn ttl(r: R, ttl: u64) -> Cached<R> {
Self(r, format!("public, immutable, max-age={}", ttl))
} }
} }