Skip to main content

capy_jobs/
lib.rs

1//! Durable, at-least-once application jobs. Handlers must be idempotent.
2//!
3//! Jobs use stable explicit names and versions, JSON payloads and the application's
4//! native SeaORM connection/transaction. No worker runs inside HTTP implicitly.
5pub mod migration;
6mod registry;
7mod storage;
8mod worker;
9
10pub use capy_core::JobsSettings;
11use capy_core::{AppConfig, AppContext};
12pub use registry::{JobEvent, JobObservation, JobObserver, Jobs};
13use serde::{de::DeserializeOwned, Serialize};
14use std::{future::Future, sync::Arc, time::Duration};
15pub use storage::{FailedJob, Queue, QueueName};
16pub use worker::Worker;
17
18/// Handler result with explicit retry/permanent classification.
19pub type JobResult = std::result::Result<(), JobError>;
20
21/// An application-owned job. Persisted names and versions are compatibility APIs.
22pub trait Job: Serialize + DeserializeOwned + Send + 'static {
23    /// Stable name, independent of Rust module paths (ASCII letters/digits/`_-.`).
24    const NAME: &'static str;
25    /// Payload version; register old versions during rolling deployments if needed.
26    const VERSION: u16 = 1;
27    /// Maximum execution attempts, including the first (1..=100).
28    const MAX_ATTEMPTS: u32 = 3;
29    /// Optional cooperative handler deadline; cannot undo external side effects.
30    const TIMEOUT: Option<Duration> = None;
31    /// Delay after a failed attempt: 5s, 30s, 180s, capped at one hour.
32    fn backoff(attempt: u32) -> Duration {
33        Duration::from_secs(
34            5u64.saturating_mul(6u64.saturating_pow(attempt.saturating_sub(1)))
35                .min(3600),
36        )
37    }
38    /// Execute ordinary application code. The returned future must be Send.
39    fn handle(self, ctx: JobContext) -> impl Future<Output = JobResult> + Send;
40}
41
42/// A safe failure summary. Never put secrets, payloads or raw provider errors here.
43#[derive(Clone)]
44pub struct JobError {
45    pub(crate) permanent: bool,
46    pub(crate) category: &'static str,
47    pub(crate) summary: String,
48}
49impl JobError {
50    /// Retry with bounded backoff. The supplied summary is persisted, not logged.
51    pub fn retry(safe_summary: impl Into<String>) -> Self {
52        Self::new(false, "retryable", safe_summary.into())
53    }
54    /// Preserve as a failed job immediately, without another automatic attempt.
55    pub fn permanent(safe_summary: impl Into<String>) -> Self {
56        Self::new(true, "permanent", safe_summary.into())
57    }
58    pub(crate) fn new(permanent: bool, category: &'static str, summary: String) -> Self {
59        Self {
60            permanent,
61            category,
62            summary: summary
63                .chars()
64                .filter(|c| !c.is_control())
65                .take(512)
66                .collect(),
67        }
68    }
69}
70impl std::fmt::Debug for JobError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.write_str(self.category)
73    }
74}
75impl std::fmt::Display for JobError {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.write_str(self.category)
78    }
79}
80impl std::error::Error for JobError {}
81impl From<sea_orm::DbErr> for JobError {
82    fn from(_: sea_orm::DbErr) -> Self {
83        Self::new(false, "database", "Database operation failed".into())
84    }
85}
86impl From<capy_core::AppError> for JobError {
87    fn from(error: capy_core::AppError) -> Self {
88        Self::new(false, error.kind(), "Application operation failed".into())
89    }
90}
91
92/// Application services and safe reservation metadata supplied to a handler.
93#[derive(Clone, Debug)]
94pub struct JobContext {
95    /// The same application configuration used by HTTP.
96    pub config: Arc<AppConfig>,
97    /// Native application pool. Use normal SeaORM transactions as needed.
98    pub db: sea_orm::DatabaseConnection,
99    /// Stable operational UUID, retained across retries. Not a secret.
100    pub job_id: String,
101    /// Current attempt, starting at one.
102    pub attempt: u32,
103}
104
105/// Dispatch access without changing the application's shared context layout.
106pub trait JobDispatch {
107    /// Access the durable default queue, without starting a worker.
108    fn jobs(&self) -> Queue;
109}
110impl JobDispatch for AppContext {
111    fn jobs(&self) -> Queue {
112        Queue::new(self.db.clone())
113    }
114}
115impl JobDispatch for JobContext {
116    fn jobs(&self) -> Queue {
117        Queue::new(self.db.clone())
118    }
119}
120
121pub(crate) fn validate_name(name: &str) -> capy_core::Result<()> {
122    if name.is_empty()
123        || name.len() > 128
124        || !name
125            .bytes()
126            .all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
127    {
128        return Err(capy_core::AppError::Configuration(
129            "Job/queue names require 1..=128 ASCII letters, digits, underscores, dots or hyphens."
130                .into(),
131        ));
132    }
133    Ok(())
134}
135
136pub(crate) fn validate_job<J: Job>() -> capy_core::Result<()> {
137    validate_name(J::NAME)?;
138    if J::VERSION == 0
139        || !(1..=100).contains(&J::MAX_ATTEMPTS)
140        || J::TIMEOUT.is_some_and(|d| d.is_zero() || d > Duration::from_secs(86400 * 7))
141    {
142        return Err(capy_core::AppError::Configuration("Jobs require VERSION >= 1, MAX_ATTEMPTS 1..=100 and optional TIMEOUT > 0 and <= 7 days.".into()));
143    }
144    Ok(())
145}
146
147#[cfg(test)]
148mod tests;