footing 0.5.5

Feature-gated foundations for Rust backend services
Documentation
//! PostgreSQL presence operations.

use std::{fmt, time::Duration};

use sqlx::PgPool;
use time::OffsetDateTime;

use super::{
    OnlineUser, OnlineUsers, PresenceError, validate_config, validate_limit, validate_user_id,
};

/// Frozen version 1 schema for PostgreSQL, to copy into a host-owned migration.
///
/// Creates `public.footing_presence` and its indexes. These SQL bytes will remain
/// unchanged; future schema changes will be separate incremental migrations.
/// Apply this once using the host's own migration version. It deliberately fails
/// if the table already exists rather than accepting an incompatible schema.
pub const POSTGRES_SCHEMA: &str = include_str!("postgres_v1.sql");

/// PostgreSQL presence operations for one trusted scope and online timeout.
///
/// Clones share the pool and the same configuration. Construction performs no
/// I/O. All operations are scoped, and cleanup uses the same timeout as queries.
#[derive(Clone)]
pub struct PostgresPresence {
    pool: PgPool,
    scope: String,
    online_timeout: Duration,
}

impl fmt::Debug for PostgresPresence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PostgresPresence")
            .field("online_timeout", &self.online_timeout)
            .finish_non_exhaustive()
    }
}

impl PostgresPresence {
    /// Creates a scoped store without accessing PostgreSQL.
    ///
    /// Scope and user IDs must contain 1–256 UTF-8 bytes and no control
    /// characters. Values are preserved exactly, without trimming or case
    /// folding. The timeout must be positive, exactly representable in whole
    /// milliseconds, and at most [`MAX_ONLINE_TIMEOUT`](super::MAX_ONLINE_TIMEOUT).
    /// Invalid configuration is rejected instead of rounded or replaced with
    /// defaults.
    pub fn new(
        pool: PgPool,
        scope: impl Into<String>,
        online_timeout: Duration,
    ) -> Result<Self, PresenceError> {
        let scope = scope.into();
        validate_config(&scope, online_timeout)?;
        Ok(Self {
            pool,
            scope,
            online_timeout,
        })
    }

    /// Returns the store's exact scope.
    pub fn scope(&self) -> &str {
        &self.scope
    }

    /// Returns the online window shared by queries and cleanup.
    pub const fn online_timeout(&self) -> Duration {
        self.online_timeout
    }

    /// Records a heartbeat for a user authenticated by the host application.
    ///
    /// Concurrent calls for the same user share one row. A single atomic UPSERT
    /// records PostgreSQL's statement start time, preserving a newer existing
    /// timestamp if an older statement waited for a lock. Time spent waiting
    /// for that lock does not renew the online window. There is no
    /// immediate-offline operation: deleting the shared row on one tab's logout
    /// would also remove the presence of other active tabs or devices.
    pub async fn heartbeat(&self, user_id: &str) -> Result<OffsetDateTime, PresenceError> {
        validate_user_id(user_id)?;
        Ok(sqlx::query_scalar(
            "INSERT INTO public.footing_presence (scope, user_id, last_seen)
             VALUES ($1, $2, statement_timestamp())
             ON CONFLICT (scope, user_id) DO UPDATE
             SET last_seen = GREATEST(footing_presence.last_seen, EXCLUDED.last_seen)
             RETURNING last_seen",
        )
        .bind(&self.scope)
        .bind(user_id)
        .fetch_one(&self.pool)
        .await?)
    }

    /// Counts users whose last heartbeat is newer than this query's cutoff.
    ///
    /// Each scoped user counts once regardless of the number of tabs or devices.
    /// This and a separate list call can differ as users arrive or expire.
    pub async fn count_online(&self) -> Result<i64, PresenceError> {
        Ok(sqlx::query_scalar(
            "SELECT count(*) FROM public.footing_presence
             WHERE scope = $1 AND last_seen > statement_timestamp() - $2::interval",
        )
        .bind(&self.scope)
        .bind(self.online_timeout)
        .fetch_one(&self.pool)
        .await?)
    }

    /// Lists online users after an optional exclusive user-ID boundary.
    ///
    /// `limit` must be between 1 and [`MAX_BATCH_SIZE`](super::MAX_BATCH_SIZE).
    /// The ID ordering does not change when heartbeats arrive. Successive pages
    /// are live queries: users can expire between pages, and newly active IDs
    /// before the boundary are only visible after restarting pagination. An
    /// empty next page is valid.
    pub async fn list_online(
        &self,
        after_user_id: Option<&str>,
        limit: u32,
    ) -> Result<OnlineUsers, PresenceError> {
        validate_limit(limit)?;
        if let Some(after) = after_user_id {
            validate_user_id(after)?;
        }
        let rows: Vec<(String, OffsetDateTime)> = sqlx::query_as(
            "SELECT user_id, last_seen FROM public.footing_presence
             WHERE scope = $1 AND last_seen > statement_timestamp() - $2::interval
               AND user_id > $3 COLLATE \"C\"
             ORDER BY user_id LIMIT $4",
        )
        .bind(&self.scope)
        .bind(self.online_timeout)
        // Every valid ID is nonempty, so the empty string is the first-page
        // lower bound under C collation, leaving a directly indexable range.
        .bind(after_user_id.unwrap_or(""))
        .bind(i64::from(limit) + 1)
        .fetch_all(&self.pool)
        .await?;
        let users = rows
            .into_iter()
            .map(|(user_id, last_seen)| OnlineUser { user_id, last_seen })
            .collect();
        Ok(OnlineUsers::from_users(users, limit))
    }

    /// Deletes at most `limit` expired records in this scope, returning the count.
    ///
    /// `limit` must be between 1 and [`MAX_BATCH_SIZE`](super::MAX_BATCH_SIZE).
    /// Rows being written by another transaction are skipped, so zero does not
    /// guarantee that every expired record was removed. Row selection and deletion are atomic;
    /// a concurrent heartbeat cannot renew a selected row before it is deleted.
    /// A later heartbeat can create the row again. Queries exclude expired users
    /// even when this method is never called.
    pub async fn prune_expired(&self, limit: u32) -> Result<u64, PresenceError> {
        validate_limit(limit)?;
        Ok(sqlx::query(
            "WITH expired AS (
                SELECT scope, user_id FROM public.footing_presence
                WHERE scope = $1 AND last_seen <= statement_timestamp() - $2::interval
                ORDER BY last_seen, user_id
                LIMIT $3 FOR UPDATE SKIP LOCKED
             )
             DELETE FROM public.footing_presence AS presence USING expired
             WHERE presence.scope = expired.scope AND presence.user_id = expired.user_id",
        )
        .bind(&self.scope)
        .bind(self.online_timeout)
        .bind(i64::from(limit))
        .execute(&self.pool)
        .await?
        .rows_affected())
    }
}