background-jobs/jobs-actix/src/worker.rs

90 lines
2 KiB
Rust
Raw Normal View History

2018-12-16 18:43:44 +00:00
use std::sync::Arc;
use actix::{
fut::{wrap_future, ActorFuture},
Actor, Addr, AsyncContext, Context, Handler, Message,
};
use background_jobs_core::{JobInfo, ProcessorMap, Storage};
2018-12-16 18:43:44 +00:00
use log::info;
use crate::{RequestJob, ReturningJob, Server};
2018-12-16 18:43:44 +00:00
pub struct ProcessJob {
job: JobInfo,
}
impl ProcessJob {
pub fn new(job: JobInfo) -> Self {
ProcessJob { job }
}
}
impl Message for ProcessJob {
type Result = ();
}
pub struct LocalWorker<S, State>
2018-12-16 18:43:44 +00:00
where
S: Storage + 'static,
2019-05-24 03:41:34 +00:00
State: Clone + 'static,
2018-12-16 18:43:44 +00:00
{
id: u64,
2018-12-16 18:43:44 +00:00
queue: String,
processors: Arc<ProcessorMap<State>>,
server: Addr<Server<S, LocalWorker<S, State>>>,
2018-12-16 18:43:44 +00:00
}
impl<S, State> LocalWorker<S, State>
2018-12-16 18:43:44 +00:00
where
S: Storage + 'static,
2019-05-24 03:41:34 +00:00
State: Clone + 'static,
2018-12-16 18:43:44 +00:00
{
pub fn new(
id: u64,
2018-12-16 18:43:44 +00:00
queue: String,
processors: Arc<ProcessorMap<State>>,
server: Addr<Server<S, Self>>,
2018-12-16 18:43:44 +00:00
) -> Self {
LocalWorker {
id,
queue,
processors,
server,
}
}
}
impl<S, State> Actor for LocalWorker<S, State>
2018-12-16 18:43:44 +00:00
where
S: Storage + 'static,
2019-05-24 03:41:34 +00:00
State: Clone + 'static,
2018-12-16 18:43:44 +00:00
{
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.server
.do_send(RequestJob::new(self.id, &self.queue, ctx.address()));
}
}
impl<S, State> Handler<ProcessJob> for LocalWorker<S, State>
2018-12-16 18:43:44 +00:00
where
S: Storage + 'static,
2019-05-24 03:41:34 +00:00
State: Clone + 'static,
2018-12-16 18:43:44 +00:00
{
type Result = ();
fn handle(&mut self, msg: ProcessJob, ctx: &mut Self::Context) -> Self::Result {
info!("Worker {} processing job {}", self.id, msg.job.id());
let fut =
wrap_future::<_, Self>(self.processors.process_job(msg.job)).map(|job, actor, ctx| {
actor.server.do_send(ReturningJob(job));
2018-12-16 18:43:44 +00:00
actor
.server
.do_send(RequestJob::new(actor.id, &actor.queue, ctx.address()));
});
ctx.spawn(fut);
}
}