1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
//
// SPDX-License-Identifier: EUPL-1.2

use core::fmt::Display;
use core::time::Duration;
use moka::future::Cache as LocalCache;
use redis::{AsyncCommands, RedisError, ToRedisArgs};
use serde::de::DeserializeOwned;
use serde::Serialize;
use siphasher::sip128::{Hasher128, SipHasher24};
use snafu::Snafu;
use std::hash::Hash;
use std::time::Instant;

type RedisConnection = redis::aio::ConnectionManager;

/// Application level cache which can store entries both in a locally and distributed using redis
pub struct Cache<K, V> {
    local: LocalCache<K, LocalEntry<V>>,
    redis: Option<RedisConfig>,
}

struct RedisConfig {
    redis: RedisConnection,
    prefix: String,
    ttl: Duration,
    hash_key: bool,
}

#[derive(Debug, Snafu)]
pub enum CacheError {
    #[snafu(display("Redis error: {}", source), context(false))]
    Redis { source: RedisError },
    #[snafu(display("Serde error: {}", source), context(false))]
    Serde { source: bincode::Error },
}

impl<K, V> Cache<K, V>
where
    K: Display + Hash + Eq + Send + Sync + 'static,
    V: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
{
    pub fn new(ttl: Duration) -> Self {
        Self {
            local: LocalCache::builder().time_to_live(ttl).build(),
            redis: None,
        }
    }

    pub fn with_redis(
        self,
        redis: RedisConnection,
        prefix: impl Into<String>,
        ttl: Duration,
        hash_key: bool,
    ) -> Self {
        Self {
            redis: Some(RedisConfig {
                redis,
                prefix: prefix.into(),
                ttl,
                hash_key,
            }),
            ..self
        }
    }

    /// Return the longest duration an entry might live for
    pub fn longest_ttl(&self) -> Duration {
        let local_ttl = self
            .local
            .policy()
            .time_to_live()
            .expect("local always has a ttl");

        if let Some(redis) = &self.redis {
            redis.ttl.max(local_ttl)
        } else {
            local_ttl
        }
    }

    pub async fn get(&self, key: &K) -> Result<Option<V>, CacheError> {
        if let Some(entry) = self
            .local
            .get(key)
            .await
            .filter(|entry| entry.still_valid())
        {
            Ok(Some(entry.value))
        } else if let Some(RedisConfig {
            redis,
            prefix,
            hash_key,
            ..
        }) = &self.redis
        {
            let v: Option<Vec<u8>> = redis
                .clone()
                .get(RedisCacheKey {
                    prefix,
                    key,
                    hash_key: *hash_key,
                })
                .await?;

            if let Some(v) = v {
                let v = bincode::deserialize(&v)?;

                Ok(Some(v))
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    /// Insert a key-value pair with the cache's default TTL
    pub async fn insert(&self, key: K, value: V) -> Result<(), CacheError> {
        if let Some(RedisConfig {
            redis,
            prefix,
            ttl,
            hash_key,
        }) = &self.redis
        {
            redis
                .clone()
                .set_ex(
                    RedisCacheKey {
                        prefix,
                        key: &key,
                        hash_key: *hash_key,
                    },
                    bincode::serialize(&value)?,
                    ttl.as_secs(),
                )
                .await?;
        }

        self.local
            .insert(
                key,
                LocalEntry {
                    value,
                    expires_at: None,
                },
            )
            .await;

        Ok(())
    }

    /// Insert an entry with a custom TTL
    ///
    /// Note that TTLs larger than the configured one will be ignored
    pub async fn insert_with_ttl(&self, key: K, value: V, ttl: Duration) -> Result<(), CacheError> {
        if ttl >= self.longest_ttl() {
            return self.insert(key, value).await;
        }

        if let Some(RedisConfig {
            redis,
            prefix,
            hash_key,
            ..
        }) = &self.redis
        {
            redis
                .clone()
                .set_ex(
                    RedisCacheKey {
                        prefix,
                        key: &key,
                        hash_key: *hash_key,
                    },
                    bincode::serialize(&value)?,
                    ttl.as_secs(),
                )
                .await?;
        }

        self.local
            .insert(
                key,
                LocalEntry {
                    value,
                    expires_at: Some(Instant::now() + ttl),
                },
            )
            .await;

        Ok(())
    }
}

/// [`ToRedisArgs`] implementation for the cache-key
/// Takes the prefix and cache-key to turn them into a redis-key
struct RedisCacheKey<'a, K> {
    hash_key: bool,
    prefix: &'a str,
    key: &'a K,
}

impl<K: Display + Hash> Display for RedisCacheKey<'_, K> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.hash_key {
            let mut h = SipHasher24::new_with_keys(!0x113, 0x311);
            self.key.hash(&mut h);
            let hash = h.finish128().as_u128();

            write!(f, "opentalk-cache:{}:{:x}", self.prefix, hash)
        } else {
            write!(f, "opentalk-cache:{}:{}", self.prefix, self.key)
        }
    }
}

impl<D: Display + Hash> ToRedisArgs for RedisCacheKey<'_, D> {
    fn write_redis_args<W>(&self, out: &mut W)
    where
        W: ?Sized + redis::RedisWrite,
    {
        out.write_arg_fmt(self)
    }
}

#[derive(Debug, Clone, Copy)]
struct LocalEntry<V> {
    value: V,
    /// Custom expiration value to work around moka's limitation to set a custom ttl for an entry
    expires_at: Option<Instant>,
}

impl<V> LocalEntry<V> {
    // Check if the custom ttl has expired
    fn still_valid(&self) -> bool {
        if let Some(exp) = self.expires_at {
            exp.saturating_duration_since(Instant::now()) > Duration::ZERO
        } else {
            true
        }
    }
}