1use core::fmt;
11use core::hash::Hash;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use coqui_access::guatiao::library::ProviderError;
16use coqui_access::{
17 AccountInfo, AccountPut, Accounts, AuthorizationDecision, AuthorizationRequest, Authorizer,
18 Description, Directory, Lookup, Person, PutOutcome, Waiting,
19};
20use coqui_builder::Describe;
21use moka::Expiry;
22use moka::sync::Cache;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
33#[non_exhaustive]
34pub struct CacheOptions {
35 #[map(default = DEFAULT_TTL)]
37 pub ttl: Duration,
38 #[map(default = DEFAULT_NEGATIVE_TTL)]
40 pub negative_ttl: Duration,
41 #[map(default = DEFAULT_MAX_ENTRIES)]
43 pub max_entries: u64,
44}
45
46pub const DEFAULT_TTL: Duration = Duration::from_secs(5);
48pub const DEFAULT_NEGATIVE_TTL: Duration = Duration::from_secs(1);
50pub const DEFAULT_MAX_ENTRIES: u64 = 10_000;
52
53impl Default for CacheOptions {
54 fn default() -> Self {
55 Self {
56 ttl: DEFAULT_TTL,
57 negative_ttl: DEFAULT_NEGATIVE_TTL,
58 max_entries: DEFAULT_MAX_ENTRIES,
59 }
60 }
61}
62
63impl CacheOptions {
64 pub const fn off() -> Self {
66 Self {
67 ttl: Duration::ZERO,
68 negative_ttl: Duration::ZERO,
69 max_entries: 0,
70 }
71 }
72
73 #[must_use]
75 pub const fn ttl(mut self, ttl: Duration) -> Self {
76 self.ttl = ttl;
77 self
78 }
79
80 #[must_use]
82 pub const fn negative_ttl(mut self, negative_ttl: Duration) -> Self {
83 self.negative_ttl = negative_ttl;
84 self
85 }
86
87 #[must_use]
89 pub const fn max_entries(mut self, max_entries: u64) -> Self {
90 self.max_entries = max_entries;
91 self
92 }
93
94 pub fn exceeds_default(&self) -> bool {
98 self.ttl > DEFAULT_TTL || self.negative_ttl > DEFAULT_NEGATIVE_TTL
99 }
100
101 fn keeps_anything(&self) -> bool {
102 self.max_entries > 0 && !(self.ttl.is_zero() && self.negative_ttl.is_zero())
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
108#[map(untagged)]
109pub enum CacheSetting {
110 Enabled(bool),
112 Tuned(CacheOptions),
114}
115
116impl Default for CacheSetting {
117 fn default() -> Self {
118 Self::Enabled(true)
119 }
120}
121
122impl CacheSetting {
123 pub fn options(&self) -> CacheOptions {
125 match *self {
126 Self::Enabled(true) => CacheOptions::default(),
127 Self::Enabled(false) => CacheOptions::off(),
128 Self::Tuned(options) => options,
129 }
130 }
131}
132
133struct Lifetimes<V> {
135 ttl: Duration,
136 negative_ttl: Duration,
137 negative: fn(&V) -> bool,
138}
139
140impl<K, V> Expiry<K, V> for Lifetimes<V> {
141 fn expire_after_create(&self, _key: &K, value: &V, _created_at: Instant) -> Option<Duration> {
142 Some(if (self.negative)(value) {
143 self.negative_ttl
144 } else {
145 self.ttl
146 })
147 }
148}
149
150fn cache<K, V>(options: CacheOptions, negative: fn(&V) -> bool) -> Option<Cache<K, V>>
151where
152 K: Hash + Eq + Send + Sync + 'static,
153 V: Clone + Send + Sync + 'static,
154{
155 options.keeps_anything().then(|| {
156 Cache::builder()
157 .max_capacity(options.max_entries)
158 .expire_after(Lifetimes {
159 ttl: options.ttl,
160 negative_ttl: options.negative_ttl,
161 negative,
162 })
163 .build()
164 })
165}
166
167type DecisionKey = (String, String, Vec<String>, String, String, Vec<String>);
169
170pub struct Cached<T: ?Sized> {
196 inner: Arc<T>,
197 options: CacheOptions,
198 lookups: Option<Cache<(String, String), Option<Person>>>,
199 decisions: Option<Cache<DecisionKey, AuthorizationDecision>>,
200}
201
202impl<T: ?Sized> fmt::Debug for Cached<T> {
203 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204 let count = |cache: Option<u64>| cache.unwrap_or(0);
205 formatter
206 .debug_struct("Cached")
207 .field("options", &self.options)
208 .field(
209 "lookups",
210 &count(self.lookups.as_ref().map(Cache::entry_count)),
211 )
212 .field(
213 "decisions",
214 &count(self.decisions.as_ref().map(Cache::entry_count)),
215 )
216 .finish_non_exhaustive()
217 }
218}
219
220impl<T: ?Sized> Cached<T> {
221 pub fn new(inner: Arc<T>, options: CacheOptions) -> Self {
223 Self {
224 inner,
225 options,
226 lookups: cache(options, Option::is_none),
227 decisions: cache(options, |decision: &AuthorizationDecision| {
228 !decision.allowed
229 }),
230 }
231 }
232
233 pub fn inner(&self) -> &Arc<T> {
235 &self.inner
236 }
237
238 pub fn options(&self) -> CacheOptions {
240 self.options
241 }
242
243 pub fn invalidate(&self, lookup: &Lookup) {
245 if let Some(lookups) = &self.lookups {
246 lookups.invalidate(&(lookup.by.clone(), lookup.value.clone()));
247 }
248 }
249
250 pub fn invalidate_all(&self) {
252 if let Some(lookups) = &self.lookups {
253 lookups.invalidate_all();
254 }
255 if let Some(decisions) = &self.decisions {
256 decisions.invalidate_all();
257 }
258 }
259}
260
261impl<T: Directory + ?Sized> Directory for Cached<T> {
262 fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
263 let Some(lookups) = &self.lookups else {
264 return self.inner.lookup(lookup);
265 };
266 let key = (lookup.by.clone(), lookup.value.clone());
267 if let Some(kept) = lookups.get(&key) {
268 return Ok(kept);
269 }
270 let found = self.inner.lookup(lookup)?;
271 lookups.insert(key, found.clone());
272 Ok(found)
273 }
274
275 fn describe(&self) -> Result<Description, ProviderError> {
276 Directory::describe(&*self.inner)
277 }
278}
279
280impl<T: Authorizer + ?Sized> Authorizer for Cached<T> {
281 fn authorize(
282 &self,
283 request: AuthorizationRequest,
284 ) -> Result<AuthorizationDecision, ProviderError> {
285 let Some(decisions) = &self.decisions else {
286 return self.inner.authorize(request);
287 };
288 let mut groups = request.person.groups.clone();
289 groups.sort();
290 let key = (
291 request.person.id.clone(),
292 request.person.name.clone(),
293 groups,
294 request.action.clone(),
295 request.resource.clone(),
296 request.ancestors.clone(),
298 );
299 if let Some(kept) = decisions.get(&key) {
300 return Ok(kept);
301 }
302 let decided = self.inner.authorize(request)?;
303 decisions.insert(key, decided.clone());
304 Ok(decided)
305 }
306}
307
308impl<T: Accounts + ?Sized> Accounts for Cached<T> {
309 fn accounts(&self) -> Result<Vec<AccountInfo>, ProviderError> {
310 self.inner.accounts()
311 }
312
313 fn put(&self, account: AccountPut) -> Result<PutOutcome, ProviderError> {
314 let outcome = self.inner.put(account);
315 self.invalidate_all();
316 outcome
317 }
318
319 fn remove(&self, name: String) -> Result<(), ProviderError> {
320 let removed = self.inner.remove(name);
321 self.invalidate_all();
322 removed
323 }
324
325 fn waiting(&self) -> Result<Vec<Waiting>, ProviderError> {
326 self.inner.waiting()
327 }
328}
329
330#[cfg(test)]
331mod tests;