background-jobs/jobs-core/src/lib.rs

337 lines
8.4 KiB
Rust
Raw Normal View History

2018-11-05 02:13:06 +00:00
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
2018-11-06 02:53:03 +00:00
use std::collections::HashMap;
2018-11-05 02:13:06 +00:00
2018-11-07 03:26:48 +00:00
use chrono::{offset::Utc, DateTime, Duration as OldDuration};
2018-11-05 02:13:06 +00:00
use failure::Error;
use futures::future::{Either, Future, IntoFuture};
use serde::{de::DeserializeOwned, ser::Serialize};
use serde_json::Value;
2018-11-06 02:53:03 +00:00
pub mod storage;
2018-11-05 02:13:06 +00:00
#[derive(Debug, Fail)]
pub enum JobError {
#[fail(display = "Error performing job: {}", _0)]
Processing(#[cause] Error),
#[fail(display = "Could not make JSON value from arguments")]
Json,
#[fail(display = "No processor available for job")]
MissingProcessor,
}
/// The Processor trait
///
2018-11-07 02:01:43 +00:00
/// Processors define the logic for executing jobs
2018-11-08 01:50:21 +00:00
pub trait Processor: Clone {
2018-11-05 02:13:06 +00:00
type Arguments: Serialize + DeserializeOwned;
/// The name of the processor
///
/// This name must be unique!!! It is used to look up which processor should handle a job
fn name() -> &'static str;
/// Define the default number of retries for a given processor
///
/// Jobs can override
fn max_retries() -> MaxRetries;
2018-11-07 03:26:48 +00:00
/// Define the default backoff strategy for a given processor
///
/// Jobs can override
fn backoff_strategy() -> Backoff;
2018-11-05 02:13:06 +00:00
/// Defines how jobs for this processor are processed
///
/// Please do not perform blocking operations in the process method except if put behind
/// tokio's `blocking` abstraction
fn process(&self, args: Self::Arguments) -> Box<dyn Future<Item = (), Error = Error> + Send>;
/// A provided method to create a new Job from provided arguments
///
/// ### Example
///
/// ```rust
/// #[macro_use]
/// extern crate log;
///
/// use jobs::{Processor, MaxRetries};
/// use failure::Error;
/// use futures::future::{Future, IntoFuture};
///
/// struct MyProcessor;
///
/// impl Processor for MyProcessor {
/// type Arguments = i32;
///
/// fn name() -> &'static str {
/// "IncrementProcessor"
/// }
///
/// fn max_retries() -> MaxRetries {
/// MaxRetries::Count(1)
/// }
///
2018-11-07 03:26:48 +00:00
/// fn backoff_strategy() -> Backoff {
/// Backoff::Exponential(2)
/// }
///
2018-11-05 02:13:06 +00:00
/// fn process(
/// &self,
/// args: Self::Arguments,
/// ) -> Box<dyn Future<Item = (), Error = Error> + Send> {
/// info!("Processing {}", args);
///
/// Box::new(Ok(()).into_future())
/// }
/// }
///
/// fn main() -> Result<(), Error> {
/// let job = MyProcessor::new_job(1234, None)?;
///
/// Ok(())
/// }
/// ```
2018-11-07 03:26:48 +00:00
fn new_job(
args: Self::Arguments,
max_retries: Option<MaxRetries>,
backoff_strategy: Option<Backoff>,
) -> Result<JobInfo, Error> {
2018-11-05 02:13:06 +00:00
let job = JobInfo {
id: None,
processor: Self::name().to_owned(),
status: JobStatus::Pending,
args: serde_json::to_value(args)?,
2018-11-07 03:26:48 +00:00
retry_count: 0,
max_retries: max_retries.unwrap_or(Self::max_retries()),
next_queue: None,
backoff_strategy: backoff_strategy.unwrap_or(Self::backoff_strategy()),
2018-11-05 02:13:06 +00:00
};
Ok(job)
}
/// A provided method to coerce arguments into the expected type
fn do_processing(&self, args: Value) -> Box<dyn Future<Item = (), Error = JobError> + Send> {
let res = serde_json::from_value::<Self::Arguments>(args);
let fut = match res {
Ok(item) => Either::A(self.process(item).map_err(JobError::Processing)),
Err(_) => Either::B(Err(JobError::Json).into_future()),
};
Box::new(fut)
}
}
2018-11-07 02:01:43 +00:00
/// Set the status of a job when storing it
2018-11-05 02:13:06 +00:00
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum JobStatus {
2018-11-07 02:01:43 +00:00
/// Job should be queued
2018-11-05 02:13:06 +00:00
Pending,
2018-11-07 02:01:43 +00:00
/// Job is running
Running,
/// Job has failed
Failed,
/// Job has finished
2018-11-05 02:13:06 +00:00
Finished,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum Backoff {
/// Seconds between execution
Linear(usize),
/// Base for seconds between execution
Exponential(usize),
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum MaxRetries {
/// Keep retrying forever
Infinite,
/// Put a limit on the number of retries
Count(usize),
}
2018-11-07 03:26:48 +00:00
impl MaxRetries {
fn compare(&self, retry_count: u32) -> ShouldStop {
match *self {
MaxRetries::Infinite => ShouldStop::Requeue,
MaxRetries::Count(ref count) => {
if (retry_count as usize) <= *count {
2018-11-07 03:26:48 +00:00
ShouldStop::Requeue
} else {
ShouldStop::LimitReached
}
}
}
}
}
2018-11-05 02:13:06 +00:00
#[derive(Clone, Debug, Eq, PartialEq)]
2018-11-06 02:53:03 +00:00
pub enum ShouldStop {
2018-11-05 02:13:06 +00:00
LimitReached,
Requeue,
}
impl ShouldStop {
2018-11-06 02:53:03 +00:00
pub fn should_requeue(&self) -> bool {
2018-11-05 02:13:06 +00:00
*self == ShouldStop::Requeue
}
}
2018-11-07 02:01:43 +00:00
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
2018-11-05 02:13:06 +00:00
pub struct JobInfo {
/// ID of the job, None means an ID has not been set
id: Option<usize>,
/// Name of the processor that should handle this job
processor: String,
/// Arguments for a given job
args: Value,
/// Status of the job
status: JobStatus,
/// Retries left for this job, None means no limit
2018-11-07 03:26:48 +00:00
retry_count: u32,
/// the initial MaxRetries value, for comparing to the current retry count
max_retries: MaxRetries,
/// How often retries should be scheduled
backoff_strategy: Backoff,
2018-11-06 02:53:03 +00:00
/// The time this job was re-queued
2018-11-07 03:26:48 +00:00
next_queue: Option<DateTime<Utc>>,
2018-11-05 02:13:06 +00:00
}
impl JobInfo {
2018-11-07 03:26:48 +00:00
fn id(&self) -> Option<usize> {
2018-11-05 02:13:06 +00:00
self.id.clone()
}
2018-11-07 03:26:48 +00:00
fn set_id(&mut self, id: usize) {
2018-11-05 02:13:06 +00:00
if self.id.is_none() {
self.id = Some(id);
}
}
2018-11-07 02:01:43 +00:00
2018-11-07 03:26:48 +00:00
fn increment(&mut self) -> ShouldStop {
self.retry_count += 1;
self.max_retries.compare(self.retry_count)
}
fn next_queue(&mut self) {
let now = Utc::now();
let next_queue = match self.backoff_strategy {
Backoff::Linear(secs) => now + OldDuration::seconds(secs as i64),
Backoff::Exponential(base) => {
let secs = base.pow(self.retry_count);
now + OldDuration::seconds(secs as i64)
}
};
self.next_queue = Some(next_queue);
}
fn is_ready(&self, now: DateTime<Utc>) -> bool {
match self.next_queue {
Some(ref time) => now > *time,
None => true,
}
}
fn is_failed(&self) -> bool {
self.status == JobStatus::Failed
}
fn pending(&mut self) {
self.status = JobStatus::Pending;
}
2018-11-07 02:01:43 +00:00
fn fail(&mut self) {
self.status = JobStatus::Failed;
}
fn pass(&mut self) {
self.status = JobStatus::Finished;
}
2018-11-05 02:13:06 +00:00
}
pub type ProcessFn =
Box<dyn Fn(Value) -> Box<dyn Future<Item = (), Error = JobError> + Send> + Send>;
pub struct Processors {
inner: HashMap<String, ProcessFn>,
}
impl Processors {
pub fn new() -> Self {
Default::default()
}
pub fn register_processor<P>(&mut self, processor: P)
where
P: Processor + Send + Sync + 'static,
{
self.inner.insert(
P::name().to_owned(),
Box::new(move |value| processor.do_processing(value)),
);
}
2018-11-06 02:53:03 +00:00
pub fn process_job(&self, job: JobInfo) -> impl Future<Item = JobInfo, Error = ()> {
let opt = self
.inner
.get(&job.processor)
.map(|processor| process(processor, job.clone()));
if let Some(fut) = opt {
Either::A(fut)
} else {
error!("Processor {} not present", job.processor);
Either::B(Ok(job).into_future())
2018-11-05 02:13:06 +00:00
}
}
}
impl Default for Processors {
fn default() -> Self {
Processors {
inner: Default::default(),
}
}
}
2018-11-07 02:01:43 +00:00
fn process(process_fn: &ProcessFn, mut job: JobInfo) -> impl Future<Item = JobInfo, Error = ()> {
2018-11-05 02:13:06 +00:00
let args = job.args.clone();
let processor = job.processor.clone();
2018-11-06 02:53:03 +00:00
process_fn(args).then(move |res| match res {
Ok(_) => {
info!("Job completed, {}", processor);
2018-11-07 02:01:43 +00:00
job.pass();
2018-11-06 02:53:03 +00:00
Ok(job)
}
2018-11-05 02:13:06 +00:00
Err(e) => {
error!("Job errored, {}, {}", processor, e);
2018-11-07 02:01:43 +00:00
job.fail();
2018-11-06 02:53:03 +00:00
Ok(job)
2018-11-05 02:13:06 +00:00
}
})
}