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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use crate::errors::{TaskError, TaskResult};
use crate::retry::RetryPolicy;
use crate::task::{
boxed_callback, CallbackFn, Task, TaskStep, TaskStepStatusErr, TaskStepStatusOk,
};
use chrono::TimeZone;
use cron::Schedule;
use std::future::Future;
use std::time::Duration;
/// Task builder function.
///
/// Used to generate/build a `TaskStep` instance.
pub struct TaskBuilder<T>
where
T: TimeZone + Send + 'static,
{
/// An optional task description.
description: Option<String>,
/// The provided `TaskStep` vector.
steps: Vec<TaskStep>,
/// The provided `Schedule`, if not given,
/// it will be defaulted to once every hour.
schedule: Option<Schedule>,
/// The original expression string, for error reporting
expression: String,
/// Max number of repeats.
repeats: Option<usize>,
/// (Optional) per-step execution timeout.
timeout: Option<Duration>,
/// (Optional) retry policy for failing steps.
retry_policy: Option<RetryPolicy>,
/// (Optional) callback invoked after a successful execution.
on_success: Option<Box<CallbackFn>>,
/// (Optional) callback invoked after a failed execution.
on_failure: Option<Box<CallbackFn>>,
/// (Optional) callback invoked once the task reaches a terminal state.
on_finish: Option<Box<CallbackFn>>,
/// The Task/Scheduler timezone.
timezone: T,
}
impl<T> TaskBuilder<T>
where
T: TimeZone + Send + 'static,
{
/// Create a new `TaskBuilder` instance.
///
/// # Arguments
///
/// * timezone - A valid timezone for the generated `Task`.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task_builder = TaskBuilder::new(chrono::Utc);
/// ```
pub fn new(timezone: T) -> TaskBuilder<T> {
TaskBuilder {
steps: Vec::new(),
description: None,
schedule: None,
expression: "* * * * * * *".to_string(), // Default expression
repeats: None,
timeout: None,
retry_policy: None,
on_success: None,
on_failure: None,
on_finish: None,
timezone,
}
}
/// Set the optional description of the generated `Task`.
///
/// # Arguments
///
/// - description - A description for the task.
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local).every("* * * * * * *").description("Description").build().unwrap();
/// ```
pub fn description(mut self, description: &str) -> TaskBuilder<T> {
self.description = Some(description.to_string());
self
}
/// Set the execution schedule of the task to be generated.
///
/// # Arguments
///
/// * expression - A valid cron expression.
///
/// # Examples
///
/// ```rust
/// # use tasklet::{TaskBuilder, Task};
/// let _task = TaskBuilder::new(chrono::Local).every("* * * * * * *").build().unwrap();
/// ```
pub fn every(mut self, expression: &str) -> TaskBuilder<T> {
self.expression = expression.to_string();
match expression.parse() {
Ok(schedule) => {
self.schedule = Some(schedule);
}
Err(_) => {
// We'll validate at build time
self.schedule = None;
}
};
self
}
/// Set the max repeats for the generated `Task`.
///
/// # Arguments
///
/// * repeats - The max amount of repeats.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local).repeat(5);
/// ```
pub fn repeat(mut self, repeat: usize) -> TaskBuilder<T> {
self.repeats = Some(repeat);
self
}
/// Set a per-step execution timeout for the generated `Task`.
///
/// A step whose future does not resolve within `timeout` is cancelled and
/// treated as a (retryable) failure.
///
/// # Arguments
///
/// * timeout - The maximum duration allowed for a single step attempt.
///
/// # Examples
///
/// ```rust
/// # use std::time::Duration;
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local)
/// .every("* * * * * * *")
/// .timeout(Duration::from_secs(5))
/// .build()
/// .unwrap();
/// ```
pub fn timeout(mut self, timeout: Duration) -> TaskBuilder<T> {
self.timeout = Some(timeout);
self
}
/// Set the retry policy applied to failing steps of the generated `Task`.
///
/// Only steps returning [`TaskStepStatusErr::Error`] (or timing out) are retried;
/// [`TaskStepStatusErr::ErrorDelete`] bypasses retries.
///
/// # Arguments
///
/// * policy - The [`RetryPolicy`] to apply.
///
/// # Examples
///
/// ```rust
/// # use std::time::Duration;
/// # use tasklet::{RetryPolicy, TaskBuilder};
/// let _task = TaskBuilder::new(chrono::Local)
/// .every("* * * * * * *")
/// .retry(RetryPolicy::fixed(3, Duration::from_millis(100)))
/// .build()
/// .unwrap();
/// ```
pub fn retry(mut self, policy: RetryPolicy) -> TaskBuilder<T> {
self.retry_policy = Some(policy);
self
}
/// Register a callback invoked after each successful execution of the task.
///
/// # Arguments
///
/// * callback - An async closure invoked when a run completes successfully.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local)
/// .every("* * * * * * *")
/// .on_success(|| async { println!("task succeeded"); })
/// .build()
/// .unwrap();
/// ```
pub fn on_success<F, Fut>(mut self, callback: F) -> TaskBuilder<T>
where
F: (FnMut() -> Fut) + 'static + Send,
Fut: Future<Output = ()> + Send + 'static,
{
self.on_success = Some(boxed_callback(callback));
self
}
/// Register a callback invoked after a failed execution of the task.
///
/// # Arguments
///
/// * callback - An async closure invoked when a run fails.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local)
/// .every("* * * * * * *")
/// .on_failure(|| async { eprintln!("task failed"); })
/// .build()
/// .unwrap();
/// ```
pub fn on_failure<F, Fut>(mut self, callback: F) -> TaskBuilder<T>
where
F: (FnMut() -> Fut) + 'static + Send,
Fut: Future<Output = ()> + Send + 'static,
{
self.on_failure = Some(boxed_callback(callback));
self
}
/// Register a callback invoked once when the task reaches a terminal state
/// (its repeat cycle is exhausted or it is force-removed).
///
/// # Arguments
///
/// * callback - An async closure invoked when the task finishes.
///
/// # Examples
///
/// ```rust
/// # use tasklet::TaskBuilder;
/// let _task = TaskBuilder::new(chrono::Local)
/// .every("* * * * * * *")
/// .repeat(1)
/// .on_finish(|| async { println!("task finished"); })
/// .build()
/// .unwrap();
/// ```
pub fn on_finish<F, Fut>(mut self, callback: F) -> TaskBuilder<T>
where
F: (FnMut() -> Fut) + 'static + Send,
Fut: Future<Output = ()> + Send + 'static,
{
self.on_finish = Some(boxed_callback(callback));
self
}
/// Add a new step for the generated task.
///
/// # Arguments
///
/// * description - An optional description for the task's step.
/// * function - The executable body of the task's step.
///
/// # Examples
///
/// ```rust
/// # use tasklet::task::TaskStepStatusErr::Error;
/// # use tasklet::TaskBuilder;
/// let _ = TaskBuilder::new(chrono::Utc).add_step("A step that fails.", || async { Err(Error) });
/// ```
pub fn add_step<F, Fut>(mut self, description: &str, function: F) -> TaskBuilder<T>
where
F: (FnMut() -> Fut) + Send + 'static,
Fut: std::future::Future<Output = Result<TaskStepStatusOk, TaskStepStatusErr>>
+ Send
+ 'static,
{
self.steps.push(TaskStep::new(description, function));
self
}
/// Add a new step to the generated task (without description).
///
/// # Arguments
///
/// * function - The executable body of the task's step.
///
/// ```
/// # use tasklet::task::TaskStepStatusOk::Success;
/// use tasklet::TaskBuilder;
/// let _ = TaskBuilder::new(chrono::Local).add_step_default(|| async { Ok(Success) });
/// ```
pub fn add_step_default<F, Fut>(mut self, function: F) -> TaskBuilder<T>
where
F: (FnMut() -> Fut) + 'static + Send,
Fut: std::future::Future<Output = Result<TaskStepStatusOk, TaskStepStatusErr>>
+ Send
+ 'static,
{
self.steps.push(TaskStep::default(function));
self
}
/// Build a new `Task` instance from the current configuration.
///
/// # Examples
///
/// ```rust
/// # use tasklet::{TaskBuilder, Task};
/// let mut _task = TaskBuilder::new(chrono::Utc).build().unwrap();
/// ```
pub fn build(self) -> TaskResult<Task<T>> {
// Validate schedule if provided
let schedule = match self.schedule {
Some(s) => s,
None => {
// Try to parse the expression
self.expression.parse().map_err(|e| {
TaskError::InvalidCronExpression(format!(
"Invalid cron expression '{}': {}",
self.expression, e
))
})?
}
};
// Create the task with default expression - we'll replace the schedule after
let mut task = Task::new(
"* * * * * * *", // This is just a placeholder, we'll set the real schedule next
self.description.as_deref(),
self.repeats,
self.timezone,
)?;
// Set the validated schedule
task.set_schedule(schedule);
// Set the steps
task.set_steps(self.steps);
// Transfer the optional timeout / retry configuration.
if let Some(timeout) = self.timeout {
task.set_timeout(timeout);
}
if let Some(policy) = self.retry_policy {
task.set_retry_policy(policy);
}
// Transfer the lifecycle callbacks.
task.set_callbacks(self.on_success, self.on_failure, self.on_finish);
Ok(task)
}
}
/// Module's tests.
#[cfg(test)]
mod test {
use super::*;
use crate::task::TaskStepStatusOk::Success;
/// Test helper macros.
///
/// Assert a given list of `Option<>` is `None`.
macro_rules! assert_none {
($x:expr) => (assert_eq!($x.is_some(), false););
($x:expr, $($y:expr),+) => (
assert_none!($x);
assert_none!($($y),+);
);
}
/// Test helper macros.
///
/// Assert a given list of `Option<>` is `Some`
macro_rules! assert_some {
($x:expr) => (assert_eq!($x.is_some(), true););
($x:expr, $($y:expr),+) => (
assert_some!($x);
assert_some!($($y),+);
);
}
/// Test the normal initialization of a `TaskBuilder`.
#[test]
pub fn test_task_builder_init() {
let builder = TaskBuilder::new(chrono::Utc);
assert_none!(builder.repeats);
assert_eq!(builder.steps.len(), 0);
assert_eq!(builder.timezone, chrono::Utc);
}
/// Test the normal functionality of the description() function of `TaskBuilder`.
#[test]
pub fn test_task_builder_with_description() {
let builder = TaskBuilder::new(chrono::Utc).description("Some description");
assert_none!(builder.repeats);
assert_eq!(builder.steps.len(), 0);
assert_some!(builder.description);
assert_eq!(builder.timezone, chrono::Utc);
}
/// Test the normal initialization of a task with a schedule.
#[test]
pub fn test_task_builder_with_schedule() {
let builder = TaskBuilder::new(chrono::Utc).every("* * * * * * *");
assert_eq!(builder.timezone, chrono::Utc);
assert_none!(builder.repeats, builder.description);
assert_eq!(builder.steps.len(), 0);
assert_some!(builder.schedule);
}
/// Test the normal functionality of the repeat() function of the `TaskBuilder`.
#[test]
pub fn test_task_builder_repeat() {
let builder = TaskBuilder::new(chrono::Utc).repeat(5);
assert_eq!(builder.timezone, chrono::Utc);
assert_eq!(builder.steps.len(), 0);
assert_some!(builder.repeats);
}
/// Test the normal functionality of the add_step() function of the `TaskBuilder`.
#[test]
pub fn test_task_builder_add_step() {
let builder = TaskBuilder::new(chrono::Utc).add_step_default(|| async { Ok(Success) });
assert_eq!(builder.timezone, chrono::Utc);
assert_eq!(builder.steps.len(), 1);
}
/// Test the normal functionality of build() function of the `TaskBuilder`.
#[test]
pub fn test_task_builder_build() {
let task = TaskBuilder::new(chrono::Utc)
.every("* * * * * * *")
.repeat(5)
.description("Some description")
.add_step("Step 1", || async { Ok(Success) })
.build()
.unwrap();
assert_some!(task.repeats);
assert_eq!(task.description, "Some description");
assert_eq!(task.timezone, chrono::Utc);
assert_eq!(task.steps.len(), 1);
}
/// Test the normal functionality of build() function of the `TaskBuilder`.
#[test]
pub fn test_task_builder_build_default() {
let task = TaskBuilder::new(chrono::Utc)
.repeat(5)
.add_step("Step 1", || async { Ok(Success) })
.build()
.unwrap();
assert_some!(task.repeats);
assert_eq!(task.timezone, chrono::Utc);
assert_eq!(task.steps.len(), 1);
}
/// Test building with an invalid cron expression
#[test]
pub fn test_task_builder_invalid_expression() {
let result = TaskBuilder::new(chrono::Utc)
.every("invalid expression")
.build();
assert!(result.is_err());
}
#[test]
fn test_task_builder_invalid_schedule() {
// Test with valid schedule
let result = TaskBuilder::new(chrono::Utc).every("* * * * * * *").build();
assert!(result.is_ok());
// Test with invalid schedule
let result = TaskBuilder::new(chrono::Utc).every("invalid cron").build();
assert!(result.is_err());
// Test that the error is the correct type
match result {
Err(TaskError::InvalidCronExpression(_)) => {} // Expected
_ => panic!("Expected InvalidCronExpression error"),
}
}
}