Skip to main content

mdx_gen/
cache.rs

1//! Opt-in full-document render cache (`cache` feature).
2//!
3//! [`CachingProcessor`] owns one [`MarkdownOptions`] and memoises the
4//! output of [`process_markdown`] and [`process_markdown_with_toc`]
5//! per input document. Because the options are fixed when the
6//! processor is built, the cache key only has to identify the
7//! content: build one processor per option set.
8//!
9//! # Keying and correctness
10//!
11//! Entries are looked up by a 64-bit hash of the input, then the
12//! stored input is compared byte for byte before a hit is returned.
13//! A hash collision therefore costs a re-render, never a wrong
14//! answer. The cache holds a copy of every cached input alongside
15//! its HTML, so memory is roughly `capacity x (input + output)`.
16//!
17//! # Eviction
18//!
19//! The cache is bounded by entry count ([`DEFAULT_CAPACITY`] unless
20//! set with [`CachingProcessor::with_capacity`]). When full, the
21//! least recently used entry is evicted. Eviction scans the entries,
22//! which is negligible next to a Markdown render at the default
23//! bound.
24//!
25//! # Concurrency
26//!
27//! `CachingProcessor` is `Send + Sync` and can be shared behind an
28//! `Arc`. The map sits behind one [`std::sync::Mutex`] held only for
29//! lookup and insertion; rendering happens outside the lock, so
30//! threads rendering different documents do not serialise on each
31//! other. Two threads that miss on the same document at the same
32//! time both render it and the second insert wins, which is
33//! harmless because the outputs are identical. A poisoned lock is
34//! recovered rather than propagated: the map holds only finished
35//! renders, so a panic elsewhere cannot leave it half-updated.
36//!
37//! Hits and misses are reported through the `log` crate at `debug`
38//! level, and counted in [`CacheStats`].
39
40use crate::error::MarkdownError;
41use crate::extensions::Heading;
42use crate::markdown::{
43    process_markdown, process_markdown_with_toc, MarkdownOptions,
44};
45use log::debug;
46use std::collections::hash_map::DefaultHasher;
47use std::collections::HashMap;
48use std::hash::{Hash, Hasher};
49use std::sync::{Mutex, MutexGuard};
50
51/// Default number of documents a [`CachingProcessor`] keeps.
52pub const DEFAULT_CAPACITY: usize = 1000;
53
54/// Hit and miss counters for a [`CachingProcessor`].
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
56pub struct CacheStats {
57    /// Lookups answered from the cache.
58    pub hits: u64,
59    /// Lookups that had to render the document.
60    pub misses: u64,
61}
62
63/// Which entry point produced a cached value; the HTML-only and the
64/// table-of-contents variants are cached separately.
65#[derive(Clone, Copy, PartialEq, Eq, Hash)]
66enum Variant {
67    Html,
68    Toc,
69}
70
71struct Entry {
72    content: String,
73    html: String,
74    toc: Vec<Heading>,
75    last_used: u64,
76}
77
78#[derive(Default)]
79struct Inner {
80    entries: HashMap<(Variant, u64), Entry>,
81    tick: u64,
82    stats: CacheStats,
83}
84
85impl Inner {
86    fn lookup(
87        &mut self,
88        key: (Variant, u64),
89        content: &str,
90    ) -> Option<(String, Vec<Heading>)> {
91        self.tick += 1;
92        let tick = self.tick;
93        let found = match self.entries.get_mut(&key) {
94            Some(e) if e.content == content => {
95                e.last_used = tick;
96                Some((e.html.clone(), e.toc.clone()))
97            }
98            _ => None,
99        };
100        if found.is_some() {
101            self.stats.hits += 1;
102        } else {
103            self.stats.misses += 1;
104        }
105        found
106    }
107
108    fn insert(
109        &mut self,
110        key: (Variant, u64),
111        entry: Entry,
112        cap: usize,
113    ) {
114        if !self.entries.contains_key(&key) && self.entries.len() >= cap
115        {
116            self.evict_lru();
117        }
118        self.entries.insert(key, entry);
119    }
120
121    fn evict_lru(&mut self) {
122        let oldest = self
123            .entries
124            .iter()
125            .min_by_key(|(_, e)| e.last_used)
126            .map(|(k, _)| *k);
127        if let Some(k) = oldest {
128            let _ = self.entries.remove(&k);
129        }
130    }
131}
132
133/// A Markdown processor that caches rendered output per document.
134///
135/// # Example
136///
137/// ```
138/// use mdx_gen::{CachingProcessor, MarkdownOptions};
139///
140/// let processor = CachingProcessor::new(MarkdownOptions::default());
141/// let first = processor.process("# Hello").unwrap();   // miss: renders
142/// let second = processor.process("# Hello").unwrap();  // hit: cached
143/// assert_eq!(first, second);
144///
145/// let stats = processor.stats();
146/// assert_eq!((stats.hits, stats.misses), (1, 1));
147/// ```
148pub struct CachingProcessor<'a> {
149    options: MarkdownOptions<'a>,
150    capacity: usize,
151    inner: Mutex<Inner>,
152}
153
154impl<'a> CachingProcessor<'a> {
155    /// Creates a processor with [`DEFAULT_CAPACITY`] entries.
156    pub fn new(options: MarkdownOptions<'a>) -> Self {
157        Self::with_capacity(options, DEFAULT_CAPACITY)
158    }
159
160    /// Creates a processor that keeps at most `capacity` documents.
161    /// A capacity of `0` disables caching: every call renders.
162    pub fn with_capacity(
163        options: MarkdownOptions<'a>,
164        capacity: usize,
165    ) -> Self {
166        Self {
167            options,
168            capacity,
169            inner: Mutex::new(Inner::default()),
170        }
171    }
172
173    /// The options every render uses.
174    pub fn options(&self) -> &MarkdownOptions<'a> {
175        &self.options
176    }
177
178    /// The maximum number of cached documents.
179    pub fn capacity(&self) -> usize {
180        self.capacity
181    }
182
183    /// Number of documents currently cached (both variants).
184    pub fn len(&self) -> usize {
185        self.lock().entries.len()
186    }
187
188    /// Returns `true` when nothing is cached.
189    pub fn is_empty(&self) -> bool {
190        self.len() == 0
191    }
192
193    /// Hit and miss counts since creation or the last [`clear`].
194    ///
195    /// [`clear`]: CachingProcessor::clear
196    pub fn stats(&self) -> CacheStats {
197        self.lock().stats
198    }
199
200    /// Drops every cached document and resets the counters.
201    pub fn clear(&self) {
202        *self.lock() = Inner::default();
203    }
204
205    /// Cached equivalent of [`process_markdown`].
206    ///
207    /// # Errors
208    ///
209    /// Mirrors [`process_markdown`]. Errors are not cached.
210    pub fn process(
211        &self,
212        content: &str,
213    ) -> Result<String, MarkdownError> {
214        self.cached(Variant::Html, content, |c, o| {
215            process_markdown(c, o).map(|html| (html, Vec::new()))
216        })
217        .map(|(html, _)| html)
218    }
219
220    /// Cached equivalent of [`process_markdown_with_toc`].
221    ///
222    /// # Errors
223    ///
224    /// Mirrors [`process_markdown_with_toc`]. Errors are not cached.
225    pub fn process_with_toc(
226        &self,
227        content: &str,
228    ) -> Result<(String, Vec<Heading>), MarkdownError> {
229        self.cached(Variant::Toc, content, process_markdown_with_toc)
230    }
231
232    fn cached<F>(
233        &self,
234        variant: Variant,
235        content: &str,
236        render: F,
237    ) -> Result<(String, Vec<Heading>), MarkdownError>
238    where
239        F: FnOnce(
240            &str,
241            &MarkdownOptions<'a>,
242        )
243            -> Result<(String, Vec<Heading>), MarkdownError>,
244    {
245        let key = (variant, hash_content(content));
246        if let Some(hit) = self.lock().lookup(key, content) {
247            debug!("mdx-gen cache hit ({} bytes)", content.len());
248            return Ok(hit);
249        }
250        debug!("mdx-gen cache miss ({} bytes)", content.len());
251        let (html, toc) = render(content, &self.options)?;
252        if self.capacity > 0 {
253            let (content, cached_html, cached_toc) =
254                (content.to_owned(), html.clone(), toc.clone());
255            let mut inner = self.lock();
256            let entry = Entry {
257                content,
258                html: cached_html,
259                toc: cached_toc,
260                last_used: inner.tick,
261            };
262            inner.insert(key, entry, self.capacity);
263        }
264        Ok((html, toc))
265    }
266
267    fn lock(&self) -> MutexGuard<'_, Inner> {
268        self.inner
269            .lock()
270            .unwrap_or_else(std::sync::PoisonError::into_inner)
271    }
272}
273
274impl std::fmt::Debug for CachingProcessor<'_> {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.debug_struct("CachingProcessor")
277            .field("options", &self.options)
278            .field("capacity", &self.capacity)
279            .field("len", &self.len())
280            .field("stats", &self.stats())
281            .finish()
282    }
283}
284
285fn hash_content(content: &str) -> u64 {
286    let mut h = DefaultHasher::new();
287    content.hash(&mut h);
288    h.finish()
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn capacity_bound_evicts_least_recently_used() {
297        let p = CachingProcessor::with_capacity(
298            MarkdownOptions::default(),
299            2,
300        );
301        p.process("a").unwrap();
302        p.process("b").unwrap();
303        p.process("a").unwrap(); // touch a, so b is the LRU entry
304        p.process("c").unwrap(); // evicts b
305        assert_eq!(p.len(), 2);
306        let before = p.stats();
307        p.process("a").unwrap();
308        assert_eq!(p.stats().hits, before.hits + 1, "a survived");
309        p.process("b").unwrap();
310        assert_eq!(
311            p.stats().misses,
312            before.misses + 1,
313            "b was evicted"
314        );
315    }
316
317    #[test]
318    fn colliding_key_with_different_content_is_a_miss() {
319        let p = CachingProcessor::new(MarkdownOptions::default());
320        let key = (Variant::Html, hash_content("# one"));
321        p.lock().insert(
322            key,
323            Entry {
324                content: "# other".into(),
325                html: "<p>stale</p>".into(),
326                toc: Vec::new(),
327                last_used: 0,
328            },
329            10,
330        );
331        assert!(p.lock().lookup(key, "# one").is_none());
332    }
333
334    #[test]
335    fn zero_capacity_never_stores() {
336        let p = CachingProcessor::with_capacity(
337            MarkdownOptions::default(),
338            0,
339        );
340        p.process("# x").unwrap();
341        p.process("# x").unwrap();
342        assert!(p.is_empty());
343        assert_eq!(p.stats(), CacheStats { hits: 0, misses: 2 });
344    }
345}