1pub 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
20pub type JobResult = std::result::Result<(), JobError>;
22
23pub trait Job: Serialize + DeserializeOwned + Send + 'static {
25 const NAME: &'static str;
27 const VERSION: u16 = 1;
29 const MAX_ATTEMPTS: u32 = 3;
31 const TIMEOUT: Option<Duration> = None;
33 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 fn handle(self, ctx: JobContext) -> impl Future<Output = JobResult> + Send;
42}
43
44#[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 pub fn retry(safe_summary: impl Into<String>) -> Self {
54 Self::new(false, "retryable", safe_summary.into())
55 }
56 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#[derive(Clone, Debug)]
102pub struct JobContext {
103 pub config: Arc<AppConfig>,
105 pub db: sea_orm::DatabaseConnection,
107 pub services: Services,
109 pub job_id: String,
111 pub attempt: u32,
113}
114
115impl JobContext {
116 pub fn service<T: Send + Sync + 'static>(&self) -> capy_core::Result<Arc<T>> {
118 self.services.get::<T>()
119 }
120 #[cfg(feature = "storage")]
122 pub fn storage(&self) -> capy_core::Result<Arc<capy_storage::Storage>> {
123 self.service::<capy_storage::Storage>()
124 }
125}
126
127pub trait JobDispatch {
129 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
172pub trait TransactionalJobDispatch {
175 fn jobs(&self) -> TransactionalQueue<'_>;
177}
178impl TransactionalJobDispatch for capy_core::EventContext<'_> {
179 fn jobs(&self) -> TransactionalQueue<'_> {
180 TransactionalQueue::new(self.transaction)
181 }
182}