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
//! A session backend for managing session state.
//!
//! This crate provides the ability to use custom backends for session
//! management by implementing the [`SessionStore`] trait. This trait defines
//! the necessary operations for creating, saving, loading, and deleting session
//! records.
//!
//! # Implementing a Custom Store
//!
//! Below is an example of implementing a custom session store using an
//! in-memory [`HashMap`]. This example is for illustration purposes only; you
//! can use the provided [`MemoryStore`] directly without implementing it
//! yourself.
//!
//! ```rust
//! use std::{collections::HashMap, sync::Arc};
//!
//! use async_trait::async_trait;
//! use time::OffsetDateTime;
//! use tokio::sync::Mutex;
//! use tower_sessions_core::{
//!     session::{Id, Record},
//!     session_store, SessionStore,
//! };
//!
//! #[derive(Clone, Debug, Default)]
//! pub struct MemoryStore(Arc<Mutex<HashMap<Id, Record>>>);
//!
//! #[async_trait]
//! impl SessionStore for MemoryStore {
//!     async fn create(&self, record: &mut Record) -> session_store::Result<()> {
//!         let mut store_guard = self.0.lock().await;
//!         while store_guard.contains_key(&record.id) {
//!             // Session ID collision mitigation.
//!             record.id = Id::default();
//!         }
//!         store_guard.insert(record.id, record.clone());
//!         Ok(())
//!     }
//!
//!     async fn save(&self, record: &Record) -> session_store::Result<()> {
//!         self.0.lock().await.insert(record.id, record.clone());
//!         Ok(())
//!     }
//!
//!     async fn load(&self, session_id: &Id) -> session_store::Result<Option<Record>> {
//!         Ok(self
//!             .0
//!             .lock()
//!             .await
//!             .get(session_id)
//!             .filter(|Record { expiry_date, .. }| is_active(*expiry_date))
//!             .cloned())
//!     }
//!
//!     async fn delete(&self, session_id: &Id) -> session_store::Result<()> {
//!         self.0.lock().await.remove(session_id);
//!         Ok(())
//!     }
//! }
//!
//! fn is_active(expiry_date: OffsetDateTime) -> bool {
//!     expiry_date > OffsetDateTime::now_utc()
//! }
//! ```
//!
//! # Session Store Trait
//!
//! The [`SessionStore`] trait defines the interface for session management.
//! Implementations must handle session creation, saving, loading, and deletion.
//!
//! # CachingSessionStore
//!
//! The [`CachingSessionStore`] provides a layered caching mechanism with a
//! cache as the frontend and a store as the backend. This can improve read
//! performance by reducing the need to access the backend store for frequently
//! accessed sessions.
//!
//! # ExpiredDeletion
//!
//! The [`ExpiredDeletion`] trait provides a method for deleting expired
//! sessions. Implementations can optionally provide a method for continuously
//! deleting expired sessions at a specified interval.
use std::fmt::Debug;

use async_trait::async_trait;

use crate::session::{Id, Record};

/// Stores must map any errors that might occur during their use to this type.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Encoding failed with: {0}")]
    Encode(String),

    #[error("Decoding failed with: {0}")]
    Decode(String),

    #[error("{0}")]
    Backend(String),
}

pub type Result<T> = std::result::Result<T, Error>;

/// Defines the interface for session management.
///
/// See [`session_store`](crate::session_store) for more details.
#[async_trait]
pub trait SessionStore: Debug + Send + Sync + 'static {
    /// Creates a new session in the store with the provided session record.
    ///
    /// Implementers must decide how to handle potential ID collisions. For
    /// example, they might generate a new unique ID or return `Error::Backend`.
    ///
    /// The record is given as an exclusive reference to allow modifications,
    /// such as assigning a new ID, during the creation process.
    async fn create(&self, session_record: &mut Record) -> Result<()> {
        default_create(self, session_record).await
    }

    /// Saves the provided session record to the store.
    ///
    /// This method is intended for updating the state of an existing session.
    async fn save(&self, session_record: &Record) -> Result<()>;

    /// Loads an existing session record from the store using the provided ID.
    ///
    /// If a session with the given ID exists, it is returned. If the session
    /// does not exist or has been invalidated (e.g., expired), `None` is
    /// returned.
    async fn load(&self, session_id: &Id) -> Result<Option<Record>>;

    /// Deletes a session record from the store using the provided ID.
    ///
    /// If the session exists, it is removed from the store.
    async fn delete(&self, session_id: &Id) -> Result<()>;
}

