use std::sync::{Arc, Mutex, PoisonError};
use handlebars::Handlebars;
use lru_time_cache::LruCache;
use serde::Serialize;
use super::HandlebarsResponse;
use crate::{EntityTag, EtagIfNoneMatch, functions::compute_data_etag};
#[allow(clippy::type_complexity)]
#[derive(Educe)]
#[educe(Debug)]
pub struct HandlebarsContextManager {
pub handlebars: Handlebars<'static>,
#[educe(Debug(ignore))]
cache_table: Option<Mutex<LruCache<String, (Arc<str>, Arc<EntityTag<'static>>)>>>,
}
impl HandlebarsContextManager {
#[inline]
pub(crate) fn new(
handlebars: Handlebars<'static>,
cache_capacity: usize,
) -> HandlebarsContextManager {
HandlebarsContextManager {
handlebars,
cache_table: (cache_capacity > 0)
.then(|| Mutex::new(LruCache::with_capacity(cache_capacity))),
}
}
#[inline]
pub fn build<S: AsRef<str>, V: Serialize>(
&self,
etag_if_none_match: &EtagIfNoneMatch<'_>,
minify: bool,
name: S,
context: V,
) -> HandlebarsResponse {
let html = self.render(name, context);
let etag = compute_data_etag(html.as_bytes());
if etag_if_none_match.weak_eq(&etag) {
return HandlebarsResponse::not_modified_with_etag(&etag);
}
let html = if minify { html_minifier::minify(&html).unwrap_or(html) } else { html };
HandlebarsResponse::build_not_cache(html, etag)
}
#[inline]
pub fn build_from_cache<K: AsRef<str>>(
&self,
etag_if_none_match: &EtagIfNoneMatch<'_>,
key: K,
) -> Option<HandlebarsResponse> {
let mut cache = self.cache_table.as_ref()?.lock().unwrap_or_else(PoisonError::into_inner);
let (html, etag) = cache.get(key.as_ref())?;
if etag_if_none_match.weak_eq(etag) {
let etag = etag.clone();
drop(cache);
Some(HandlebarsResponse::not_modified_with_etag(&etag))
} else {
Some(HandlebarsResponse::build_cache(html.clone(), etag.clone()))
}
}
#[inline]
pub fn render<S: AsRef<str>, V: Serialize>(&self, name: S, context: V) -> String {
self.handlebars.render(name.as_ref(), &context).unwrap()
}
#[inline]
pub fn clear_cache(&self) {
if let Some(cache) = &self.cache_table {
cache.lock().unwrap_or_else(PoisonError::into_inner).clear();
}
}
#[inline]
pub fn contains_key<S: AsRef<str>>(&self, key: S) -> bool {
self.cache_table.as_ref().is_some_and(|cache| {
cache.lock().unwrap_or_else(PoisonError::into_inner).contains_key(key.as_ref())
})
}
#[inline]
pub fn get<S: AsRef<str>>(&self, key: S) -> Option<(Arc<str>, Arc<EntityTag<'static>>)> {
self.cache_table
.as_ref()?
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(key.as_ref())
.map(|(html, etag)| (html.clone(), etag.clone()))
}
#[inline]
pub fn insert<S: Into<String>>(
&self,
key: S,
cache: (Arc<str>, Arc<EntityTag<'static>>),
) -> Option<(Arc<str>, Arc<EntityTag<'static>>)> {
self.cache_table
.as_ref()?
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key.into(), cache)
}
}