servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! A finite set of named operations retains native SQLx connection and pool access.
use super::{PgConfig, PgError, PgPool, operation_metrics::Measurements};
use crate::setup::SetupContext;
use std::{collections::BTreeSet, future::Future, pin::Pin, sync::Arc};

/// A native query/transaction future borrowing the operation's checked-out connection.
pub type OperationFuture<'connection, T> =
    Pin<Box<dyn Future<Output = Result<T, super::Error>> + Send + 'connection>>;

/// Native pool access and the finite operation handles declared during setup.
#[derive(Clone)]
pub struct PgOperations {
    pool: PgPool,
    operations: Vec<PgOperation>,
}
impl PgOperations {
    /// Native SQLx pool escape hatch. Direct queries retain native semantics.
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }
    /// Clone a predeclared operation handle; unknown names never create instruments.
    pub fn get(&self, name: &str) -> Option<PgOperation> {
        self.operations
            .iter()
            .find(|operation| operation.name() == name)
            .cloned()
    }
}

/// A cloneable named operation with explicit deadlines, spans, and outcome metrics.
///
/// Call [`Self::run`] with an admitted request's absolute deadline, or an explicit
/// worker deadline. The callback uses a native SQLx connection and may begin its
/// own transaction. No SQL, binds, return values, or native error details are logged.
#[derive(Clone)]
pub struct PgOperation {
    pub(super) pool: PgPool,
    pub(super) pool_name: Arc<str>,
    pub(super) name: Arc<str>,
    pub(super) metrics: Measurements,
}
impl PgOperation {
    /// Stable operation name approved during setup.
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl SetupContext {
    /// Connect a managed native pool and register 1..=32 named operation handles.
    ///
    /// Names are unique, at most 64 ASCII bytes, using letters, digits, `_`, `-`,
    /// or `.`. They are metric labels and span fields; choose stable non-secret
    /// categories. Invalid names fail before connecting. Metric-capacity failure
    /// remains a setup error; propagating it performs normal managed rollback.
    /// [`Self::postgres`] remains available when only a native pool is needed.
    ///
    /// ```no_run
    /// # async fn example(mut ctx: servlet::setup::SetupContext, config: servlet::sql::PgConfig,
    /// # deadline: servlet::web::RequestDeadline) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let database = ctx.postgres_operations("primary", config, &["orders.count"]).await?;
    /// let count = database.get("orders.count").unwrap();
    /// let total: i64 = count.run(deadline.instant(), |connection| {
    ///     Box::pin(servlet::sql::query_scalar("SELECT count(*) FROM orders").fetch_one(connection))
    /// }).await?;
    /// # let _ = total;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn postgres_operations(
        &mut self,
        name: impl Into<String>,
        config: PgConfig,
        operations: &[&str],
    ) -> Result<PgOperations, PgError> {
        validate_names(operations)?;
        let name = name.into();
        let pool = self.postgres(name.clone(), config).await?;
        let measurements = super::operation_metrics::register(&self.metrics(), &name, operations)?;
        let pool_name: Arc<str> = name.into();
        let operations = operations
            .iter()
            .zip(measurements)
            .map(|(name, metrics)| PgOperation {
                pool: pool.clone(),
                pool_name: pool_name.clone(),
                name: (*name).into(),
                metrics,
            })
            .collect();
        Ok(PgOperations { pool, operations })
    }
}
fn validate_names(names: &[&str]) -> Result<(), PgError> {
    let mut unique = BTreeSet::new();
    if names.is_empty() || names.len() > 32 {
        return Err(PgError::Configuration);
    }
    for name in names {
        if name.is_empty()
            || name.len() > 64
            || !unique.insert(name)
            || !name
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
        {
            return Err(PgError::Configuration);
        }
    }
    Ok(())
}

#[cfg(test)]
#[path = "operations_test.rs"]
mod operations_test;