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
//! Prioritised, parallel job scheduler with concurrent exclusion, job merging, recurring jobs and load limiting for lower priorities.
//!
//! A job scheduler executes tasks on it's own thread or thread pool. This job scheduler is particularly designed to consider heavier weight or more expensive jobs, which likely have side effects. In this case it can be valuable to prioritise the jobs and merge alike jobs in the queue.
//!
//! __Features__
//!
//! * Recurring jobs: jobs which will be re-enqueued at some interval
//! * Job queue: send jobs from various threads using the cloneable [`JobRunner`]
//! * Future Jobs: (Optionally) create `Future`s to get results from the jobs
//! * Job prioritisation: provide a priority for jobs and all the jobs will be executed in that order
//! * Job merging: merge identical / similar jobs in the queue to reduce workload
//! * Parallel execution: run jobs on multiple threads and lock jobs which should be run exclusively, they remain in the queue and don't occupy other resources
//! * Concurrent exclusion: key-based locking to avoid jobs running concurrently which shouldn't
//! * Priority throttling: in order to have idle threads ready to pick up higher-priority jobs, throttle lower priority jobs by restricting them to a lower number of threads
//!
//! __Limitations__
//!
//! * some of the tests are very dependent on timing and will fail if run slowly
//!
//! ## Example
//!
//! See `/examples/full.rs` for a full example, or below for examples focusing on particular capabilities.
//!
//! ## Capabilities
//!
//! Below, the examples show minimal usages of each of the capabilities for clarity, but if you're using this you probably want most or all of these.
//!
//! ### Recurring jobs
//!
//! Recurring jobs are configured on the runner when it is built, the runner then clones the job and enquese it if a matching job is not enqueued within the interval.
//!
//! You need to call [`Builder::set_recurring`] and you need to implement [`RecurrableJob`].
//!
//! ```
//! use gaffer::{Job, JobRunner, NoExclusion, RecurrableJob};
//! use std::time::Duration;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let _runner = JobRunner::builder()
//!         .set_recurring(
//!             Duration::from_secs(2),
//!             std::time::Instant::now(),
//!             MyJob("recurring"),
//!         )
//!         .build(1);
//!
//!     std::thread::sleep(Duration::from_secs(7));
//!     Ok(())
//! }
//!
//! #[derive(Debug, Clone)]
//! struct MyJob(&'static str);
//!
//! impl Job for MyJob {
//!     type Exclusion = NoExclusion;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         NoExclusion
//!     }
//!
//!     fn execute(self) {
//!         println!("Completed job {:?}", self);
//!     }
//!
//!     type Priority = ();
//!
//!     fn priority(&self) -> Self::Priority {}
//! }
//!
//! impl RecurrableJob for MyJob {
//!     fn matches(&self, other: &Self) -> bool {
//!         self.0 == other.0
//!     }
//! }
//!
//! ```
//!
//! ### Job queue
//!
//! Call [`JobRunner::send`] to add jobs onto the queue, they will be executed in the order that they are enqueued
//!
//! ```
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = gaffer::JobRunner::builder().build(1);
//!
//!     for i in 1..=5 {
//!         let name = format!("Job {}", i);
//!         runner.send(move || {
//!             std::thread::sleep(std::time::Duration::from_secs(1));
//!             println!("Completed job {:?}", name);
//!         })?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(std::time::Duration::from_secs(7));
//!     Ok(())
//! }
//! ```
//!
//! ### Job prioritisation
//!
//! Return a value from [`Job::priority`] and jobs from the queue will be executed in priority order
//!
//! ```
//! use gaffer::{Job, JobRunner, NoExclusion};
//! use std::time::Duration;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = JobRunner::builder().build(1);
//!
//!     for (i, priority) in (1..=5).zip([1, 2].iter().cycle()) {
//!         runner.send(PrioritisedJob(format!("Job {}", i), *priority))?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(Duration::from_secs(7));
//!     Ok(())
//! }
//!
//! #[derive(Debug)]
//! struct PrioritisedJob(String, u8);
//!
//! impl Job for PrioritisedJob {
//!     type Exclusion = NoExclusion;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         NoExclusion
//!     }
//!
//!     type Priority = u8;
//!
//!     /// This Job is prioritied
//!     fn priority(&self) -> Self::Priority {
//!         self.1
//!     }
//!
//!     fn execute(self) {
//!         std::thread::sleep(Duration::from_secs(1));
//!         println!("Completed job {:?}", self);
//!     }
//! }
//!
//! ```
//!
//! ### Job merging
//!
//! Gracefully handle spikes in duplicate or overlapping jobs by automatically merging those jobs in the queue.
//! Call [`Builder::enable_merge`].
//!
//! ```
//! use gaffer::{Job, JobRunner, MergeResult, NoExclusion};
//! use std::time::Duration;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = JobRunner::builder().enable_merge(merge_jobs).build(1);
//!
//!     for i in 10..=50 {
//!         runner.send(MergeJob(format!("Job {}", i)))?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(Duration::from_secs(7));
//!     Ok(())
//! }
//!
//! #[derive(Debug)]
//! struct MergeJob(String);
//!
//! impl Job for MergeJob {
//!     type Exclusion = NoExclusion;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         NoExclusion
//!     }
//!
//!     type Priority = ();
//!
//!     fn priority(&self) -> Self::Priority {}
//!
//!     fn execute(self) {
//!         std::thread::sleep(Duration::from_secs(1));
//!         println!("Completed job {:?}", self);
//!     }
//! }
//!
//! fn merge_jobs(this: MergeJob, that: &mut MergeJob) -> MergeResult<MergeJob> {
//!     if this.0[..this.0.len() - 1] == that.0[..that.0.len() - 1] {
//!         that.0 = format!("{}x", &that.0[..that.0.len() - 1]);
//!         MergeResult::Success
//!     } else {
//!         MergeResult::NotMerged(this)
//!     }
//! }
//!
//! ```
//!
//! ### Parallel execution
//!
//! Jobs can be run over multiple threads, just provide the number of threads to [`Builder::build`]
//!
//! ```
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = gaffer::JobRunner::builder().build(10);
//!
//!     for i in 1..=50 {
//!         let name = format!("WaitJob {}", i);
//!         runner.send(move || {
//!             std::thread::sleep(std::time::Duration::from_secs(1));
//!             println!("Completed job {:?}", name);
//!         })?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(std::time::Duration::from_secs(7));
//!     Ok(())
//! }
//! ```
//!
//! ### Concurrent exclusion
//!
//! Exclusion keys can be provided to show which jobs need to be run exclusively
//!
//! ```
//! use gaffer::{ExclusionOption, Job, JobRunner};
//! use std::time::Duration;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = JobRunner::builder().build(2);
//!
//!     for (i, exclusion) in (1..=10).zip([ExclusionOption::Some(1), ExclusionOption::Some(2), ExclusionOption::None].iter().cycle()) {
//!         runner.send(ExcludedJob(format!("Job {}", i), *exclusion))?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(Duration::from_secs(7));
//!     Ok(())
//! }
//!
//! #[derive(Debug)]
//! struct ExcludedJob(String, ExclusionOption<u8>);
//!
//! impl Job for ExcludedJob {
//!     type Exclusion = ExclusionOption<u8>;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         self.1
//!     }
//!
//!     type Priority = ();
//!
//!     fn priority(&self) -> Self::Priority {}
//!
//!     fn execute(self) {
//!         std::thread::sleep(Duration::from_secs(1));
//!         println!("Completed job {:?}", self);
//!     }
//! }
//!
//! ```
//!
//! ### Priority throttling
//!
//! Lower priority jobs can be restricted to less threads to reduce the load on system resources and encourage merging (if using).
//!
//! Use [`Builder::limit_concurrency`].
//!
//! ```
//! use gaffer::{Job, JobRunner, NoExclusion};
//! use std::time::Duration;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = JobRunner::builder()
//!         .limit_concurrency(|priority| (priority == 1).then(|| 1))
//!         .build(4);
//!
//!     for (i, priority) in (1..=10).zip([1, 2].iter().cycle()) {
//!         runner.send(PrioritisedJob(format!("Job {}", i), *priority))?;
//!     }
//!
//!     println!("Jobs enqueued");
//!     std::thread::sleep(Duration::from_secs(7));
//!     Ok(())
//! }
//!
//! #[derive(Debug)]
//! struct PrioritisedJob(String, u8);
//!
//! impl Job for PrioritisedJob {
//!     type Exclusion = NoExclusion;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         NoExclusion
//!     }
//!
//!     type Priority = u8;
//!
//!     /// This Job is prioritied
//!     fn priority(&self) -> Self::Priority {
//!         self.1
//!     }
//!
//!     fn execute(self) {
//!         std::thread::sleep(Duration::from_secs(1));
//!         println!("Completed job {:?}", self);
//!     }
//! }
//!
//! ```
//!
//! ### Future jobs
//!
//! Use a [`future::Promise`] in the job to allow `await`ing job results in async code. When combined with merging, all the futures of the merged jobs will complete with clones of the single job which actually ran
//!
//! ```
//! use gaffer::{
//!     future::{Promise, PromiseFuture},
//!     Job, JobRunner, MergeResult, NoExclusion,
//! };
//! use std::time::Duration;
//!
//! use futures::{executor::block_on, FutureExt, StreamExt};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let runner = JobRunner::builder()
//!         .enable_merge(|this: ProcessString, that: &mut ProcessString| {
//!             if this.0[..this.0.len() - 1] == that.0[..that.0.len() - 1] {
//!                 that.0 = format!("{}x", &that.0[..that.0.len() - 1]);
//!                 that.1.merge(this.1);
//!                 MergeResult::Success
//!             } else {
//!                 MergeResult::NotMerged(this)
//!             }
//!         })
//!         .build(1);
//!
//!     let mut futures: futures::stream::SelectAll<_> = (10..=50)
//!         .filter_map(|i| {
//!             ProcessString::new(format!("Job {}", i), &runner)
//!                 .ok()
//!                 .map(|f| f.into_stream())
//!         })
//!         .collect();
//!     println!("Jobs enqueued");
//!
//!     block_on(async {
//!         while let Some(result) = futures.next().await {
//!             let processed_string = result.unwrap();
//!             println!(">> {}", processed_string);
//!         }
//!     });
//!     Ok(())
//! }
//!
//! struct ProcessString(String, Promise<String>);
//!
//! impl ProcessString {
//!     fn new(
//!         name: String,
//!         runner: &JobRunner<ProcessString>,
//!     ) -> Result<PromiseFuture<String>, crossbeam_channel::SendError<ProcessString>> {
//!         let (promise, future) = Promise::new();
//!         runner.send(ProcessString(name, promise))?;
//!         Ok(future)
//!     }
//! }
//!
//! impl Job for ProcessString {
//!     type Exclusion = NoExclusion;
//!
//!     fn exclusion(&self) -> Self::Exclusion {
//!         NoExclusion
//!     }
//!
//!     type Priority = ();
//!
//!     fn priority(&self) -> Self::Priority {}
//!
//!     fn execute(self) {
//!         println!("Processing job {}", self.0);
//!         std::thread::sleep(Duration::from_secs(1));
//!         self.1.fulfill(format!("Processed : [{}]", self.0));
//!     }
//! }
//! ```