async fn default_create<S: SessionStore + ?Sized>(
    store: &S,
    session_record: &mut Record,
) -> Result<()> {
    tracing::warn!(
        "The default implementation of `SessionStore::create` is being used, which relies on \
         `SessionStore::save`. To properly handle potential ID collisions, it is recommended that \
         stores implement their own version of `SessionStore::create`."
    );
    store.save(session_record).await?;
    Ok(())
}

/// Provides a layered caching mechanism with a cache as the frontend and a
/// store as the backend..
///
/// Contains both a cache, which acts as a frontend, and a store which acts as a
/// backend. Both cache and store implement `SessionStore`.
///
/// By using a cache, the cost of reads can be greatly reduced as once cached,
/// reads need only interact with the frontend, forgoing the cost of retrieving
/// the session record from the backend.
///
/// # Examples
///
/// ```rust,ignore
/// # tokio_test::block_on(async {
/// use tower_sessions::CachingSessionStore;
/// use tower_sessions_moka_store::MokaStore;
/// use tower_sessions_sqlx_store::{SqlitePool, SqliteStore};
/// let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
/// let sqlite_store = SqliteStore::new(pool);
/// let moka_store = MokaStore::new(Some(2_000));
/// let caching_store = CachingSessionStore::new(moka_store, sqlite_store);
/// # })
/// ```
#[derive(Debug, Clone)]
pub struct CachingSessionStore<Cache: SessionStore, Store: SessionStore> {
    cache: Cache,
    store: Store,
}

impl<Cache: SessionStore, Store: SessionStore> CachingSessionStore<Cache, Store> {
    /// Create a new `CachingSessionStore`.
    pub fn new(cache: Cache, store: Store) -> Self {
        Self { cache, store }
    }
}

#[async_trait]
impl<Cache, Store> SessionStore for CachingSessionStore<Cache, Store>
where
    Cache: SessionStore,
    Store: SessionStore,
{
    async fn create(&self, record: &mut Record) -> Result<()> {
        self.store.create(record).await?;
        self.cache.create(record).await?;
        Ok(())
    }

    async fn save(&self, record: &Record) -> Result<()> {
        let store_save_fut = self.store.save(record);
        let cache_save_fut = self.cache.save(record);

        futures::try_join!(store_save_fut, cache_save_fut)?;

        Ok(())
    }

    async fn load(&self, session_id: &Id) -> Result<Option<Record>> {
        match self.cache.load(session_id).await {
            // We found a session in the cache, so let's use it.
            Ok(Some(session_record)) => Ok(Some(session_record)),

            // We didn't find a session in the cache, so we'll try loading from the backend.
            //
            // When we find a session in the backend, we'll hydrate our cache with it.
            Ok(None) => {
                let session_record = self.store.load(session_id).await?;

                if let Some(ref session_record) = session_record {
                    self.cache.save(session_record).await?;
                }

                Ok(session_record)
            }

            // Some error occurred with our cache so we'll bubble this up.
            Err(err) => Err(err),
        }
    }

    async fn delete(&self, session_id: &Id) -> Result<()> {
        let store_delete_fut = self.store.delete(session_id);
        let cache_delete_fut = self.cache.delete(session_id);

        futures::try_join!(store_delete_fut, cache_delete_fut)?;

        Ok(())
    }
}

/// Provides a method for deleting expired sessions.
#[async_trait]
pub trait ExpiredDeletion: SessionStore
where
    Self: Sized,
{
    /// A method for deleting expired sessions from the store.
    async fn delete_expired(&self) -> Result<()>;

    /// This function will keep running indefinitely, deleting expired rows and
    /// then waiting for the specified period before deleting again.
    ///
    /// Generally this will be used as a task, for example via
    /// `tokio::task::spawn`.
    ///
    /// # Errors
    ///
    /// This function returns a `Result` that contains an error of type
    /// `sqlx::Error` if the deletion operation fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run,ignore
    /// use tower_sessions::session_store::ExpiredDeletion;
    /// use tower_sessions_sqlx_store::{sqlx::SqlitePool, SqliteStore};
    ///
    /// # {
    /// # tokio_test::block_on(async {
    /// let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
    /// let session_store = SqliteStore::new(pool);
    ///
    /// tokio::task::spawn(
    ///     session_store
    ///         .clone()
    ///         .continuously_delete_expired(tokio::time::Duration::from_secs(60)),
    /// );
    /// # })
    /// ```
    #[cfg(feature = "deletion-task")]
    #[cfg_attr(docsrs, doc(cfg(feature = "deletion-task")))]
    async fn continuously_delete_expired(self, period: tokio::time::Duration) -> Result<()> {
        let mut interval = tokio::time::interval(period);
        loop {
            self.delete_expired().await?;
            interval.tick().await;
        }
    }
}

