-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmod.rs
318 lines (284 loc) · 8.85 KB
/
mod.rs
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::default::Default;
use std::env;
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::Value;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use time::{Duration, OffsetDateTime};
use futures::executor::block_on;
use futures::future::TryFutureExt;
use redis::aio::ConnectionManager;
const REDIS_URL_ENV: &str = "REDIS_URL";
const REDIS_URL_DEFAULT: &str = "redis://127.0.0.1/";
pub type RedisPool = ConnectionManager;
#[derive(Debug)]
pub struct ClientError {
kind: ErrorKind,
}
#[derive(Debug)]
enum ErrorKind {
Redis(redis::RedisError),
}
impl std::error::Error for ClientError {}
pub fn create_redis_pool() -> Result<ConnectionManager, ClientError> {
block_on(create_async_redis_pool())
}
pub async fn create_async_redis_pool() -> Result<ConnectionManager, ClientError> {
let redis_url = &env::var(REDIS_URL_ENV).unwrap_or_else(|_| REDIS_URL_DEFAULT.to_owned());
// Note: this connection is multiplexed. Users of this object will call clone(), but the same underlying connection will be used.
// https://docs.rs/redis/latest/redis/aio/struct.ConnectionManager.html
match ConnectionManager::new(redis::Client::open((*redis_url).clone()).unwrap()).await {
Ok(pool) => Ok(pool),
Err(err) => Err(ClientError {
kind: ErrorKind::Redis(err),
}),
}
}
pub struct Job {
pub class: String,
pub args: Vec<Value>,
pub retry: i64,
pub queue: String,
pub jid: String,
pub created_at: u64,
pub enqueued_at: u64,
}
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ErrorKind::Redis(ref err) => err.fmt(f),
}
}
}
impl From<redis::RedisError> for ClientError {
fn from(error: redis::RedisError) -> ClientError {
ClientError {
kind: ErrorKind::Redis(error),
}
}
}
pub struct JobOpts {
pub retry: i64,
pub queue: String,
pub jid: String,
pub created_at: u64,
pub enqueued_at: u64,
}
impl Default for JobOpts {
fn default() -> JobOpts {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as u64;
let mut rng = thread_rng();
let jid: String = (&mut rng)
.sample_iter(Alphanumeric)
.take(24)
.map(char::from)
.collect();
JobOpts {
retry: 25,
queue: "default".to_string(),
jid,
created_at: now,
enqueued_at: now,
}
}
}
/// # Examples
///
/// ```
/// use std::default::Default;
/// use sidekiq::Value;
/// use sidekiq::{Job, JobOpts};
///
/// // Create a job
/// let class = "Maman".to_string();
/// let job_opts = JobOpts {
/// queue: "test".to_string(),
/// ..Default::default()
/// };
/// let job = Job::new(class, vec![sidekiq::Value::Null], job_opts);
/// ```
impl Job {
pub fn new(class: String, args: Vec<Value>, opts: JobOpts) -> Job {
Job {
class,
args,
retry: opts.retry,
queue: opts.queue,
jid: opts.jid,
created_at: opts.created_at,
enqueued_at: opts.enqueued_at,
}
}
}
impl Serialize for Job {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("Job", 7)?;
s.serialize_field("class", &self.class)?;
s.serialize_field("args", &self.args)?;
s.serialize_field("retry", &self.retry)?;
s.serialize_field("queue", &self.queue)?;
s.serialize_field("jid", &self.jid)?;
s.serialize_field("created_at", &self.created_at)?;
s.serialize_field("enqueued_at", &self.enqueued_at)?;
s.end()
}
}
#[derive(Default)]
pub struct ClientOpts {
pub namespace: Option<String>,
}
pub struct Client {
pub redis_pool: ConnectionManager,
pub namespace: Option<String>,
}
/// # Examples
///
/// ```
///
/// use sidekiq::{Job, Value};
/// use sidekiq::{Client, ClientOpts, create_redis_pool};
/// use time::{OffsetDateTime, Duration};
///
/// let ns = "test";
/// let client_opts = ClientOpts {
/// namespace: Some(ns.to_string()),
/// ..Default::default()
/// };
/// let pool = create_redis_pool().unwrap();
/// let client = Client::new(pool, client_opts);
/// let class = "Maman";
/// let job = Job::new(class.to_string(), vec![sidekiq::Value::Null], Default::default());
/// match client.push(job) {
/// Ok(_) => {},
/// Err(err) => {
/// println!("Sidekiq push failed: {}", err);
/// },
/// }
/// let job = Job::new(class.to_string(), vec![sidekiq::Value::Null], Default::default());
/// let interval = Duration::hours(1);
/// match client.perform_in(interval, job) {
/// Ok(_) => {},
/// Err(err) => {
/// println!("Sidekiq push failed: {}", err);
/// },
/// }
/// let job = Job::new(class.to_string(), vec![sidekiq::Value::Null], Default::default());
/// let start_at = OffsetDateTime::now_utc().checked_add(Duration::HOUR).unwrap();
/// match client.perform_at(start_at, job) {
/// Ok(_) => {},
/// Err(err) => {
/// println!("Sidekiq push failed: {}", err);
/// },
/// }
/// ```
impl Client {
pub fn new(redis_pool: ConnectionManager, opts: ClientOpts) -> Client {
Client {
redis_pool,
namespace: opts.namespace,
}
}
fn calc_at(&self, target_millsec_number: f64) -> Option<f64> {
let maximum_target: f64 = 1_000_000_000_f64;
let target_millsec: f64 = target_millsec_number;
let now_millisec = OffsetDateTime::now_utc().unix_timestamp() as f64;
let start_at: f64 = if target_millsec < maximum_target {
now_millisec + target_millsec
} else {
target_millsec
};
if start_at <= now_millisec {
None
} else {
Some(start_at)
}
}
pub fn perform_in(&self, interval: Duration, job: Job) -> Result<(), ClientError> {
block_on(self.perform_in_async(interval, job))
}
pub fn perform_at(&self, datetime: OffsetDateTime, job: Job) -> Result<(), ClientError> {
block_on(self.perform_at_async(datetime, job))
}
pub fn push(&self, job: Job) -> Result<(), ClientError> {
block_on(self.push_async(job))
}
pub fn push_bulk(&self, jobs: &[Job]) -> Result<(), ClientError> {
block_on(self.push_bulk_async(jobs))
}
pub async fn perform_in_async(&self, interval: Duration, job: Job) -> Result<(), ClientError> {
let interval: f64 = interval.whole_seconds() as f64;
self.raw_push(&[job], self.calc_at(interval)).await
}
pub async fn perform_at_async(
&self,
datetime: OffsetDateTime,
job: Job,
) -> Result<(), ClientError> {
let timestamp: f64 = datetime.unix_timestamp() as f64;
self.raw_push(&[job], self.calc_at(timestamp)).await
}
pub async fn push_async(&self, job: Job) -> Result<(), ClientError> {
self.raw_push(&[job], None).await
}
pub async fn push_bulk_async(&self, jobs: &[Job]) -> Result<(), ClientError> {
self.raw_push(jobs, None).await
}
async fn raw_push(&self, payloads: &[Job], at: Option<f64>) -> Result<(), ClientError> {
let payload = &payloads[0];
let to_push = payloads
.iter()
.map(|entry| serde_json::to_string(&entry).unwrap())
.collect::<Vec<_>>();
if let Some(value) = at {
redis::pipe()
.atomic()
.cmd("ZADD")
.arg(self.schedule_queue_name())
.arg(value)
.arg(to_push)
.query_async(&mut self.redis_pool.clone())
.map_err(|err| ClientError {
kind: ErrorKind::Redis(err),
})
.await
} else {
redis::pipe()
.atomic()
.cmd("SADD")
.arg("queues")
.arg(payload.queue.to_string())
.ignore()
.cmd("LPUSH")
.arg(self.queue_name(&payload.queue))
.arg(to_push)
.query_async(&mut self.redis_pool.clone())
.map_err(|err| ClientError {
kind: ErrorKind::Redis(err),
})
.await
}
}
fn schedule_queue_name(&self) -> String {
if let Some(ref ns) = self.namespace {
format!("{}:schedule", ns)
} else {
"schedule".to_string()
}
}
fn queue_name(&self, queue: &str) -> String {
if let Some(ref ns) = self.namespace {
format!("{}:queue:{}", ns, queue)
} else {
format!("queue:{}", queue)
}
}
}