capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use serde::{Deserialize, Serialize};

/// Automatic hardware/budget selection or an explicit worker count.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum HashConcurrency {
    /// Select from CPU parallelism and the memory budget.
    #[default]
    Auto,
    /// Explicit concurrent blocking operations (1..=32), within the memory budget.
    Fixed(usize),
}
impl Serialize for HashConcurrency {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Fixed(n) => n.serialize(serializer),
        }
    }
}
impl<'de> Deserialize<'de> for HashConcurrency {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Value {
            Name(String),
            Count(usize),
        }
        match Value::deserialize(deserializer)? {
            Value::Name(name) if name == "auto" => Ok(Self::Auto),
            Value::Count(n) => Ok(Self::Fixed(n)),
            _ => Err(serde::de::Error::custom(
                "use auto or an integer concurrency",
            )),
        }
    }
}

/// Per-application Argon2id admission and resource limits (`AUTH_PASSWORD_*`).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct PasswordSettings {
    /// `auto` (default) or 1..=32 workers. Cloned services share the same pool.
    pub hash_concurrency: HashConcurrency,
    /// Maximum wait for admission, milliseconds (1..=60000; default 5000).
    pub hash_queue_timeout_ms: u64,
    /// Maximum queued callers, excluding active workers (1..=4096; default 128).
    pub hash_queue_capacity: usize,
    /// Argon2 memory in KiB per operation (19456..=262144; default 19456).
    pub memory_cost_kib: u32,
    /// Argon2 passes (2..=10; default 2). Lanes remain one.
    pub time_cost: u32,
    /// Per-pool memory budget in KiB, including 1 MiB worker headroom (default 65536).
    /// Tune against the container limit and other application allocations.
    pub memory_budget_kib: u32,
}
impl Default for PasswordSettings {
    fn default() -> Self {
        Self {
            hash_concurrency: HashConcurrency::default(),
            hash_queue_timeout_ms: 5000,
            hash_queue_capacity: 128,
            memory_cost_kib: 19456,
            time_cost: 2,
            memory_budget_kib: 65536,
        }
    }
}
impl PasswordSettings {
    /// Validate all bounds and resolve automatic concurrency. The default budget caps
    /// memory even on hosts reporting hundreds of CPUs; it is not a process RSS limit.
    pub fn concurrency(&self) -> Result<usize> {
        let invalid = || {
            AppError::Configuration("Invalid auth.password settings: use hash_concurrency = \"auto\" or 1..=32, hash_queue_timeout_ms 1..=60000, hash_queue_capacity 1..=4096, memory_cost_kib 19456..=262144, time_cost 2..=10, and memory_budget_kib <=1048576 covering (memory_cost_kib + 1024) per worker. Reduce concurrency or increase the budget within your container memory limit.".into())
        };
        if !(1..=60000).contains(&self.hash_queue_timeout_ms)
            || !(1..=4096).contains(&self.hash_queue_capacity)
            || !(19456..=262144).contains(&self.memory_cost_kib)
            || !(2..=10).contains(&self.time_cost)
            || self.memory_budget_kib > 1048576
        {
            return Err(invalid());
        }
        let memory_workers = (self.memory_budget_kib / (self.memory_cost_kib + 1024)) as usize;
        if memory_workers == 0 {
            return Err(invalid());
        }
        match &self.hash_concurrency {
            HashConcurrency::Auto => Ok(std::thread::available_parallelism()
                .map_or(1, usize::from)
                .min(memory_workers)
                .min(32)),
            HashConcurrency::Fixed(n) if (1..=32).contains(n) && *n <= memory_workers => Ok(*n),
            _ => Err(invalid()),
        }
    }
}