sova-store 0.1.3

KvStore trait + memory / file / sql / redis / redb backends for Sova
Documentation
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Byte-oriented key-value store for Sova plugins (sessions, cache, CSRF, rate-limit).
//!
//! Trait is stable (memory + file + sql + redis + redb backends).
//! Enable feature `unstable-store` for backwards-compatible feature flags.
//! **Not in sova-core** — wire with `app.state(store.namespace("sess"))`.

mod cache;
#[cfg(feature = "store-crypto")]
mod encrypted;
#[cfg(feature = "file")]
mod file;
#[cfg(feature = "redb")]
mod redb;
#[cfg(feature = "redis")]
mod redis;
#[cfg(feature = "sql")]
mod sql;

use bytes::Bytes;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

pub use cache::{Cache, CacheError};

pub trait KvStore: Send + Sync + 'static {
    fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<Bytes>>;
    fn set<'a>(&'a self, key: &'a str, val: Bytes, ttl: Option<Duration>) -> BoxFuture<'a, ()>;
    fn remove<'a>(&'a self, key: &'a str) -> BoxFuture<'a, ()>;
    /// Atomic increment; creates the key at `by` when missing. Returns new value.
    fn incr<'a>(&'a self, key: &'a str, by: i64, ttl: Option<Duration>) -> BoxFuture<'a, u64>;
    /// Remove keys starting with `prefix`. Returns how many were removed.
    fn clear_prefix<'a>(&'a self, prefix: &'a str) -> BoxFuture<'a, u64>;
}

pub fn namespace(store: Arc<dyn KvStore>, name: &str) -> Namespace {
    Namespace {
        store,
        prefix: format!("{name}:"),
    }
}

/// App-wide store handle — `app.state(AppStore::memory())` or via facade `SharedStore` plugin.
/// Session / meta / rate-limit can reuse namespaced views of the same backend.
#[derive(Clone)]
pub struct AppStore {
    pub inner: Arc<dyn KvStore>,
}

impl AppStore {
    pub fn new(store: Arc<dyn KvStore>) -> Self {
        Self { inner: store }
    }

    pub fn memory() -> Self {
        Self::new(Arc::new(MemoryStore::new()))
    }

    pub fn namespaced(&self, name: &str) -> Arc<dyn KvStore> {
        Arc::new(namespace(Arc::clone(&self.inner), name))
    }
}

#[cfg(feature = "store-crypto")]
pub use encrypted::{encrypted, encrypted_ns, AppKey, Encrypted};

#[cfg(feature = "file")]
pub use file::{Durability, FileStore};

#[cfg(feature = "redb")]
pub use redb::RedbStore;

#[cfg(feature = "redis")]
pub use redis::RedisStore;

#[cfg(feature = "sql")]
pub use sql::SqlStore;

/// Scoped handle — prefixes all keys; [`clear_prefix`](KvStore::clear_prefix) stays inside.
#[derive(Clone)]
pub struct Namespace {
    store: Arc<dyn KvStore>,
    prefix: String,
}

impl Namespace {
    fn full(&self, key: &str) -> String {
        format!("{}{key}", self.prefix)
    }
}

impl KvStore for Namespace {
    fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<Bytes>> {
        let k = self.full(key);
        Box::pin(async move { self.store.get(&k).await })
    }

    fn set<'a>(&'a self, key: &'a str, val: Bytes, ttl: Option<Duration>) -> BoxFuture<'a, ()> {
        let k = self.full(key);
        Box::pin(async move { self.store.set(&k, val, ttl).await })
    }

    fn remove<'a>(&'a self, key: &'a str) -> BoxFuture<'a, ()> {
        let k = self.full(key);
        Box::pin(async move { self.store.remove(&k).await })
    }

    fn incr<'a>(&'a self, key: &'a str, by: i64, ttl: Option<Duration>) -> BoxFuture<'a, u64> {
        let k = self.full(key);
        Box::pin(async move { self.store.incr(&k, by, ttl).await })
    }

    fn clear_prefix<'a>(&'a self, prefix: &'a str) -> BoxFuture<'a, u64> {
        let p = self.full(prefix);
        Box::pin(async move { self.store.clear_prefix(&p).await })
    }
}

