ryuk 0.1.0

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
//! Cookie sessions (tower-sessions 0.14). Inertia flash/errors and `auth` both sit on this.
//!
//! Any `tower_sessions::SessionStore` works with `App::sessions(store)`. Official stores are
//! re-exported so apps need only `ryuk`: [`file`] (`session-file`), [`moka`] (`session-moka`),
//! [`redis`] (`session-redis`); plus [`DbStore`] (`session-db`) and the default memory store.
//!
//! ```ignore
//! use ryuk::{app::App, session::{self, DbStore}};
//! // file:  App::new(()).sessions(session::file::FileSessionStorage::new_in_folder(std::path::Path::new("storage/sessions")))
//! // moka:  App::new(()).sessions(session::moka::MokaStore::new(Some(10_000)))
//! // redis: let pool = session::redis::fred::prelude::Pool::new(
//! //            session::redis::fred::prelude::Config::from_url("redis://127.0.0.1")?, None, None, None, 4)?;
//! //        pool.connect(); pool.wait_for_connect().await?;
//! //        App::new(()).sessions(session::redis::RedisStore::new(pool))
//! // db:    let s = DbStore::new(ryuk::db::connect("sqlite::memory:").await?);
//! //        s.ensure_table().await?; App::new(()).sessions(s)
//! ```
//!
//! # Log out everywhere (`DbStore` only)
//! `DbStore` keeps a nullable, indexed `user_id` column filled on every save from the record's
//! `"user_id"` key (what `auth::login` stores; missing or non-integer values are stored as NULL, so
//! anonymous sessions work as before). [`DbStore::delete_for_user`] drops all of a user's sessions and
//! [`DbStore::count_for_user`] counts the live ones. The file, moka and redis stores have no user
//! index: this feature does not exist for them. `DbStore` is a cheap `Clone` (a connection pool
//! handle), so keep a clone in `AppState` next to the one given to `App::sessions`:
//!
//! ```ignore
//! let store = DbStore::new(db); store.ensure_table().await?; // also upgrades an old `sessions` table
//! let app = App::new(AppState { sessions: store.clone(), .. }).sessions(store);
//! // after a password reset: state.sessions.delete_for_user(user_id).await?;
//! ```
use tower_sessions::{
    Expiry, MemoryStore, SessionManagerLayer, cookie::SameSite,
    cookie::time::Duration as CookieDuration,
};
// Re-exported so apps need no direct `tower-sessions` dependency (and cannot end up on a mismatched version).
pub use tower_sessions::{Session, SessionStore};

/// Session lifetime and cookie name. Defaults: the store's own expiry (2 weeks for `DbStore`), a
/// browser-session cookie named `id`.
///
/// `lifetime` is **inactivity** based: every request that touches the session pushes it forward, and
/// the cookie gets a matching `Max-Age`. It applies to every session; tower-sessions re-applies the
/// layer's expiry on each request, so a per-session `Session::set_expiry` (a "remember me" switch)
/// does not survive the next request. Set it here instead.
///
/// ```
/// use std::time::Duration;
/// let o = ryuk::session::SessionOptions::default().lifetime(Duration::from_secs(60 * 60)).cookie_name("shop_session");
/// let _ = ryuk::session::layer_with(tower_sessions::MemoryStore::default(), &o);
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SessionOptions {
    lifetime: Option<std::time::Duration>,
    cookie_name: Option<String>,
}

impl SessionOptions {
    /// Keep a session alive this long after its last use. Must be at least one second.
    pub fn lifetime(mut self, d: std::time::Duration) -> Self {
        self.lifetime = Some(d);
        self
    }

    /// Name of the session cookie (letters, digits, `-` and `_`).
    pub fn cookie_name(mut self, name: impl Into<String>) -> Self {
        self.cookie_name = Some(name.into());
        self
    }

