rexecutor 0.1.1

A robust job processing library
Documentation
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
//! The API for configuring the job pruner.
//!
//! After jobs have completed, been cancelled, or discarded it is useful to be able to clean up.
//!
//! Given the different ways in which jobs can finish it is often useful to be able to have fine
//! grained control over how old jobs should be cleaned up. [`PrunerConfig`] enables such control.
//!
//! When constructing [`PrunerConfig`] a [`cron::Schedule`] is provided to specify when the pruner
//! should run.
//!
//! Depending on the load/throughput of the system the pruner can be scheduled to run anywhere
//! from once a year through to multiple times per hour.
//!
//! [`PrunerConfig`] can have a number of individual [`Pruner`]s configured, each one specific for
//! cleaning up jobs matching specify criteria. This way fine grained control can be achieved to.
//! For example, is is possible to configure the pruner to achieve all of the following:
//!
//! - clean up completed jobs for a single executor so there is only 10 completed jobs at a time,
//! - clean up all completed jobs for all executors that are more than a month old,
//! - clean up cancelled jobs that are a year old, and
//! - keeping all discarded jobs indefinitely.
//!
//!
//! # Example
//!
//! To remove all completed jobs more than a month old for both the `RefreshWorker` and
//! `EmailScheduler` while only maintaining the last 200 discarded jobs for all executors expect
//! the `EmailScheduler` and `RefreshWorker`, you could use the following config.
//!
//! ```
//! # use rexecutor::prelude::*;
//! # use std::str::FromStr;
//! # use chrono::TimeDelta;
//! # pub(crate) struct RefreshWorker;
//! # pub(crate) struct EmailScheduler;
//! #
//! # #[async_trait::async_trait]
//! # impl Executor for RefreshWorker {
//! #     type Data = String;
//! #     type Metadata = String;
//! #     const NAME: &'static str = "refresh_worker";
//! #     const MAX_ATTEMPTS: u16 = 2;
//! #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
//! #         ExecutionResult::Done
//! #     }
//! # }
//! # #[async_trait::async_trait]
//! # impl Executor for EmailScheduler {
//! #     type Data = String;
//! #     type Metadata = String;
//! #     const NAME: &'static str = "email_scheduler";
//! #     const MAX_ATTEMPTS: u16 = 2;
//! #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
//! #         ExecutionResult::Done
//! #     }
//! # }
//! let config = PrunerConfig::new(cron::Schedule::from_str("0 0 * * * *").unwrap())
//!     .with_max_concurrency(Some(2))
//!     .with_pruner(
//!         Pruner::max_age(TimeDelta::days(31), JobStatus::Complete)
//!             .only::<RefreshWorker>()
//!             .and::<EmailScheduler>(),
//!     )
//!     .with_pruner(
//!         Pruner::max_length(200, JobStatus::Discarded)
//!             .except::<RefreshWorker>()
//!             .and::<EmailScheduler>(),
//!     );
//! ```

use chrono::TimeDelta;

pub(crate) mod runner;

use crate::{executor::Executor, job::JobStatus};

/// Fine grained configuration for how jobs should be cleaned up.
///
/// When constructing [`PrunerConfig`] a [`cron::Schedule`]
/// is provided to specify when the pruner should run.
///
/// Depending on the load/throughput of the system the pruner can be scheduled to run anywhere
/// from once a year through to multiple times per hour.
///
/// [`PrunerConfig`] can have a number of individual [`Pruner`]s configured, each one specific for
/// cleaning up jobs matching specify criteria. This way fine grained control can be achieved to.
/// For example, is is possible to configure the pruner to achieve all of the following:
///
/// - clean up completed jobs for a single executor so there is only 10 completed jobs
///   at a time,
/// - clean up all completed jobs for all executors that are more than a month old
/// - clean up cancelled jobs that are a year old
/// - keeping all discarded jobs indefinitely
///
/// Once constructed, [`PrunerConfig`] it should be passed to [`crate::Rexecutor::with_job_pruner`].
///
/// # Example
///
/// To remove all completed jobs more than a month old for both the `RefreshWorker` and
/// `EmailScheduler` while only maintaining the last 200 discarded jobs for all executors expect
/// the `EmailScheduler` and `RefreshWorker`, you could use the following config.
///
/// ```
/// # use rexecutor::prelude::*;
/// # use std::str::FromStr;
/// # use chrono::TimeDelta;
/// # pub(crate) struct RefreshWorker;
/// # pub(crate) struct EmailScheduler;
/// #
/// # #[async_trait::async_trait]
/// # impl Executor for RefreshWorker {
/// #     type Data = String;
/// #     type Metadata = String;
/// #     const NAME: &'static str = "refresh_worker";
/// #     const MAX_ATTEMPTS: u16 = 2;
/// #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
/// #         ExecutionResult::Done
/// #     }
/// # }
/// # #[async_trait::async_trait]
/// # impl Executor for EmailScheduler {
/// #     type Data = String;
/// #     type Metadata = String;
/// #     const NAME: &'static str = "email_scheduler";
/// #     const MAX_ATTEMPTS: u16 = 2;
/// #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
/// #         ExecutionResult::Done
/// #     }
/// # }
/// let config = PrunerConfig::new(cron::Schedule::from_str("0 0 * * * *").unwrap())
///     .with_max_concurrency(Some(2))
///     .with_pruners([
///         Pruner::max_age(TimeDelta::days(31), JobStatus::Complete)
///             .only::<RefreshWorker>()
///             .and::<EmailScheduler>(),
///         Pruner::max_length(200, JobStatus::Discarded)
///             .only::<RefreshWorker>()
///             .and::<EmailScheduler>(),
///     ]);
/// ```
pub struct PrunerConfig {
    schedule: cron::Schedule,
    max_concurrency: Option<usize>,
    pruners: Vec<PruneSpec>,
}

