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
use async_trait::async_trait;
use chrono::{DateTime, Local};
use cron::Schedule;
use dashmap::DashMap;
use parking_lot::RwLock;
use serde_json::Value;
use std::str::FromStr;
use std::sync::Arc;

use crate::errors::{SchedulerError, SchedulerErrorKind};
use crate::job::{JobContext, ScheduleJob, WillExecuteJobFuture};

///
/// `JobStorage` is used to store all jobs and context.
/// # Usage
/// `register_job`: Register a job
///
/// `add_job`: Add a job with given cron expression and args
///
/// `delete_job`: Delete a exist job
///
/// `has_job`: Judge is there a job with given JobId
///
/// `get_all_should_execute_jobs`: Get all jobs that should execute now
///
/// `restore_jobs`: Restore all jobs from storage
#[async_trait]
pub trait JobStorage<Tz>: Send + Sync
where
    Tz: chrono::TimeZone,
    Tz::Offset: Send + Sync,
{
    ///Register a job
    ///
    /// # Arguments
    /// job: A struct which implements `ScheduleJob` trait.
    ///
    /// # Attention
    /// Every job should provide a unique `job_name` in `get_job_name()` function!
    async fn register_job(&self, job: Box<dyn ScheduleJob>) -> Result<(), SchedulerError>;
    ///Add a job with given cron expression and context.
    ///
    /// # Arguments
    /// 1. `job_name`: A job's name which must be registered before
    ///
    /// 2. `cron`: Cron expression
    ///
    /// 3. `args`: Job args, it's just the alias of `serde_json::Value`
    ///
    /// # Returns
    /// JobId
    async fn add_job(
        &self,
        job_name: &str,
        cron: &str,
        args: &Option<Value>,
    ) -> Result<String, SchedulerError>;
    /// Add a job which is going to retry.
    async fn add_retry_job(
        &self,
        origin_id: &str,
        job_name: &str,
        args: &Option<Value>,
        retry_times: u64,
    ) -> Result<String, SchedulerError>;
    ///Delete a job.
    /// # Arguments
    /// 1. `id`: JobId
    async fn delete_job(&self, id: &str) -> Result<(), SchedulerError>;
    /// Judge is there a job with given JobId
    ///
    /// # Arguments
    /// 1. `id`: JobId
    ///
    /// # Returns
    /// A bool which represents the existence of job with given JobId
    async fn has_job(&self, id: &str) -> Result<bool, SchedulerError>;
    /// Get all jobs which should execute now.
    ///
    /// The return value should be `(JobName,JobId,JobArgs,JobRetryTimes)`
    ///
    /// # Returns
    /// A vec which store all future which should execute now. The last `u64` argument represents `retry_times`. If the task is not in retry queue, this value should be 0.
    async fn get_all_should_execute_jobs(
        &self,
    ) -> Result<Vec<(String, String, Option<Value>, u64)>, SchedulerError>;
    /// Restore all jobs from storage
    async fn restore_jobs(&self) -> Result<(), SchedulerError>;
    /// Get a `job` from `JobStorage` by it's name
    async fn get_job_by_name(
        &self,
        name: &str,
        id: &str,
        args: &Option<Value>,
        retry_times: u64,
    ) -> Result<Option<WillExecuteJobFuture>, SchedulerError>;
    /// Get many `job` from `JobStorage` by it's name
    ///
    /// # Arguments
    /// `exprs` is &Vec<(JobName,JobId,JobArguments)>
    /// # Returns
    /// The return value of this function is `Vec<(WillExecuteJobFuture,JobName,JobId,JobArguments)>`
    ///
    /// **You must return the values in the same order**
    async fn get_jobs_by_name(
        &self,
        exprs: &Vec<(String, String, Option<Value>, u64)>,
    ) -> Result<Vec<(WillExecuteJobFuture, String, String, Option<Value>)>, SchedulerError>;
}

/// Simple Memory Job Storage implements `JobStorage`
///
/// !!! This JobStorage is not recommended for production environment !!!
pub struct MemoryJobStorage<Tz = chrono::Utc>
where
    Tz: chrono::TimeZone + Sync + Send,
{
    tasks: DashMap<String, Box<dyn ScheduleJob>>,
    jobs: DashMap<String, (Schedule, String, Option<Value>)>,
    retry_jobs: DashMap<String, (String, String, Option<Value>, u64)>,
    timezone: Tz,
    last_check_time: Arc<RwLock<DateTime<Tz>>>,
}

impl<Tz> MemoryJobStorage<Tz>
where
    Tz: chrono::TimeZone + Send + Sync,
{
    pub fn new(timezone: Tz) -> Self {
        Self {
            tasks: DashMap::new(),
            jobs: DashMap::new(),
            retry_jobs: DashMap::new(),
            timezone: timezone.to_owned(),
            last_check_time: Arc::new(RwLock::new(Local::now().with_timezone(&timezone))),
        }
    }

    pub fn with_timezone(mut self, tz: Tz) -> Self {
        self.timezone = tz;
        self
    }
}

