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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
mod errors;

use errors::*;
use lazy_static::lazy_static;
use radix_fmt::radix_36;
use rand::seq::IteratorRandom;
use redis::{aio::Connection, pipe, Client, Script};

#[derive(Debug)]
struct QueueDescriptor {
    vt: u64,
    delay: u64,
    maxsize: u64,
    ts: u64,
    uid: Option<String>,
}

#[derive(Debug)]
pub struct RsmqOptions {
    host: String,
    port: String,
    realtime: bool,
    password: Option<String>,
    ns: String,
}

impl Default for RsmqOptions {
    fn default() -> Self {
        RsmqOptions {
            host: "localhost".to_string(),
            port: "6379".to_string(),
            realtime: false,
            password: None,
            ns: "rsmq".to_string(),
        }
    }
}

#[derive(Debug)]
pub struct RsmqMessage {
    id: String,
    message: String,
    rc: u64,
    fr: u64,
    sent: u64,
}

#[derive(Debug)]
pub struct RsmqQueueAttributes {
    vt: u64,
    delay: u64,
    maxsize: u64,
    totalrecv: u64,
    totalsent: u64,
    created: u64,
    modified: u64,
    msgs: u64,
    hiddenmsgs: u64,
}

struct RedisConnection(Connection);

impl std::fmt::Debug for RedisConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "RedisAsyncConnnection")
    }
}

lazy_static! {
    static ref CHANGE_MESSAGE_VISIVILITY: Script =
        Script::new(include_str!("./redis-scripts/changeMessageVisibility.lua"));
    static ref POP_MESSAGE: Script = Script::new(include_str!("./redis-scripts/popMessage.lua"));
    static ref RECEIVE_MESSAGE: Script =
        Script::new(include_str!("./redis-scripts/receiveMessage.lua"));
}

#[derive(Debug)]
pub struct Rsmq {
    client: Client,
    connection: RedisConnection,
    options: RsmqOptions,
}

impl Rsmq {
    pub async fn new(options: RsmqOptions) -> Result<Rsmq, RsmqError> {
        let password = if let Some(password) = options.password.clone() {
            format!("redis:{}@", password)
        } else {
            "".to_string()
        };

        let url = format!("redis://{}{}:{}", password, options.host, options.port);

        let client = redis::Client::open(url)?;

        let connection = client.get_async_connection().await?;

        Ok(Rsmq {
            client,
            connection: RedisConnection(connection),
            options,
        })
    }

    pub async fn change_message_visibility_async(
        &mut self,
        qname: &str,
        message_id: &str,
        hidden_duration: u64,
    ) -> Result<(), RsmqError> {
        number_in_range(hidden_duration, 0, 9_999_999)?;

        let queue = self.get_queue(qname, false).await?;
        //options.id, q.ts + options.vt * 1000
        CHANGE_MESSAGE_VISIVILITY
            .arg(3)
            .arg(format!("{}{}", self.options.ns, qname))
            .arg(message_id)
            .arg(queue.ts + hidden_duration * 1000)
            .invoke_async::<_, bool>(&mut self.connection.0)
            .await?;

        Ok(())
    }

    pub async fn create_queue_async(
        &mut self,
        qname: &str,
        seconds_hidden: Option<u32>,
        delay: Option<u32>,
        maxsize: Option<i32>,
    ) -> Result<(), RsmqError> {

        valid_name_format(qname)?;

        let key = format!("{}{}:Q", self.options.ns, qname);
        let seconds_hidden = seconds_hidden.unwrap_or(30);
        let delay = delay.unwrap_or(0);
        let maxsize = maxsize.unwrap_or(65536);

        number_in_range(seconds_hidden, 0, 9_999_999)?;
        number_in_range(delay, 0, 9_999_999)?;
        if let Err(error) = number_in_range(maxsize, 1024, 65536) {
            if maxsize != -1 {
                // TODO: Create another error in order to explain that -1 is allowed
                return Err(error);
            }
        }

        let time: (u64, u64) = redis::cmd("TIME")
            .query_async(&mut self.connection.0)
            .await?;

        let results: (bool, bool, bool, bool, bool) = pipe()
            .cmd("HSETNX")
            .arg(&key)
            .arg("vt")
            .arg(seconds_hidden)
            .cmd("HSETNX")
            .arg(&key)
            .arg("delay")
            .arg(delay)
            .cmd("HSETNX")
            .arg(&key)
            .arg("maxsize")
            .arg(maxsize)
            .cmd("HSETNX")
            .arg(&key)
            .arg("created")
            .arg(time.0)
            .cmd("HSETNX")
            .arg(&key)
            .arg("modified")
            .arg(time.0)
            .query_async(&mut self.connection.0)
            .await?;

        if !results.0 {
            return Err(QueueExists {}.into());
        }

        redis::cmd("SADD")
            .arg(format!("{}QUEUES", self.options.ns))
            .arg(qname)
            .query_async(&mut self.connection.0)
            .await?;

        Ok(())
    }

