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
use super::runtime_trace::task_handle::DelayTaskHandler;
use cron_clock::Utc;
use cron_clock::{Schedule, ScheduleIteratorOwned};
use std::fmt;
use std::fmt::Pointer;
use std::str::FromStr;
//TaskMark is use to remove/stop the task.
#[derive(Default, Debug, Clone, Copy)]
pub(crate) struct TaskMark {
    pub(crate) task_id: u64,
    slot_mark: u64,
}

impl TaskMark {
    pub(crate) fn new(task_id: u64, slot_mark: u64) -> Self {
        TaskMark { task_id, slot_mark }
    }

    pub(crate) fn get_slot_mark(&self) -> u64 {
        self.slot_mark
    }

    pub(crate) fn set_slot_mark(&mut self, slot_mark: u64) {
        self.slot_mark = slot_mark;
    }
}

#[derive(Debug, Copy, Clone)]
///Enumerated values of repeating types.
pub enum Frequency<'a> {
    ///Repeat once.
    Once(&'a str),
    ///Repeat ad infinitum.
    Repeated(&'a str),
    ///Type of countdown.
    CountDown(u32, &'a str),
}
///Iterator for task internal control of execution time.
#[derive(Debug, Clone)]
pub(crate) enum FrequencyInner {
    ///Unlimited repetition types.
    Repeated(ScheduleIteratorOwned<Utc>),
    ///Type of countdown.
    CountDown(u32, ScheduleIteratorOwned<Utc>),
}

impl FrequencyInner {
    //How many times the acquisition needs to be performed.
    #[allow(dead_code)]
    fn residual_time(&self) -> u32 {
        match self {
            FrequencyInner::Repeated(_) => u32::MAX,
            FrequencyInner::CountDown(ref time, _) => *time,
        }
    }

    fn next_alarm_timestamp(&mut self) -> i64 {
        //TODO:handle error
        match self {
            FrequencyInner::CountDown(_, ref mut clock) => clock.next().unwrap().timestamp(),
            FrequencyInner::Repeated(ref mut clock) => clock.next().unwrap().timestamp(),
        }
    }

    #[warn(unused_parens)]
    fn down_count(&mut self) {
        match self {
            FrequencyInner::CountDown(ref mut exec_count, _) => {
                *exec_count -= 1u32;
            }
            FrequencyInner::Repeated(_) => {}
        };
    }

    fn is_down_over(&mut self) -> bool {
        !matches!(self, FrequencyInner::CountDown(0, _))
    }
}

#[derive(Debug, Default, Copy, Clone)]
///Cycle plan task builder.
pub struct TaskBuilder<'a> {
    ///Repeat type.
    frequency: Option<Frequency<'a>>,

    ///Task_id should unique.
    task_id: u64,

    ///Maximum execution time (optional).
    maximum_running_time: Option<u64>,
}

//TODO:Future tasks will support single execution (not multiple executions in the same time frame).
type SafeBoxFn = Box<dyn Fn() -> Box<dyn DelayTaskHandler> + 'static + Send + Sync>;

pub(crate) struct SafeStructBoxedFn(pub(crate) SafeBoxFn);
impl fmt::Debug for SafeStructBoxedFn {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <&Self as Pointer>::fmt(&self, f).unwrap();
        Ok(())
    }
}

#[derive(Debug)]
pub struct Task {
    ///Unique task-id.
    pub task_id: u64,
    ///Iter of frequencies and executive clocks.
    frequency: FrequencyInner,
    /// A Fn in box it can be run and return delayTaskHandler.
    pub(crate) body: SafeStructBoxedFn,
    ///Maximum execution time (optional).
    maximum_running_time: Option<u64>,
    ///Loop the line and check how many more clock cycles it will take to execute it.
    cylinder_line: u64,
    ///Validity.
    valid: bool,
}

//bak type BoxFn
// type BoxFn = Box<dyn Fn(i32) -> Pin<Box<dyn Future<Output = i32>>>>;

enum RepeatType {
    Num(u32),
    Always,
}

impl<'a> TaskBuilder<'a> {
    ///Set task Frequency.
    #[inline(always)]
    pub fn set_frequency(&mut self, frequency: Frequency<'a>) -> &mut Self {
        self.frequency = Some(frequency);
        self
    }

    ///Set task-id.
    #[inline(always)]
    pub fn set_task_id(&mut self, task_id: u64) -> &mut Self {
        self.task_id = task_id;
        self
    }

    ///Set maximum execution time (optional).
    #[inline(always)]
    pub fn set_maximum_running_time(&mut self, maximum_running_time: u64) -> &mut Self {
        self.maximum_running_time = Some(maximum_running_time);
        self
    }

