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
use std::{collections::BTreeMap, path::PathBuf, sync::Arc};

use actix::{Actor, Addr, SyncArbiter};
use background_jobs_core::{Processor, ProcessorMap, Stats, Storage};
use failure::Error;
use futures::Future;

mod pinger;
mod server;
mod worker;
pub use self::{server::Server, worker::LocalWorker};

use self::{
    pinger::Pinger,
    server::{CheckDb, EitherJob, GetStats, RequestJob},
    worker::ProcessJob,
};

pub struct ServerConfig {
    server_id: usize,
    db_path: PathBuf,
}

impl ServerConfig {
    pub fn new(server_id: usize, db_path: PathBuf) -> Self {
        ServerConfig { server_id, db_path }
    }

    pub fn start<S>(self) -> QueueHandle<S>
    where
        S: Clone + Send + Sync + 'static,
    {
        let ServerConfig { server_id, db_path } = self;

        let server = SyncArbiter::start(1, move || {
            Server::new(server_id, Storage::init(db_path.clone()).unwrap())
        });

        Pinger::new(server.clone()).start();

        QueueHandle { inner: server }
    }
}

pub struct WorkerConfig<S>
where
    S: Clone + Send + Sync + 'static,
{
    processors: ProcessorMap<S>,
    queues: BTreeMap<String, usize>,
}

impl<S> WorkerConfig<S>
where
    S: Clone + Send + Sync + 'static,
{
    pub fn new(state: S) -> Self {
        WorkerConfig {
            processors: ProcessorMap::new(state),
            queues: BTreeMap::new(),
        }
    }

    pub fn register<P>(&mut self, processor: P)
    where
        P: Processor<S> + Send + Sync + 'static,
    {
        self.queues.insert(P::QUEUE.to_owned(), 4);
        self.processors.register_processor(processor);
    }

    pub fn set_processor_count(&mut self, queue: &str, count: usize) {
        self.queues.insert(queue.to_owned(), count);
    }

    pub fn start(self, queue_handle: QueueHandle<S>) {
        let processors = Arc::new(self.processors);

        self.queues.into_iter().fold(0, |acc, (key, count)| {
            (0..count).for_each(|i| {
                LocalWorker::new(
                    acc + i + 1000,
                    key.clone(),
                    processors.clone(),
                    queue_handle.inner.clone(),
                )
                .start();
            });

            acc + count
        });
    }
}

#[derive(Clone)]
pub struct QueueHandle<S>
where
    S: Clone + Send + Sync + 'static,
{
    inner: Addr<Server<LocalWorker<S>>>,
}

impl<S> QueueHandle<S>
where
    S: Clone + Send + Sync + 'static,
{
    pub fn queue<P>(&self, job: P::Job) -> Result<(), Error>
    where
        P: Processor<S>,
    {
        self.inner.do_send(EitherJob::New(P::new_job(job)?));
        Ok(())
    }

    pub fn get_stats(&self) -> Box<dyn Future<Item = Stats, Error = Error> + Send> {
        Box::new(self.inner.send(GetStats).then(coerce))
    }
}

fn coerce<I, E, F>(res: Result<Result<I, E>, F>) -> Result<I, E>
where
    E: From<F>,
{
    match res {
        Ok(inner) => inner,
        Err(e) => Err(e.into()),
    }
}