fix: add language to cache key

This commit is contained in:
Ondrej Vlach 2023-12-11 23:06:16 +01:00
parent a08c7d09f9
commit c0fe6d7a43
Signed by: ovlach
GPG Key ID: 4FF1A23B4914DE70
3 changed files with 7 additions and 6 deletions

View File

@ -62,26 +62,26 @@ fn render_template(template_name: &str, file: &NamedTempFile, tera: NanoTera, cv
#[allow(clippy::too_many_arguments)]
#[get("/cv/<username>/<language>/output.pdf?<force_rebuild>")]
pub async fn render_pdf_cv(username: &str, tera: NanoTera, tracing: TracingSpan, request_client: OtelReqwestClient,
cv_config: &State<CVBackendConfig>, language: RequestLanguage, browser: BrowserHolder, cache: &State<NanoCache<String, PdfStream>>,
cv_config: &State<CVBackendConfig>, language: RequestLanguage, browser: BrowserHolder, cache: &State<NanoCache<(RequestLanguage, String), PdfStream>>,
force_rebuild: Option<bool>) -> Result<PdfStream, Status> {
async move {
match fetch_cv_data_from_backend(&cv_config.cv_backend_path, &username.to_string(), &request_client.0).await {
Ok(cv_data) => {
// TODO: CV hasher
let data = json!(cv_data).to_string();
match cache.get(&data, force_rebuild).await {
match cache.get(&(language.clone(), data.clone()), force_rebuild).await {
Some(data) => {
Ok(data.clone())
}
None => {
let file = tempfile::Builder::new().suffix(".html").tempfile().unwrap();
render_template("two_column", &file, tera, cv_data, language.language);
render_template("two_column", &file, tera, cv_data, language.clone().language);
let span = info_span!("render_pdf", username = username);
let pdf = span.in_scope(||{
generate_pdf(browser.browser, &file)
});
let result = PdfStream::new(pdf);
cache.insert(data, result.clone()).await;
cache.insert((language.clone(), data), result.clone()).await;
Ok(result)
}
}

View File

@ -5,7 +5,7 @@ use once_cell::sync::Lazy;
use rocket_prometheus::{prometheus::{IntCounterVec, opts, Error}, PrometheusMetrics};
use std::hash::Hash;
use super::pdf::PdfStream;
use super::{pdf::PdfStream, rocket::RequestLanguage};
static CACHE_EVICTION_COUNT: Lazy<IntCounterVec> = Lazy::new(||
IntCounterVec::new(opts!(format!("{}_{}", std::env::var("ROCKET_PROMETHEUS_NAMESPACE").unwrap_or("app".to_string()), "cache_eviction"), "Count of cache eviction"), &["cause"])
@ -25,7 +25,7 @@ pub fn cache_prometheus_metrics(metrics: &PrometheusMetrics) -> Result<(), Error
Ok(())
}
pub fn build_cache() -> NanoCache<String, PdfStream> {
pub fn build_cache() -> NanoCache<(RequestLanguage, String), PdfStream> {
let cache = Cache::builder()
.time_to_live(Duration::from_secs(60 * 60))
.eviction_listener(|_k, _v, cause| {

View File

@ -1,6 +1,7 @@
use phf::phf_map;
use rocket::request::FromParam;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RequestLanguage {
pub language: String,
}