impl PrunerConfig {
    /// Construct a new instance of [`PrunerConfig`] scheduled to run on the provided cron
    /// schedule.
    pub fn new(schedule: cron::Schedule) -> Self {
        Self {
            schedule,
            max_concurrency: Some(10),
            pruners: Default::default(),
        }
    }

    /// Specify the maximum number of pruners that should be ran simultaneously.
    ///
    /// If the pruner runs when the rest of the system is busy, it might be advisable to limit the
    /// concurrency of the pruner to avoid too much load on the backend.
    pub fn with_max_concurrency(mut self, limit: Option<usize>) -> Self {
        self.max_concurrency = limit;
        self
    }

    /// Add a single [`Pruner`] to the config.
    #[allow(private_bounds)]
    pub fn with_pruner<T>(mut self, pruner: Pruner<T>) -> Self
    where
        T: IntoSpec,
    {
        self.pruners.push(pruner.into());
        self
    }

    /// Add multiple [`Pruner`]s of a single type to the config.
    #[allow(private_bounds)]
    pub fn with_pruners<T>(mut self, pruner: impl IntoIterator<Item = Pruner<T>>) -> Self
    where
        T: IntoSpec,
    {
        self.pruners.extend(pruner.into_iter().map(Into::into));
        self
    }
}

/// The specification of a single pruner for consumption by the backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruneSpec {
    /// The status of the jobs that should be affected by this pruner.
    pub status: JobStatus,
    /// The particular pruning strategy to apply, either max length or max age.
    pub prune_by: PruneBy,
    /// The specification of the executors to be affected by this pruner.
    pub executors: Spec,
}

impl<T> From<Pruner<T>> for PruneSpec
where
    T: IntoSpec,
{
    fn from(value: Pruner<T>) -> Self {
        Self {
            status: value.status,
            prune_by: value.prune_by,
            executors: value.executors.into_spec(),
        }
    }
}

/// Configuration for a single pruner.
///
/// Pruners can either be configured to prune by the age of jobs constructed via
/// [`Pruner::max_age`] or the total number of job via [`Pruner::max_length`].
///
/// By default when constructed a pruner will prune jobs for all executors. To only prune jobs
/// related to a specific set of of executors, you can use [`Pruner::only`] followed by
/// [`Pruner::and`].
///
/// Similarly, to prune jobs for all but a specified set of executors, you can call
/// [`Pruner::except`] followed by [`Pruner::and`].
///
/// # Example
///
/// To prune all completed jobs which are older than 2 weeks:
///
/// ```
/// # use rexecutor::prelude::*;
/// # use chrono::TimeDelta;
/// let pruner = Pruner::max_age(TimeDelta::days(14), JobStatus::Complete);
/// ```
///
/// Similarly to only prune a specific set of executors:
///
/// ```
/// # use rexecutor::prelude::*;
/// # pub(crate) struct RefreshWorker;
/// # pub(crate) struct EmailScheduler;
/// #
/// # #[async_trait::async_trait]
/// # impl Executor for RefreshWorker {
/// #     type Data = String;
/// #     type Metadata = String;
/// #     const NAME: &'static str = "refresh_worker";
/// #     const MAX_ATTEMPTS: u16 = 2;
/// #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
/// #         ExecutionResult::Done
/// #     }
/// # }
/// # #[async_trait::async_trait]
/// # impl Executor for EmailScheduler {
/// #     type Data = String;
/// #     type Metadata = String;
/// #     const NAME: &'static str = "email_scheduler";
/// #     const MAX_ATTEMPTS: u16 = 2;
/// #     async fn execute(_job: Job<Self::Data, Self::Metadata>) -> ExecutionResult {
/// #         ExecutionResult::Done
/// #     }
/// # }
/// let pruner = Pruner::max_length(200, JobStatus::Discarded)
///     .only::<RefreshWorker>()
///     .and::<EmailScheduler>();
/// ```
#[allow(private_bounds)]
pub struct Pruner<T>
where
    T: IntoSpec,
{
    status: JobStatus,
    prune_by: PruneBy,
    executors: T,
}