struct Entry {
    val: Bytes,
    exp: Option<Instant>,
}

type ShardMap = Arc<Mutex<HashMap<String, Entry>>>;

/// In-process KvStore (sharded Mutex maps + TTL).
#[derive(Clone)]
pub struct MemoryStore {
    shards: Arc<[ShardMap]>,
}

impl Default for MemoryStore {
    fn default() -> Self {
        Self::new()
    }
}

impl MemoryStore {
    /// Default shard count: `max(1, available_parallelism * 2)`.
    pub fn new() -> Self {
        let n = std::thread::available_parallelism()
            .map(|p| p.get() * 2)
            .unwrap_or(2)
            .max(1);
        Self::with_shards(n)
    }

    /// Explicit shard count (minimum 1).
    pub fn with_shards(n: usize) -> Self {
        let n = n.max(1);
        let shards: Vec<_> = (0..n)
            .map(|_| Arc::new(Mutex::new(HashMap::new())))
            .collect();
        Self {
            shards: shards.into(),
        }
    }

    fn shard(&self, key: &str) -> &ShardMap {
        &self.shards[shard_index(key, self.shards.len())]
    }

    fn alive(e: &Entry, now: Instant) -> bool {
        e.exp.map(|t| t > now).unwrap_or(true)
    }
}

fn shard_index(key: &str, n: usize) -> usize {
    let mut h = DefaultHasher::new();
    key.hash(&mut h);
    (h.finish() as usize) % n
}

fn trunc_key(key: &str) -> String {
    const MAX: usize = 120;
    if key.len() <= MAX {
        key.to_string()
    } else {
        format!("{}", &key[..MAX - 1])
    }
}

impl KvStore for MemoryStore {
    fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<Bytes>> {
        let shard = Arc::clone(self.shard(key));
        let key = key.to_string();
        Box::pin(async move {
            let started = Instant::now();
            let mut map = shard.lock().await;
            let now = Instant::now();
            let val = match map.get(&key) {
                Some(e) if Self::alive(e, now) => Some(e.val.clone()),
                Some(_) => {
                    map.remove(&key);
                    None
                }
                None => None,
            };
            let hit = val.is_some();
            let n = val.as_ref().map(|b| b.len() as u64);
            tracing::debug!(
                target: "sova.store",
                op = "get",
                backend = "memory",
                key = %trunc_key(&key),
                hit,
                bytes = n,
                duration_ms = started.elapsed().as_secs_f64() * 1000.0,
                request_id = sova_core::current_request_id().as_deref().unwrap_or(""),
                "sova.store"
            );
            val
        })
    }

    fn set<'a>(&'a self, key: &'a str, val: Bytes, ttl: Option<Duration>) -> BoxFuture<'a, ()> {
        let shard = Arc::clone(self.shard(key));
        let key = key.to_string();
        Box::pin(async move {
            let started = Instant::now();
            let n = val.len() as u64;
            let mut map = shard.lock().await;
            map.insert(
                key.clone(),
                Entry {
                    val,
                    exp: ttl.map(|d| Instant::now() + d),
                },
            );
            tracing::debug!(
                target: "sova.store",
                op = "set",
                backend = "memory",
                key = %trunc_key(&key),
                bytes = n,
                duration_ms = started.elapsed().as_secs_f64() * 1000.0,
                request_id = sova_core::current_request_id().as_deref().unwrap_or(""),
                "sova.store"
            );
        })
    }

    fn remove<'a>(&'a self, key: &'a str) -> BoxFuture<'a, ()> {
        let shard = Arc::clone(self.shard(key));
        let key = key.to_string();
        Box::pin(async move {
            shard.lock().await.remove(&key);
        })
    }

    fn incr<'a>(&'a self, key: &'a str, by: i64, ttl: Option<Duration>) -> BoxFuture<'a, u64> {
        let shard = Arc::clone(self.shard(key));
        let key = key.to_string();
        Box::pin(async move {
            let mut map = shard.lock().await;
            let now = Instant::now();
            let cur = match map.get(&key) {
                Some(e) if Self::alive(e, now) => {
                    let s = std::str::from_utf8(&e.val).unwrap_or("0");
                    s.parse::<i64>().unwrap_or(0)
                }
                _ => 0,
            };
            let next = (cur + by).max(0) as u64;
            map.insert(
                key,
                Entry {
                    val: Bytes::from(next.to_string()),
                    exp: ttl.map(|d| now + d),
                },
            );
            next
        })
    }