impl Default for MemoryJobStorage<chrono::Utc> {
    fn default() -> Self {
        Self {
            tasks: DashMap::new(),
            jobs: DashMap::new(),
            retry_jobs: DashMap::new(),
            timezone: chrono::Utc,
            last_check_time: Arc::new(RwLock::new(Local::now().with_timezone(&chrono::Utc))),
        }
    }
}

unsafe impl<Tz: chrono::TimeZone + Sync + Send> Send for MemoryJobStorage<Tz> {}

unsafe impl<Tz: chrono::TimeZone + Sync + Send> Sync for MemoryJobStorage<Tz> {}

#[async_trait]
impl<Tz> JobStorage<Tz> for MemoryJobStorage<Tz>
where
    Tz: chrono::TimeZone + Sync + Send,
    Tz::Offset: Send + Sync,
{
    async fn register_job(&self, job: Box<dyn ScheduleJob>) -> Result<(), SchedulerError> {
        let is_registered = self.tasks.get(&job.get_job_name()).is_some();

        if is_registered {
            return Err(SchedulerError::new(SchedulerErrorKind::JobRegistered));
        }

        self.tasks.insert(job.get_job_name(), job);
        Ok(())
    }

    async fn add_job(
        &self,
        job_name: &str,
        cron: &str,
        args: &Option<Value>,
    ) -> Result<String, SchedulerError> {
        let cron = Schedule::from_str(&cron)
            .map_err(|_| SchedulerError::new(SchedulerErrorKind::CronInvalid))?;
        let id = uuid::Uuid::new_v4().to_string();

        self.jobs
            .insert(id.to_owned(), (cron, job_name.to_owned(), args.to_owned()));

        Ok(id)
    }

    async fn add_retry_job(
        &self,
        origin_id: &str,
        job_name: &str,
        args: &Option<Value>,
        retry_times: u64,
    ) -> Result<String, SchedulerError> {
        let id = uuid::Uuid::new_v4().to_string();

        self.retry_jobs.insert(
            id.to_owned(),
            (
                origin_id.to_owned(),
                job_name.to_owned(),
                args.to_owned(),
                retry_times,
            ),
        );

        Ok(id)
    }

    async fn delete_job(&self, id: &str) -> Result<(), SchedulerError> {
        self.jobs.remove(id);

        Ok(())
    }

    async fn has_job(&self, id: &str) -> Result<bool, SchedulerError> {
        let has = self.jobs.contains_key(id);

        Ok(has)
    }

    async fn get_all_should_execute_jobs(
        &self,
    ) -> Result<Vec<(String, String, Option<Value>, u64)>, SchedulerError> {
        let time_now = Local::now().with_timezone(&self.timezone);

        let last_check_at = self.last_check_time.read();
        let cron_and_name: Vec<(Schedule, String, Option<Value>, String)> = self
            .jobs
            .iter()
            .map(|v| {
                (
                    v.value().0.to_owned(),
                    v.value().1.to_owned(),
                    v.value().2.to_owned(),
                    v.key().to_owned(),
                )
            })
            .collect();

        let mut result_vec = vec![];

        for (cron, name, args, id) in cron_and_name {
            for time in cron.after(&last_check_at) {
                if time <= time_now {
                    result_vec.push((name.to_owned(), id.to_owned(), args.to_owned(), 0_u64))
                } else {
                    break;
                }
            }
        }

        drop(last_check_at);
        *self.last_check_time.write() = time_now;

        let mut all_should_retry_jobs = self
            .retry_jobs
            .iter()
            .map(|v| {
                (
                    v.value().1.to_owned(),
                    v.value().0.to_owned(),
                    v.value().2.to_owned(),
                    v.value().3,
                )
            })
            .collect();

        result_vec.append(&mut all_should_retry_jobs);

        self.retry_jobs.clear();
        Ok(result_vec)
    }

    async fn restore_jobs(&self) -> Result<(), SchedulerError> {
        Ok(())
    }

    async fn get_job_by_name(
        &self,
        name: &str,
        id: &str,
        args: &Option<Value>,
        retry_times: u64,
    ) -> Result<Option<WillExecuteJobFuture>, SchedulerError> {
        if let Some(task) = self.tasks.get(name) {
            let job_context = JobContext::new(id.to_owned(), args.to_owned(), retry_times);
            Ok(Some(WillExecuteJobFuture::new(
                task.execute(job_context.to_owned()),
                job_context,
            )))
        } else {
            Ok(None)
        }
    }

    async fn get_jobs_by_name(
        &self,
        exprs: &Vec<(String, String, Option<Value>, u64)>,
    ) -> Result<Vec<(WillExecuteJobFuture, String, String, Option<Value>)>, SchedulerError> {
        let mut result = vec![];

        for (name, id, args, retry_times) in exprs {
            let job = match self.get_job_by_name(&name, &id, args, *retry_times).await? {
                Some(j) => j,
                None => continue,
            };
            result.push((job, name.to_owned(), id.to_owned(), args.to_owned()));
        }
        Ok(result)
    }
}