    pub async fn delete_message_async(&mut self, qname: &str, id: &str) -> Result<bool, RsmqError> {
        let key = format!("{}{}", self.options.ns, qname);

        let results: (u16, u16) = pipe()
            .cmd("ZREM")
            .arg(&key)
            .arg(id)
            .cmd("HDEL")
            .arg(format!("{}:Q", &key))
            .arg(id)
            .arg(format!("{}:rc", id))
            .arg(format!("{}:fr", id))
            .query_async(&mut self.connection.0)
            .await?;

        if results.0 == 1 && results.1 > 0 {
            return Ok(true);
        }

        Ok(false)
    }

    pub async fn delete_queue_async(&mut self, qname: &str) -> Result<(), RsmqError> {
        let key = format!("{}{}", self.options.ns, qname);

        let results: (u16, u16) = pipe()
            .cmd("DEL")
            .arg(format!("{}:Q", &key))
            .arg(key)
            .cmd("SREM")
            .arg(format!("{}QUEUES", self.options.ns))
            .arg(qname)
            .query_async(&mut self.connection.0)
            .await?;

        if results.0 == 0 {
            return Err(QueueNotFound {}.into());
        }

        Ok(())
    }

    pub async fn get_queue_attributes_async(
        &mut self,
        qname: &str,
    ) -> Result<RsmqQueueAttributes, RsmqError> {
        let key = format!("{}{}", self.options.ns, qname);

        let time: (u64, u64) = redis::cmd("TIME")
            .query_async(&mut self.connection.0)
            .await?;

        let result: (Vec<u64>, u64, u64) = pipe()
            .cmd("HMGET")
            .arg(format!("{}:Q", key))
            .arg("vt")
            .arg("delay")
            .arg("maxsize")
            .arg("totalrecv")
            .arg("totalsent")
            .arg("created")
            .arg("modified")
            .cmd("ZCARD")
            .arg(&key)
            .cmd("ZCOUNT")
            .arg(&key)
            .arg(time.0 * 1000)
            .arg("+inf")
            .query_async(&mut self.connection.0)
            .await?;

        if result.0.is_empty() {
            return Err(QueueNotFound {}.into());
        }

        Ok(RsmqQueueAttributes {
            vt: *result.0.get(0).unwrap_or(&0),
            delay: *result.0.get(1).unwrap_or(&0),
            maxsize: *result.0.get(2).unwrap_or(&0),
            totalrecv: *result.0.get(3).unwrap_or(&0),
            totalsent: *result.0.get(4).unwrap_or(&0),
            created: *result.0.get(5).unwrap_or(&0),
            modified: *result.0.get(6).unwrap_or(&0),
            msgs: result.1,
            hiddenmsgs: result.2,
        })
    }

    pub async fn list_queues_async(&mut self) -> Result<Vec<String>, RsmqError> {
        let queues = redis::cmd("SMEMBERS")
            .arg(format!("{}QUEUES", self.options.ns))
            .query_async::<_, Vec<String>>(&mut self.connection.0)
            .await?;

        Ok(queues)
    }

    pub async fn pop_message_async(&mut self, qname: &str) -> Result<RsmqMessage, RsmqError> {
        let queue = self.get_queue(qname, false).await?;

        let result: (String, String, u64, u64) = POP_MESSAGE
            .arg(2)
            .arg(format!("{}{}", self.options.ns, qname))
            .arg(queue.ts)
            .invoke_async(&mut self.connection.0)
            .await?;

        Ok(RsmqMessage {
            id: result.0.clone(),
            message: result.1,
            rc: result.2,
            fr: result.3,
            sent: u64::from_str_radix(&result.0[0..10], 36).unwrap_or(0),
        })
    }

    pub async fn receive_message_async(
        &mut self,
        qname: &str,
        hidden_duration: Option<u64>,
    ) -> Result<RsmqMessage, RsmqError> {
        let queue = self.get_queue(qname, false).await?;

        let hidden_duration = hidden_duration.unwrap_or(queue.vt) * 1000;

        number_in_range(hidden_duration, 0, 9_999_999)?;

        let result: (String, String, u64, u64) = RECEIVE_MESSAGE
            .arg(3)
            .arg(format!("{}{}", self.options.ns, qname))
            .arg(queue.ts)
            .arg(queue.ts + hidden_duration)
            .invoke_async(&mut self.connection.0)
            .await?;

        Ok(RsmqMessage {
            id: result.0.clone(),
            message: result.1,
            rc: result.2,
            fr: result.3,
            sent: u64::from_str_radix(&result.0[0..10], 36).unwrap_or(0),
        })
    }

