2019-09-22 17:33:33 +00:00
|
|
|
#![deny(missing_docs)]
|
|
|
|
|
|
|
|
//! # An Actix-based Jobs Processor
|
|
|
|
//!
|
|
|
|
//! This library will spin up as many actors as requested for each processor to process jobs
|
|
|
|
//! concurrently. Keep in mind that, by default, spawned actors run on the same Arbiter, so in
|
|
|
|
//! order to achieve parallel execution, multiple Arbiters must be in use.
|
|
|
|
//!
|
|
|
|
//! The thread count is used to spawn Synchronous Actors to handle the storage of job
|
|
|
|
//! information. For storage backends that cannot be parallelized, a thread-count of 1 should be
|
|
|
|
//! used. By default, the number of cores of the running system is used.
|
|
|
|
//!
|
|
|
|
//! ### Example
|
2019-09-22 17:49:28 +00:00
|
|
|
//! ```rust,ignore
|
2020-03-21 03:24:31 +00:00
|
|
|
//! use anyhow::Error;
|
2020-04-21 00:30:56 +00:00
|
|
|
//! use background_jobs::{create_server, Backoff, Job, MaxRetries, WorkerConfig};
|
2020-03-21 14:44:38 +00:00
|
|
|
//! use futures::future::{ok, Ready};
|
2019-09-22 17:33:33 +00:00
|
|
|
//!
|
|
|
|
//! const DEFAULT_QUEUE: &'static str = "default";
|
|
|
|
//!
|
|
|
|
//! #[derive(Clone, Debug)]
|
|
|
|
//! pub struct MyState {
|
|
|
|
//! pub app_name: String,
|
|
|
|
//! }
|
|
|
|
//!
|
2020-03-21 14:44:38 +00:00
|
|
|
//! #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
2019-09-22 17:33:33 +00:00
|
|
|
//! pub struct MyJob {
|
|
|
|
//! some_usize: usize,
|
|
|
|
//! other_usize: usize,
|
|
|
|
//! }
|
|
|
|
//!
|
2020-03-21 02:31:03 +00:00
|
|
|
//! #[actix_rt::main]
|
|
|
|
//! async fn main() -> Result<(), Error> {
|
2019-09-22 17:33:33 +00:00
|
|
|
//! // Set up our Storage
|
|
|
|
//! // For this example, we use the default in-memory storage mechanism
|
|
|
|
//! use background_jobs::memory_storage::Storage;
|
|
|
|
//! let storage = Storage::new();
|
|
|
|
//!
|
|
|
|
//! // Start the application server. This guards access to to the jobs store
|
2020-03-21 03:24:31 +00:00
|
|
|
//! let queue_handle = create_server(storage);
|
2019-09-22 17:33:33 +00:00
|
|
|
//!
|
|
|
|
//! // Configure and start our workers
|
|
|
|
//! WorkerConfig::new(move || MyState::new("My App"))
|
2020-04-21 00:30:56 +00:00
|
|
|
//! .register::<MyJob>()
|
|
|
|
//! .set_worker_count(DEFAULT_QUEUE, 16)
|
2019-09-22 17:33:33 +00:00
|
|
|
//! .start(queue_handle.clone());
|
|
|
|
//!
|
|
|
|
//! // Queue our jobs
|
|
|
|
//! queue_handle.queue(MyJob::new(1, 2))?;
|
|
|
|
//! queue_handle.queue(MyJob::new(3, 4))?;
|
|
|
|
//! queue_handle.queue(MyJob::new(5, 6))?;
|
|
|
|
//!
|
2020-03-21 02:31:03 +00:00
|
|
|
//! actix_rt::signal::ctrl_c().await?;
|
|
|
|
//!
|
2019-09-22 17:33:33 +00:00
|
|
|
//! Ok(())
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! impl MyState {
|
|
|
|
//! pub fn new(app_name: &str) -> Self {
|
|
|
|
//! MyState {
|
|
|
|
//! app_name: app_name.to_owned(),
|
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! impl MyJob {
|
|
|
|
//! pub fn new(some_usize: usize, other_usize: usize) -> Self {
|
|
|
|
//! MyJob {
|
|
|
|
//! some_usize,
|
|
|
|
//! other_usize,
|
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//!
|
2020-03-21 02:31:03 +00:00
|
|
|
//! #[async_trait::async_trait]
|
2019-09-22 17:33:33 +00:00
|
|
|
//! impl Job for MyJob {
|
|
|
|
//! type State = MyState;
|
2020-03-21 14:44:38 +00:00
|
|
|
//! type Future = Ready<Result<(), Error>>;
|
2019-09-22 17:33:33 +00:00
|
|
|
//!
|
2020-04-21 00:30:56 +00:00
|
|
|
//! // The name of the job. It is super important that each job has a unique name,
|
|
|
|
//! // because otherwise one job will overwrite another job when they're being
|
2019-09-22 17:33:33 +00:00
|
|
|
//! // registered.
|
2020-04-21 00:30:56 +00:00
|
|
|
//! const NAME: &'static str = "MyJob";
|
2019-09-22 17:33:33 +00:00
|
|
|
//!
|
|
|
|
//! // The queue that this processor belongs to
|
|
|
|
//! //
|
|
|
|
//! // Workers have the option to subscribe to specific queues, so this is important to
|
|
|
|
//! // determine which worker will call the processor
|
|
|
|
//! //
|
|
|
|
//! // Jobs can optionally override the queue they're spawned on
|
|
|
|
//! const QUEUE: &'static str = DEFAULT_QUEUE;
|
|
|
|
//!
|
|
|
|
//! // The number of times background-jobs should try to retry a job before giving up
|
|
|
|
//! //
|
2020-03-21 03:24:31 +00:00
|
|
|
//! // This value defaults to MaxRetries::Count(5)
|
2019-09-22 17:33:33 +00:00
|
|
|
//! // Jobs can optionally override this value
|
|
|
|
//! const MAX_RETRIES: MaxRetries = MaxRetries::Count(1);
|
|
|
|
//!
|
|
|
|
//! // The logic to determine how often to retry this job if it fails
|
|
|
|
//! //
|
2020-03-21 03:24:31 +00:00
|
|
|
//! // This value defaults to Backoff::Exponential(2)
|
2019-09-22 17:33:33 +00:00
|
|
|
//! // Jobs can optionally override this value
|
|
|
|
//! const BACKOFF_STRATEGY: Backoff = Backoff::Exponential(2);
|
2020-03-21 03:24:31 +00:00
|
|
|
//!
|
|
|
|
//! // When should the job be considered dead
|
|
|
|
//! //
|
|
|
|
//! // The timeout defines when a job is allowed to be considered dead, and so can be retried
|
|
|
|
//! // by the job processor. The value is in milliseconds and defaults to 15,000
|
|
|
|
//! const TIMEOUT: i64 = 15_000
|
2020-04-21 00:30:56 +00:00
|
|
|
//!
|
|
|
|
//! async fn run(self, state: MyState) -> Self::Future {
|
|
|
|
//! println!("{}: args, {:?}", state.app_name, self);
|
|
|
|
//!
|
|
|
|
//! ok(())
|
|
|
|
//! }
|
2019-09-22 17:33:33 +00:00
|
|
|
//! }
|
|
|
|
//! ```
|
|
|
|
|
2021-02-03 22:32:56 +00:00
|
|
|
use actix_rt::{Arbiter, ArbiterHandle};
|
2020-03-21 02:31:03 +00:00
|
|
|
use anyhow::Error;
|
2020-04-21 17:04:18 +00:00
|
|
|
use background_jobs_core::{new_job, new_scheduled_job, Job, ProcessorMap, Stats, Storage};
|
|
|
|
use chrono::{DateTime, Utc};
|
2020-03-21 02:31:03 +00:00
|
|
|
use log::error;
|
|
|
|
use std::{collections::BTreeMap, sync::Arc, time::Duration};
|
2018-12-16 18:43:44 +00:00
|
|
|
|
2019-05-28 00:23:25 +00:00
|
|
|
mod every;
|
2018-12-16 18:43:44 +00:00
|
|
|
mod server;
|
2019-05-27 17:29:11 +00:00
|
|
|
mod storage;
|
2018-12-16 18:43:44 +00:00
|
|
|
mod worker;
|
2019-05-28 00:23:25 +00:00
|
|
|
|
2020-03-21 02:31:03 +00:00
|
|
|
use self::{every::every, server::Server, worker::local_worker};
|
2018-12-16 18:43:44 +00:00
|
|
|
|
2020-03-30 15:36:49 +00:00
|
|
|
pub use background_jobs_core::ActixJob;
|
|
|
|
|
2020-03-21 02:31:03 +00:00
|
|
|
/// Create a new Server
|
2019-09-22 17:33:33 +00:00
|
|
|
///
|
2020-03-21 02:31:03 +00:00
|
|
|
/// In previous versions of this library, the server itself was run on it's own dedicated threads
|
|
|
|
/// and guarded access to jobs via messages. Since we now have futures-aware synchronization
|
|
|
|
/// primitives, the Server has become an object that gets shared between client threads.
|
|
|
|
///
|
2021-01-06 18:24:27 +00:00
|
|
|
/// This method will panic if not called from an actix runtime
|
2020-03-21 02:31:03 +00:00
|
|
|
pub fn create_server<S>(storage: S) -> QueueHandle
|
2019-05-25 20:22:26 +00:00
|
|
|
where
|
|
|
|
S: Storage + Sync + 'static,
|
|
|
|
{
|
2021-01-06 18:24:27 +00:00
|
|
|
let arbiter = Arbiter::current();
|
2020-03-21 02:31:03 +00:00
|
|
|
QueueHandle {
|
2021-01-06 18:24:27 +00:00
|
|
|
inner: Server::new(&arbiter, storage),
|
|
|
|
arbiter,
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Worker Configuration
|
|
|
|
///
|
|
|
|
/// This type is used for configuring and creating workers to process jobs. Before starting the
|
2020-04-21 00:30:56 +00:00
|
|
|
/// workers, register `Job` types with this struct. This worker registration allows for
|
2019-06-01 15:58:25 +00:00
|
|
|
/// different worker processes to handle different sets of workers.
|
|
|
|
#[derive(Clone)]
|
2019-05-25 20:22:26 +00:00
|
|
|
pub struct WorkerConfig<State>
|
2018-12-16 18:43:44 +00:00
|
|
|
where
|
2019-05-25 20:22:26 +00:00
|
|
|
State: Clone + 'static,
|
2018-12-16 18:43:44 +00:00
|
|
|
{
|
2019-05-25 20:22:26 +00:00
|
|
|
processors: ProcessorMap<State>,
|
|
|
|
queues: BTreeMap<String, u64>,
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
|
2019-05-25 20:22:26 +00:00
|
|
|
impl<State> WorkerConfig<State>
|
2018-12-16 18:43:44 +00:00
|
|
|
where
|
2019-05-25 20:22:26 +00:00
|
|
|
State: Clone + 'static,
|
2018-12-16 18:43:44 +00:00
|
|
|
{
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Create a new WorkerConfig
|
|
|
|
///
|
|
|
|
/// The supplied function should return the State required by the jobs intended to be
|
|
|
|
/// processed. The function must be sharable between threads, but the state itself does not
|
|
|
|
/// have this requirement.
|
2019-05-25 20:22:26 +00:00
|
|
|
pub fn new(state_fn: impl Fn() -> State + Send + Sync + 'static) -> Self {
|
2018-12-16 18:43:44 +00:00
|
|
|
WorkerConfig {
|
2019-06-01 15:58:25 +00:00
|
|
|
processors: ProcessorMap::new(Arc::new(state_fn)),
|
2018-12-16 18:43:44 +00:00
|
|
|
queues: BTreeMap::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-21 00:30:56 +00:00
|
|
|
/// Register a `Job` with the worker
|
2019-06-01 15:58:25 +00:00
|
|
|
///
|
|
|
|
/// This enables the worker to handle jobs associated with this processor. If a processor is
|
|
|
|
/// not registered, none of it's jobs will be run, even if another processor handling the same
|
|
|
|
/// job queue is registered.
|
2020-04-21 00:30:56 +00:00
|
|
|
pub fn register<J>(mut self) -> Self
|
2019-05-28 01:49:46 +00:00
|
|
|
where
|
|
|
|
J: Job<State = State>,
|
|
|
|
{
|
2020-04-21 00:30:56 +00:00
|
|
|
self.queues.insert(J::QUEUE.to_owned(), 4);
|
|
|
|
self.processors.register::<J>();
|
2019-05-27 17:29:11 +00:00
|
|
|
self
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Set the number of workers to run for a given queue
|
|
|
|
///
|
|
|
|
/// This does not spin up any additional threads. The `Arbiter` the workers are spawned onto
|
|
|
|
/// will handle processing all workers, regardless of how many are configured.
|
|
|
|
///
|
|
|
|
/// By default, 4 workers are spawned
|
2020-04-21 00:30:56 +00:00
|
|
|
pub fn set_worker_count(mut self, queue: &str, count: u64) -> Self {
|
2018-12-16 18:43:44 +00:00
|
|
|
self.queues.insert(queue.to_owned(), count);
|
2019-05-27 17:29:11 +00:00
|
|
|
self
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Start the workers in the current arbiter
|
2021-01-06 18:24:27 +00:00
|
|
|
///
|
|
|
|
/// This method will panic if not called from an actix runtime
|
2019-05-27 17:29:11 +00:00
|
|
|
pub fn start(self, queue_handle: QueueHandle) {
|
2021-10-07 02:09:07 +00:00
|
|
|
let handle = Arbiter::current();
|
|
|
|
|
|
|
|
self.start_in_arbiter_handle(&handle, queue_handle);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start the workers in the provided arbiter
|
|
|
|
pub fn start_in_arbiter(self, arbiter: &Arbiter, queue_handle: QueueHandle) {
|
2021-10-07 02:12:16 +00:00
|
|
|
self.start_in_arbiter_handle(&arbiter.handle(), queue_handle)
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
2019-06-01 15:58:25 +00:00
|
|
|
|
2021-10-07 02:09:07 +00:00
|
|
|
/// Start the workers in the provided arbiter via it's handle
|
|
|
|
pub fn start_in_arbiter_handle(self, arbiter: &ArbiterHandle, queue_handle: QueueHandle) {
|
2020-03-22 17:52:43 +00:00
|
|
|
for (key, count) in self.queues.into_iter() {
|
|
|
|
for _ in 0..count {
|
2019-06-01 15:58:25 +00:00
|
|
|
let key = key.clone();
|
2020-03-22 17:52:43 +00:00
|
|
|
let processors = self.processors.clone();
|
|
|
|
let server = queue_handle.inner.clone();
|
|
|
|
|
2021-02-03 22:32:56 +00:00
|
|
|
arbiter.spawn_fn(move || {
|
2020-03-22 17:52:43 +00:00
|
|
|
local_worker(key, processors.cached(), server);
|
2019-06-01 15:58:25 +00:00
|
|
|
});
|
2020-03-22 17:52:43 +00:00
|
|
|
}
|
|
|
|
}
|
2019-06-01 15:58:25 +00:00
|
|
|
}
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 15:58:25 +00:00
|
|
|
/// A handle to the job server, used for queuing new jobs
|
|
|
|
///
|
|
|
|
/// `QueueHandle` should be stored in your application's state in order to allow all parts of your
|
|
|
|
/// application to spawn jobs.
|
2018-12-16 18:43:44 +00:00
|
|
|
#[derive(Clone)]
|
2019-05-27 17:29:11 +00:00
|
|
|
pub struct QueueHandle {
|
2020-03-21 02:31:03 +00:00
|
|
|
inner: Server,
|
2021-02-03 22:32:56 +00:00
|
|
|
arbiter: ArbiterHandle,
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|
|
|
|
|
2019-05-27 17:29:11 +00:00
|
|
|
impl QueueHandle {
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Queues a job for execution
|
|
|
|
///
|
|
|
|
/// This job will be sent to the server for storage, and will execute whenever a worker for the
|
|
|
|
/// job's queue is free to do so.
|
2019-05-28 00:01:21 +00:00
|
|
|
pub fn queue<J>(&self, job: J) -> Result<(), Error>
|
2018-12-16 18:43:44 +00:00
|
|
|
where
|
2019-05-28 00:01:21 +00:00
|
|
|
J: Job,
|
2018-12-16 18:43:44 +00:00
|
|
|
{
|
2020-04-21 00:30:56 +00:00
|
|
|
let job = new_job(job)?;
|
2020-03-21 02:31:03 +00:00
|
|
|
let server = self.inner.clone();
|
2021-02-03 22:32:56 +00:00
|
|
|
self.arbiter.spawn(async move {
|
2020-03-21 02:31:03 +00:00
|
|
|
if let Err(e) = server.new_job(job).await {
|
|
|
|
error!("Error creating job, {}", e);
|
|
|
|
}
|
2021-02-03 22:32:56 +00:00
|
|
|
});
|
2018-12-16 18:43:44 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2018-12-18 22:50:47 +00:00
|
|
|
|
2020-04-21 17:04:18 +00:00
|
|
|
/// Schedule a job for execution later
|
|
|
|
///
|
|
|
|
/// This job will be sent to the server for storage, and will execute after the specified time
|
|
|
|
/// and when a worker for the job's queue is free to do so.
|
|
|
|
pub fn schedule<J>(&self, job: J, after: DateTime<Utc>) -> Result<(), Error>
|
|
|
|
where
|
|
|
|
J: Job,
|
|
|
|
{
|
|
|
|
let job = new_scheduled_job(job, after)?;
|
|
|
|
let server = self.inner.clone();
|
2021-02-03 22:32:56 +00:00
|
|
|
self.arbiter.spawn(async move {
|
2020-04-21 17:04:18 +00:00
|
|
|
if let Err(e) = server.new_job(job).await {
|
|
|
|
error!("Error creating job, {}", e);
|
|
|
|
}
|
2021-02-03 22:32:56 +00:00
|
|
|
});
|
2020-04-21 17:04:18 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2019-06-01 15:58:25 +00:00
|
|
|
/// Queues a job for recurring execution
|
|
|
|
///
|
|
|
|
/// This job will be added to it's queue on the server once every `Duration`. It will be
|
|
|
|
/// processed whenever workers are free to do so.
|
|
|
|
pub fn every<J>(&self, duration: Duration, job: J)
|
|
|
|
where
|
2021-01-06 18:24:27 +00:00
|
|
|
J: Job + Clone + Send + 'static,
|
2019-06-01 15:58:25 +00:00
|
|
|
{
|
2021-01-06 18:24:27 +00:00
|
|
|
every(self, duration, job);
|
2019-06-01 15:58:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return an overview of the processor's statistics
|
2020-03-21 02:31:03 +00:00
|
|
|
pub async fn get_stats(&self) -> Result<Stats, Error> {
|
|
|
|
self.inner.get_stats().await
|
2018-12-18 22:50:47 +00:00
|
|
|
}
|
2018-12-16 18:43:44 +00:00
|
|
|
}
|