async-session-r2d2 0.1.3

Provides session management using r2d2 for async-session.
Documentation
/*!
*/

#![forbid(unsafe_code, future_incompatible)]
#![deny(
    missing_debug_implementations,
    nonstandard_style,
    missing_docs,
    unreachable_pub,
    missing_copy_implementations,
    unused_qualifications
)]

use std::sync::Arc;

/// r2d2-backed session store for `async_session`
#[derive(Debug)]
pub struct PooledSessionStore<M: r2d2::ManageConnection> {
    pool: Arc<r2d2::Pool<M>>,
    table_name: String,
}

impl<M: r2d2::ManageConnection> Clone for PooledSessionStore<M> {
    fn clone(&self) -> Self {
        Self {
            pool: self.pool.clone(),
            table_name: self.table_name.clone(),
        }
    }
}

/// Provides generic operations for sessions across their database adapters.
pub trait TableOperations<M: r2d2::ManageConnection> {
    /// Adds in the necessary tables, if possible, for this session manager.
    fn add_table(&self) -> async_session::Result<()>;

    /// Cleans up expired sessions.
    fn clean_up(&self) -> async_session::Result<()>;

    /// Obtains a connection to the underlying database for this session.
    fn connection(&self) -> async_session::Result<r2d2::PooledConnection<M>>;

    /// Get the number of sessions in the store.
    fn count(&self) -> async_session::Result<usize>;
}

impl<M: r2d2::ManageConnection> PooledSessionStore<M> {
    /// Creates a new session manager with the provided pool and table name.
    pub fn from_pool(pool: r2d2::Pool<M>, table_name: String) -> async_session::Result<Self>
    where
        Self: TableOperations<M>,
    {
        let session = Self {
            pool: Arc::new(pool),
            table_name,
        };
        session.add_table().and(Ok(session))
    }
}

#[cfg(feature = "with-rusqlite")]
pub mod sqlite;

#[cfg(test)]
mod test;