    pub async fn send_message_async(
        &mut self,
        qname: &str,
        message: &str,
        delay: Option<u64>,
    ) -> Result<String, RsmqError> {
        let queue = self.get_queue(qname, true).await?;
        let delay = delay.unwrap_or(queue.delay) * 1000;
        let key = format!("{}{}", self.options.ns, qname);

        number_in_range(delay, 0, 9_999_999)?;

        if message.len() as u64 > queue.maxsize {
            return Err(MessageTooLong {}.into());
        }

        let queue_uid = queue.uid.unwrap();
        let queue_key = format!("{}:Q", key);

        let mut piping = pipe();

        let mut commands = piping
            .cmd("ZADD")
            .arg(&key)
            .arg(queue.ts + delay)
            .arg(&queue_uid)
            .cmd("HSET")
            .arg(&queue_key)
            .arg(&queue_uid)
            .arg(message)
            .cmd("HINCRBY")
            .arg(&queue_key)
            .arg("totalsent")
            .arg(1_u64);

        if self.options.realtime {
            commands = commands.cmd("ZCARD").arg(&key);
        }

        let result: (u64, u64, i64, u64) = commands.query_async(&mut self.connection.0).await?;

        if self.options.realtime {
            redis::cmd("PUBLISH")
                .arg(format!("{}rt:{}", self.options.ns, qname))
                .arg(result.3)
                .query_async::<_, Vec<String>>(&mut self.connection.0)
                .await?;
        }

        Ok(queue_uid)
    }

    pub async fn set_queue_attributes_async(
        &mut self,
        qname: &str,
        hidden_duration: Option<u64>,
        delay: Option<u64>,
        maxsize: Option<i64>,
    ) -> Result<RsmqQueueAttributes, RsmqError> {
        self.get_queue(qname, false).await?;

        let queue_name = format!("{}{}:Q", self.options.ns, qname);


        let time: (u64, u64) = redis::cmd("TIME")
            .query_async(&mut self.connection.0)
            .await?;

        let mut commands = &mut pipe();

        commands = commands
            .cmd("HSET")
            .arg(&queue_name)
            .arg("modified")
            .arg(time.0);

        if let Some(duration) = hidden_duration {
            number_in_range(duration, 0, 9_999_999)?;
            commands = commands
                .cmd("HSET")
                .arg(&queue_name)
                .arg("vt")
                .arg(duration);
        }

        if let Some(delay) = delay {
            number_in_range(delay, 0, 9_999_999)?;
            commands = commands
                .cmd("HSET")
                .arg(&queue_name)
                .arg("delay")
                .arg(delay);
        }

        if let Some(maxsize) = maxsize {
            if let Err(error) = number_in_range(maxsize, 1024, 65536) {
                if maxsize != -1 {
                    // TODO: Create another error in order to explain that -1 is allowed
                    return Err(error);
                }
            }
            commands = commands
                .cmd("HSET")
                .arg(&queue_name)
                .arg("maxsize")
                .arg(maxsize);
        }

        commands.query_async(&mut self.connection.0).await?;

        self.get_queue_attributes_async(qname).await
    }

    async fn get_queue(&mut self, qname: &str, uid: bool) -> Result<QueueDescriptor, RsmqError> {
        let result: (Vec<String>, (u64, u64)) = pipe()
            .cmd("HMGET")
            .arg(format!("{}{}:Q", self.options.ns, qname))
            .arg("vt")
            .arg("delay")
            .arg("maxsize")
            .cmd("TIME")
            .query_async(&mut self.connection.0)
            .await?;

        let time_seconds = (result.1).0;
        let time_microseconds = (result.1).1;

        let (hmget_first, hmget_second, hmget_third) =
            match (result.0.get(0), result.0.get(1), result.0.get(2)) {
                (Some(v0), Some(v1), Some(v2)) => (v0, v1, v2),
                _ => return Err(QueueNotFound {}.into()),
            };

        let ts = time_seconds * 1000 + time_microseconds / 1000;

        let quid = if uid {
            Some(radix_36(ts).to_string() + &Rsmq::make_id(22))
        } else {
            None
        };

        Ok(QueueDescriptor {
            vt: hmget_first.parse().expect("cannot parse queue vt"),
            delay: hmget_second.parse().expect("cannot parse queue delay"),
            maxsize: hmget_third.parse().expect("cannot parse queue maxsize"),
            ts,
            uid: quid,
        })
    }

    fn make_id(len: usize) -> String {
        let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        let mut rng = rand::thread_rng();

        let mut id = String::with_capacity(len);

        for _ in 0..len {
            id.push(possible.chars().choose(&mut rng).unwrap());
        }

        id
    }

}

fn number_in_range<T: std::cmp::PartialOrd + std::fmt::Display>(value: T, min: T, max: T) -> Result<(), RsmqError> {
    if value >= min && value <= max {
        Ok(())
    } else {
        Err(InvalidValue(format!("{}", value), format!("{}", min), format!("{}", max)).into())
    }
}

fn valid_name_format(name: &str) -> Result<(), RsmqError> {
    if name.is_empty() && name.len() > 160 {
        return Err(InvalidFormat(name.to_string()).into());
    } else {
        name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    }

    Ok(())
}