impl Pruner<All> {
    /// Constructs a pruner that will prune jobs on the bases of their age.
    pub const fn max_age(age: TimeDelta, status: JobStatus) -> Self {
        Self {
            status,
            prune_by: PruneBy::MaxAge(age),
            executors: All,
        }
    }

    /// Constructs a pruner that will prune jobs on the bases of the number of matching jobs.
    pub const fn max_length(length: u32, status: JobStatus) -> Self {
        Self {
            status,
            prune_by: PruneBy::MaxLength(length),
            executors: All,
        }
    }

    /// Restrict this pruner to only prune jobs for the given [`Executor`].
    pub fn only<E: Executor>(self) -> Pruner<Only> {
        Pruner {
            status: self.status,
            prune_by: self.prune_by,
            executors: Only(vec![E::NAME]),
        }
    }

    /// Restrict this pruner to not prune jobs for the given [`Executor`].
    pub fn except<E: Executor>(self) -> Pruner<Except> {
        Pruner {
            status: self.status,
            prune_by: self.prune_by,
            executors: Except(vec![E::NAME]),
        }
    }
}

impl Pruner<Only> {
    /// Additionally prune jobs for the given [`Executor`].
    pub fn and<E: Executor>(mut self) -> Self {
        self.executors.0.push(E::NAME);
        self
    }
}

impl Pruner<Except> {
    /// Add another [`Executor`] to the exclusion list for this pruner.
    pub fn and<E: Executor>(mut self) -> Self {
        self.executors.0.push(E::NAME);
        self
    }
}

/// The strategy to prune by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PruneBy {
    /// Each time the pruner is ran it should remove all jobs older than then given [`TimeDelta`]
    MaxAge(TimeDelta),
    /// Each time the pruner runs it should ensure that the max length of remaining jobs is equal
    /// to the given length.
    ///
    /// It should prune the oldest jobs first.
    MaxLength(u32),
}

/// An exclusion/inclusion specification.
///
/// For the pruner this should specify whether the pruner should prune on the basis of exception or
/// inclusion in the given [`Vec`]s.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Spec {
    /// Prune jobs for all executors except those given.
    Except(Vec<&'static str>),
    /// Prune jobs only for the executors provided.
    Only(Vec<&'static str>),
}

trait IntoSpec {
    fn into_spec(self) -> Spec;
}
#[doc(hidden)]
pub struct All;
impl IntoSpec for All {
    fn into_spec(self) -> Spec {
        Spec::Except(Vec::new())
    }
}
#[doc(hidden)]
pub struct Except(Vec<&'static str>);
impl IntoSpec for Except {
    fn into_spec(self) -> Spec {
        Spec::Except(self.0)
    }
}
#[doc(hidden)]
pub struct Only(Vec<&'static str>);
impl IntoSpec for Only {
    fn into_spec(self) -> Spec {
        Spec::Only(self.0)
    }
}

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use crate::executor::test::{MockReturnExecutor, SimpleExecutor};

    use super::*;

    #[test]
    fn config() {
        let config = PrunerConfig::new(cron::Schedule::from_str("0 0 * * * *").unwrap())
            .with_pruner(
                Pruner::max_age(TimeDelta::days(31), JobStatus::Complete)
                    .only::<SimpleExecutor>()
                    .and::<MockReturnExecutor>(),
            )
            .with_pruner(
                Pruner::max_length(200, JobStatus::Discarded)
                    .except::<SimpleExecutor>()
                    .and::<MockReturnExecutor>(),
            );

        assert_eq!(config.pruners.len(), 2);
    }

    #[test]
    fn into_spec_all() {
        let spec = IntoSpec::into_spec(All);
        assert_eq!(spec, Spec::Except(Vec::new()));
    }
}