Skip to main content

djs_cache/
backend.rs

1//! The storage the cache is built on: a [`Store`] per resource, created by a [`Backend`].
2
3use core::{fmt, hash::Hash};
4use std::sync::Arc;
5
6use crate::{Limit, Resource};
7
8/// The map holding the entries of one [`Resource`].
9///
10/// The cache keeps one store per enabled resource and does everything else itself: it
11/// decides what to insert and remove for each gateway event, keeps the guild and channel
12/// indexes, and enforces the [`Limit`]s. A store only has to be a concurrent map of
13/// [`Arc`]ed values (D-151, D-155).
14///
15/// Every method takes `&self`: the cache is shared between shards, so a store synchronises
16/// internally. Each call must be atomic on its own; nothing more is required (the cache never
17/// relies on two calls happening together).
18///
19/// discord.js counterpart: the `Collection` a `makeCache` function returns for one manager.
20///
21/// # Examples
22///
23/// A store over a [`Mutex`](std::sync::Mutex)ed [`HashMap`](std::collections::HashMap), for
24/// illustration; [`DashMapStore`](crate::DashMapStore) is the default:
25///
26/// ```
27/// use std::{collections::HashMap, hash::Hash, sync::{Arc, Mutex}};
28///
29/// use djs_cache::Store;
30///
31/// #[derive(Debug, Default)]
32/// struct MutexStore<K, V>(Mutex<HashMap<K, Arc<V>>>);
33///
34/// impl<K, V> Store<K, V> for MutexStore<K, V>
35/// where
36///     K: Eq + Hash + Copy + Send + Sync,
37///     V: Send + Sync,
38/// {
39///     fn get(&self, key: &K) -> Option<Arc<V>> {
40///         self.0.lock().unwrap().get(key).cloned()
41///     }
42///     fn insert(&self, key: K, value: Arc<V>) -> Option<Arc<V>> {
43///         self.0.lock().unwrap().insert(key, value)
44///     }
45///     fn remove(&self, key: &K) -> Option<Arc<V>> {
46///         self.0.lock().unwrap().remove(key)
47///     }
48///     fn len(&self) -> usize {
49///         self.0.lock().unwrap().len()
50///     }
51///     fn retain(&self, keep: &mut dyn FnMut(&K, &V) -> bool) {
52///         self.0.lock().unwrap().retain(|key, value| keep(key, value));
53///     }
54///     fn values(&self) -> Vec<Arc<V>> {
55///         self.0.lock().unwrap().values().cloned().collect()
56///     }
57///     fn keys(&self) -> Vec<K> {
58///         self.0.lock().unwrap().keys().copied().collect()
59///     }
60/// }
61///
62/// let store = MutexStore::default();
63/// assert!(store.insert(1_u64, Arc::new("one")).is_none());
64/// assert_eq!(store.insert(1, Arc::new("uno")).as_deref(), Some(&"one"));
65/// assert_eq!(store.get(&1).as_deref(), Some(&"uno"));
66/// assert_eq!(store.len(), 1);
67/// ```
68pub trait Store<K, V>: Send + Sync {
69    /// Returns the value of `key`, if any.
70    fn get(&self, key: &K) -> Option<Arc<V>>;
71
72    /// Inserts or replaces the value of `key`, returning the previous one.
73    fn insert(&self, key: K, value: Arc<V>) -> Option<Arc<V>>;
74
75    /// Removes the value of `key`, returning it.
76    fn remove(&self, key: &K) -> Option<Arc<V>>;
77
78    /// Returns the number of entries.
79    fn len(&self) -> usize;
80
81    /// Returns whether the store has no entries.
82    fn is_empty(&self) -> bool {
83        self.len() == 0
84    }
85
86    /// Returns whether `key` has a value.
87    fn contains_key(&self, key: &K) -> bool {
88        self.get(key).is_some()
89    }
90
91    /// Removes every entry for which `keep` returns `false`.
92    ///
93    /// Entries inserted while this runs may or may not be visited.
94    fn retain(&self, keep: &mut dyn FnMut(&K, &V) -> bool);
95
96    /// Returns a snapshot of every value, in no particular order.
97    ///
98    /// Entries changed while this runs may appear in their old or new state, or not at all.
99    fn values(&self) -> Vec<Arc<V>>;
100
101    /// Returns a snapshot of every key, in no particular order, with the same consistency as
102    /// [`values`](Self::values).
103    fn keys(&self) -> Vec<K>;
104}
105
106/// Creates the [`Store`] of each [`Resource`].
107///
108/// A backend is chosen once, as the type parameter of [`Cache`](crate::Cache), so every store
109/// call is a static call (D-155). The default is [`DashMapBackend`](crate::DashMapBackend).
110///
111/// discord.js counterpart: the `makeCache` client option, called once per manager.
112///
113/// # Examples
114///
115/// A backend creating the `MutexStore` of the [`Store`] example:
116///
117/// ```
118/// # use std::{collections::HashMap, hash::Hash, sync::{Arc, Mutex}};
119/// # use djs_cache::Store;
120/// # #[derive(Debug, Default)]
121/// # struct MutexStore<K, V>(Mutex<HashMap<K, Arc<V>>>);
122/// # impl<K: Eq + Hash + Copy + Send + Sync, V: Send + Sync> Store<K, V> for MutexStore<K, V> {
123/// #     fn get(&self, key: &K) -> Option<Arc<V>> { self.0.lock().unwrap().get(key).cloned() }
124/// #     fn insert(&self, key: K, value: Arc<V>) -> Option<Arc<V>> { self.0.lock().unwrap().insert(key, value) }
125/// #     fn remove(&self, key: &K) -> Option<Arc<V>> { self.0.lock().unwrap().remove(key) }
126/// #     fn len(&self) -> usize { self.0.lock().unwrap().len() }
127/// #     fn retain(&self, keep: &mut dyn FnMut(&K, &V) -> bool) { self.0.lock().unwrap().retain(|k, v| keep(k, v)); }
128/// #     fn values(&self) -> Vec<Arc<V>> { self.0.lock().unwrap().values().cloned().collect() }
129/// #     fn keys(&self) -> Vec<K> { self.0.lock().unwrap().keys().copied().collect() }
130/// # }
131/// use djs_cache::{Backend, Cache, CacheConfig, Limit, Resource};
132///
133/// #[derive(Debug)]
134/// struct MutexBackend;
135///
136/// impl Backend for MutexBackend {
137///     type Store<K, V>
138///         = MutexStore<K, V>
139///     where
140///         K: Eq + Hash + Copy + Send + Sync + 'static,
141///         V: Send + Sync + 'static;
142///
143///     fn store<K, V>(&self, _resource: Resource, _limit: Limit) -> MutexStore<K, V>
144///     where
145///         K: Eq + Hash + Copy + Send + Sync + 'static,
146///         V: Send + Sync + 'static,
147///     {
148///         MutexStore(Mutex::new(HashMap::new()))
149///     }
150/// }
151///
152/// let cache = Cache::with_backend(CacheConfig::default(), MutexBackend);
153/// # let _ = cache;
154/// ```
155pub trait Backend: fmt::Debug + Send + Sync + 'static {
156    /// The store this backend creates for values of type `V` under keys of type `K`.
157    type Store<K, V>: Store<K, V>
158    where
159        K: Eq + Hash + Copy + Send + Sync + 'static,
160        V: Send + Sync + 'static;
161
162    /// Creates the store of `resource`.
163    ///
164    /// Called once per enabled resource when the [`Cache`](crate::Cache) is created. `limit`
165    /// is the resource's configured limit, for information: it counts in the resource's scope
166    /// (per guild for members, D-159) and the cache enforces it, so a store does not evict
167    /// anything itself.
168    fn store<K, V>(&self, resource: Resource, limit: Limit) -> Self::Store<K, V>
169    where
170        K: Eq + Hash + Copy + Send + Sync + 'static,
171        V: Send + Sync + 'static;
172}