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

/// Durable worker policy. Jobs are activated by `App::jobs`, never implicitly.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct JobsSettings {
    /// Maximum active handlers per worker (1..=256); SQLite requires 1.
    pub concurrency: usize,
    /// Time between empty polls and database error retries (100..=60000 ms).
    pub poll_interval_ms: u64,
    /// Reservation lifetime (3..=86400 seconds), renewed every third of this time.
    pub lease_seconds: u64,
    /// Maximum shutdown drain time (1..=3600 seconds).
    pub shutdown_timeout_seconds: u64,
}

impl Default for JobsSettings {
    fn default() -> Self {
        Self {
            concurrency: 1,
            poll_interval_ms: 1000,
            lease_seconds: 60,
            shutdown_timeout_seconds: 30,
        }
    }
}

impl JobsSettings {
    /// Check backend/pool constraints for an enabled worker, without connecting.
    pub fn validate_database(&self, database: &crate::DatabaseSettings) -> Result<()> {
        self.validate()?;
        if database.url.starts_with("sqlite:") && self.concurrency != 1 {
            return Err(AppError::Configuration(
                "SQLite workers require jobs.concurrency = 1.".into(),
            ));
        }
        if database.url.starts_with("postgres")
            && self.concurrency >= database.max_connections as usize
        {
            return Err(AppError::Configuration("Worker concurrency must be smaller than database.max_connections, leaving capacity for claims and heartbeats.".into()));
        }
        Ok(())
    }

    /// Validate without connecting to a database.
    pub fn validate(&self) -> Result<()> {
        if !(1..=256).contains(&self.concurrency)
            || !(100..=60000).contains(&self.poll_interval_ms)
            || !(3..=86400).contains(&self.lease_seconds)
            || !(1..=3600).contains(&self.shutdown_timeout_seconds)
        {
            return Err(AppError::Configuration("Invalid jobs settings: concurrency 1..=256, poll_interval_ms 100..=60000, lease_seconds 3..=86400, shutdown_timeout_seconds 1..=3600.".into()));
        }
        Ok(())
    }
}