    /// `SESSION_LIFETIME` (minutes, like Laravel) and `SESSION_COOKIE`. Unset keeps the defaults.
    /// A malformed value is an error: a typo must not silently leave sessions at two weeks.
    ///
    /// ```
    /// let o = ryuk::session::SessionOptions::from_lookup(|k| (k == "SESSION_LIFETIME").then(|| "120".into())).unwrap();
    /// assert_eq!(o, ryuk::session::SessionOptions::default().lifetime(std::time::Duration::from_secs(7200)));
    /// ```
    pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, String> {
        let mut o = Self::default();
        if let Some(v) = get("SESSION_LIFETIME").filter(|v| !v.trim().is_empty()) {
            let minutes: u64 = v.trim().parse().map_err(|_| {
                format!("SESSION_LIFETIME must be a whole number of minutes, got `{v}`")
            })?;
            if minutes == 0 {
                return Err("SESSION_LIFETIME must be at least 1 minute".into());
            }
            o.lifetime = Some(std::time::Duration::from_secs(minutes * 60));
        }
        if let Some(v) = get("SESSION_COOKIE").filter(|v| !v.trim().is_empty()) {
            o.cookie_name = Some(v.trim().to_string());
        }
        o.validate()?;
        Ok(o)
    }

    /// [`from_lookup`](Self::from_lookup) over the process environment.
    pub fn from_env() -> Result<Self, String> {
        Self::from_lookup(|k| std::env::var(k).ok())
    }

    fn validate(&self) -> Result<(), String> {
        if self.lifetime.is_some_and(|d| d.as_secs() == 0) {
            return Err("session lifetime must be at least one second".into());
        }
        if let Some(n) = &self.cookie_name
            && (n.is_empty()
                || n.len() > 64
                || !n
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'))
        {
            return Err(format!(
                "SESSION_COOKIE `{n}` must be 1-64 letters, digits, `-` or `_`"
            ));
        }
        Ok(())
    }
}

/// Session middleware over any store: HttpOnly, SameSite=Lax, Secure only when `APP_ENV=production`.
/// Lifetime and cookie name come from `SESSION_LIFETIME` / `SESSION_COOKIE` (see [`SessionOptions`]).
///
/// ```
/// let _ = ryuk::session::layer(tower_sessions::MemoryStore::default());
/// ```
pub fn layer<St: SessionStore + Clone>(store: St) -> SessionManagerLayer<St> {
    let o = SessionOptions::from_env().unwrap_or_else(|e| panic!("{e}"));
    layer_with(store, &o)
}

/// [`layer`] with explicit [`SessionOptions`]. Panics on an invalid option (a boot-time config error).
pub fn layer_with<St: SessionStore + Clone>(
    store: St,
    o: &SessionOptions,
) -> SessionManagerLayer<St> {
    o.validate().unwrap_or_else(|e| panic!("{e}"));
    let mut l = SessionManagerLayer::new(store)
        .with_http_only(true)
        .with_same_site(SameSite::Lax)
        .with_secure(std::env::var("APP_ENV").is_ok_and(|v| v == "production"));
    if let Some(d) = o.lifetime {
        l = l.with_expiry(Expiry::OnInactivity(CookieDuration::seconds(
            d.as_secs().min(i64::MAX as u64) as i64,
        )));
    }
    if let Some(n) = &o.cookie_name {
        l = l.with_name(n.clone());
    }
    l
}

/// In-memory sessions: `router.layer(auth::session_layer())`.
pub fn session_layer() -> SessionManagerLayer<MemoryStore> {
    // shortcut: in-memory store, sessions are lost on restart and not shared across processes; use App::sessions(DbStore/file/redis stores) before scaling out.
    layer(MemoryStore::default())
}

#[cfg(feature = "session-db")]
fn enc(r: &tower_sessions::session::Record) -> tower_sessions::session_store::Result<Vec<u8>> {
    serde_json::to_vec(r).map_err(|e| tower_sessions::session_store::Error::Encode(e.to_string()))
}

#[cfg(feature = "session-db")]
fn dec(b: &[u8]) -> tower_sessions::session_store::Result<tower_sessions::session::Record> {
    serde_json::from_slice(b)
        .map_err(|e| tower_sessions::session_store::Error::Decode(e.to_string()))
}

/// SeaORM entity for the `sessions` table.
#[cfg(feature = "session-db")]
pub mod sessions {
    use sea_orm::entity::prelude::*;
    /// One session: `data` is the JSON-encoded record, `expiry` unix seconds.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "sessions")]
    pub struct Model {
        #[sea_orm(primary_key, auto_increment = false)]
        pub id: String,
        // Explicit: SeaORM's default for Vec<u8> is `varbinary(255)` on MySQL, which silently broke every
        // session over 255 bytes (any flash message with errors).
        // shortcut: MySQL `blob` caps at 64KB per session; switch to a long blob column if sessions grow that big.
        #[sea_orm(column_type = "Blob")]
        pub data: Vec<u8>,
        pub expiry: i64,
        /// The logged-in user (`"user_id"` in the record), NULL for anonymous sessions.
        #[sea_orm(indexed)]
        pub user_id: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

#[cfg(feature = "session-db")]
pub use db_store::DbStore;

#[cfg(feature = "session-db")]
mod db_store {
    use super::{dec, enc, sessions};
    use async_trait::async_trait;
    use sea_orm::sea_query::{
        Alias, ColumnDef, Expr, ExprTrait, Func, OnConflict, Query as SqlQuery, Table,
    };
    use sea_orm::{ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbErr, Schema};
    use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter};
    use sea_orm_migration::SchemaManager;
    use tower_sessions::SessionStore;
    use tower_sessions::session::{Id, Record};
    use tower_sessions::session_store::{Error, Result};

