1pub 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
18pub type JobResult = std::result::Result<(), JobError>;
20
21pub trait Job: Serialize + DeserializeOwned + Send + 'static {
23 const NAME: &'static str;
25 const VERSION: u16 = 1;
27 const MAX_ATTEMPTS: u32 = 3;
29 const TIMEOUT: Option<Duration> = None;
31 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 fn handle(self, ctx: JobContext) -> impl Future<Output = JobResult> + Send;
40}
41
42#[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 pub fn retry(safe_summary: impl Into<String>) -> Self {
52 Self::new(false, "retryable", safe_summary.into())
53 }
54 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#[derive(Clone, Debug)]
94pub struct JobContext {
95 pub config: Arc<AppConfig>,
97 pub db: sea_orm::DatabaseConnection,
99 pub job_id: String,
101 pub attempt: u32,
103}
104
105pub trait JobDispatch {
107 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;