servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Native query behavior and acquisition deadlines for predeclared operations.
use super::support::{config, settings};
use servlet::{
    App, Running,
    ecosystem::tokio,
    metrics::Registry,
    sql::{
        Connection, Error, PgConfig, PgFallibleOperationError, PgOperationError, PgOperations,
        PgReadiness, PgSession, query, query_scalar,
    },
    sync::oneshot,
    time::{Instant, sleep},
};
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

pub(super) async fn start(name: &str) -> (Running, PgOperations, Registry) {
    let config = config(false)
        .with_readiness(PgReadiness::NotRequired)
        .unwrap()
        .with_session(PgSession {
            statement_timeout: Duration::from_secs(1),
            ..PgSession::default()
        })
        .unwrap();
    start_with_config(name, config).await
}
pub(super) async fn start_with_config(
    name: &str,
    config: PgConfig,
) -> (Running, PgOperations, Registry) {
    let metrics = Registry::new();
    let (sender, receiver) = oneshot::channel();
    let name = name.to_owned();
    let running = App::new("sql-operations")
        .config(settings())
        .metrics(metrics.clone())
        .setup(move |mut ctx| async move {
            let database = ctx.postgres_operations("primary", config, &[&name]).await?;
            sender
                .send(database)
                .map_err(|_| "operation receiver dropped")?;
            Ok(())
        })
        .start()
        .await
        .unwrap();
    (running, receiver.await.unwrap(), metrics)
}
pub(super) fn outcome(registry: &Registry, name: &str, value: &str, expected: u64) {
    let output = registry.encode().unwrap();
    assert!(
        output
            .lines()
            .any(|line| line.starts_with("servlet_sql_operations_total{")
                && line.contains(&format!("operation=\"{name}\""))
                && line.contains(&format!("outcome=\"{value}\""))
                && line.ends_with(&format!(" {expected}"))),
        "{output}"
    );
}
pub(super) async fn stop(running: Running, operations: PgOperations) {
    running.handle().shutdown();
    running.wait().await.unwrap();
    assert!(operations.pool().is_closed());
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn native_success_error_and_closed_pool_outcomes_are_recorded_without_error_details() {
    let (running, database, metrics) = start("lookup").await;
    assert!(database.get("undeclared").is_none());
    let lookup = database.get("lookup").unwrap();
    let result = lookup
        .run(Instant::now() + Duration::from_secs(1), |connection| {
            Box::pin(
                query_scalar::<_, i32>("SELECT $1")
                    .bind(42)
                    .fetch_one(connection),
            )
        })
        .await
        .unwrap();
    assert_eq!(result, 42);
    let error = lookup
        .run(Instant::now() + Duration::from_secs(1), |connection| {
            Box::pin(
                query_scalar::<_, i32>("SELECT secret_value FROM private_error_detail")
                    .fetch_one(connection),
            )
        })
        .await
        .unwrap_err();
    assert!(matches!(error, PgOperationError::Query(_)));
    assert!(error.native().unwrap().as_database_error().is_some());
    assert!(!format!("{error:?} {error}").contains("private_error_detail"));
    outcome(&metrics, "lookup", "ok", 1);
    outcome(&metrics, "lookup", "query_error", 1);
    database.pool().close().await;
    let error = lookup
        .run(Instant::now() + Duration::from_secs(1), |_connection| {
            Box::pin(async { Ok(()) })
        })
        .await
        .unwrap_err();
    assert!(matches!(error, PgOperationError::Acquire(_)));
    outcome(&metrics, "lookup", "acquire_error", 1);
    acquire_outcome(&metrics, "lookup", "ok", 2);
    acquire_outcome(&metrics, "lookup", "error", 1);
    stop(running, database).await;
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn acquisition_uses_remaining_deadline_and_never_invokes_rejected_callback() {
    let (running, database, metrics) = start("saturated").await;
    let first = database.pool().acquire().await.unwrap();
    let second = database.pool().acquire().await.unwrap();
    let called = Arc::new(AtomicBool::new(false));
    let callback_called = called.clone();
    let deadline = Instant::now() + Duration::from_millis(120);
    sleep(Duration::from_millis(80)).await;
    let started = Instant::now();
    let operation = database.get("saturated").unwrap();
    let error = operation
        .run(deadline, move |_connection| {
            Box::pin(async move {
                callback_called.store(true, Ordering::SeqCst);
                Ok(())
            })
        })
        .await
        .unwrap_err();
    assert!(matches!(error, PgOperationError::Deadline));
    assert!(started.elapsed() < Duration::from_millis(300));
    assert!(!called.load(Ordering::SeqCst));
    outcome(&metrics, "saturated", "timeout", 1);
    let expired_called = called.clone();
    let expired = operation
        .run(Instant::now(), move |_| {
            expired_called.store(true, Ordering::SeqCst);
            Box::pin(async { Ok(()) })
        })
        .await;
    assert!(!called.load(Ordering::SeqCst));
    assert!(matches!(expired, Err(PgOperationError::Deadline)));
    let invalid = operation
        .run(Instant::now() + Duration::from_secs(86401), |_| {
            Box::pin(async { Ok(()) })
        })
        .await;
    assert!(matches!(invalid, Err(PgOperationError::InvalidDeadline)));
    outcome(&metrics, "saturated", "timeout", 2);
    outcome(&metrics, "saturated", "invalid_deadline", 1);
    acquire_outcome(&metrics, "saturated", "timeout", 2);
    acquire_outcome(&metrics, "saturated", "ok", 0);
    drop(first);
    drop(second);
    stop(running, database).await;
}

enum WriteError {
    Forbidden(&'static str),
    Sql(Error),
}

impl From<Error> for WriteError {
    fn from(error: Error) -> Self {
        Self::Sql(error)
    }
}

#[tokio::test]
#[ignore = "requires isolated PostgreSQL; python3 -B scripts/postgres_test.py"]
async fn fallible_operation_preserves_application_errors_and_transaction_boundaries() {
    let (running, database, metrics) = start("scoped-write").await;
    query(
        "CREATE TABLE fallible_operation_records
         (id int PRIMARY KEY, owner_id int NOT NULL, revision int NOT NULL)",
    )
    .execute(database.pool())
    .await
    .unwrap();
    query("INSERT INTO fallible_operation_records VALUES (1, 7, 0)")
        .execute(database.pool())
        .await
        .unwrap();

    let operation = database.get("scoped-write").unwrap();
    let write = |actor: i32| {
        operation.run_fallible(Instant::now() + Duration::from_secs(1), move |connection| {
            Box::pin(async move {
                let mut transaction = connection.begin().await?;
                let allowed = query_scalar::<_, bool>(
                    "SELECT owner_id = $1 FROM fallible_operation_records WHERE id = 1 FOR UPDATE",
                )
                .bind(actor)
                .fetch_one(&mut *transaction)
                .await?;
                if !allowed {
                    return Err(WriteError::Forbidden("private-authorization-detail"));
                }
                let revision = query_scalar::<_, i32>(
                    "UPDATE fallible_operation_records
                     SET revision = revision + 1 WHERE id = 1 RETURNING revision",
                )
                .fetch_one(&mut *transaction)
                .await?;
                transaction.commit().await?;
                Ok(revision)
            })
        })
    };

    let denied = write(9).await.unwrap_err();
    assert!(!format!("{denied:?} {denied}").contains("private-authorization-detail"));
    assert!(std::error::Error::source(&denied).is_none());
    assert!(matches!(
        denied,
        PgFallibleOperationError::Application(WriteError::Forbidden(
            "private-authorization-detail"
        ))
    ));
    assert_eq!(write(7).await.unwrap(), 1);
    let revision: i32 =
        query_scalar("SELECT revision FROM fallible_operation_records WHERE id = 1")
            .fetch_one(database.pool())
            .await
            .unwrap();
    assert_eq!(revision, 1);

    let native = operation
        .run_fallible(Instant::now() + Duration::from_secs(1), |connection| {
            Box::pin(async move {
                Ok::<i32, WriteError>(
                    query_scalar("SELECT secret_column FROM missing_operation_table")
                        .fetch_one(connection)
                        .await?,
                )
            })
        })
        .await
        .unwrap_err();
    assert!(!format!("{native:?} {native}").contains("missing_operation_table"));
    assert!(matches!(
        native,
        PgFallibleOperationError::Application(WriteError::Sql(error))
            if error.as_database_error().is_some()
    ));

    let expired = operation
        .run_fallible::<(), WriteError, _>(Instant::now(), |_| {
            panic!("expired operation invoked callback");
        })
        .await;
    assert!(matches!(
        expired,
        Err(PgFallibleOperationError::Operation(
            PgOperationError::Deadline
        ))
    ));
    database.pool().close().await;
    let closed = operation
        .run_fallible::<(), WriteError, _>(Instant::now() + Duration::from_secs(1), |_| {
            panic!("closed pool invoked callback");
        })
        .await;
    assert!(matches!(
        closed,
        Err(PgFallibleOperationError::Operation(
            PgOperationError::Acquire(_)
        ))
    ));
    outcome(&metrics, "scoped-write", "ok", 1);
    outcome(&metrics, "scoped-write", "query_error", 2);
    outcome(&metrics, "scoped-write", "timeout", 1);
    outcome(&metrics, "scoped-write", "acquire_error", 1);
    stop(running, database).await;
}

fn acquire_outcome(registry: &Registry, name: &str, value: &str, expected: u64) {
    let output = registry.encode().unwrap();
    assert!(
        output
            .lines()
            .any(|line| line.starts_with("servlet_sql_acquires_total{")
                && line.contains(&format!("operation=\"{name}\""))
                && line.contains(&format!("outcome=\"{value}\""))
                && line.ends_with(&format!(" {expected}"))),
        "{output}"
    );
}