    fn be(e: DbErr) -> Error {
        Error::Backend(e.to_string())
    }

    /// Sessions in the `sessions` table through SeaORM; works on sqlite, postgres and mysql.
    ///
    /// ```no_run
    /// # async fn f() -> Result<(), sea_orm::DbErr> {
    /// let db = ryuk::db::connect("sqlite::memory:").await?;
    /// let store = ryuk::session::DbStore::new(db);
    /// store.ensure_table().await?;
    /// let app = ryuk::app::App::new(()).sessions(store);
    /// # Ok(()) }
    /// ```
    #[derive(Clone, Debug)]
    pub struct DbStore {
        db: DatabaseConnection,
    }

    impl DbStore {
        /// Store over an existing connection.
        pub fn new(db: DatabaseConnection) -> Self {
            DbStore { db }
        }

        /// Create the `sessions` table if missing, and upgrade a table created before `user_id`
        /// existed (add the column and its index in place; existing rows get NULL).
        pub async fn ensure_table(&self) -> std::result::Result<(), DbErr> {
            let b = self.db.get_database_backend();
            let schema = Schema::new(b);
            let mut t = schema.create_table_from_entity(sessions::Entity);
            self.db.execute(t.if_not_exists()).await?;
            // shortcut: SchemaManager::has_column is unsupported on SQLite, so probe by selecting the column
            // (any error means "missing"; a real outage then fails the ALTER with the actual cause).
            let probe = SqlQuery::select()
                .column((sessions::Entity, sessions::Column::UserId)) // qualified: SQLite reads an unknown bare name as a string literal
                .from(sessions::Entity)
                .limit(1)
                .to_owned();
            if self.db.query_all(&probe).await.is_err() {
                let col = ColumnDef::new(Alias::new("user_id"))
                    .big_integer()
                    .to_owned();
                let alter = Table::alter()
                    .table(sessions::Entity)
                    .add_column(col)
                    .to_owned();
                // A concurrent instance may have added it first: only fail if it is still missing.
                if let Err(e) = SchemaManager::new(&self.db).alter_table(alter).await
                    && self.db.query_all(&probe).await.is_err()
                {
                    return Err(e);
                }
            }
            for mut i in schema.create_index_from_entity(sessions::Entity) {
                if b == sea_orm::DbBackend::MySql {
                    // MySQL has no CREATE INDEX IF NOT EXISTS (nor SchemaManager::has_index): look it up in
                    // information_schema, create, and tolerate a concurrent create.
                    let name = i.get_index_spec().get_name().unwrap_or_default().to_owned();
                    let has = || async {
                        let q = SqlQuery::select()
                            .column(Alias::new("index_name"))
                            .from((Alias::new("information_schema"), Alias::new("statistics")))
                            .and_where(
                                Expr::col(Alias::new("table_schema"))
                                    .eq(Func::cust(Alias::new("DATABASE"))),
                            )
                            .and_where(Expr::col(Alias::new("table_name")).eq("sessions"))
                            .and_where(Expr::col(Alias::new("index_name")).eq(name.as_str()))
                            .limit(1)
                            .to_owned();
                        self.db.query_all(&q).await.map(|r| !r.is_empty())
                    };
                    if !has().await?
                        && let Err(e) = self.db.execute(&i).await
                        && !has().await?
                    {
                        return Err(e);
                    }
                } else {
                    self.db.execute(i.if_not_exists()).await?;
                }
            }
            Ok(())
        }