    fn clear_prefix<'a>(&'a self, prefix: &'a str) -> BoxFuture<'a, u64> {
        let prefix = prefix.to_string();
        let shards: Vec<_> = self.shards.iter().cloned().collect();
        Box::pin(async move {
            let mut total = 0u64;
            for shard in shards {
                let mut map = shard.lock().await;
                let keys: Vec<_> = map
                    .keys()
                    .filter(|k| k.starts_with(&prefix))
                    .cloned()
                    .collect();
                total += keys.len() as u64;
                for k in keys {
                    map.remove(&k);
                }
            }
            total
        })
    }
}

/// Shared conformance suite for any [`KvStore`].
pub mod conformance {
    use super::*;
    use std::sync::Arc;

    pub async fn run(store: Arc<dyn KvStore>) {
        get_set_ttl(store.clone()).await;
        namespace_isolation(store.clone()).await;
        incr_atomic(store.clone()).await;
        clear_prefix_scoped(store).await;
    }

    async fn get_set_ttl(store: Arc<dyn KvStore>) {
        store
            .set("a", Bytes::from_static(b"1"), Some(Duration::from_millis(50)))
            .await;
        assert_eq!(store.get("a").await.as_deref(), Some(b"1".as_slice()));
        tokio::time::sleep(Duration::from_millis(80)).await;
        assert!(store.get("a").await.is_none());
    }

    async fn namespace_isolation(store: Arc<dyn KvStore>) {
        let a = namespace(store.clone(), "a");
        let b = namespace(store.clone(), "b");
        a.set("k", Bytes::from_static(b"A"), None).await;
        b.set("k", Bytes::from_static(b"B"), None).await;
        assert_eq!(a.get("k").await.as_deref(), Some(b"A".as_slice()));
        assert_eq!(b.get("k").await.as_deref(), Some(b"B".as_slice()));
        a.clear_prefix("").await;
        assert!(a.get("k").await.is_none());
        assert_eq!(b.get("k").await.as_deref(), Some(b"B".as_slice()));
    }

    async fn incr_atomic(store: Arc<dyn KvStore>) {
        store.remove("c").await;
        let mut handles = Vec::new();
        for _ in 0..50 {
            let s = store.clone();
            handles.push(tokio::spawn(async move {
                s.incr("c", 1, None).await;
            }));
        }
        for h in handles {
            h.await.unwrap();
        }
        assert_eq!(store.get("c").await.unwrap().as_ref(), b"50");
    }

    async fn clear_prefix_scoped(store: Arc<dyn KvStore>) {
        store.set("p:1", Bytes::from_static(b"x"), None).await;
        store.set("p:2", Bytes::from_static(b"y"), None).await;
        store.set("q:1", Bytes::from_static(b"z"), None).await;
        assert_eq!(store.clear_prefix("p:").await, 2);
        assert!(store.get("p:1").await.is_none());
        assert_eq!(store.get("q:1").await.as_deref(), Some(b"z".as_slice()));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn memory_conformance() {
        conformance::run(Arc::new(MemoryStore::new())).await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn sharded_clear_prefix_across_shards() {
        let store = MemoryStore::with_shards(4);
        for i in 0..32 {
            store
                .set(
                    &format!("shard:{i}"),
                    Bytes::from_static(b"v"),
                    None,
                )
                .await;
        }
        store
            .set("other:1", Bytes::from_static(b"z"), None)
            .await;
        assert_eq!(store.clear_prefix("shard:").await, 32);
        assert!(store.get("shard:0").await.is_none());
        assert_eq!(
            store.get("other:1").await.as_deref(),
            Some(b"z".as_slice())
        );
    }

    #[tokio::test]
    async fn cache_remember_memory() {
        let store = AppStore::memory();
        let cache = store.cache();
        let v = cache
            .remember("k", None, || async { Ok::<_, CacheError>(42u32) })
            .await
            .unwrap();
        assert_eq!(v, 42);
        let hit = cache.get_json::<u32>("k").await;
        assert_eq!(hit, Some(42));
    }
}