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
extern crate redis;
extern crate rustc_serialize;
extern crate uuid;

use std::error::Error;
use std::thread;
use std::sync::mpsc::channel;
use std::time::Duration;
use std::thread::sleep;
use std::marker::{Send, Sync};
use std::sync::Arc;

use redis::{Commands, Client};
use rustc_serialize::json::{encode, decode};
use uuid::Uuid;


#[derive(RustcEncodable, RustcDecodable, Debug, PartialEq)]
pub enum Status {
    QUEUED,
    RUNNING,
    LOST,
    FINISHED,
    FAILED,
}


#[derive(RustcEncodable, RustcDecodable, Debug)]
struct Job {
    uuid: String,
    status: Status,
    args: Vec<String>,
    result: String,
}


impl Job {
    fn new(args: Vec<String>) -> Job {
        Job {
            uuid: Uuid::new_v4().to_string(),
            status: Status::QUEUED,
            args: args,
            result: "".to_string(),
        }
    }
}


pub struct Queue {
    url: String,
    name: String,
}


impl Queue {
    pub fn new(url: &str, name: &str) -> Queue {
        Queue {
            url: url.to_string(),
            name: name.to_string(),
        }
    }

    pub fn drop(&self) -> Result<(), Box<Error>> {
        let client = try!(Client::open(self.url.as_str()));
        let conn = try!(client.get_connection());

        try!(conn.del(format!("{}:uuids", self.name)));

        Ok(())
    }

    pub fn enqueue(&self, args: Vec<String>, expire: usize) -> Result<String, Box<Error>> {
        let client = try!(Client::open(self.url.as_str()));
        let conn = try!(client.get_connection());

        let job = Job::new(args);

        try!(conn.set_ex(format!("{}:{}", self.name, job.uuid),
                         try!(encode(&job)),
                         expire));
        try!(conn.rpush(format!("{}:uuids", self.name), &job.uuid));

        Ok(job.uuid)
    }

    pub fn status(&self, uuid: &str) -> Result<Status, Box<Error>> {
        let client = try!(redis::Client::open(self.url.as_str()));
        let conn = try!(client.get_connection());

        let json: String = try!(conn.get(format!("{}:{}", self.name, uuid)));
        let job: Job = try!(decode(&json));

        Ok(job.status)
    }

    pub fn work<F: Fn(String, Vec<String>) -> Result<String, Box<Error>> + Send + Sync + 'static>
        (&self,
         wait: usize,
         fun: F,
         timeout: usize,
         freq: usize,
         expire: usize,
         fall: bool,
         infinite: bool)
         -> Result<(), Box<Error>> {
        let client = try!(redis::Client::open(self.url.as_str()));
        let conn = try!(client.get_connection());

        let a_fun = Arc::new(fun);
        let uuids_key = format!("{}:uuids", self.name);
        loop {
            let uuids: Vec<String> = try!(conn.blpop(&uuids_key, wait));
            if uuids.len() < 2 {
                if !infinite {
                    break;
                }
                continue;
            }

            let uuid = (&uuids[1]).to_string();
            let key = format!("{}:{}", self.name, uuid);
            let json: String = conn.get(&key).unwrap_or("".to_string());

            if json == "" {
                if !infinite {
                    break;
                }
                continue;
            }

            let mut job: Job = try!(decode(&json));

            job.status = Status::RUNNING;
            try!(conn.set_ex(&key, try!(encode(&job)), timeout + expire));

            let (tx, rx) = channel();
            let ca_fun = a_fun.clone();
            let cuuid = uuid.clone();
            let args = job.args.clone();
            thread::spawn(move || {
                match ca_fun(cuuid, args) {
                    Ok(res) => {
                        tx.send((Status::FINISHED, res)).unwrap_or(());
                    }
                    Err(_) => {
                        tx.send((Status::FAILED, "".to_string())).unwrap_or(());
                    }
                }
            });

            for _ in 0..(timeout * freq) {
                let (status, result) = rx.try_recv().unwrap_or((Status::RUNNING, "".to_string()));
                job.status = status;
                job.result = result;
                if job.status != Status::RUNNING {
                    break;
                }
                sleep(Duration::from_millis(1000 / freq as u64));
            }
            if job.status == Status::RUNNING {
                job.status = Status::LOST;
            }
            try!(conn.set_ex(&key, try!(encode(&job)), expire));

            if fall && job.status == Status::LOST {
                panic!("LOST");
            }

            if !infinite {
                break;
            }
        }

        Ok(())
    }

    pub fn result(&self, uuid: &str) -> Result<String, Box<Error>> {
        let client = try!(redis::Client::open(self.url.as_str()));
        let conn = try!(client.get_connection());

        let json: String = try!(conn.get(format!("{}:{}", self.name, uuid)));
        let job: Job = try!(decode(&json));

        Ok(job.result)
    }
}