1use super::*;
2
3pub struct Job {
5 pub id: uuid::Uuid,
7 pub fingerprint: Option<String>,
10 pub unique_key: Option<String>,
13 pub queue: String,
15 pub job_data: serde_json::Value,
17 pub status: String,
19 pub created_at: chrono::DateTime<chrono::Utc>,
21 pub run_at: Option<chrono::DateTime<chrono::Utc>>,
23 pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
25 pub attempt: i32,
27 pub max_attempts: i32,
29 pub(crate) reprocess_count: i32,
30}
31impl std::fmt::Debug for Job {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 f.debug_struct("Job")
34 .field("id", &self.id)
35 .field("fingerprint", &self.fingerprint)
36 .field("unique_key", &self.unique_key)
37 .field("queue", &self.queue)
38 .field("status", &self.status)
39 .field("created_at", &self.created_at)
40 .field("attempt", &self.attempt)
41 .field("max_attempts", &self.max_attempts)
42 .finish()
43 }
44}
45impl Default for Job {
46 fn default() -> Self {
47 Self {
48 id: uuid::Uuid::new_v4(),
49 fingerprint: None,
50 unique_key: None,
51 queue: "default".into(),
52 job_data: serde_json::Value::default(),
53 status: result::JobResultInternal::Pending.to_string(),
54 created_at: chrono::Utc::now(),
55 run_at: None,
56 updated_at: None,
57 attempt: 0,
58 max_attempts: 3,
59 reprocess_count: 0,
60 }
61 }
62}
63
64impl Job {
65 pub fn new<T: serde::Serialize + serde::de::DeserializeOwned>(
67 queue: &'static str,
68 job_data: T,
69 ) -> Self {
70 Self {
71 queue: queue.to_string(),
72 job_data: serde_json::to_value(job_data).unwrap_or_default(),
73 ..Default::default()
74 }
75 }
76 pub fn with_unique_key(self, unique_key: impl Into<String>) -> Self {
78 Self {
79 unique_key: Some(unique_key.into()),
80 ..self
81 }
82 }
83 pub fn with_run_at(self, run_at: chrono::DateTime<chrono::Utc>) -> Self {
85 Self {
86 run_at: Some(run_at),
87 ..self
88 }
89 }
90 pub fn with_max_attempts(self, max_attempts: i32) -> Self {
92 Self {
93 max_attempts,
94 ..self
95 }
96 }
97 pub fn with_fingerprint(self, fingerprint: impl Into<String>) -> Self {
99 Self {
100 fingerprint: Some(fingerprint.into()),
101 ..self
102 }
103 }
104}
105
106pub trait JobExt<T> {
107 fn into_job(self, queue: &'static str) -> Job;
108}
109
110impl<T: serde::Serialize + serde::de::DeserializeOwned> JobExt<T> for T {
111 fn into_job(self, queue: &'static str) -> Job {
112 Job::new(queue, self)
113 }
114}