Skip to main content

gen_models/
foreign_key_cache.rs

1use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
2
3/// Retains a related model for one model instance without writing to the database.
4///
5/// Cloning the cache creates an independent cache cell that initially holds the same model Arc.
6#[derive(Debug)]
7pub struct ForeignKeyCache<T> {
8    value: Mutex<Option<Arc<T>>>,
9}
10
11impl<T> Default for ForeignKeyCache<T> {
12    fn default() -> Self {
13        Self {
14            value: Mutex::new(None),
15        }
16    }
17}
18
19impl<T> Clone for ForeignKeyCache<T> {
20    fn clone(&self) -> Self {
21        Self {
22            value: Mutex::new(self.snapshot()),
23        }
24    }
25}
26
27impl<T> ForeignKeyCache<T> {
28    /// Returns the currently retained model, if any.
29    pub fn snapshot(&self) -> Option<Arc<T>> {
30        self.lock().as_ref().map(Arc::clone)
31    }
32
33    /// Replaces or clears the runtime-only cached model.
34    pub fn replace(&self, value: Option<Arc<T>>) {
35        *self.lock() = value;
36    }
37
38    /// Returns a matching cached value or loads and retains one while holding the cache lock.
39    pub fn get_or_load<E>(
40        &self,
41        matches: impl FnOnce(&T) -> bool,
42        load: impl FnOnce() -> Result<Arc<T>, E>,
43    ) -> Result<Arc<T>, E> {
44        let mut cached = self.lock();
45        if let Some(value) = cached.as_ref()
46            && matches(value)
47        {
48            return Ok(Arc::clone(value));
49        }
50
51        *cached = None;
52        let value = load()?;
53        *cached = Some(Arc::clone(&value));
54        Ok(value)
55    }
56
57    fn lock(&self) -> MutexGuard<'_, Option<Arc<T>>> {
58        self.value.lock().unwrap_or_else(PoisonError::into_inner)
59    }
60}