#[cfg(test)]
mod tests {
    use mockall::{
        mock,
        predicate::{self, *},
    };
    use time::{Duration, OffsetDateTime};

    use super::*;

    mock! {
        #[derive(Debug)]
        pub Cache {}

        #[async_trait]
        impl SessionStore for Cache {
            async fn create(&self, record: &mut Record) -> Result<()>;
            async fn save(&self, record: &Record) -> Result<()>;
            async fn load(&self, session_id: &Id) -> Result<Option<Record>>;
            async fn delete(&self, session_id: &Id) -> Result<()>;
        }
    }

    mock! {
        #[derive(Debug)]
        pub Store {}

        #[async_trait]
        impl SessionStore for Store {
            async fn create(&self, record: &mut Record) -> Result<()>;
            async fn save(&self, record: &Record) -> Result<()>;
            async fn load(&self, session_id: &Id) -> Result<Option<Record>>;
            async fn delete(&self, session_id: &Id) -> Result<()>;
        }
    }

    mock! {
        #[derive(Debug)]
        pub CollidingStore {}

        #[async_trait]
        impl SessionStore for CollidingStore {
            async fn save(&self, record: &Record) -> Result<()>;
            async fn load(&self, session_id: &Id) -> Result<Option<Record>>;
            async fn delete(&self, session_id: &Id) -> Result<()>;
        }
    }

    #[tokio::test]
    async fn test_create() {
        let mut store = MockCollidingStore::new();
        let mut record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };

        store
            .expect_save()
            .with(predicate::eq(record.clone()))
            .times(1)
            .returning(|_| Ok(()));
        let result = store.create(&mut record).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_save() {
        let mut store = MockStore::new();
        let record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };
        store
            .expect_save()
            .with(predicate::eq(record.clone()))
            .times(1)
            .returning(|_| Ok(()));

        let result = store.save(&record).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_load() {
        let mut store = MockStore::new();
        let session_id = Id::default();
        let record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };
        let expected_record = record.clone();

        store
            .expect_load()
            .with(predicate::eq(session_id))
            .times(1)
            .returning(move |_| Ok(Some(record.clone())));

        let result = store.load(&session_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some(expected_record));
    }

    #[tokio::test]
    async fn test_delete() {
        let mut store = MockStore::new();
        let session_id = Id::default();

        store
            .expect_delete()
            .with(predicate::eq(session_id))
            .times(1)
            .returning(|_| Ok(()));

        let result = store.delete(&session_id).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_caching_store_create() {
        let mut cache = MockCache::new();
        let mut store = MockStore::new();
        let mut record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };

        cache.expect_create().times(1).returning(|_| Ok(()));
        store.expect_create().times(1).returning(|_| Ok(()));

        let caching_store = CachingSessionStore::new(cache, store);
        let result = caching_store.create(&mut record).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_caching_store_save() {
        let mut cache = MockCache::new();
        let mut store = MockStore::new();
        let record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };

        cache
            .expect_save()
            .with(predicate::eq(record.clone()))
            .times(1)
            .returning(|_| Ok(()));
        store
            .expect_save()
            .with(predicate::eq(record.clone()))
            .times(1)
            .returning(|_| Ok(()));

        let caching_store = CachingSessionStore::new(cache, store);
        let result = caching_store.save(&record).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_caching_store_load() {
        let mut cache = MockCache::new();
        let mut store = MockStore::new();
        let session_id = Id::default();
        let record = Record {
            id: Default::default(),
            data: Default::default(),
            expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
        };
        let expected_record = record.clone();

        cache
            .expect_load()
            .with(predicate::eq(session_id))
            .times(1)
            .returning(move |_| Ok(Some(record.clone())));
        // Store load should not be called since cache returns a record
        store.expect_load().times(0);

        let caching_store = CachingSessionStore::new(cache, store);
        let result = caching_store.load(&session_id).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some(expected_record));
    }

    #[tokio::test]
    async fn test_caching_store_delete() {
        let mut cache = MockCache::new();
        let mut store = MockStore::new();
        let session_id = Id::default();

        cache
            .expect_delete()
            .with(predicate::eq(session_id))
            .times(1)
            .returning(|_| Ok(()));
        store
            .expect_delete()
            .with(predicate::eq(session_id))
            .times(1)
            .returning(|_| Ok(()));

        let caching_store = CachingSessionStore::new(cache, store);
        let result = caching_store.delete(&session_id).await;
        assert!(result.is_ok());
    }
}