    ///Spawn a task.
    pub fn spawn<F>(self, body: F) -> Task
    where
        F: Fn() -> Box<dyn DelayTaskHandler> + 'static + Send + Sync,
    {
        let frequency_inner;

        //The user inputs are pattern matched for different repetition types.
        let (expression_str, repeat_type) = match self.frequency.unwrap() {
            Frequency::Once(expression_str) => (expression_str, RepeatType::Num(1)),
            Frequency::Repeated(expression_str) => (expression_str, RepeatType::Always),
            Frequency::CountDown(exec_count, expression_str) => {
                (expression_str, RepeatType::Num(exec_count))
            }
        };

        //From cron-expression-str build time-iter.
        let schedule = Schedule::from_str(expression_str).unwrap();
        let taskschedule = schedule.upcoming_owned(Utc);

        //Building TaskFrequencyInner patterns based on repetition types.
        frequency_inner = match repeat_type {
            RepeatType::Always => FrequencyInner::Repeated(taskschedule),
            RepeatType::Num(repeat_count) => FrequencyInner::CountDown(repeat_count, taskschedule),
        };

        Task::new(
            self.task_id,
            frequency_inner,
            Box::new(body),
            self.maximum_running_time,
        )
    }
}

impl Task {
    #[inline(always)]
    pub(crate) fn new(
        task_id: u64,
        frequency: FrequencyInner,
        body: SafeBoxFn,
        maximum_running_time: Option<u64>,
    ) -> Task {
        let body = SafeStructBoxedFn(body);
        Task {
            task_id,
            frequency,
            body,
            maximum_running_time,
            cylinder_line: 0,
            valid: true,
        }
    }

    // get SafeBoxFn of Task to call.
    #[inline(always)]
    pub(crate) fn get_body(&self) -> &SafeBoxFn {
        &(self.body).0
    }

    //swap slot loction ,do this
    //down_count_and_set_vaild,will return new vaild status.
    #[inline(always)]
    pub(crate) fn down_count_and_set_vaild(&mut self) -> bool {
        self.down_count();
        self.set_valid_by_count_down();
        self.is_valid()
    }

    //down_exec_count
    #[inline(always)]
    fn down_count(&mut self) {
        self.frequency.down_count();
    }

    //set_valid_by_count_down
    #[inline(always)]
    fn set_valid_by_count_down(&mut self) {
        self.valid = self.frequency.is_down_over();
    }

    #[inline(always)]
    pub(crate) fn set_cylinder_line(&mut self, cylinder_line: u64) {
        self.cylinder_line = cylinder_line;
    }

    #[inline(always)]
    pub fn get_maximum_running_time(&self, start_time: u64) -> Option<u64> {
        self.maximum_running_time.map(|t| t + start_time)
    }

    //single slot foreach do this.
    //sub_cylinder_line
    //return is can_running?
    #[inline(always)]
    pub(crate) fn sub_cylinder_line(&mut self) -> bool {
        self.cylinder_line -= 1;
        self.is_can_running()
    }

    #[inline(always)]
    /// check if task has arrived.
    pub fn check_arrived(&mut self) -> bool {
        if self.cylinder_line == 0 {
            return self.is_can_running();
        }
        self.sub_cylinder_line()
    }

    /// check if task has already.
    #[inline(always)]
    pub fn is_already(&self) -> bool {
        self.cylinder_line == 0
    }

    /// check if task has runable status.
    #[inline(always)]
    pub fn is_can_running(&self) -> bool {
        if self.is_valid() {
            return self.is_already();
        }
        false
    }

    /// check if task has valid status.
    #[inline(always)]
    pub fn is_valid(&self) -> bool {
        self.valid
    }

    ///get_next_exec_timestamp
    #[inline(always)]
    pub fn get_next_exec_timestamp(&mut self) -> u64 {
        self.frequency.next_alarm_timestamp() as u64
    }
}

mod tests {

    #[test]
    fn test_task_valid() {
        use super::{Frequency, Task, TaskBuilder};
        use crate::utils::convenience::functions::create_default_delay_task_handler;
        let mut task_builder = TaskBuilder::default();

        //The third run returns to an invalid state.
        task_builder.set_frequency(Frequency::CountDown(3, "* * * * * * *"));
        let mut task: Task = task_builder.spawn(|| create_default_delay_task_handler());

        assert!(task.down_count_and_set_vaild());
        assert!(task.down_count_and_set_vaild());
        assert!(!task.down_count_and_set_vaild());
    }

    #[test]
    fn test_is_can_running() {
        use super::{Frequency, Task, TaskBuilder};
        use crate::utils::convenience::functions::create_default_delay_task_handler;
        let mut task_builder = TaskBuilder::default();

        //The third run returns to an invalid state.
        task_builder.set_frequency(Frequency::CountDown(3, "* * * * * * *"));
        let mut task: Task = task_builder.spawn(|| create_default_delay_task_handler());

        assert!(task.is_can_running());

        task.set_cylinder_line(1);
        assert!(!task.is_can_running());

        assert!(task.check_arrived());
    }
}