Skip to main content

rustysan_sword/
cache.rs

1use crate::{Error, parser, source_map::Translation};
2use minijinja::Environment;
3use std::{
4    collections::VecDeque,
5    path::{Path, PathBuf},
6    sync::{Arc, Mutex},
7};
8
9/// Snapshot of the renderer's bounded in-memory cache.
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
11pub struct CacheStats {
12    /// Maximum retained entries.
13    pub capacity: usize,
14    /// Currently retained entries.
15    pub entries: usize,
16    /// Reuses of translated Sword source.
17    pub translation_hits: u64,
18    /// Successful Sword translations performed.
19    pub translations: u64,
20    /// Reuses of a compiled root template.
21    pub compiled_root_hits: u64,
22    /// Successful root template compilations.
23    pub root_compilations: u64,
24}
25
26#[derive(Debug)]
27struct Entry {
28    name: String,
29    path: Option<PathBuf>,
30    source: String,
31    translated: Arc<Translation>,
32    root_env: Option<Environment<'static>>,
33}
34
35#[derive(Debug)]
36struct Inner {
37    entries: VecDeque<Entry>,
38    stats: CacheStats,
39}
40
41#[derive(Debug)]
42pub(crate) struct Cache(Mutex<Inner>, Arc<crate::component::Components>);
43
44impl Cache {
45    pub fn new(capacity: usize, components: Arc<crate::component::Components>) -> Self {
46        Self(
47            Mutex::new(Inner {
48                entries: VecDeque::new(),
49                stats: CacheStats {
50                    capacity,
51                    ..CacheStats::default()
52                },
53            }),
54            components,
55        )
56    }
57
58    /// Change the capacity, dropping the oldest entries that no longer fit.
59    #[cfg(feature = "laravel")]
60    pub fn set_capacity(&self, capacity: usize) {
61        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
62        inner.stats.capacity = capacity;
63        while inner.entries.len() > capacity {
64            inner.entries.pop_front();
65        }
66        inner.stats.entries = inner.entries.len();
67    }
68
69    pub fn components(&self) -> Arc<crate::component::Components> {
70        Arc::clone(&self.1)
71    }
72
73    pub fn stats(&self) -> CacheStats {
74        self.0.lock().unwrap_or_else(|e| e.into_inner()).stats
75    }
76
77    pub fn translation(
78        &self,
79        name: &str,
80        path: Option<&Path>,
81        source: &str,
82    ) -> Result<Arc<Translation>, Error> {
83        {
84            let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
85            if let Some(index) = inner.entries.iter().position(|entry| {
86                entry.name == name && entry.path.as_deref() == path && entry.source == source
87            }) {
88                let entry = inner.entries.remove(index).expect("entry exists");
89                let result = Arc::clone(&entry.translated);
90                inner.entries.push_back(entry);
91                inner.stats.translation_hits += 1;
92                tracing::debug!(
93                    view = name,
94                    cache = "translation",
95                    hit = true,
96                    "sword cache"
97                );
98                return Ok(result);
99            }
100        }
101        tracing::debug!(
102            view = name,
103            cache = "translation",
104            hit = false,
105            "sword cache"
106        );
107        let translated = Arc::new(parser::translate(name, source, &self.1)?);
108        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
109        inner.stats.translations += 1;
110        if inner.stats.capacity > 0 {
111            inner
112                .entries
113                .retain(|entry| entry.name != name || entry.path.as_deref() != path);
114            while inner.entries.len() >= inner.stats.capacity {
115                inner.entries.pop_front();
116            }
117            inner.entries.push_back(Entry {
118                name: name.to_owned(),
119                path: path.map(Path::to_path_buf),
120                source: source.to_owned(),
121                translated: Arc::clone(&translated),
122                root_env: None,
123            });
124            inner.stats.entries = inner.entries.len();
125        }
126        Ok(translated)
127    }
128
129    pub fn root_env(
130        &self,
131        name: &str,
132        path: Option<&Path>,
133        source: &str,
134    ) -> Option<Environment<'static>> {
135        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
136        let env = inner
137            .entries
138            .iter()
139            .find(|entry| {
140                entry.name == name && entry.path.as_deref() == path && entry.source == source
141            })
142            .and_then(|entry| entry.root_env.clone());
143        if env.is_some() {
144            inner.stats.compiled_root_hits += 1;
145        }
146        tracing::debug!(
147            view = name,
148            cache = "root",
149            hit = env.is_some(),
150            "sword cache"
151        );
152        env
153    }
154
155    pub fn store_root(
156        &self,
157        name: &str,
158        path: Option<&Path>,
159        source: &str,
160        env: &Environment<'static>,
161    ) {
162        let mut inner = self.0.lock().unwrap_or_else(|e| e.into_inner());
163        inner.stats.root_compilations += 1;
164        if let Some(entry) = inner.entries.iter_mut().find(|entry| {
165            entry.name == name && entry.path.as_deref() == path && entry.source == source
166        }) {
167            entry.root_env = Some(env.clone());
168        }
169    }
170}