        /// Log a user out everywhere: delete all their sessions; returns how many were removed.
        pub async fn delete_for_user(&self, user_id: i64) -> std::result::Result<u64, DbErr> {
            Ok(sessions::Entity::delete_many()
                .filter(sessions::Column::UserId.eq(user_id))
                .exec(&self.db)
                .await?
                .rows_affected)
        }

        /// Number of unexpired sessions of a user.
        pub async fn count_for_user(&self, user_id: i64) -> std::result::Result<u64, DbErr> {
            sessions::Entity::find()
                .filter(sessions::Column::UserId.eq(user_id))
                .filter(sessions::Column::Expiry.gte(chrono::Utc::now().timestamp()))
                .count(&self.db)
                .await
        }

        /// Delete expired rows (call from a scheduler / now and then).
        pub async fn delete_expired(&self) -> std::result::Result<u64, DbErr> {
            let now = chrono::Utc::now().timestamp();
            Ok(sessions::Entity::delete_many()
                .filter(sessions::Column::Expiry.lt(now))
                .exec(&self.db)
                .await?
                .rows_affected)
        }

        /// The insert-or-update statement `save` runs (public so its per-backend SQL can be reviewed).
        pub fn upsert(record: &Record) -> Result<sea_orm::Insert<sessions::ActiveModel>> {
            let row = sessions::ActiveModel {
                id: Set(record.id.to_string()),
                data: Set(enc(record)?),
                expiry: Set(record.expiry_date.unix_timestamp()),
                // Anything but an integer (missing, string, float) is anonymous: NULL, never an error.
                user_id: Set(record.data.get("user_id").and_then(|v| v.as_i64())),
            };
            Ok(sessions::Entity::insert(row).on_conflict(
                OnConflict::column(sessions::Column::Id)
                    .update_columns([
                        sessions::Column::Data,
                        sessions::Column::Expiry,
                        sessions::Column::UserId,
                    ])
                    .to_owned(),
            ))
        }
    }