#![warn(missing_docs)]
#![warn(rust_2018_idioms)]

use parking_lot::Mutex;

use std::{
    fmt,
    sync::Arc,
    time::{Duration, Instant},
};

use runner::ConcurrencyLimitFn;
pub use source::RecurrableJob;
use source::{IntervalRecurringJob, RecurringJob, SourceManager};

pub mod future;
mod runner;
mod source;

/// Top level structure of the crate. Currently, recurring jobs would keep being scheduled once this is dropped, but that will probably change.
///
/// See crate level docs
pub struct JobRunner<J> {
    sender: crossbeam_channel::Sender<J>,
}

impl<J: Job + 'static> JobRunner<J> {
    /// Create a Builder to start building a [`JobRunner`]
    pub fn builder() -> Builder<J> {
        Builder::new()
    }

    /// Send a job to the queue
    pub fn send(&self, job: J) -> Result<(), crossbeam_channel::SendError<J>> {
        self.sender.send(job)
    }
}

impl<J> Clone for JobRunner<J> {
    fn clone(&self) -> Self {
        Self {
            sender: self.sender.clone(),
        }
    }
}

/// Builder of [`JobRunner`]
pub struct Builder<J: Job + 'static> {
    concurrency_limit: Box<ConcurrencyLimitFn<J>>,
    recurring: Vec<Box<dyn RecurringJob<J> + Send>>,
    /// optional function to allow merging of jobs
    merge_fn: Option<fn(J, &mut J) -> MergeResult<J>>,
}

