laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::sync::Arc;
use std::time::Duration;

use jiff::Timestamp;

use super::{Identity, SessionStore, Write};
use crate::config::session::{Driver, Session as SessionConfig};
use crate::container::Registrar;
use crate::db::identifier::is_identifier_path;
use crate::db::{self, Builder, DatabaseManager, Value, col, values};
use crate::error::Result;
use crate::foundation::ServiceProvider;

struct DatabaseStore {
    database: Arc<DatabaseManager>,
    connection: Option<String>,
    table: String,
}

/// Adds the `database` session driver, the way a package adds a driver of its own.
pub(crate) struct DatabaseSessionServiceProvider;

impl ServiceProvider for DatabaseSessionServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.sessions().extend("database", |app| async move {
            let config = &app.config().session;

            Ok(DatabaseStore {
                database: app.resolve::<DatabaseManager>().await?,
                connection: config.connection.clone(),
                table: config.table.clone(),
            })
        });
    }
}

/// Check the table's name when the application starts, since the store writes it into its queries.
pub(crate) fn validate(config: &SessionConfig) -> Result<()> {
    if matches!(config.driver, Driver::Database) && !is_identifier_path(&config.table) {
        return Err(crate::error::fail(format!(
            "the session table `{}` must be letters, digits and underscores, optionally schema-qualified",
            config.table
        )));
    }

    Ok(())
}

impl DatabaseStore {
    fn sessions(&self) -> Result<Builder> {
        let connection = match &self.connection {
            Some(name) => self.database.connection(name)?,
            None => self.database.default_connection()?,
        };

        Ok(connection.table(self.table.as_str()))
    }
}

impl SessionStore for DatabaseStore {
    async fn read(&self, id: &str, lifetime: Duration) -> Result<Option<String>> {
        // A replica may not have the previous request's write yet...
        self.sessions()?
            .select(["payload"])
            .filter(col("id").eq(id) & col("last_activity").ge(idle_since(lifetime)))
            .use_write_connection()
            .into_query()
            .retry_on_lost_connection()
            .scalar()
            .await
    }

    async fn write(
        &self,
        id: &str,
        payload: String,
        _lifetime: Duration,
        identity: &Identity,
        write: Write,
    ) -> Result<()> {
        let sessions = self.sessions()?;
        // A guest's ID is a literal NULL, which fits whatever type the column has. A bound NULL needs a type, and
        // PostgreSQL rejects one that doesn't match the column...
        let row = values! {
            user_id: identity.user_id().map(|user_id| db::expr(bindable(user_id))),
            ip_address: identity.ip_address().map(|ip| ip.to_string()),
            user_agent: identity.user_agent(),
            payload: payload,
            last_activity: crate::clock::system_timestamp(),
        };

        // Only update a session that was read, so a request in flight during a logout can't store it again...
        match write {
            Write::Existing => sessions.filter(col("id").eq(id)).update(row).await?,
            Write::New => {
                let updates = ["user_id", "ip_address", "user_agent", "payload", "last_activity"];
                sessions.upsert(row.set("id", id), ["id"], updates).await?
            }
        };

        Ok(())
    }

    async fn destroy_others(&self, user_id: &serde_json::Value, except: &str) -> Result<()> {
        self.sessions()?
            .filter(col("user_id").eq(bindable(user_id)) & col("id").ne(except))
            .delete()
            .await?;

        Ok(())
    }

    async fn destroy(&self, id: &str) -> Result<()> {
        self.sessions()?.filter(col("id").eq(id)).delete().await?;

        Ok(())
    }

    async fn collect_garbage(&self, lifetime: Duration) -> Result<()> {
        self.sessions()?
            .filter(col("last_activity").lt(idle_since(lifetime)))
            .delete()
            .await?;

        Ok(())
    }
}

/// The last activity before which a session has expired.
fn idle_since(lifetime: Duration) -> Timestamp {
    crate::clock::system_timestamp()
        .checked_sub(lifetime)
        .unwrap_or(Timestamp::MIN)
}

/// Bind a user's ID as the column type it most likely has: integers for a `BIGINT`, UUIDs for a PostgreSQL `UUID`,
/// and other strings as text.
fn bindable(user_id: &serde_json::Value) -> Value<'_> {
    match user_id {
        serde_json::Value::Number(id) if id.is_i64() => Value::BigInteger(id.as_i64()),
        serde_json::Value::Number(id) if id.is_u64() => Value::UnsignedInteger(id.as_u64()),
        serde_json::Value::String(id) => match uuid::Uuid::parse_str(id) {
            Ok(uuid) => Value::Uuid(Some(uuid)),
            Err(_) => Value::Text(Some(id.as_str().into())),
        },
        other => Value::Text(Some(other.to_string().into())),
    }
}