-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
249 lines (214 loc) · 7.7 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use std::fmt::Display;
use std::time::Duration;
use async_trait::async_trait;
use chrono::TimeDelta;
use rexecutor::prelude::*;
use rexecutor_sqlx::RexecutorPgBackend;
const DEFAULT_DATABASE_URL: &str = "postgresql://postgres:postgres@localhost:5432/postgres";
const DATABASE_URL: &str = "DATABASE_URL";
#[tokio::main]
pub async fn main() {
let db_url = std::env::var(DATABASE_URL).unwrap_or_else(|_| DEFAULT_DATABASE_URL.to_owned());
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
let pruner_config = PrunerConfig::new("0/2 * * * * *".try_into().unwrap())
.with_pruner(Pruner::max_length(20, JobStatus::Complete).only::<CronJob>())
.with_pruner(Pruner::max_age(TimeDelta::days(1), JobStatus::Complete).except::<CronJob>())
.with_pruners([
Pruner::max_age(TimeDelta::days(2), JobStatus::Discarded),
Pruner::max_age(TimeDelta::days(2), JobStatus::Cancelled),
]);
let every_second = cron::Schedule::try_from("* * * * * *").unwrap();
let backend = RexecutorPgBackend::from_db_url(&db_url).await.unwrap();
backend.run_migrations().await.unwrap();
// let backend = rexecutor::backend::memory::InMemoryBackend::default();
let _guard = Rexecutor::new(backend)
.with_executor::<BasicJob>()
.with_executor::<TimeoutJob>()
.with_executor::<CancelledJob>()
.with_executor::<SnoozeJob>()
.with_executor::<FlakyJob>()
.with_cron_executor::<CronJob>(every_second.clone(), "tick".to_owned())
.with_cron_executor::<CronJob>(every_second, "tock".to_owned())
.with_job_pruner(pruner_config)
.set_global_backend()
.unwrap()
.drop_guard();
let job_id = BasicJob::builder()
.with_max_attempts(3)
.with_tags(vec!["initial_job"])
.with_data("First job".into())
.with_metadata("Delayed attempt".into())
.schedule_in(TimeDelta::seconds(2))
.enqueue()
.await
.unwrap();
println!("Inserted job {job_id}");
let job_id_2 = BasicJob::builder()
.with_max_attempts(2)
.add_tag("second_job")
.add_tag("running_again")
.with_data("Second job".into())
.with_priority(2)
.enqueue()
.await
.unwrap();
println!("Inserted job {job_id_2}");
let job_id = FlakyJob::builder()
.with_max_attempts(3)
.with_tags(vec!["flaky_job"])
.with_data("Flaky job".into())
.schedule_in(TimeDelta::seconds(1))
.enqueue()
.await
.unwrap();
println!("Inserted job {job_id}");
let job_id = FlakyJob::builder()
.with_data("Discarded job".into())
.enqueue()
.await
.unwrap();
println!("Inserted job {job_id}");
let job_id = TimeoutJob::builder().with_data(15).enqueue().await.unwrap();
println!("Inserted job {job_id}");
let job_id = CancelledJob::builder().enqueue().await.unwrap();
println!("Inserted job {job_id}");
let job_id = SnoozeJob::builder().enqueue().await.unwrap();
println!("Inserted job {job_id}");
// Based on the uniqueness criteria of the job this will override the priority.
let job_id = SnoozeJob::builder()
.with_priority(42)
.enqueue()
.await
.unwrap();
println!("Inserted job {job_id}");
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
BasicJob::rerun_job(job_id_2).await.unwrap();
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
let recent_jobs = BasicJob::query_jobs(
Where::tagged_by_one_of(&["second_job", "initial_job"])
.and(!Where::status_equals(JobStatus::Discarded))
.and(!Where::status_equals(JobStatus::Cancelled))
.and(Where::scheduled_at_within_the_last(TimeDelta::minutes(10))),
)
.await
.unwrap();
assert!(recent_jobs.len() >= 2);
}
struct BasicJob;
#[async_trait]
impl Executor for BasicJob {
type Data = String;
type Metadata = String;
const NAME: &'static str = "basic_job";
const MAX_ATTEMPTS: u16 = 2;
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {}", Self::NAME, job.data);
ExecutionResult::Done
}
}
struct FlakyJob;
#[derive(Debug)]
struct FlakyJobError;
impl Display for FlakyJobError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for FlakyJobError {}
impl ExecutionError for FlakyJobError {
fn error_type(&self) -> &'static str {
"network_error"
}
}
#[async_trait]
impl Executor for FlakyJob {
type Data = String;
type Metadata = ();
const NAME: &'static str = "flaky_job";
const MAX_ATTEMPTS: u16 = 1;
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {}", Self::NAME, job.data);
match job.attempt {
1 => panic!("Terrible things happened"),
2 => FlakyJobError.into(),
_ => ExecutionResult::Done,
}
}
fn backoff(job: &Job<Self::Data, Self::Metadata>) -> TimeDelta {
BackoffStrategy::constant(TimeDelta::seconds(1))
.with_jitter(Jitter::Relative(0.5))
.backoff(job.attempt)
}
}
struct TimeoutJob;
#[async_trait]
impl Executor for TimeoutJob {
type Data = u64;
type Metadata = ();
const NAME: &'static str = "timeout_job";
const MAX_ATTEMPTS: u16 = 3;
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {}", Self::NAME, job.data);
tokio::time::sleep(Duration::from_millis(job.data)).await;
ExecutionResult::Done
}
fn backoff(job: &Job<Self::Data, Self::Metadata>) -> TimeDelta {
BackoffStrategy::linear(TimeDelta::seconds(1))
.with_jitter(Jitter::Absolute(TimeDelta::milliseconds(500)))
.backoff(job.attempt)
}
fn timeout(job: &Job<Self::Data, Self::Metadata>) -> Option<Duration> {
Some(Duration::from_millis(10 * job.attempt as u64))
}
}
struct CancelledJob;
#[async_trait]
impl Executor for CancelledJob {
type Data = ();
type Metadata = ();
const NAME: &'static str = "cancel_job";
const MAX_ATTEMPTS: u16 = 1;
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {:?}", Self::NAME, job.data);
ExecutionResult::Cancel {
reason: Box::new("Didn't like the job"),
}
}
}
struct SnoozeJob;
#[async_trait]
impl Executor for SnoozeJob {
type Data = ();
type Metadata = ();
const NAME: &'static str = "snooze_job";
const MAX_ATTEMPTS: u16 = 1;
const UNIQUENESS_CRITERIA: Option<UniquenessCriteria<'static>> = Some(
UniquenessCriteria::by_executor()
.and_within(TimeDelta::seconds(60))
.on_conflict(Replace::priority().for_statuses(&JobStatus::ALL)),
);
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {:?}", Self::NAME, job.data);
if (job.scheduled_at - job.inserted_at).num_seconds() < 1 {
ExecutionResult::Snooze {
delay: TimeDelta::seconds(1),
}
} else {
ExecutionResult::Done
}
}
}
struct CronJob;
#[async_trait]
impl Executor for CronJob {
type Data = String;
type Metadata = ();
const NAME: &'static str = "cron_job";
const MAX_ATTEMPTS: u16 = 1;
async fn execute(job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
println!("{} running, with args: {:?}", Self::NAME, job.data);
ExecutionResult::Done
}
}