impl<J: Job + Send + 'static> Builder<J> {
    /// Start building a [`JobRunner`]
    fn new() -> Self {
        Builder {
            concurrency_limit: Box::new(|_: <J as Prioritised>::Priority| None as Option<u8>),
            recurring: vec![],
            merge_fn: None,
        }
    }

    /// Enable merging of Jobs in the queue, if a merge function is provided here, it will be tried with each job added to the queue against each job already in the queue
    pub fn enable_merge(mut self, f: fn(J, &mut J) -> MergeResult<J>) -> Self {
        self.merge_fn = Some(f);
        self
    }
}

impl<J: Job + Send + RecurrableJob + 'static> Builder<J> {
    /// Set a job as recurring, the job will be enqueued every time `interval` passes since the `last_enqueue` of a matching job
    pub fn set_recurring(mut self, interval: Duration, last_enqueue: Instant, job: J) -> Self {
        self.recurring.push(Box::new(IntervalRecurringJob {
            last_enqueue,
            interval,
            job,
        }));
        self
    }
}

impl<J: Job + Send + 'static> Default for Builder<J> {
    fn default() -> Self {
        Self::new()
    }
}

impl<J: Job + Send + 'static> Builder<J> {
    /// Function determining, for each priority, how many threads can be allocated to jobs of this priority, any remaining threads will be left idle to service higher-priority jobs. `None` means parallelism won't be limited
    pub fn limit_concurrency(
        mut self,
        concurrency_limit: impl Fn(<J as Job>::Priority) -> Option<u8> + Send + Sync + 'static,
    ) -> Self {
        self.concurrency_limit = Box::new(concurrency_limit);
        self
    }

    /// Build the [`JobRunner`], spawning `thread_num` threads as workers
    pub fn build(self, thread_num: usize) -> JobRunner<J> {
        let (sender, sources) =
            SourceManager::<J, Box<dyn RecurringJob<J> + Send>>::new_with_recurring(
                self.recurring,
                self.merge_fn,
            );
        let jobs = Arc::new(Mutex::new(sources));
        let _threads = runner::spawn(thread_num, jobs, self.concurrency_limit);
        JobRunner { sender }
    }
}

