accumulo_access/
caching.rs

1// Copyright 2024 Lars Wilhelmsen <sral-backwards@sral.org>. All rights reserved.
2// Use of this source code is governed by the MIT or Apache-2.0 license that can be found in the LICENSE_MIT or LICENSE_APACHE files.
3
4use cached::{proc_macro::cached, Cached, SizedCache};
5
6fn get_cache_size() -> usize {
7    std::env::var("ACCUMULO_ACCESS_CACHE_SIZE")
8        .unwrap_or_else(|_| String::from("20000"))
9        .parse::<usize>()
10        .unwrap_or(20000)
11}
12
13#[cached(ty = "SizedCache<String, Result<bool, super::ParserError>>",
14create = "{ SizedCache::with_size(get_cache_size()) }",
15convert = r##"{ format!("{}{}", expression, tokens) }"##
16)]
17pub fn check_authorization_csv(
18    expression: String,
19    tokens: String,
20) -> Result<bool, super::ParserError> {
21    super::check_authorization_csv(expression, tokens)
22}
23
24pub fn clear_authz_cache() -> Result<(), String> {
25    let mut cache = crate::caching::CHECK_AUTHORIZATION_CSV
26        .lock()
27        .map_err(|e| format!("Failed to lock cache: {}", e))?;
28    cache.cache_clear();
29    Ok(())
30}
31
32pub struct AuthzCacheStats {
33    pub hits: u64,
34    pub misses: u64,
35    pub size: usize,
36}
37
38impl AuthzCacheStats {
39    pub fn new(hits: u64, misses: u64, size: usize) -> Self {
40        Self {
41            hits,
42            misses,
43            size,
44        }
45    }
46}
47
48pub fn authz_cache_stats() -> Result<AuthzCacheStats, String> {
49    let cache = crate::caching::CHECK_AUTHORIZATION_CSV
50        .lock()
51        .map_err(|e| format!("Failed to lock cache: {}", e))?;
52
53    Ok(AuthzCacheStats::new(cache.cache_hits().unwrap(), cache.cache_misses().unwrap(), cache.cache_size()))
54}