use std::{fmt, time::Duration};
use sqlx::PgPool;
use time::OffsetDateTime;
use crate::db::postgres::PostgresPoolError;
use super::{
OnlineUser, OnlineUsers, PresenceError, validate_config, validate_limit, validate_user_id,
};
pub const POSTGRES_SCHEMA: &str = include_str!("postgres_v1.sql");
#[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 {
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,
})
}
pub fn scope(&self) -> &str {
&self.scope
}
pub const fn online_timeout(&self) -> Duration {
self.online_timeout
}
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
.map_err(PostgresPoolError::from)?)
}
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
.map_err(PostgresPoolError::from)?)
}
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)
.bind(after_user_id.unwrap_or(""))
.bind(i64::from(limit) + 1)
.fetch_all(&self.pool)
.await
.map_err(PostgresPoolError::from)?;
let users = rows
.into_iter()
.map(|(user_id, last_seen)| OnlineUser { user_id, last_seen })
.collect();
Ok(OnlineUsers::from_users(users, limit))
}
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
.map_err(PostgresPoolError::from)?
.rows_affected())
}
}