/// A job which can be executed by the runner, with features to synchronise jobs that would interfere with each other and reduce the parallelisation of low priority jobs
pub trait Job: Send {
    /// Type used to check which jobs should not be allowed to run concurrently, see [`Job::exclusion()`]. Use [`NoExclusion`] for jobs which can always be run at the same time, see also [`ExclusionOption`].
    type Exclusion: PartialEq + Copy + fmt::Debug + Send;

    /// Used to check which jobs should not be allowed to run concurrently, if `<Job::Exclusion as PartialEq>::eq(job1.exclusion(), job2.exclusion())`, then `job1` and `job2` can't run at the same time.
    fn exclusion(&self) -> Self::Exclusion;

    /// Type of the priority, the higher prioritys are those which are larger based on [`Ord::cmp`].
    type Priority: Ord + Copy + Send;

    /// Get the priority of this thing
    fn priority(&self) -> Self::Priority;

    /// Execute and consume the job
    fn execute(self);
}

/// A type that can be put in a priority queue, tells the queue which order the items should come out in, whether / how to merge them, and checking whether item's match
trait Prioritised: Sized {
    /// Type of the priority, the higher prioritys are those which are larger based on [`Ord::cmp`].
    type Priority: Ord + Copy + Send;

    /// Get the priority of this thing
    fn priority(&self) -> Self::Priority;
}

impl<J: Job> Prioritised for J {
    type Priority = <J as Job>::Priority;

    fn priority(&self) -> Self::Priority {
        <J as Job>::priority(self)
    }
}

impl<T> Job for T
where
    T: FnOnce() + Send,
{
    type Exclusion = NoExclusion;

    fn exclusion(&self) -> Self::Exclusion {
        NoExclusion
    }

    type Priority = ();

    fn priority(&self) -> Self::Priority {}

    fn execute(self) {
        (self)()
    }
}

/// Result of an attempted merge, see [`Builder::enable_merge`]
pub enum MergeResult<P> {
    /// merge was sucessful, eg. either because the items are the same or one is a superset of the other
    Success,
    /// the attempted items were not suitable for merging
    NotMerged(P),
}

/// Allows any jobs to run at the same time
#[derive(Debug, Copy, Clone)]
pub struct NoExclusion;

impl PartialEq for NoExclusion {
    fn eq(&self, _other: &Self) -> bool {
        false
    }
}

/// Allows some jobs to be run at the same time, others to acquire a keyed exclusive lock, and others to acquire a global exclusive lock
#[derive(Debug, Copy, Clone)]
pub enum ExclusionOption<T> {
    /// This job excludes all others, it can only be run whilst all other workers are idle. NOTE: If the runner is busy this will have to wait until all jobs are finished
    All,
    /// This job excludes some other jobs which match `T`
    Some(T),
    /// This job excludes no other jobs and can run at any time
    None,
}

impl<T: PartialEq> PartialEq for ExclusionOption<T> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ExclusionOption::Some(me), ExclusionOption::Some(other)) => me == other,
            (ExclusionOption::All, _) => true,
            (_, ExclusionOption::All) => true,
            _ => false,
        }
    }
}

impl<T> From<Option<T>> for ExclusionOption<T> {
    fn from(val: Option<T>) -> Self {
        if let Some(val) = val {
            ExclusionOption::Some(val)
        } else {
            ExclusionOption::None
        }
    }
}

impl<T> From<T> for ExclusionOption<T> {
    fn from(val: T) -> Self {
        ExclusionOption::Some(val)
    }
}