ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Application cache with a Laravel-style API: JSON values (serde), per-key TTL, atomic
//! `add` and `increment`.
//!
//! Stores: in-memory (default) and, with the `db` feature, the SeaORM table `cache`
//! (self-created by [`Cache::ensure_tables`], SQLite/PostgreSQL/MySQL). Expired entries are
//! never returned.
//!
//! ```
//! # #[tokio::main] async fn main() {
//! use ryuk::cache::Cache;
//! use std::time::Duration;
//!
//! let cache = Cache::memory();
//! cache.put("greeting", &"hello", Duration::from_secs(60)).await.unwrap();
//! assert_eq!(cache.get::<String>("greeting").await.unwrap().as_deref(), Some("hello"));
//! let n = cache.increment("hits", 1).await.unwrap();
//! assert_eq!(n, 1);
//! let v: u32 = cache.remember("answer", Duration::from_secs(60), || async { 42 }).await.unwrap();
//! assert_eq!(v, 42);
//! # }
//! ```
use serde::{Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Cache failure.
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    /// The value did not serialize, or the stored JSON is not a `T`.
    #[error("cache value: {0}")]
    Serde(#[from] serde_json::Error),
    /// `increment` on a key whose value is not an integer.
    #[error("cache key `{0}` does not hold an integer")]
    NotInteger(String),
    /// `CACHE_DRIVER` is not `memory` or `database`, or `database` without a connection.
    #[error("cache driver: {0}")]
    Driver(String),
    /// Database error.
    #[cfg(feature = "db")]
    #[error("database: {0}")]
    Db(#[from] sea_orm::DbErr),
}

/// Entries the memory store holds before it evicts (expired first, then soonest to expire).
const MEMORY_CAP: usize = 10_000;

type Map = HashMap<String, (String, Option<Instant>)>;

/// Process-local store.
///
/// shortcut: per process, lost on restart and not shared between instances; use the database
/// store for that. At the cap the soonest-to-expire entry is found by a linear scan (O(n) per
/// over-cap write); switch to an ordered index if that ever shows up in a profile.
struct Memory {
    map: Mutex<Map>,
    cap: usize,
}

impl Memory {
    fn lock(&self) -> std::sync::MutexGuard<'_, Map> {
        self.map.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Live value for `key`; an expired one is dropped on the spot.
    fn live(m: &mut Map, key: &str) -> Option<String> {
        match m.get(key) {
            Some((_, Some(t))) if *t <= Instant::now() => {
                m.remove(key);
                None
            }
            Some((v, _)) => Some(v.clone()),
            None => None,
        }
    }

    fn insert(&self, m: &mut Map, key: &str, v: String, exp: Option<Instant>) {
        if !m.contains_key(key) && m.len() >= self.cap {
            let now = Instant::now();
            m.retain(|_, (_, t)| t.is_none_or(|t| t > now));
            if m.len() >= self.cap {
                // forever (None) sorts last, so permanent entries go only when nothing expires
                let victim = m
                    .iter()
                    .min_by_key(|(_, (_, t))| t.map_or((1, now), |t| (0, t)))
                    .map(|(k, _)| k.clone());
                if let Some(k) = victim {
                    m.remove(&k);
                }
            }
        }
        m.insert(key.to_owned(), (v, exp));
    }

    fn prune(&self) -> u64 {
        let mut m = self.lock();
        let (n, now) = (m.len(), Instant::now());
        m.retain(|_, (_, t)| t.is_none_or(|t| t > now));
        (n - m.len()) as u64
    }
}

/// `cache` table.
#[cfg(feature = "db")]
pub mod entry {
    use sea_orm::entity::prelude::*;
    /// One cached value.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "cache")]
    pub struct Model {
        #[sea_orm(primary_key, auto_increment = false)]
        pub key: String,
        /// JSON text.
        #[sea_orm(column_type = "Text")]
        pub value: String,
        /// Authoritative value while set (integers), so `increment` is a single
        /// `counter = counter + n` statement; NULL for non-integer values.
        pub counter: Option<i64>,
        /// Unix milliseconds; the entry is dead at and after this instant. 0 = forever.
        pub expires_at: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

#[cfg(feature = "db")]
mod dbops {
    use super::{CacheError, entry as cache};
    use cache::{Column, Entity};
    use sea_orm::sea_query::{Expr, OnConflict};
    use sea_orm::{
        ActiveValue::Set, ColumnTrait, Condition, ConnectionTrait, DatabaseConnection, EntityTrait,
        ExprTrait, QueryFilter, Schema, SqlErr, TransactionTrait,
    };

    pub fn now_ms() -> i64 {
        chrono::Utc::now().timestamp_millis()
    }

    fn live() -> Condition {
        Condition::any()
            .add(Column::ExpiresAt.eq(0))
            .add(Column::ExpiresAt.gt(now_ms()))
    }

    fn json(row: cache::Model) -> String {
        row.counter.map_or(row.value, |c| c.to_string())
    }

    fn row(key: &str, v: &str, exp: i64) -> cache::ActiveModel {
        cache::ActiveModel {
            key: Set(key.into()),
            value: Set(v.into()),
            // an integer JSON value is also the counter, so a later increment continues from it
            counter: Set(v.parse::<i64>().ok()),
            expires_at: Set(exp),
        }
    }

    pub async fn ensure(db: &DatabaseConnection) -> Result<(), CacheError> {
        let mut t = Schema::new(db.get_database_backend()).create_table_from_entity(Entity);
        db.execute(t.if_not_exists()).await?;
        Ok(())
    }

    pub async fn get(db: &DatabaseConnection, key: &str) -> Result<Option<String>, CacheError> {
        Ok(Entity::find_by_id(key)
            .filter(live())
            .one(db)
            .await?
            .map(json))
    }

    pub async fn put(
        db: &DatabaseConnection,
        key: &str,
        v: &str,
        exp: i64,
    ) -> Result<(), CacheError> {
        Entity::insert(row(key, v, exp))
            .on_conflict(
                OnConflict::column(Column::Key)
                    .update_columns([Column::Value, Column::Counter, Column::ExpiresAt])
                    .to_owned(),
            )
            .exec_without_returning(db)
            .await?;
        Ok(())
    }

    /// Clear a dead row, then plain INSERT: the primary key arbitrates, the loser gets a unique
    /// violation.
    pub async fn add(
        db: &DatabaseConnection,
        key: &str,
        v: &str,
        exp: i64,
    ) -> Result<bool, CacheError> {
        Entity::delete_many()
            .filter(Column::Key.eq(key))
            .filter(Column::ExpiresAt.gt(0))
            .filter(Column::ExpiresAt.lte(now_ms()))
            .exec(db)
            .await?;
        match Entity::insert(row(key, v, exp))
            .exec_without_returning(db)
            .await
        {
            Ok(_) => Ok(true),
            Err(e) if matches!(e.sql_err(), Some(SqlErr::UniqueConstraintViolation(_))) => {
                Ok(false)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// `DELETE` is the claim: of N racing pulls exactly one sees the row go.
    pub async fn pull(db: &DatabaseConnection, key: &str) -> Result<Option<String>, CacheError> {
        let Some(v) = get(db, key).await? else {
            return Ok(None);
        };
        let won = Entity::delete_by_id(key).exec(db).await?.rows_affected == 1;
        Ok(won.then_some(v))
    }

    pub async fn forget(db: &DatabaseConnection, key: &str) -> Result<bool, CacheError> {
        let live_row = get(db, key).await?.is_some();
        let gone = Entity::delete_by_id(key).exec(db).await?.rows_affected > 0;
        Ok(live_row && gone)
    }

    pub async fn flush(db: &DatabaseConnection) -> Result<(), CacheError> {
        Entity::delete_many().exec(db).await?;
        Ok(())
    }

    pub async fn prune(db: &DatabaseConnection) -> Result<u64, CacheError> {
        Ok(Entity::delete_many()
            .filter(Column::ExpiresAt.gt(0))
            .filter(Column::ExpiresAt.lte(now_ms()))
            .exec(db)
            .await?
            .rows_affected)
    }

    /// Single statements: insert-if-absent at 0, revive a dead row at 0, then
    /// `counter = counter + by` and the read-back in one transaction (the row lock keeps the
    /// returned number this caller's own). No read-modify-write in application code.
    pub async fn incr(db: &DatabaseConnection, key: &str, by: i64) -> Result<i64, CacheError> {
        Entity::insert(row(key, "0", 0))
            .on_conflict_do_nothing()
            .exec_without_returning(db)
            .await?;
        Entity::update_many()
            .col_expr(Column::Counter, Expr::value(0i64))
            .col_expr(Column::Value, Expr::value("0"))
            .col_expr(Column::ExpiresAt, Expr::value(0i64))
            .filter(Column::Key.eq(key))
            .filter(Column::ExpiresAt.gt(0))
            .filter(Column::ExpiresAt.lte(now_ms()))
            .exec(db)
            .await?;
        let tx = db.begin().await?;
        Entity::update_many()
            .col_expr(Column::Counter, Expr::col(Column::Counter).add(by))
            .filter(Column::Key.eq(key))
            .exec(&tx)
            .await?;
        let r = Entity::find_by_id(key).one(&tx).await?;
        tx.commit().await?;
        r.and_then(|r| r.counter)
            .ok_or_else(|| CacheError::NotInteger(key.into()))
    }
}

#[derive(Clone)]
enum Backend {
    Memory(Arc<Memory>),
    #[cfg(feature = "db")]
    Db(sea_orm::DatabaseConnection),
}

/// Cache handle; cheap to clone, share it through axum state.
#[derive(Clone)]
pub struct Cache(Backend);

fn deadline(ttl: Duration) -> Option<Instant> {
    // a TTL too large to represent is as good as forever
    Instant::now().checked_add(ttl)
}

#[cfg(feature = "db")]
fn expires_ms(ttl: Duration) -> i64 {
    dbops::now_ms().saturating_add(ttl.as_millis().min(i64::MAX as u128 / 2) as i64)
}

impl Cache {
    /// In-memory store (per process; see the `shortcut:` on `Memory` in the source).
    pub fn memory() -> Self {
        Self::memory_capped(MEMORY_CAP)
    }

    /// In-memory store holding at most `cap` entries.
    pub fn memory_capped(cap: usize) -> Self {
        Cache(Backend::Memory(Arc::new(Memory {
            map: Mutex::default(),
            cap: cap.max(1),
        })))
    }

    /// Database store over `db`; call [`ensure_tables`](Cache::ensure_tables) once at startup.
    #[cfg(feature = "db")]
    pub fn database(db: sea_orm::DatabaseConnection) -> Self {
        Cache(Backend::Db(db))
    }

    /// Pick the store from `CACHE_DRIVER` (`memory`, the default). `database` needs a
    /// connection, so use `Cache::from_env_db` (feature `db`); here it is an error.
    pub fn from_env() -> Result<Self, CacheError> {
        match std::env::var("CACHE_DRIVER").ok().as_deref() {
            None | Some("") | Some("memory") => Ok(Self::memory()),
            Some("database") => Err(CacheError::Driver(
                "CACHE_DRIVER=database needs a connection: use Cache::from_env_db(db)".into(),
            )),
            Some(o) => Err(CacheError::Driver(format!(
                "unknown CACHE_DRIVER `{o}` (use memory or database)"
            ))),
        }
    }

    /// Like [`from_env`](Cache::from_env), with `db` used when `CACHE_DRIVER=database`
    /// (tables are created for you).
    #[cfg(feature = "db")]
    pub async fn from_env_db(db: sea_orm::DatabaseConnection) -> Result<Self, CacheError> {
        if std::env::var("CACHE_DRIVER").as_deref() == Ok("database") {
            let c = Self::database(db);
            c.ensure_tables().await?;
            return Ok(c);
        }
        Self::from_env()
    }

    /// Create the `cache` table if missing (no-op for the memory store).
    pub async fn ensure_tables(&self) -> Result<(), CacheError> {
        match &self.0 {
            Backend::Memory(_) => Ok(()),
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::ensure(db).await,
        }
    }

    async fn get_raw(&self, key: &str) -> Result<Option<String>, CacheError> {
        match &self.0 {
            Backend::Memory(m) => Ok(Memory::live(&mut m.lock(), key)),
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::get(db, key).await,
        }
    }

    async fn put_raw(&self, key: &str, v: String, ttl: Option<Duration>) -> Result<(), CacheError> {
        if ttl == Some(Duration::ZERO) {
            self.forget(key).await?;
            return Ok(());
        }
        match &self.0 {
            Backend::Memory(m) => {
                let exp = ttl.and_then(deadline);
                m.insert(&mut m.lock(), key, v, exp);
                Ok(())
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::put(db, key, &v, ttl.map_or(0, expires_ms)).await,
        }
    }

    /// The value for `key`, `None` when missing or expired. A stored value that is not a
    /// `T` is an error, not `None`.
    pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, CacheError> {
        self.get_raw(key)
            .await?
            .map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(Into::into)
    }

    /// Store `value` for `ttl` (overwrites; a zero `ttl` removes the key).
    pub async fn put<T: Serialize + ?Sized>(
        &self,
        key: &str,
        value: &T,
        ttl: Duration,
    ) -> Result<(), CacheError> {
        self.put_raw(key, serde_json::to_string(value)?, Some(ttl))
            .await
    }

    /// Store `value` with no expiry.
    pub async fn forever<T: Serialize + ?Sized>(
        &self,
        key: &str,
        value: &T,
    ) -> Result<(), CacheError> {
        self.put_raw(key, serde_json::to_string(value)?, None).await
    }

    /// Store `value` only if the key is missing or expired; `true` when stored. Atomic: of N
    /// racing adds exactly one returns `true`.
    pub async fn add<T: Serialize + ?Sized>(
        &self,
        key: &str,
        value: &T,
        ttl: Duration,
    ) -> Result<bool, CacheError> {
        let v = serde_json::to_string(value)?;
        if ttl.is_zero() {
            return Ok(false);
        }
        match &self.0 {
            Backend::Memory(m) => {
                let mut g = m.lock();
                if Memory::live(&mut g, key).is_some() {
                    return Ok(false);
                }
                m.insert(&mut g, key, v, deadline(ttl));
                Ok(true)
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::add(db, key, &v, expires_ms(ttl)).await,
        }
    }

    /// Whether a live value exists.
    pub async fn has(&self, key: &str) -> Result<bool, CacheError> {
        Ok(self.get_raw(key).await?.is_some())
    }

    /// Opposite of [`has`](Cache::has).
    pub async fn missing(&self, key: &str) -> Result<bool, CacheError> {
        Ok(!self.has(key).await?)
    }

    /// Remove `key`; `true` if a live value was removed.
    pub async fn forget(&self, key: &str) -> Result<bool, CacheError> {
        match &self.0 {
            Backend::Memory(m) => {
                let mut g = m.lock();
                let was = Memory::live(&mut g, key).is_some();
                g.remove(key);
                Ok(was)
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::forget(db, key).await,
        }
    }

    /// Get and remove in one step; of N racing pulls exactly one gets the value.
    pub async fn pull<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, CacheError> {
        let raw = match &self.0 {
            Backend::Memory(m) => {
                let mut g = m.lock();
                let v = Memory::live(&mut g, key);
                g.remove(key);
                v
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::pull(db, key).await?,
        };
        raw.map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(Into::into)
    }

    /// Remove every entry.
    pub async fn flush(&self) -> Result<(), CacheError> {
        match &self.0 {
            Backend::Memory(m) => {
                m.lock().clear();
                Ok(())
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::flush(db).await,
        }
    }

    /// The cached value, or run `f`, cache its result for `ttl` and return it.
    ///
    /// shortcut: no stampede lock; concurrent misses each run `f` and the last write wins.
    /// Guard with [`add`](Cache::add) on a lock key if `f` is expensive or has side effects.
    pub async fn remember<T, F, Fut>(&self, key: &str, ttl: Duration, f: F) -> Result<T, CacheError>
    where
        T: Serialize + DeserializeOwned,
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        if let Some(v) = self.get(key).await? {
            return Ok(v);
        }
        let v = f().await;
        self.put(key, &v, ttl).await?;
        Ok(v)
    }

    /// [`remember`](Cache::remember) with no expiry.
    pub async fn remember_forever<T, F, Fut>(&self, key: &str, f: F) -> Result<T, CacheError>
    where
        T: Serialize + DeserializeOwned,
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        if let Some(v) = self.get(key).await? {
            return Ok(v);
        }
        let v = f().await;
        self.forever(key, &v).await?;
        Ok(v)
    }

    /// Add `by` to an integer key (a missing or expired key starts at 0, no expiry) and return
    /// the new value. Atomic on every store; keeps an existing TTL.
    pub async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError> {
        match &self.0 {
            Backend::Memory(m) => {
                let mut g = m.lock();
                let cur = match Memory::live(&mut g, key) {
                    Some(s) => s
                        .parse::<i64>()
                        .map_err(|_| CacheError::NotInteger(key.into()))?,
                    None => 0,
                };
                let n = cur.saturating_add(by);
                let exp = g.get(key).and_then(|(_, t)| *t);
                m.insert(&mut g, key, n.to_string(), exp);
                Ok(n)
            }
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::incr(db, key, by).await,
        }
    }

    /// `increment(key, -by)`.
    pub async fn decrement(&self, key: &str, by: i64) -> Result<i64, CacheError> {
        self.increment(key, by.saturating_neg()).await
    }

    /// Drop expired entries (memory: scan; database: one `DELETE`); returns how many. Run it
    /// from the hourly maintenance task. Reads already ignore expired entries.
    pub async fn prune(&self) -> Result<u64, CacheError> {
        match &self.0 {
            Backend::Memory(m) => Ok(m.prune()),
            #[cfg(feature = "db")]
            Backend::Db(db) => dbops::prune(db).await,
        }
    }
}

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

    const MIN: Duration = Duration::from_secs(60);

    /// Every store under test: memory always; a SQLite file DB (pooled connections, so races are
    /// real; `sqlite::memory:` would give each connection its own empty DB) plus Postgres/MySQL when
    /// `TEST_POSTGRES_URL` / `TEST_MYSQL_URL` are set.
    async fn stores() -> Vec<(&'static str, Cache)> {
        #[allow(unused_mut)] // pushes need the db feature
        let mut v = vec![("memory", Cache::memory())];
        #[cfg(feature = "sqlite")]
        {
            let ns = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos();
            let path = std::env::temp_dir().join(format!("ryuk-cache-{ns}.db"));
            let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
                .await
                .unwrap();
            v.push(("sqlite", Cache::database(db)));
        }
        #[cfg(feature = "db")]
        for (name, var) in [
            ("postgres", "TEST_POSTGRES_URL"),
            ("mysql", "TEST_MYSQL_URL"),
        ] {
            if let Ok(url) = std::env::var(var) {
                v.push((
                    name,
                    Cache::database(sea_orm::Database::connect(url).await.unwrap()),
                ));
            }
        }
        for (_, c) in &v {
            c.ensure_tables().await.unwrap();
            c.ensure_tables().await.unwrap();
            c.flush().await.unwrap();
        }
        v
    }

    #[tokio::test]
    async fn basic_api() {
        for (n, c) in stores().await {
            assert_eq!(c.get::<i32>("a").await.unwrap(), None, "{n}");
            assert!(c.missing("a").await.unwrap(), "{n}");
            c.put("a", &vec![1, 2], MIN).await.unwrap();
            assert_eq!(
                c.get::<Vec<i32>>("a").await.unwrap(),
                Some(vec![1, 2]),
                "{n}"
            );
            assert!(c.has("a").await.unwrap(), "{n}");
            assert!(
                c.get::<String>("a").await.is_err(),
                "{n}: wrong type is an error"
            );
            c.put("a", &"x", MIN).await.unwrap();
            assert_eq!(
                c.get::<String>("a").await.unwrap().unwrap(),
                "x",
                "{n}: overwrite"
            );

            c.forever("f", &true).await.unwrap();
            assert_eq!(c.get::<bool>("f").await.unwrap(), Some(true), "{n}");
            assert!(c.forget("f").await.unwrap(), "{n}");
            assert!(!c.forget("f").await.unwrap(), "{n}");

            assert!(
                !c.add("a", &"y", MIN).await.unwrap(),
                "{n}: add keeps existing"
            );
            assert!(c.add("b", &"y", MIN).await.unwrap(), "{n}");
            assert_eq!(c.pull::<String>("b").await.unwrap().unwrap(), "y", "{n}");
            assert_eq!(c.pull::<String>("b").await.unwrap(), None, "{n}");

            c.flush().await.unwrap();
            assert!(c.missing("a").await.unwrap(), "{n}");
        }
    }

    #[tokio::test]
    async fn expiry_add_after_expiry_and_prune() {
        for (n, c) in stores().await {
            let short = Duration::from_millis(1100);
            c.put("e", &1, short).await.unwrap();
            c.put("keep", &1, MIN).await.unwrap();
            c.put("i", &10, short).await.unwrap();
            c.put("z", &1, Duration::ZERO).await.unwrap();
            assert!(
                c.missing("z").await.unwrap(),
                "{n}: zero ttl stores nothing"
            );
            tokio::time::sleep(Duration::from_millis(1300)).await;
            assert_eq!(c.get::<i32>("e").await.unwrap(), None, "{n}: expired");
            assert!(
                !c.forget("e").await.unwrap(),
                "{n}: expired is not removable"
            );
            assert!(
                c.add("e", &2, MIN).await.unwrap(),
                "{n}: add over an expired key"
            );
            assert_eq!(c.get::<i32>("e").await.unwrap(), Some(2), "{n}");
            assert_eq!(
                c.increment("i", 1).await.unwrap(),
                1,
                "{n}: increment revives from 0"
            );
            c.put("gone", &1, short).await.unwrap();
            tokio::time::sleep(Duration::from_millis(1300)).await;
            assert_eq!(c.prune().await.unwrap(), 1, "{n}");
            assert_eq!(c.prune().await.unwrap(), 0, "{n}");
            assert!(c.has("keep").await.unwrap(), "{n}");
        }
    }

    #[tokio::test]
    async fn increment_decrement_and_types() {
        for (n, c) in stores().await {
            assert_eq!(c.increment("c", 5).await.unwrap(), 5, "{n}");
            assert_eq!(c.decrement("c", 2).await.unwrap(), 3, "{n}");
            assert_eq!(c.get::<i64>("c").await.unwrap(), Some(3), "{n}");
            c.put("p", &7, MIN).await.unwrap();
            assert_eq!(
                c.increment("p", 1).await.unwrap(),
                8,
                "{n}: continues a put integer"
            );
            assert_eq!(c.get::<i64>("p").await.unwrap(), Some(8), "{n}");
            c.put("s", &"text", MIN).await.unwrap();
            assert!(
                matches!(c.increment("s", 1).await, Err(CacheError::NotInteger(_))),
                "{n}"
            );
            c.put("p", &"now text", MIN).await.unwrap();
            assert_eq!(
                c.get::<String>("p").await.unwrap().unwrap(),
                "now text",
                "{n}"
            );
        }
    }

    #[tokio::test]
    async fn remember_runs_once() {
        for (n, c) in stores().await {
            let a: u32 = c.remember("r", MIN, || async { 1 }).await.unwrap();
            let b: u32 = c.remember("r", MIN, || async { 2 }).await.unwrap();
            assert_eq!((a, b), (1, 1), "{n}");
            let a: String = c
                .remember_forever("rf", || async { "x".to_string() })
                .await
                .unwrap();
            assert_eq!(a, "x", "{n}");
        }
    }

    #[tokio::test]
    async fn concurrent_add_increment_pull() {
        for (n, c) in stores().await {
            let adds: Vec<_> = (0..16)
                .map(|i| {
                    let c = c.clone();
                    tokio::spawn(async move { c.add("lock", &i, MIN).await.unwrap() })
                })
                .collect();
            let mut won = 0;
            for h in adds {
                won += h.await.unwrap() as u32;
            }
            assert_eq!(won, 1, "{n}: exactly one add wins");

            let incs: Vec<_> = (0..32)
                .map(|_| {
                    let c = c.clone();
                    tokio::spawn(async move { c.increment("ctr", 1).await.unwrap() })
                })
                .collect();
            let mut seen = Vec::new();
            for h in incs {
                seen.push(h.await.unwrap());
            }
            seen.sort();
            assert_eq!(
                seen,
                (1..=32).collect::<Vec<_>>(),
                "{n}: no lost or duplicate increments"
            );

            let pulls: Vec<_> = (0..16)
                .map(|_| {
                    let c = c.clone();
                    tokio::spawn(async move { c.pull::<i32>("lock").await.unwrap().is_some() })
                })
                .collect();
            let mut got = 0;
            for h in pulls {
                got += h.await.unwrap() as u32;
            }
            assert_eq!(got, 1, "{n}: exactly one pull wins");
        }
    }

    #[tokio::test]
    async fn memory_cap_evicts_soonest_to_expire() {
        let c = Cache::memory_capped(3);
        c.put("short", &1, Duration::from_secs(10)).await.unwrap();
        c.put("long", &1, MIN).await.unwrap();
        c.forever("perm", &1).await.unwrap();
        c.put("new", &1, MIN).await.unwrap();
        assert!(
            c.missing("short").await.unwrap(),
            "soonest to expire goes first"
        );
        for k in ["long", "perm", "new"] {
            assert!(c.has(k).await.unwrap(), "{k}");
        }
        match &c.0 {
            Backend::Memory(m) => assert_eq!(m.lock().len(), 3),
            #[cfg(feature = "db")]
            _ => unreachable!(),
        }
    }

    #[cfg(feature = "db")]
    #[test]
    fn sql_text_all_backends() {
        use sea_orm::{DbBackend, EntityTrait, QueryTrait, Schema};
        for b in [DbBackend::Sqlite, DbBackend::Postgres, DbBackend::MySql] {
            let c = b
                .build(&Schema::new(b).create_table_from_entity(entry::Entity))
                .to_string();
            assert!(
                c.contains("expires_at") && c.contains("counter"),
                "{b:?}: {c}"
            );
            let s = entry::Entity::delete_many().build(b).to_string();
            assert!(s.starts_with("DELETE FROM"), "{b:?}: {s}");
        }
    }
}