Skip to main content

capy_core/
jobs_config.rs

1use crate::{AppError, Result};
2use serde::{Deserialize, Serialize};
3
4/// Durable worker policy. Jobs are activated by `App::jobs`, never implicitly.
5#[derive(Clone, Debug, Deserialize, Serialize)]
6#[serde(default, deny_unknown_fields)]
7pub struct JobsSettings {
8    /// Maximum active handlers per worker (1..=256); SQLite requires 1.
9    pub concurrency: usize,
10    /// Time between empty polls and database error retries (100..=60000 ms).
11    pub poll_interval_ms: u64,
12    /// Reservation lifetime (3..=86400 seconds), renewed every third of this time.
13    pub lease_seconds: u64,
14    /// Maximum shutdown drain time (1..=3600 seconds).
15    pub shutdown_timeout_seconds: u64,
16}
17
18impl Default for JobsSettings {
19    fn default() -> Self {
20        Self {
21            concurrency: 1,
22            poll_interval_ms: 1000,
23            lease_seconds: 60,
24            shutdown_timeout_seconds: 30,
25        }
26    }
27}
28
29impl JobsSettings {
30    /// Check backend/pool constraints for an enabled worker, without connecting.
31    pub fn validate_database(&self, database: &crate::DatabaseSettings) -> Result<()> {
32        self.validate()?;
33        if database.url.starts_with("sqlite:") && self.concurrency != 1 {
34            return Err(AppError::Configuration(
35                "SQLite workers require jobs.concurrency = 1.".into(),
36            ));
37        }
38        if database.url.starts_with("postgres")
39            && self.concurrency >= database.max_connections as usize
40        {
41            return Err(AppError::Configuration("Worker concurrency must be smaller than database.max_connections, leaving capacity for claims and heartbeats.".into()));
42        }
43        Ok(())
44    }
45
46    /// Validate without connecting to a database.
47    pub fn validate(&self) -> Result<()> {
48        if !(1..=256).contains(&self.concurrency)
49            || !(100..=60000).contains(&self.poll_interval_ms)
50            || !(3..=86400).contains(&self.lease_seconds)
51            || !(1..=3600).contains(&self.shutdown_timeout_seconds)
52        {
53            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()));
54        }
55        Ok(())
56    }
57}