servlet 1.0.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::{PgConfig, PgOperationError, PgOperations, PgReadiness, PgSession, 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;
}

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}"
    );
}