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