    #[async_trait]
    impl SessionStore for DbStore {
        async fn create(&self, record: &mut Record) -> Result<()> {
            // shortcut: check-then-insert can race on an id collision; ids are 128 random bits so it is not realistic.
            while sessions::Entity::find_by_id(record.id.to_string())
                .one(&self.db)
                .await
                .map_err(be)?
                .is_some()
            {
                record.id = Id::default();
            }
            self.save(record).await
        }
        async fn save(&self, record: &Record) -> Result<()> {
            Self::upsert(record)?
                .exec_without_returning(&self.db)
                .await
                .map_err(be)?;
            Ok(())
        }
        async fn load(&self, id: &Id) -> Result<Option<Record>> {
            let Some(row) = sessions::Entity::find_by_id(id.to_string())
                .one(&self.db)
                .await
                .map_err(be)?
            else {
                return Ok(None);
            };
            let rec = dec(&row.data)?;
            Ok((row.expiry >= chrono::Utc::now().timestamp()).then_some(rec))
        }
        async fn delete(&self, id: &Id) -> Result<()> {
            sessions::Entity::delete_by_id(id.to_string())
                .exec(&self.db)
                .await
                .map_err(be)?;
            Ok(())
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use sea_orm::sea_query::{Alias, ColumnDef, Query as SqlQuery, Table};
        use sea_orm::{DbBackend, QueryTrait};
        use tower_sessions::session::Record;

        fn rec() -> Record {
            Record {
                id: Id::default(),
                data: [("k".to_string(), "v".into())].into(),
                expiry_date: tower_sessions::cookie::time::OffsetDateTime::from_unix_timestamp(
                    32_503_680_000,
                )
                .unwrap(),
            }
        }

        async fn round_trip(db: DatabaseConnection) {
            let s = DbStore::new(db);
            s.ensure_table().await.unwrap();
            let mut r = rec();
            s.create(&mut r).await.unwrap();
            assert_eq!(s.load(&r.id).await.unwrap(), Some(r.clone()));
            r.data.insert("k2".into(), 2.into());
            s.save(&r).await.unwrap(); // upsert path: row exists
            assert_eq!(s.load(&r.id).await.unwrap(), Some(r.clone()));
            // Regression: MySQL once created `data` as varbinary(255); real sessions are bigger.
            r.data.insert("big".into(), "x".repeat(10_000).into());
            s.save(&r).await.unwrap();
            assert_eq!(s.load(&r.id).await.unwrap(), Some(r.clone()));
            let mut gone = rec();
            gone.expiry_date =
                tower_sessions::cookie::time::OffsetDateTime::from_unix_timestamp(1).unwrap();
            s.save(&gone).await.unwrap(); // upsert path: row new
            assert_eq!(s.load(&gone.id).await.unwrap(), None); // expired rows are invisible
            assert_eq!(s.delete_expired().await.unwrap(), 1);
            s.delete(&r.id).await.unwrap();
            assert_eq!(s.load(&r.id).await.unwrap(), None);
        }

        fn user_rec(uid: serde_json::Value) -> Record {
            let mut r = rec();
            r.data.insert("user_id".into(), uid);
            r
        }

        async fn user_ids(s: &DbStore) -> Vec<Option<i64>> {
            let mut v: Vec<_> = sessions::Entity::find()
                .all(&s.db)
                .await
                .unwrap()
                .into_iter()
                .map(|m| m.user_id)
                .collect();
            v.sort();
            v
        }

        // Unique ids per run: shared DBs keep rows between runs.
        fn uniq() -> i64 {
            chrono::Utc::now().timestamp_micros() % 1_000_000_000 * 10
        }

        async fn per_user(db: DatabaseConnection) {
            let s = DbStore::new(db);
            s.ensure_table().await.unwrap();
            let (a, b) = (uniq() + 1, uniq() + 2);
            for r in [user_rec(a.into()), user_rec(a.into()), user_rec(b.into())] {
                s.create(&mut { r }).await.unwrap();
            }
            let mut anon = rec();
            s.create(&mut anon).await.unwrap();
            for odd in [
                serde_json::json!("7"),
                serde_json::json!(1.5),
                serde_json::json!(null),
            ] {
                let mut r = user_rec(odd);
                s.create(&mut r).await.unwrap(); // never an error, stored as NULL
                assert_eq!(s.load(&r.id).await.unwrap(), Some(r));
            }
            let n = |u| s.count_for_user(u);
            assert_eq!((n(a).await.unwrap(), n(b).await.unwrap()), (2, 1));
            assert_eq!(s.delete_for_user(a).await.unwrap(), 2);
            assert_eq!(s.delete_for_user(a).await.unwrap(), 0);
            assert_eq!((n(a).await.unwrap(), n(b).await.unwrap()), (0, 1));
            assert_eq!(s.load(&anon.id).await.unwrap(), Some(anon.clone())); // anonymous untouched
            // Logging in on an existing anonymous session indexes it (upsert updates user_id).
            anon.data.insert("user_id".into(), b.into());
            s.save(&anon).await.unwrap();
            assert_eq!(n(b).await.unwrap(), 2);
            // Concurrent saves of distinct sessions all land and are indexed.
            let c = uniq() + 3;
            let hs: Vec<_> = (0..30)
                .map(|_| {
                    let s = s.clone();
                    tokio::spawn(async move { s.save(&user_rec(c.into())).await.unwrap() })
                })
                .collect();
            for h in hs {
                h.await.unwrap();
            }
            assert_eq!(n(c).await.unwrap(), 30);
            assert_eq!(s.delete_for_user(c).await.unwrap(), 30);
            assert_eq!(s.delete_for_user(b).await.unwrap(), 2);
        }

        /// An old-schema table (no `user_id`) with rows is upgraded in place; ensure_table is idempotent.
        async fn upgrade(db: DatabaseConnection) {
            let mut old = Table::create();
            old.table(sessions::Entity)
                .col(
                    ColumnDef::new(Alias::new("id"))
                        .string()
                        .not_null()
                        .primary_key(),
                )
                .col(ColumnDef::new(Alias::new("data")).blob().not_null())
                .col(
                    ColumnDef::new(Alias::new("expiry"))
                        .big_integer()
                        .not_null(),
                );
            db.execute(&old).await.unwrap();
            let r = user_rec(5.into());
            let ins = SqlQuery::insert()
                .into_table(sessions::Entity)
                .columns([Alias::new("id"), Alias::new("data"), Alias::new("expiry")])
                .values_panic([
                    r.id.to_string().into(),
                    enc(&r).unwrap().into(),
                    r.expiry_date.unix_timestamp().into(),
                ])
                .to_owned();
            db.execute(&ins).await.unwrap();
            let s = DbStore::new(db);
            // Two instances upgrading at once, then once more (idempotent).
            let (x, y) = tokio::join!(s.ensure_table(), s.ensure_table());
            x.unwrap();
            y.unwrap();
            s.ensure_table().await.unwrap();
            assert_eq!(s.load(&r.id).await.unwrap(), Some(r.clone())); // old row loads
            assert_eq!(user_ids(&s).await, vec![None]); // not backfilled
            let mut n = user_rec(6.into());
            s.create(&mut n).await.unwrap();
            assert_eq!(s.count_for_user(6).await.unwrap(), 1);
            assert_eq!(user_ids(&s).await, vec![None, Some(6)]);
        }

        #[cfg(feature = "sqlite")]
        #[tokio::test]
        async fn sqlite_per_user_and_upgrade() {
            let mem = || async { sea_orm::Database::connect("sqlite::memory:").await.unwrap() };
            upgrade(mem().await).await;
            per_user(mem().await).await;
            let f = std::env::temp_dir().join(format!("ryuk-sess-{}.db", std::process::id()));
            let _ = std::fs::remove_file(&f);
            let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", f.display()))
                .await
                .unwrap();
            per_user(db).await; // file db: real concurrent connections
            let _ = std::fs::remove_file(&f);
        }

        #[tokio::test]
        async fn server_backends_per_user_and_upgrade_if_configured() {
            for var in ["TEST_POSTGRES_URL", "TEST_MYSQL_URL"] {
                let Ok(url) = std::env::var(var) else {
                    eprintln!("skipped: {var} not set");
                    continue;
                };
                let db = sea_orm::Database::connect(&url).await.unwrap();
                let _ = db.execute_unprepared("DROP TABLE IF EXISTS sessions").await;
                upgrade(db.clone()).await;
                per_user(db.clone()).await;
                let s = DbStore::new(db);
                let q = if var == "TEST_MYSQL_URL" {
                    "SHOW INDEX FROM sessions"
                } else {
                    "SELECT indexname::text FROM pg_indexes WHERE tablename = 'sessions'"
                };
                let stmt = sea_orm::Statement::from_string(s.db.get_database_backend(), q);
                let rows = s.db.query_all_raw(stmt).await.unwrap();
                assert!(
                    rows.iter().any(|r| r
                        .try_get_by_index::<String>(if var == "TEST_MYSQL_URL" { 2 } else { 0 })
                        .unwrap()
                        == "idx-sessions-user_id"),
                    "{var}: no user_id index in {rows:?}"
                );
            }
        }

        #[cfg(feature = "sqlite")]
        #[tokio::test]
        async fn sqlite_round_trip() {
            round_trip(sea_orm::Database::connect("sqlite::memory:").await.unwrap()).await;
        }

        #[tokio::test]
        async fn server_backends_round_trip_if_configured() {
            for var in ["TEST_POSTGRES_URL", "TEST_MYSQL_URL"] {
                match std::env::var(var) {
                    Ok(url) => {
                        let db = sea_orm::Database::connect(&url).await.unwrap();
                        let _ = db.execute_unprepared("DROP TABLE IF EXISTS sessions").await;
                        round_trip(db).await;
                    }
                    Err(_) => eprintln!("skipped: {var} not set"),
                }
            }
        }

        #[test]
        fn upsert_sql_per_backend() {
            let r = rec();
            let sql = |b| DbStore::upsert(&r).unwrap().build(b).to_string();
            let pg = sql(DbBackend::Postgres);
            assert!(pg.contains(r#"ON CONFLICT ("id") DO UPDATE SET "data" = "excluded"."data", "expiry" = "excluded"."expiry", "user_id" = "excluded"."user_id""#), "{pg}");
            let my = sql(DbBackend::MySql);
            assert!(
                my.contains(
                    "ON DUPLICATE KEY UPDATE `data` = VALUES(`data`), `expiry` = VALUES(`expiry`), `user_id` = VALUES(`user_id`)"
                ),
                "{my}"
            );
            let lite = sql(DbBackend::Sqlite);
            assert!(lite.contains(r#"ON CONFLICT ("id") DO UPDATE SET "data" = "excluded"."data", "expiry" = "excluded"."expiry", "user_id" = "excluded"."user_id""#), "{lite}");
        }
    }
}

/// Official file store (`session-file`), re-exported.
#[cfg(feature = "session-file")]
pub use tower_sessions_file_store as file;
/// Official moka in-process cache store (`session-moka`), re-exported.
#[cfg(feature = "session-moka")]
pub use tower_sessions_moka_store as moka;
/// Official Redis store (`session-redis`), re-exported (includes `fred`).
#[cfg(feature = "session-redis")]
pub use tower_sessions_redis_store as redis;

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

    fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
        move |k| {
            pairs
                .iter()
                .find(|(n, _)| *n == k)
                .map(|(_, v)| v.to_string())
        }
    }

    #[test]
    fn env_values_are_parsed_and_typos_are_errors() {
        assert_eq!(
            SessionOptions::from_lookup(env(&[])).unwrap(),
            SessionOptions::default()
        );
        let o = SessionOptions::from_lookup(env(&[
            ("SESSION_LIFETIME", " 30 "),
            ("SESSION_COOKIE", "shop-1_x"),
        ]))
        .unwrap();
        assert_eq!(
            o,
            SessionOptions::default()
                .lifetime(std::time::Duration::from_secs(1800))
                .cookie_name("shop-1_x")
        );
        // Empty means unset (an exported-but-blank variable is not a typo).
        assert_eq!(
            SessionOptions::from_lookup(env(&[("SESSION_LIFETIME", ""), ("SESSION_COOKIE", " ")]))
                .unwrap(),
            SessionOptions::default()
        );
        for bad in ["abc", "0", "-5", "1.5", "2 weeks"] {
            let e = SessionOptions::from_lookup(move |k| {
                (k == "SESSION_LIFETIME").then(|| bad.to_string())
            })
            .unwrap_err();
            assert!(e.contains("SESSION_LIFETIME"), "{bad}: {e}");
        }
        for bad in ["a b", "a;b", "a=b", "é", &"x".repeat(65)] {
            let b = bad.to_string();
            let e =
                SessionOptions::from_lookup(move |k| (k == "SESSION_COOKIE").then(|| b.clone()))
                    .unwrap_err();
            assert!(e.contains("SESSION_COOKIE"), "{bad}: {e}");
        }
    }

    #[test]
    #[should_panic(expected = "at least one second")]
    fn a_zero_lifetime_is_rejected_when_building_the_layer() {
        let _ = layer_with(
            MemoryStore::default(),
            &SessionOptions::default().lifetime(std::time::Duration::ZERO),
        );
    }
}