footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
//! Shared online user queries based on recent authenticated heartbeats.
//!
//! Enable `presence-postgres` for `PostgresPresence` or `presence-sqlite` for
//! `SqlitePresence`. Both may be enabled together. Each backend keeps one row
//! per opaque `(scope, user_id)`: multiple tabs, devices, and application instances
//! using the same database share that row. A user is online when
//! `last_seen > database_time - timeout`.
//! This measures recently received heartbeats, not human attention, current
//! page visibility, or whether a login session is still valid.
//!
//! # Integration
//!
//! 1. Copy `POSTGRES_SCHEMA` or `SQLITE_SCHEMA` into a host-owned, versioned
//!    migration file. They create `public.footing_presence` (PostgreSQL) or
//!    `main.footing_presence` (SQLite), without a foreign key to business tables.
//!    These are **frozen version 1** schemas; future changes will be separate
//!    incremental migrations. Preserve the copied SQL and host-assigned version:
//!    do not regenerate an applied migration from a newer dependency. One migration
//!    sequence owns this table even when multiple services use it. Footing does
//!    not run migrations automatically or maintain a second migration history.
//! 2. Construct a store with the application's existing pool, a trusted scope,
//!    and an online timeout. All instances sharing a scope must use the same
//!    timeout, including cleanup jobs. Use separate scopes for applications,
//!    environments, or tenants whose users must not be combined; avoid ambiguous
//!    concatenation when constructing a scope from multiple identifiers.
//! 3. In an authenticated heartbeat handler, pass the **verified user's ID** to
//!    the store's `heartbeat` method. Do not take identity or scope from an
//!    untrusted request body. Apply normal credential validation, CSRF protection
//!    where applicable, and rate limits. Configure authentication so heartbeats
//!    do not extend sliding login sessions.
//! 4. Authorize count/list queries in the host. Join returned IDs to names or
//!    departments there. No HTTP routes, tasks, or migrations are installed by
//!    enabling the feature or constructing a store.
//!
//! PostgreSQL:
//!
//! ```no_run
//! # #[cfg(feature = "presence-postgres")]
//! # async fn example(pool: sqlx::PgPool, verified_user_id: &str)
//! # -> Result<(), footing::presence::PresenceError> {
//! use footing::presence::{DEFAULT_ONLINE_TIMEOUT, PostgresPresence};
//!
//! // The host has already applied POSTGRES_SCHEMA through its migration system.
//! let presence = PostgresPresence::new(pool, "admin:production", DEFAULT_ONLINE_TIMEOUT)?;
//! presence.heartbeat(verified_user_id).await?;
//! let count = presence.count_online().await?;
//! let first = presence.list_online(None, 50).await?;
//! if let Some(after) = first.next_user_id.as_deref() {
//!     let next = presence.list_online(Some(after), 50).await?;
//! #   let _ = next;
//! }
//! // Optional, bounded maintenance; expiration does not depend on this call.
//! presence.prune_expired(500).await?;
//! # let _ = count;
//! # Ok(())
//! # }
//! ```
//!
//! SQLite exposes the same operations:
//!
//! ```no_run
//! # #[cfg(feature = "presence-sqlite")]
//! # async fn example(pool: sqlx::SqlitePool, verified_user_id: &str)
//! # -> Result<(), footing::presence::PresenceError> {
//! use footing::presence::{DEFAULT_ONLINE_TIMEOUT, SqlitePresence};
//!
//! // The host has applied SQLITE_SCHEMA through its migration system.
//! let presence = SqlitePresence::new(pool, "admin:production", DEFAULT_ONLINE_TIMEOUT)?;
//! presence.heartbeat(verified_user_id).await?;
//! let page = presence.list_online(None, 50).await?;
//! # let _ = page;
//! # Ok(())
//! # }
//! ```
//!
//! # Browser behavior and guarantees
//!
//! A reasonable starting point is a heartbeat every 30 seconds while the page
//! is visible and authenticated, with a 90-second online timeout. Send a fresh
//! heartbeat on becoming visible. Allow at most one request in flight, bound its
//! duration, and wait for the next interval after a failure: do not buffer or
//! replay heartbeats. Stop on logout, authentication failure, or account changes.
//! The host must also coordinate cross-tab account changes; an old page using a
//! newly switched cookie would otherwise report the newly authenticated user.
//! This API does not bind browser instances to login sessions.
//!
//! There are no event IDs, client timestamps, or exactly-once delivery guarantees.
//! A delayed request can extend presence on arrival.
//! Unknown commit outcomes are reported as errors; the next regular heartbeat
//! can recover without a retry queue.
//! Hiding, closing, or logging out of a page does not immediately remove the
//! user: other tabs or devices may still be active, and absence takes effect
//! through the timeout. Presence must not authorize access or serve as an audit
//! log. Identifiers must not be used as Prometheus labels.
//!
//! Both backends accept positive, whole-millisecond timeouts up to
//! [`MAX_ONLINE_TIMEOUT`]. PostgreSQL timestamps retain microsecond precision;
//! SQLite timestamps use integer Unix milliseconds. PostgreSQL samples statement
//! arrival time; SQLite samples its host's wall clock during execution, which
//! may be delayed by its write lock. See each backend's heartbeat documentation.
//! Heartbeats never reduce a stored `last_seen`, but wall-clock adjustments can
//! still affect expiration. SQLite sharing is intended for processes on one
//! host using the same local file; use PostgreSQL for deployment-wide shared state.
//!
//! Use the same database for writes and queries; replica lag can otherwise give
//! stale results. Independent queries and successive pages observe a changing
//! set, not a shared historical snapshot. Explicit `prune_expired` calls reclaim
//! storage in bounded batches. The host chooses the schedule, connection/query
//! deadlines, and backend-specific lock-wait policy.

