Skip to main content

tower_sessions_toasty_store/
lib.rs

1//! [Toasty](https://github.com/tokio-rs/toasty) session store for
2//! [`tower-sessions`](https://github.com/maxcountryman/tower-sessions).
3//!
4//! One store implementation, many backends: SQLite, PostgreSQL, MySQL, and
5//! Turso — the store uses only portable Toasty query-builder calls, so every
6//! SQL backend shares the same code path. DynamoDB is untested and not
7//! supported.
8//!
9//! # Usage
10//!
11//! With a store-owned database (the store builds its own `toasty::Db`):
12//!
13//! ```rust,no_run
14//! use tower_sessions_toasty_store::ToastyStore;
15//!
16//! # tokio_test::block_on(async {
17//! let store = ToastyStore::connect("sqlite::memory:").await.unwrap();
18//! store.migrate().await.unwrap();
19//! # })
20//! ```
21//!
22//! With an application-owned [`toasty::Db`], sharing its connection pool.
23//! **The Db must register [`TowerSession`]** — using an unregistered model
24//! panics inside Toasty:
25//!
26//! ```rust,no_run
27//! use tower_sessions_toasty_store::{ToastyStore, TowerSession};
28//!
29//! # tokio_test::block_on(async {
30//! let db = toasty::Db::builder()
31//!     // your own models join the list: toasty::models!(TowerSession, crate::*)
32//!     .models(toasty::models!(TowerSession))
33//!     .connect("sqlite::memory:")
34//!     .await
35//!     .unwrap();
36//! let store = ToastyStore::new(db);
37//! store.migrate().await.unwrap();
38//! # })
39//! ```
40
41use async_trait::async_trait;
42use time::OffsetDateTime;
43pub use toasty;
44use tower_sessions_core::{
45    session::{Id, Record},
46    session_store, ExpiredDeletion, SessionStore,
47};
48
49/// The session model, mapped to the `tower_sessions` table.
50///
51/// Public so applications that bring their own [`toasty::Db`] can register it:
52/// `toasty::models!(tower_sessions_toasty_store::TowerSession, crate::*)`.
53/// To rename the table at runtime, use
54/// `toasty::Db::builder().table_name_prefix(..)` — Toasty fixes the base table
55/// name at compile time.
56#[derive(Debug, toasty::Model)]
57#[table = "tower_sessions"]
58pub struct TowerSession {
59    #[key]
60    id: String,
61
62    /// The full `Record`, encoded with `rmp-serde`.
63    data: Vec<u8>,
64
65    /// Unix seconds. An `i64` column works on every Toasty backend;
66    /// `time::OffsetDateTime` is not a Toasty field type.
67    expiry_date: i64,
68}
69
70/// An error type for Toasty stores.
71#[derive(thiserror::Error, Debug)]
72pub enum ToastyStoreError {
73    /// A variant to map `toasty` errors.
74    #[error(transparent)]
75    Toasty(#[from] toasty::Error),
76
77    /// A variant to map `rmp_serde` encode errors.
78    #[error(transparent)]
79    Encode(#[from] rmp_serde::encode::Error),
80
81    /// A variant to map `rmp_serde` decode errors.
82    #[error(transparent)]
83    Decode(#[from] rmp_serde::decode::Error),
84}
85
86impl From<ToastyStoreError> for session_store::Error {
87    fn from(err: ToastyStoreError) -> Self {
88        match err {
89            ToastyStoreError::Toasty(inner) => session_store::Error::Backend(inner.to_string()),
90            ToastyStoreError::Decode(inner) => session_store::Error::Decode(inner.to_string()),
91            ToastyStoreError::Encode(inner) => session_store::Error::Encode(inner.to_string()),
92        }
93    }
94}
95
96/// A Toasty session store.
97#[derive(Clone, Debug)]
98pub struct ToastyStore {
99    db: toasty::Db,
100
101    /// Whether the backend has a primary-key upsert. MySQL has none: its
102    /// `ON DUPLICATE KEY UPDATE` reacts to any unique key, so Toasty rejects it.
103    upsert: bool,
104}
105
106impl ToastyStore {
107    /// Create a new Toasty store from an application-owned [`toasty::Db`].
108    ///
109    /// The store clones the handle per operation; clones share the underlying
110    /// connection pool, so this is cheap. The `Db` **must** have
111    /// [`TowerSession`] registered in its `toasty::models!` list — Toasty
112    /// panics on queries for unregistered models.
113    ///
114    /// # Examples
115    ///
116    /// ```rust,no_run
117    /// use tower_sessions_toasty_store::{ToastyStore, TowerSession};
118    ///
119    /// # tokio_test::block_on(async {
120    /// let db = toasty::Db::builder()
121    ///     .models(toasty::models!(TowerSession))
122    ///     .connect("sqlite::memory:")
123    ///     .await
124    ///     .unwrap();
125    /// let session_store = ToastyStore::new(db);
126    /// # })
127    /// ```
128    pub fn new(db: toasty::Db) -> Self {
129        let upsert = db.driver().capability().upsert_primary_key;
130        Self { db, upsert }
131    }
132
133    /// Create a store with its own [`toasty::Db`] (and connection pool) from a
134    /// connection URL, registering only the session model.
135    ///
136    /// The URL scheme selects the driver; enable the matching `toasty` cargo
137    /// feature (`sqlite`, `postgresql`, `mysql`, `turso`) in your application.
138    ///
139    /// # Examples
140    ///
141    /// ```rust,no_run
142    /// use tower_sessions_toasty_store::ToastyStore;
143    ///
144    /// # tokio_test::block_on(async {
145    /// let session_store = ToastyStore::connect("sqlite::memory:").await.unwrap();
146    /// # })
147    /// ```
148    pub async fn connect(url: impl AsRef<str>) -> toasty::Result<Self> {
149        let db = toasty::Db::builder()
150            .models(toasty::models!(TowerSession))
151            .connect(url.as_ref())
152            .await?;
153        Ok(Self::new(db))
154    }
155
156    /// Migrate the session schema. Idempotent — safe to call on every start.
157    ///
158    /// `push_schema` fails if tables already exist, so this probes the session
159    /// table with a cheap query first and only pushes when the probe errors.
160    /// With an application-owned `Db`, `push_schema` pushes the *whole*
161    /// registered schema; applications managing their schema with toasty-cli
162    /// migrations should include [`TowerSession`] there and skip `migrate`.
163    ///
164    /// # Examples
165    ///
166    /// ```rust,no_run
167    /// use tower_sessions_toasty_store::ToastyStore;
168    ///
169    /// # tokio_test::block_on(async {
170    /// let session_store = ToastyStore::connect("sqlite::memory:").await.unwrap();
171    /// session_store.migrate().await.unwrap();
172    /// # })
173    /// ```
174    pub async fn migrate(&self) -> toasty::Result<()> {
175        let mut db = self.db.clone();
176        if self.probe(&mut db).await.is_ok() {
177            return Ok(());
178        }
179        if let Err(push_err) = db.push_schema().await {
180            // A concurrent migrate may have pushed between probe and push. If
181            // the table exists now, the schema is in place and this succeeded.
182            if self.probe(&mut db).await.is_ok() {
183                return Ok(());
184            }
185            return Err(push_err);
186        }
187        Ok(())
188    }
189
190    async fn probe(&self, db: &mut toasty::Db) -> toasty::Result<()> {
191        TowerSession::filter_by_id("")
192            .first()
193            .exec(db)
194            .await
195            .map(|_| ())
196    }
197}
198
199/// Toasty deliberately does not retry retryable transaction conflicts — the
200/// caller re-runs them. Turso, PostgreSQL, and MySQL classify such conflicts
201/// as structured serialization failures; the SQLite driver reports
202/// `SQLITE_BUSY` as an unstructured error, hence the string match.
203fn is_retryable(err: &toasty::Error) -> bool {
204    err.is_serialization_failure() || err.to_string().contains("database is locked")
205}
206
207/// Matches SQLite's default busy timeout.
208const RETRY_FOR: std::time::Duration = std::time::Duration::from_secs(5);
209
210/// 1ms, 2ms, 4ms, ... capped at 32ms per attempt. Turso fails a contended
211/// write immediately instead of waiting for the write lock, which is held for
212/// about a millisecond, so a longer backoff mostly leaves the lock idle.
213fn backoff(attempt: u32) -> std::time::Duration {
214    std::time::Duration::from_millis(1u64 << attempt.min(5))
215}
216
217/// Re-evaluates `$op` until it succeeds, fails non-retryably, or has retried
218/// for [`RETRY_FOR`].
219macro_rules! retry_on_conflict {
220    ($op:expr) => {{
221        let deadline = tokio::time::Instant::now() + RETRY_FOR;
222        let mut attempt = 0;
223        loop {
224            match $op {
225                Err(ToastyStoreError::Toasty(err))
226                    if is_retryable(&err) && tokio::time::Instant::now() < deadline =>
227                {
228                    tokio::time::sleep(backoff(attempt)).await;
229                    attempt += 1;
230                }
231                result => break result,
232            }
233        }
234    }};
235}
236
237#[async_trait]
238impl ExpiredDeletion for ToastyStore {
239    async fn delete_expired(&self) -> session_store::Result<()> {
240        Ok(retry_on_conflict!(self.try_delete_expired().await)?)
241    }
242}
243
244#[async_trait]
245impl SessionStore for ToastyStore {
246    async fn create(&self, record: &mut Record) -> session_store::Result<()> {
247        Ok(retry_on_conflict!(self.try_create(record).await)?)
248    }
249
250    async fn save(&self, record: &Record) -> session_store::Result<()> {
251        Ok(retry_on_conflict!(self.try_save(record).await)?)
252    }
253
254    async fn load(&self, session_id: &Id) -> session_store::Result<Option<Record>> {
255        Ok(retry_on_conflict!(self.try_load(session_id).await)?)
256    }
257
258    async fn delete(&self, session_id: &Id) -> session_store::Result<()> {
259        Ok(retry_on_conflict!(self.try_delete(session_id).await)?)
260    }
261}
262
263impl ToastyStore {
264    async fn try_delete_expired(&self) -> Result<(), ToastyStoreError> {
265        let mut db = self.db.clone();
266        let now = OffsetDateTime::now_utc().unix_timestamp();
267        TowerSession::filter(TowerSession::fields().expiry_date().lt(now))
268            .delete()
269            .exec(&mut db)
270            .await
271            .map_err(ToastyStoreError::Toasty)?;
272        Ok(())
273    }
274
275    async fn id_exists(db: &mut toasty::Db, id: &Id) -> Result<bool, ToastyStoreError> {
276        Ok(TowerSession::filter_by_id(id.to_string())
277            .first()
278            .exec(db)
279            .await
280            .map_err(ToastyStoreError::Toasty)?
281            .is_some())
282    }
283
284    async fn try_create(&self, record: &mut Record) -> Result<(), ToastyStoreError> {
285        if !self.upsert {
286            return self.try_create_without_upsert(record).await;
287        }
288        let mut db = self.db.clone();
289
290        loop {
291            // the record encodes its own id, so encode after each id change
292            let data = rmp_serde::to_vec(record).map_err(ToastyStoreError::Encode)?;
293
294            let inserted = TowerSession::upsert_by_id(record.id.to_string())
295                .data(data)
296                .expiry_date(record.expiry_date.unix_timestamp())
297                .or_ignore()
298                .exec(&mut db)
299                .await
300                .map_err(ToastyStoreError::Toasty)?;
301
302            if inserted.is_some() {
303                return Ok(());
304            }
305            record.id = Id::default();
306        }
307    }
308
309    async fn try_save(&self, record: &Record) -> Result<(), ToastyStoreError> {
310        if !self.upsert {
311            return self.try_save_without_upsert(record).await;
312        }
313        let mut db = self.db.clone();
314        let data = rmp_serde::to_vec(record).map_err(ToastyStoreError::Encode)?;
315
316        TowerSession::upsert_by_id(record.id.to_string())
317            .data(data)
318            .expiry_date(record.expiry_date.unix_timestamp())
319            .exec(&mut db)
320            .await
321            .map_err(ToastyStoreError::Toasty)?;
322        Ok(())
323    }
324
325    // The fallbacks for backends without upsert use single statements and
326    // re-check existence after a failed insert to detect a lost id race. A
327    // transaction would not close that race: a plain SELECT takes no lock
328    // that blocks a concurrent INSERT of the same id.
329
330    async fn try_create_without_upsert(&self, record: &mut Record) -> Result<(), ToastyStoreError> {
331        let mut db = self.db.clone();
332
333        loop {
334            while Self::id_exists(&mut db, &record.id).await? {
335                record.id = Id::default();
336            }
337
338            // the record encodes its own id, so encode after the id settles
339            let data = rmp_serde::to_vec(record).map_err(ToastyStoreError::Encode)?;
340
341            let created = toasty::create!(TowerSession {
342                id: record.id.to_string(),
343                data,
344                expiry_date: record.expiry_date.unix_timestamp(),
345            })
346            .exec(&mut db)
347            .await;
348
349            match created {
350                Ok(_) => return Ok(()),
351                // Toasty has no structured unique-violation error, so re-check
352                // the row: if the id exists now, a concurrent create won it —
353                // pick a new id. Otherwise surface the insert error.
354                Err(insert_err) => {
355                    if Self::id_exists(&mut db, &record.id).await? {
356                        record.id = Id::default();
357                        continue;
358                    }
359                    return Err(ToastyStoreError::Toasty(insert_err));
360                }
361            }
362        }
363    }
364
365    async fn try_save_without_upsert(&self, record: &Record) -> Result<(), ToastyStoreError> {
366        let mut db = self.db.clone();
367        let id = record.id.to_string();
368        let data = rmp_serde::to_vec(record).map_err(ToastyStoreError::Encode)?;
369        let expiry_date = record.expiry_date.unix_timestamp();
370
371        // Updates don't report whether a row matched, so: check existence,
372        // then branch.
373        let exists = Self::id_exists(&mut db, &record.id).await?;
374
375        if exists {
376            TowerSession::update_by_id(&id)
377                .data(data)
378                .expiry_date(expiry_date)
379                .exec(&mut db)
380                .await
381                .map_err(ToastyStoreError::Toasty)?;
382        } else {
383            let created = toasty::create!(TowerSession {
384                id: &id,
385                data: data.clone(),
386                expiry_date,
387            })
388            .exec(&mut db)
389            .await;
390
391            match created {
392                Ok(_) => {}
393                Err(insert_err) => {
394                    // Toasty has no structured unique-violation error, so
395                    // re-check the row instead: if it exists now, a concurrent
396                    // first-save of the same id won the insert and this save
397                    // is the update it now is. Otherwise the insert failed for
398                    // a real reason — surface it.
399                    let raced = Self::id_exists(&mut db, &record.id).await?;
400                    if !raced {
401                        return Err(ToastyStoreError::Toasty(insert_err));
402                    }
403                    TowerSession::update_by_id(&id)
404                        .data(data)
405                        .expiry_date(expiry_date)
406                        .exec(&mut db)
407                        .await
408                        .map_err(ToastyStoreError::Toasty)?;
409                }
410            }
411        }
412
413        Ok(())
414    }
415
416    async fn try_load(&self, session_id: &Id) -> Result<Option<Record>, ToastyStoreError> {
417        let mut db = self.db.clone();
418        let now = OffsetDateTime::now_utc().unix_timestamp();
419        let session = TowerSession::filter_by_id(session_id.to_string())
420            .filter(TowerSession::fields().expiry_date().gt(now))
421            .first()
422            .exec(&mut db)
423            .await
424            .map_err(ToastyStoreError::Toasty)?;
425
426        match session {
427            Some(session) => Ok(Some(
428                rmp_serde::from_slice(&session.data).map_err(ToastyStoreError::Decode)?,
429            )),
430            None => Ok(None),
431        }
432    }
433
434    async fn try_delete(&self, session_id: &Id) -> Result<(), ToastyStoreError> {
435        let mut db = self.db.clone();
436        TowerSession::delete_by_id(&mut db, session_id.to_string())
437            .await
438            .map_err(ToastyStoreError::Toasty)?;
439        Ok(())
440    }
441}
442
443// unit tests following tower-sessions-rusqlite-store, which took them from
444// https://github.com/maxcountryman/tower-sessions/blob/6ad8933b4f5e71f3202f0c1a28f194f3db5234c8/memory-store/src/lib.rs#L62
445#[cfg(test)]
446mod toasty_store_tests {
447    use time::Duration;
448
449    use super::*;
450
451    async fn create_store() -> ToastyStore {
452        let store = ToastyStore::connect("sqlite::memory:").await.unwrap();
453        store.migrate().await.unwrap();
454        assert!(store.upsert);
455        store
456    }
457
458    /// Runs the fallback path for backends without upsert on SQLite.
459    async fn create_store_without_upsert() -> ToastyStore {
460        ToastyStore {
461            upsert: false,
462            ..create_store().await
463        }
464    }
465
466    fn test_record() -> Record {
467        Record {
468            id: Default::default(),
469            data: Default::default(),
470            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
471        }
472    }
473
474    #[tokio::test]
475    async fn test_create() {
476        let store = create_store().await;
477        let mut record = test_record();
478        assert!(store.create(&mut record).await.is_ok());
479    }
480
481    #[tokio::test]
482    async fn test_save() {
483        let store = create_store().await;
484        let record = test_record();
485        assert!(store.save(&record).await.is_ok());
486    }
487
488    #[tokio::test]
489    async fn test_save_insert_then_update() {
490        save_insert_then_update(create_store().await).await;
491    }
492
493    #[tokio::test]
494    async fn test_save_insert_then_update_without_upsert() {
495        save_insert_then_update(create_store_without_upsert().await).await;
496    }
497
498    async fn save_insert_then_update(store: ToastyStore) {
499        let mut record = test_record();
500
501        // insert path: id was never created
502        store.save(&record).await.unwrap();
503        assert_eq!(Some(record.clone()), store.load(&record.id).await.unwrap());
504
505        // update path: data actually changes
506        record
507            .data
508            .insert("foo".to_string(), serde_json::to_value(42).unwrap());
509        store.save(&record).await.unwrap();
510        assert_eq!(Some(record.clone()), store.load(&record.id).await.unwrap());
511    }
512
513    #[tokio::test]
514    async fn test_load() {
515        let store = create_store().await;
516        let mut record = test_record();
517        store.create(&mut record).await.unwrap();
518        let loaded_record = store.load(&record.id).await.unwrap();
519        assert_eq!(Some(record), loaded_record);
520    }
521
522    #[tokio::test]
523    async fn test_load_expired_returns_none() {
524        let store = create_store().await;
525        let mut record = test_record();
526        record.expiry_date = OffsetDateTime::now_utc() - Duration::minutes(30);
527        store.create(&mut record).await.unwrap();
528        assert_eq!(None, store.load(&record.id).await.unwrap());
529    }
530
531    #[tokio::test]
532    async fn test_delete() {
533        let store = create_store().await;
534        let mut record = test_record();
535        store.create(&mut record).await.unwrap();
536        assert!(store.delete(&record.id).await.is_ok());
537        assert_eq!(None, store.load(&record.id).await.unwrap());
538    }
539
540    #[tokio::test]
541    async fn test_create_id_collision() {
542        create_id_collision(create_store().await).await;
543    }
544
545    #[tokio::test]
546    async fn test_create_id_collision_without_upsert() {
547        create_id_collision(create_store_without_upsert().await).await;
548    }
549
550    async fn create_id_collision(store: ToastyStore) {
551        let mut record1 = test_record();
552        let mut record2 = test_record();
553        record2
554            .data
555            .insert("foo".to_string(), serde_json::to_value(42).unwrap());
556        store.create(&mut record1).await.unwrap();
557        record2.id = record1.id; // Set the same ID for record2
558        store.create(&mut record2).await.unwrap();
559        assert_ne!(record1.id, record2.id); // IDs should be different
560
561        // the colliding create left the first record untouched
562        assert_eq!(
563            Some(record1.clone()),
564            store.load(&record1.id).await.unwrap()
565        );
566        assert_eq!(
567            Some(record2.clone()),
568            store.load(&record2.id).await.unwrap()
569        );
570    }
571
572    #[tokio::test]
573    async fn test_delete_expired() {
574        let store = create_store().await;
575        let mut record = test_record();
576        record.expiry_date = OffsetDateTime::now_utc() - Duration::minutes(30);
577        store.create(&mut record).await.unwrap();
578        store.delete_expired().await.unwrap();
579        assert_eq!(None, store.load(&record.id).await.unwrap());
580    }
581
582    #[tokio::test]
583    async fn test_migrate_idempotent() {
584        let store = ToastyStore::connect("sqlite::memory:").await.unwrap();
585        store.migrate().await.unwrap();
586        store.migrate().await.unwrap();
587
588        // still fully functional
589        let mut record = test_record();
590        store.create(&mut record).await.unwrap();
591        assert_eq!(Some(record.clone()), store.load(&record.id).await.unwrap());
592    }
593
594    #[derive(Debug, toasty::Model)]
595    struct OtherThing {
596        #[key]
597        #[auto]
598        id: u64,
599        name: String,
600    }
601
602    #[tokio::test]
603    async fn test_shared_db_with_user_model_and_prefix() {
604        let db = toasty::Db::builder()
605            .models(toasty::models!(TowerSession, OtherThing))
606            .table_name_prefix("myapp_")
607            .connect("sqlite::memory:")
608            .await
609            .unwrap();
610        let store = ToastyStore::new(db.clone());
611        store.migrate().await.unwrap();
612
613        let mut record = test_record();
614        store.create(&mut record).await.unwrap();
615        assert_eq!(Some(record.clone()), store.load(&record.id).await.unwrap());
616
617        // the user model coexists on the same Db
618        let mut db = db;
619        let thing = toasty::create!(OtherThing { name: "thing" })
620            .exec(&mut db)
621            .await
622            .unwrap();
623        assert_eq!(thing.name, "thing");
624    }
625}