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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
extern crate chrono;
extern crate cron;
use crate::errors::{TaskError, TaskResult};
use crate::{step_log, task_log};
use chrono::TimeZone;
use chrono::{DateTime, Utc};
use cron::Schedule;
use std::fmt::{self, Debug};
use tokio::sync::{mpsc, oneshot};
/// Possible success status values for a step's execution.
#[derive(Debug, Clone, PartialEq)]
pub enum TaskStepStatusOk {
/// The step was a success, move to the next one (or exit if last).
Success,
/// The step execution had errors but can continue the execution.
HadErrors,
}
/// Possible error status values for a step's execution.
#[derive(Debug, Clone, PartialEq)]
pub enum TaskStepStatusErr {
/// The task step execution failed.
Error,
/// The step failed and the task has to be removed from the execution list.
ErrorDelete,
}
/// An executable function.
pub type ExecutableFn = dyn FnMut() -> Result<TaskStepStatusOk, TaskStepStatusErr> + 'static + Send;
/// A task step.
///
/// Contains the executable body and an optional short description.
pub struct TaskStep {
/// The function's body.
pub(crate) function: Box<ExecutableFn>,
/// An (optional) short description.
pub(crate) description: Option<String>,
}
impl fmt::Display for TaskStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.description {
Some(desc) if !desc.is_empty() => write!(f, "{}", desc),
_ => write!(f, "-"),
}
}
}
impl TaskStep {
/// Default constructor.
///
/// # Arguments
///
/// * description - a description for the task step
/// * function - the executable body of the function
///
/// # Examples
///
/// ```
/// # use tasklet::task::{TaskStep, TaskStepStatusOk};
/// let _ = TaskStep::new("Some task", || Ok(TaskStepStatusOk::Success));
/// ```
pub fn new<F>(description: &str, function: F) -> Self
where
F: (FnMut() -> Result<TaskStepStatusOk, TaskStepStatusErr>) + 'static + Send,
{
Self {
description: Some(description.to_string()),
function: Box::new(function),
}
}
/// Default constructor for a task step without a provided description.
///
/// # Arguments
///
/// *function -> the executable function body
///
/// # Examples
///
/// ```
/// # use tasklet::task::TaskStep;
/// use tasklet::task::TaskStepStatusOk::Success;
/// let _ = TaskStep::default(|| {Ok(Success)});
/// ```
pub fn default<F>(function: F) -> Self
where
F: (FnMut() -> Result<TaskStepStatusOk, TaskStepStatusErr>) + 'static + Send,
{
Self {
function: Box::new(function),
description: None,
}
}
}
/// Available task statuses.
#[derive(Debug, PartialEq, Default, Clone)]
pub enum Status {
#[default]
/// The task is not initialized yet.
Init,
/// The task has been scheduled and pending execution.
Scheduled,
/// The task has executed but has failed.
Failed,
/// The task has executed successfully.
Executed,
/// The task has finished and can be removed from the queue.
Finished,
/// The task is forcibly removed from the execution list due to fatal error.
ForceRemoved,
}
/// A message response from a task
#[derive(Debug)]
pub(crate) struct TaskResponse {
/// The id of the task as set by the scheduler
pub id: usize,
/// The status after the request has been fulfilled
pub status: Status,
}
#[derive(Debug)]
/// Available commands to be sent
pub(crate) enum TaskCmd {
/// Request to initialize the task
Init {
sender: oneshot::Sender<TaskResponse>,
},
/// Execute the task
Run {
sender: oneshot::Sender<TaskResponse>,
},
/// Request the rescheduling of the task
Reschedule {
sender: oneshot::Sender<TaskResponse>,
},
}
/// A structure that contains the basic information of the job.
pub struct Task<T>
where
T: TimeZone + Send + 'static,
{
/// Task's executable tasks.
pub(crate) steps: Vec<TaskStep>,
/// The execution schedule.
pub(crate) schedule: Schedule,
/// Total number of executions, if `None` then it will run forever.
pub(crate) repeats: Option<usize>,
/// (Optional) Task's description.
pub(crate) description: String,
/// The timezone of the task.
pub(crate) timezone: T,
/// (Internal) task id.
pub(crate) task_id: usize,
/// (Internal) next execution time.
pub(crate) next_exec: Option<DateTime<T>>,
/// (Internal) task status.
pub(crate) status: Status,
/// Task receiver
pub(crate) receiver: Option<mpsc::Receiver<TaskCmd>>,
}
unsafe impl<T> Send for Task<T> where T: TimeZone + Send + 'static {}
impl<T> Debug for Task<T>
where
T: TimeZone + Send + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Task")
.field("task_id", &self.task_id)
.field("description", &self.description)
.field("status", &self.status)
.field("repeats", &self.repeats)
.field("next_exec", &self.next_exec)
.finish()
}
}
impl<T> Task<T>
where
T: TimeZone + Send + 'static,
{
/// Create a new instance of type `Task`.
///
/// # Arguments
///
/// * expression - A valid cron expression.
/// * description - (Optional) description.
/// * repeats - maximum number of repeats, if `None` this task will run forever.
/// * timezone - The tasks' timezone.
///
/// # Examples
///
/// ```
/// # use tasklet::Task;
/// // Create a new task instance. This task will execute every second for 5 times.
/// let _task = Task::new("* * * * * * * ", Some("Runs every second!"), Some(5), chrono::Utc);
/// ```
/// ```
/// # use tasklet::Task;
/// // Create a new task instance. This task will run on second 30 of each minute forever.
/// let _task_1 = Task::new("30 * * * * * *", Some("Runs every second 30 of a minute!"), None, chrono::Local);
/// ```
pub fn new(
expression: &str,
description: Option<&str>,
repeats: Option<usize>,
timezone: T,
) -> TaskResult<Task<T>> {
// Parse the schedule with proper error handling
let schedule = expression.parse().map_err(|e| {
TaskError::InvalidCronExpression(format!("Invalid cron expression: {}", e))
})?;
Ok(Task {
steps: Vec::new(),
schedule,
description: match description {
Some(s) => s.to_string(),
None => "-".to_string(),
},
repeats,
timezone,
task_id: 0,
status: Status::default(),
next_exec: None,
receiver: None,
})
}
/// Set the receiver for the task.
pub(crate) fn set_receiver(&mut self, receiver: mpsc::Receiver<TaskCmd>) {
self.receiver = Some(receiver);
}
/// Set the task id of the current task.
///
/// # Arguments
///
/// * id - the id of the task
///
/// # Examples
///
/// ```
/// # use chrono::Utc;
/// # use tasklet::task::Task;
///
/// let mut t = Task::new("* * * * * *", None, None, Utc).unwrap();
/// t.set_id(0);
/// ```
pub fn set_id(&mut self, id: usize) {
self.task_id = id;
}
/// Add a new `TaskStep` in the `Task`.
///
/// # Arguments
///
/// * description - A short task step description (Optional).
/// * function - The executable function.
#[cfg(test)]
pub(crate) fn add_step<F>(&mut self, description: &str, function: F) -> &mut Task<T>
where
F: (FnMut() -> Result<TaskStepStatusOk, TaskStepStatusErr>) + 'static + Send,
{
self.steps.push(TaskStep::new(description, function));
self
}
/// Add a new `TaskStep` in the `Task` without a provided name/description.
///
/// # Arguments
///
/// * function - the executable function
#[cfg(test)]
pub(crate) fn add_step_default<F>(&mut self, function: F) -> &mut Task<T>
where
F: (FnMut() -> Result<TaskStepStatusOk, TaskStepStatusErr>) + 'static + Send,
{
self.steps.push(TaskStep::default(function));
self
}
/// Set the value of the steps vector.
///
/// # Arguments
///
/// * steps - A vector that contains the executable steps.
pub(crate) fn set_steps(&mut self, steps: Vec<TaskStep>) -> &mut Task<T> {
self.steps = steps;
self
}
/// Set the value of `schedule` property.
///
/// # Arguments
///
/// * schedule - The schedule.
pub(crate) fn set_schedule(&mut self, schedule: Schedule) -> &mut Task<T> {
self.schedule = schedule;
self
}
/// Initialize the `Task` instance and schedule the first execution.
///
/// # Arguments
///
/// * id - The task's id.
pub(crate) fn init(&mut self) {
task_log!(self.task_id, log::Level::Debug, "Initializing");
self.next_exec = Some(
self.schedule
.upcoming(self.timezone.clone())
.next()
.unwrap(),
);
self.status = Status::Scheduled;
task_log!(self.task_id, log::Level::Debug, "Finished initializing");
}
/// Create a `TaskResponse` from the current state of the task.
fn get_task_response(&self) -> TaskResponse {
TaskResponse {
id: self.task_id,
status: self.status.clone(),
}
}
/// Execute a command sent by the scheduler.
///
/// Each of the commands triggers the underlying method of the task,
/// and responds with the id of the task and the status of the task after the execution
/// of the command has finished.
pub(crate) fn execute_command(&mut self, msg: TaskCmd) {
match msg {
TaskCmd::Run { sender } => {
if self.next_exec.as_ref().unwrap()
<= &Utc::now().with_timezone(&self.timezone.clone())
{
let _ = self.run_task(); // Ignore the result as we already update the status
}
let _ = sender.send(self.get_task_response());
}
TaskCmd::Reschedule { sender } => {
let _ = self.reschedule(); // Ignore the result as we already update the status
let _ = sender.send(self.get_task_response());
}
TaskCmd::Init { sender } => {
if self.status == Status::Init {
self.init();
}
let _ = sender.send(self.get_task_response());
}
}
}
/// Run the task and handle the output.
pub(crate) fn run_task(&mut self) -> TaskResult<()> {
match &self.status {
Status::Init => Err(TaskError::NotInitialized),
Status::Failed => Err(TaskError::Failed),
Status::Executed => Err(TaskError::AlreadyExecuted),
Status::Finished => Err(TaskError::Finished),
Status::ForceRemoved => Err(TaskError::ForceRemoved),
Status::Scheduled => {
task_log!(
self.task_id,
log::Level::Debug,
"Executing '{}'",
self.description
);
let mut had_error: bool = false;
for (index, step) in self.steps.iter_mut().enumerate() {
if !had_error {
match (step.function)() {
Ok(status) => {
match status {
TaskStepStatusOk::Success => step_log!(
self.task_id,
index,
log::Level::Debug,
"Executed successfully - {}",
step
),
TaskStepStatusOk::HadErrors => step_log!(
self.task_id,
index,
log::Level::Debug,
"Executed with non-fatal errors - {}",
step
),
}
self.status = Status::Executed
}
Err(status) => {
// Indicate that there was an error.
had_error = true;
match status {
TaskStepStatusErr::Error => {
step_log!(
self.task_id,
index,
log::Level::Error,
"Execution failed - {}",
step
);
self.status = Status::Failed
}
TaskStepStatusErr::ErrorDelete => {
step_log!(
self.task_id,
index,
log::Level::Error,
"Execution failed and task is marked for deletion - {}",
step
);
self.status = Status::ForceRemoved
}
}
}
};
}
}
// Avoid underflow in case of a task without steps.
if self.steps.is_empty() {
self.status = Status::Executed
}
// Reduce the total executions (if set).
self.repeats = self.repeats.map(|r| r - 1);
Ok(())
}
}
}
/// Reschedule the current task instance (if needed).
pub(crate) fn reschedule(&mut self) -> TaskResult<()> {
match &self.status {
Status::Init => Err(TaskError::NotInitialized),
Status::Failed | Status::Executed => {
self.next_exec = Some(
self.schedule
.upcoming(self.timezone.clone())
.next()
.unwrap(),
);
self.status = match self.repeats {
Some(t) => {
if t > 0 {
task_log!(self.task_id, log::Level::Debug, "Has been rescheduled");
Status::Scheduled
} else {
task_log!(
self.task_id,
log::Level::Warn,
"Has finished its execution cycle and will be removed"
);
Status::Finished
}
}
None => Status::Scheduled,
};
Ok(())
}
Status::Finished | Status::ForceRemoved => {
task_log!(
self.task_id,
log::Level::Warn,
"Will be removed from the queue"
);
Ok(())
}
Status::Scheduled => Ok(()), /* Do nothing, keep silent */
}
}
}
/// Wrap a `Task` around a receiver, each time a command is received, forward it to the task.
///
/// # Arguments
///
/// * task - the task to run in the background
///
/// # Examples
///
/// ```
/// # use chrono::Utc;
/// # use tasklet::task::Task;
/// # use tasklet::task::run_task;
/// # tokio_test::block_on( async {
/// let t = Task::new("* * * * * *", None, None, Utc).unwrap();
/// let h = tokio::spawn(run_task(t));
/// # h.abort();
/// # })
/// ```
pub async fn run_task<T>(mut task: Task<T>)
where
T: TimeZone + Send + 'static,
{
while let Some(msg) = task
.receiver
.as_mut()
.expect("Failed to borrow receiver.")
.recv()
.await
{
task.execute_command(msg);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::task::TaskStepStatusErr::{Error, ErrorDelete};
use crate::task::TaskStepStatusOk::Success;
use chrono::prelude::*;
#[test]
fn normal_task_flow_test() {
let mut task = Task::new("* * * * * *", Some("Test task"), Some(2), Local).unwrap();
task.add_step_default(|| Ok(Success));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Executed);
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Scheduled);
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Executed);
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Finished);
}
#[test]
fn test_task_set_schedule() {
let schedule: Schedule = "* * * * * * *".parse().unwrap();
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
task.set_schedule(schedule);
task.add_step_default(|| Ok(Success));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
}
#[test]
fn normal_task_error_flow_test() {
let mut task = Task::new("* * * * * *", Some("Test task"), Some(2), Local).unwrap();
task.add_step_default(|| Err(Error));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Failed);
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Scheduled);
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Failed);
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Finished);
}
/// Test the normal execution of a simple task, without fixed repeats.
#[test]
fn normal_task_no_fixed_repeats_test() {
let mut task = Task::new("* * * * * * *", Some("Test task"), None, Local).unwrap();
task.add_step_default(|| Ok(Success));
assert_eq!(task.status, Status::Init);
task.set_id(0);
task.init();
assert_eq!(task.status, Status::Scheduled);
// Run it for a few times.
for _i in 1..10 {
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Executed);
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Scheduled);
}
}
#[test]
fn test_reschedule_not_initialized() {
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
// This task is not initialized, so it should fail.
assert!(task.reschedule().is_err());
assert!(matches!(
task.reschedule().unwrap_err(),
TaskError::NotInitialized
));
}
#[test]
fn test_reschedule_finished_should_mark_as_finished() {
let mut task = Task::new("* * * * * * *", None, Some(1), Local).unwrap();
// Execute the task.
task.set_id(0);
task.init();
assert!(task.run_task().is_ok());
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Finished);
}
#[test]
fn test_run_uninitialized_task() {
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
assert!(task.run_task().is_err());
assert!(matches!(
task.run_task().unwrap_err(),
TaskError::NotInitialized
));
}
#[test]
fn test_run_failed_task() {
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
task.add_step_default(|| Err(Error));
task.set_id(0);
task.init();
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Failed);
// Attempt to rerun it, it should fail.
assert!(task.run_task().is_err());
assert!(matches!(task.run_task().unwrap_err(), TaskError::Failed));
}
#[test]
fn test_run_executed_task() {
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
task.add_step("Step 1", || Ok(Success));
task.set_id(0);
task.init();
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Executed);
// Attempt to run it again, it should fail.
assert!(task.run_task().is_err());
assert!(matches!(
task.run_task().unwrap_err(),
TaskError::AlreadyExecuted
));
}
#[test]
fn test_run_finished_task() {
let mut task = Task::new("* * * * * * *", None, Some(1), Local).unwrap();
task.set_id(0);
task.init();
assert!(task.run_task().is_ok());
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Finished);
// At this point the task is Finished. It should not be allowed to run again.
assert!(task.run_task().is_err());
assert!(matches!(task.run_task().unwrap_err(), TaskError::Finished));
}
#[test]
fn test_run_failed_delete() {
let mut task = Task::new("* * * * * * *", None, None, Local).unwrap();
task.add_step_default(|| Err(ErrorDelete));
task.set_id(0);
task.init();
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::ForceRemoved);
}
#[test]
fn test_invalid_cron_expression() {
let task = Task::new("invalid expression", None, None, Local);
assert!(task.is_err());
assert!(matches!(
task.unwrap_err(),
TaskError::InvalidCronExpression(_)
));
}
#[test]
fn test_task_status_transitions() {
let mut task = Task::new(
"* * * * * * *",
Some("Status transition test"),
Some(1),
Local,
)
.unwrap();
// Initial status should be Init
assert_eq!(task.status, Status::Init);
// After init(), status should be Scheduled
task.init();
assert_eq!(task.status, Status::Scheduled);
// Add a step that succeeds
task.add_step_default(|| Ok(TaskStepStatusOk::Success));
// After run_task(), status should be Executed
assert!(task.run_task().is_ok());
assert_eq!(task.status, Status::Executed);
// After reschedule(), with repeats=1 and already executed once,
// status should be Finished
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::Finished);
}
#[test]
fn test_task_step_display() {
// Test with description
let step_with_desc = TaskStep::new("Test step", || Ok(TaskStepStatusOk::Success));
assert_eq!(format!("{}", step_with_desc), "Test step");
// Test without description
let step_no_desc = TaskStep::default(|| Ok(TaskStepStatusOk::Success));
assert_eq!(format!("{}", step_no_desc), "-");
// Test with empty description
let step_empty_desc = TaskStep::new("", || Ok(TaskStepStatusOk::Success));
assert_eq!(format!("{}", step_empty_desc), "-");
}
#[tokio::test]
async fn test_task_command_execution() {
use chrono::Duration;
use tokio::sync::oneshot;
let mut task = Task::new("* * * * * * *", Some("Command test"), Some(1), Utc).unwrap();
task.set_id(1);
// Add a simple step to ensure the Run command works properly
task.add_step("Test step", || Ok(TaskStepStatusOk::Success));
// Test Init command first - this should initialize the task
let (tx_init, rx_init) = oneshot::channel();
task.execute_command(TaskCmd::Init { sender: tx_init });
let init_response = rx_init.await.unwrap();
assert_eq!(init_response.id, 1);
assert_eq!(init_response.status, Status::Scheduled);
// Set next_exec to a future time to prevent automatic execution
let future_time = Utc::now() + Duration::seconds(10);
task.next_exec = Some(future_time);
// Send Run command - this should not execute the task since next_exec is in the future
let (tx_run_no_exec, rx_run_no_exec) = oneshot::channel();
task.execute_command(TaskCmd::Run {
sender: tx_run_no_exec,
});
let no_exec_response = rx_run_no_exec.await.unwrap();
assert_eq!(no_exec_response.id, 1);
assert_eq!(
no_exec_response.status,
Status::Scheduled,
"Task should remain Scheduled when next_exec is in the future"
);
// Set next_exec to a past time to allow execution
let past_time = Utc::now() - Duration::seconds(10);
task.next_exec = Some(past_time);
// Send Run command - this should execute the task
let (tx_run, rx_run) = oneshot::channel();
task.execute_command(TaskCmd::Run { sender: tx_run });
let run_response = rx_run.await.unwrap();
assert_eq!(run_response.id, 1);
assert_eq!(run_response.status, Status::Executed);
// Test Reschedule command
let (tx_reschedule, rx_reschedule) = oneshot::channel();
task.execute_command(TaskCmd::Reschedule {
sender: tx_reschedule,
});
let reschedule_response = rx_reschedule.await.unwrap();
assert_eq!(reschedule_response.id, 1);
assert_eq!(reschedule_response.status, Status::Finished);
}
#[test]
fn test_task_multiple_steps_execution() {
use std::sync::{Arc, Mutex};
// Create counters to track step execution
let counter1 = Arc::new(Mutex::new(0));
let counter2 = Arc::new(Mutex::new(0));
let counter3 = Arc::new(Mutex::new(0));
// Create a task with multiple steps
let mut task = Task::new("* * * * * * *", Some("Multiple steps"), Some(1), Local).unwrap();
// Add steps that increment counters
let c1 = counter1.clone();
task.add_step("Step 1", move || {
*c1.lock().unwrap() += 1;
Ok(TaskStepStatusOk::Success)
});
let c2 = counter2.clone();
task.add_step("Step 2", move || {
*c2.lock().unwrap() += 1;
Ok(TaskStepStatusOk::Success)
});
let c3 = counter3.clone();
task.add_step("Step 3", move || {
*c3.lock().unwrap() += 1;
Ok(TaskStepStatusOk::Success)
});
// Initialize and run
task.init();
assert!(task.run_task().is_ok());
// Verify all steps executed
assert_eq!(*counter1.lock().unwrap(), 1);
assert_eq!(*counter2.lock().unwrap(), 1);
assert_eq!(*counter3.lock().unwrap(), 1);
// Verify final status
assert_eq!(task.status, Status::Executed);
}
#[test]
fn test_task_step_failure_scenarios() {
use std::sync::{Arc, Mutex};
// Create a counter to verify which steps executed
let execution_counter = Arc::new(Mutex::new(Vec::new()));
// Create a task with three steps, where the second step fails
let mut task = Task::new("* * * * * * *", Some("Failure test"), None, Local).unwrap();
// First step succeeds
let counter = execution_counter.clone();
task.add_step("Step 1", move || {
counter.lock().unwrap().push(1);
Ok(TaskStepStatusOk::Success)
});
// Second step fails
let counter = execution_counter.clone();
task.add_step("Step 2", move || {
counter.lock().unwrap().push(2);
Err(TaskStepStatusErr::Error)
});
// Third step should not execute due to previous failure
let counter = execution_counter.clone();
task.add_step("Step 3", move || {
counter.lock().unwrap().push(3);
Ok(TaskStepStatusOk::Success)
});
// Initialize and run
task.init();
assert!(task.run_task().is_ok());
// Verify only steps 1 and 2 executed
assert_eq!(*execution_counter.lock().unwrap(), vec![1, 2]);
// Verify task is in Failed state
assert_eq!(task.status, Status::Failed);
}
#[test]
fn test_force_removal() {
// Create a task with a step that forces removal
let mut task = Task::new("* * * * * * *", Some("Force removal"), None, Local).unwrap();
task.add_step("Failing step", || Err(TaskStepStatusErr::ErrorDelete));
// Initialize and run
task.init();
assert!(task.run_task().is_ok());
// Verify task is marked for force removal
assert_eq!(task.status, Status::ForceRemoved);
// Verify reschedule respects force removal status
assert!(task.reschedule().is_ok());
assert_eq!(task.status, Status::ForceRemoved);
}
#[test]
fn test_empty_task_execution() {
// Create a task with no steps
let mut task = Task::new("* * * * * * *", Some("Empty task"), None, Local).unwrap();
// Initialize and run
task.init();
assert!(task.run_task().is_ok());
// Verify task is marked as Executed even with no steps
assert_eq!(task.status, Status::Executed);
}
}