mod error;
#[cfg(feature = "presence-postgres")]
mod postgres;
#[cfg(feature = "presence-sqlite")]
mod sqlite;

use std::time::Duration;

use time::OffsetDateTime;

pub use error::PresenceError;
#[cfg(feature = "presence-postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "presence-postgres")))]
pub use postgres::{POSTGRES_SCHEMA, PostgresPresence};
#[cfg(feature = "presence-sqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "presence-sqlite")))]
pub use sqlite::{SQLITE_SCHEMA, SqlitePresence};

/// Suggested online window when clients send a heartbeat every 30 seconds.
pub const DEFAULT_ONLINE_TIMEOUT: Duration = Duration::from_secs(90);
/// Maximum timeout, bounded to keep timestamp arithmetic within a practical range.
pub const MAX_ONLINE_TIMEOUT: Duration = Duration::from_secs(i32::MAX as u64);
/// Maximum UTF-8 byte length of each scope and user ID.
pub const MAX_ID_LENGTH: usize = 256;
/// Maximum number of users returned or expired records deleted in one call.
pub const MAX_BATCH_SIZE: u32 = 1000;

/// One online user in a scope. Times come from the database engine, never the browser.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OnlineUser {
    /// Opaque, case-sensitive user identifier.
    pub user_id: String,
    /// Database time of the latest recorded heartbeat.
    pub last_seen: OffsetDateTime,
}

/// A bounded page ordered by user ID with a case-sensitive binary collation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OnlineUsers {
    /// Users online at this query's cutoff time.
    pub users: Vec<OnlineUser>,
    /// Pass this raw user ID as `after_user_id` to fetch the next page.
    ///
    /// Present only when this query found another online row beyond the page.
    /// It is a pagination boundary, not an authorization token or a snapshot.
    pub next_user_id: Option<String>,
}

impl OnlineUsers {
    fn from_users(mut users: Vec<OnlineUser>, limit: u32) -> Self {
        let next_user_id = if users.len() > limit as usize {
            users.truncate(limit as usize);
            users.last().map(|user| user.user_id.clone())
        } else {
            None
        };
        Self {
            users,
            next_user_id,
        }
    }
}

fn validate_config(scope: &str, online_timeout: Duration) -> Result<(), PresenceError> {
    if !valid_id(scope) {
        return Err(PresenceError::InvalidScope);
    }
    if online_timeout.is_zero()
        || online_timeout > MAX_ONLINE_TIMEOUT
        || !online_timeout.subsec_nanos().is_multiple_of(1_000_000)
    {
        return Err(PresenceError::InvalidTimeout);
    }
    Ok(())
}

fn valid_id(value: &str) -> bool {
    !value.is_empty() && value.len() <= MAX_ID_LENGTH && !value.chars().any(char::is_control)
}

fn validate_user_id(user_id: &str) -> Result<(), PresenceError> {
    if valid_id(user_id) {
        Ok(())
    } else {
        Err(PresenceError::InvalidUserId)
    }
}

fn validate_limit(limit: u32) -> Result<(), PresenceError> {
    if (1..=MAX_BATCH_SIZE).contains(&limit) {
        Ok(())
    } else {
        Err(PresenceError::InvalidLimit)
    }
}

#[cfg(test)]
mod tests;