rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
use crate::{Error, parser, source_map::Translation};
use minijinja::Environment;
use std::{
    collections::VecDeque,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

/// Snapshot of the renderer's bounded in-memory cache.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CacheStats {
    /// Maximum retained entries.
    pub capacity: usize,
    /// Currently retained entries.
    pub entries: usize,
    /// Reuses of translated Sword source.
    pub translation_hits: u64,
    /// Successful Sword translations performed.
    pub translations: u64,
    /// Reuses of a compiled root template.
    pub compiled_root_hits: u64,
    /// Successful root template compilations.
    pub root_compilations: u64,
}

#[derive(Debug)]
struct Entry {
    name: String,
    path: Option<PathBuf>,
    source: String,
    translated: Arc<Translation>,
    root_env: Option<Environment<'static>>,
}

#[derive(Debug)]
struct Inner {
    entries: VecDeque<Entry>,
    stats: CacheStats,
}

#[derive(Debug)]
pub(crate) struct Cache(Mutex<Inner>, Arc<crate::component::Components>);

impl Cache {
    pub fn new(capacity: usize, components: Arc<crate::component::Components>) -> Self {
        Self(
            Mutex::new(Inner {
                entries: VecDeque::new(),
                stats: CacheStats {
                    capacity,
                    ..CacheStats::default()
                },
            }),
            components,
        )
    }

    /// Change the capacity, dropping the oldest entries that no longer fit.
    #[cfg(feature = "laravel")]
    pub fn set_capacity(&self, capacity: usize) {
        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
        inner.stats.capacity = capacity;
        while inner.entries.len() > capacity {
            inner.entries.pop_front();
        }
        inner.stats.entries = inner.entries.len();
    }

    pub fn components(&self) -> Arc<crate::component::Components> {
        Arc::clone(&self.1)
    }

    pub fn stats(&self) -> CacheStats {
        self.0.lock().unwrap_or_else(|e| e.into_inner()).stats
    }

    pub fn translation(
        &self,
        name: &str,
        path: Option<&Path>,
        source: &str,
    ) -> Result<Arc<Translation>, Error> {
        {
            let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(index) = inner.entries.iter().position(|entry| {
                entry.name == name && entry.path.as_deref() == path && entry.source == source
            }) {
                let entry = inner.entries.remove(index).expect("entry exists");
                let result = Arc::clone(&entry.translated);
                inner.entries.push_back(entry);
                inner.stats.translation_hits += 1;
                tracing::debug!(
                    view = name,
                    cache = "translation",
                    hit = true,
                    "sword cache"
                );
                return Ok(result);
            }
        }
        tracing::debug!(
            view = name,
            cache = "translation",
            hit = false,
            "sword cache"
        );
        let translated = Arc::new(parser::translate(name, source, &self.1)?);
        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
        inner.stats.translations += 1;
        if inner.stats.capacity > 0 {
            inner
                .entries
                .retain(|entry| entry.name != name || entry.path.as_deref() != path);
            while inner.entries.len() >= inner.stats.capacity {
                inner.entries.pop_front();
            }
            inner.entries.push_back(Entry {
                name: name.to_owned(),
                path: path.map(Path::to_path_buf),
                source: source.to_owned(),
                translated: Arc::clone(&translated),
                root_env: None,
            });
            inner.stats.entries = inner.entries.len();
        }
        Ok(translated)
    }

    pub fn root_env(
        &self,
        name: &str,
        path: Option<&Path>,
        source: &str,
    ) -> Option<Environment<'static>> {
        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
        let env = inner
            .entries
            .iter()
            .find(|entry| {
                entry.name == name && entry.path.as_deref() == path && entry.source == source
            })
            .and_then(|entry| entry.root_env.clone());
        if env.is_some() {
            inner.stats.compiled_root_hits += 1;
        }
        tracing::debug!(
            view = name,
            cache = "root",
            hit = env.is_some(),
            "sword cache"
        );
        env
    }

    pub fn store_root(
        &self,
        name: &str,
        path: Option<&Path>,
        source: &str,
        env: &Environment<'static>,
    ) {
        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
        inner.stats.root_compilations += 1;
        if let Some(entry) = inner.entries.iter_mut().find(|entry| {
            entry.name == name && entry.path.as_deref() == path && entry.source == source
        }) {
            entry.root_env = Some(env.clone());
        }
    }
}