footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
use std::{error::Error, time::Duration};

#[cfg(feature = "presence-postgres")]
use sqlx::{PgPool, postgres::PgPoolOptions};

use super::*;
use crate::result::{ClassifyError, ErrorKind};

const DATABASE_ERRORS: &[fn(sqlx::Error) -> PresenceError] = &[
    #[cfg(feature = "presence-postgres")]
    |source| PresenceError::Postgres(source.into()),
    #[cfg(feature = "presence-sqlite")]
    |source| PresenceError::Sqlite(source.into()),
];

#[cfg(feature = "presence-postgres")]
fn lazy_pool() -> PgPool {
    PgPoolOptions::new()
        .connect_lazy("postgres://localhost/footing_presence_unused")
        .unwrap()
}

#[tokio::test]
#[cfg(feature = "presence-postgres")]
async fn construction_is_offline_and_preserves_opaque_scope() {
    let pool = lazy_pool();
    pool.close().await;
    let presence =
        PostgresPresence::new(pool, " Production:租户 A ", DEFAULT_ONLINE_TIMEOUT).unwrap();
    assert_eq!(presence.scope(), " Production:租户 A ");
    assert_eq!(presence.online_timeout(), Duration::from_secs(90));
    assert_eq!(presence.clone().scope(), presence.scope());
    assert!(!format!("{presence:?}").contains("租户"));
}

#[test]
fn identifiers_have_byte_limits_and_are_never_normalized() {
    for scope in [
        "".to_owned(),
        "x".repeat(257),
        "é".repeat(129),
        "bad\0id".into(),
        "bad\nid".into(),
    ] {
        assert!(matches!(
            validate_config(&scope, DEFAULT_ONLINE_TIMEOUT),
            Err(PresenceError::InvalidScope)
        ));
    }
    for scope in [
        "x".repeat(256),
        "é".repeat(128),
        "Alice".into(),
        "alice".into(),
    ] {
        validate_config(&scope, DEFAULT_ONLINE_TIMEOUT).unwrap();
    }
    assert!(valid_id("é"));
    assert!(valid_id("e\u{301}"));
}

#[test]
fn timeout_requires_exact_bounded_milliseconds() {
    for timeout in [
        Duration::ZERO,
        Duration::from_nanos(1),
        Duration::from_nanos(1001),
        Duration::from_micros(1),
        Duration::from_micros(1001),
        DEFAULT_ONLINE_TIMEOUT + Duration::from_nanos(1),
        MAX_ONLINE_TIMEOUT + Duration::from_micros(1),
        Duration::MAX,
    ] {
        assert!(matches!(
            validate_config("scope", timeout),
            Err(PresenceError::InvalidTimeout)
        ));
    }
    for timeout in [
        Duration::from_millis(1),
        DEFAULT_ONLINE_TIMEOUT,
        MAX_ONLINE_TIMEOUT,
    ] {
        validate_config("scope", timeout).unwrap();
    }
}

#[tokio::test]
#[cfg(feature = "presence-postgres")]
async fn invalid_operation_inputs_fail_before_database_access() {
    let pool = lazy_pool();
    pool.close().await;
    let presence = PostgresPresence::new(pool, "scope", DEFAULT_ONLINE_TIMEOUT).unwrap();
    for user_id in [
        "".to_owned(),
        "x".repeat(257),
        "bad\0id".into(),
        "bad\nid".into(),
    ] {
        assert!(matches!(
            presence.heartbeat(&user_id).await,
            Err(PresenceError::InvalidUserId)
        ));
        assert!(matches!(
            presence.list_online(Some(&user_id), 10).await,
            Err(PresenceError::InvalidUserId)
        ));
    }
    for limit in [0, MAX_BATCH_SIZE + 1, u32::MAX] {
        assert!(matches!(
            presence.list_online(None, limit).await,
            Err(PresenceError::InvalidLimit)
        ));
        assert!(matches!(
            presence.prune_expired(limit).await,
            Err(PresenceError::InvalidLimit)
        ));
    }
    for error in [
        presence.heartbeat("valid").await.unwrap_err(),
        presence.count_online().await.unwrap_err(),
        presence.list_online(None, 10).await.unwrap_err(),
        presence.prune_expired(10).await.unwrap_err(),
    ] {
        assert!(matches!(
            error,
            PresenceError::Postgres(crate::db::postgres::PostgresPoolError::Sqlx(
                sqlx::Error::PoolClosed
            ))
        ));
        assert!(!error.error_descriptor().retryable());
    }
}

#[test]
fn errors_classify_failures_without_exposing_inputs_or_database_details() {
    for error in [
        PresenceError::InvalidScope,
        PresenceError::InvalidUserId,
        PresenceError::InvalidTimeout,
        PresenceError::InvalidLimit,
    ] {
        assert_eq!(error.error_kind(), ErrorKind::Validation);
        assert!(!error.error_descriptor().retryable());
    }
    for wrap in DATABASE_ERRORS {
        let error = wrap(sqlx::Error::Protocol("private database detail".into()));
        assert_eq!(error.error_kind(), ErrorKind::Dependency);
        assert_eq!(error.error_code(), "presence_database_failed");
        assert!(!error.to_string().contains("private"));
        assert!(!format!("{error:?}").contains("private"));
        assert!(!format!("{:?}", error.error_descriptor()).contains("private"));
        let backend_error = error.source().unwrap();
        assert!(!backend_error.to_string().contains("private"));
        assert!(matches!(
            backend_error.source().unwrap().downcast_ref::<sqlx::Error>(),
            Some(sqlx::Error::Protocol(detail)) if detail == "private database detail"
        ));
    }
}

#[test]
fn database_failures_have_explicit_retry_classification() {
    for wrap in DATABASE_ERRORS {
        for (source, retryable) in [
            (sqlx::Error::PoolClosed, false),
            (sqlx::Error::PoolTimedOut, true),
            (sqlx::Error::RowNotFound, false),
            (sqlx::Error::Protocol("private detail".into()), false),
            (sqlx::Error::Configuration("private detail".into()), false),
            (
                sqlx::Error::Io(std::io::ErrorKind::PermissionDenied.into()),
                false,
            ),
            (sqlx::Error::Io(std::io::ErrorKind::TimedOut.into()), true),
            (
                sqlx::Error::ColumnDecode {
                    index: "last_seen".into(),
                    source: "private detail".into(),
                },
                false,
            ),
        ] {
            let error = wrap(source);
            assert_eq!(error.error_descriptor().retryable(), retryable, "{error:?}");
        }
    }
}

#[test]
#[cfg(all(feature = "presence-postgres", feature = "presence-sqlite"))]
fn io_errors_keep_their_backend_specific_meaning() {
    // A missing local file is permanent for SQLite; a PostgreSQL connection
    // failure can recover. Feature unification must not change either policy.
    let postgres =
        PresenceError::Postgres(sqlx::Error::Io(std::io::ErrorKind::NotFound.into()).into());
    let sqlite = PresenceError::Sqlite(sqlx::Error::Io(std::io::ErrorKind::NotFound.into()).into());
    assert!(postgres.error_descriptor().retryable());
    assert!(!sqlite.error_descriptor().retryable());
}