qrush 0.2.1

Lightweight Job Queue for Rust (Actix + Redis)
Documentation
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
# Qrush 🌀 – Lightweight Job Queue for Rust (Actix + Redis)

  

Qrush is a lightweight background job queue system for Rust, designed for Actix-Web projects with Redis as the backend. It supports job definition, scheduling (including delayed jobs), and monitoring with optional Basic Auth-protected Prometheus metrics.

---

## 🚀 Features

* Simple job definition using a trait
* Background job execution
* Delayed job scheduling (`enqueue_in`)
* Redis-based queue persistence
* Prometheus-style metrics endpoint (`/qrush/metrics`)
* Easy integration with Actix-Web
* Optional Basic Auth protection

---

## 📦 Installation

Add this to your `Cargo.toml`:

```toml
qrush = "0.2.0"
```

Or use:

```bash
cargo add qrush
```

---

## ⚙️ Integration Guide for Version >= 0.2.0

### 1. Initialize Qrush

Create `src/jobs/qrush.rs`:

```rust
// src/jobs/qrush.rs

use std::sync::{Arc};
use tokio::sync::Notify;
use std::env;

use qrush::config::QueueConfig;
use qrush::registry::register_job;
use qrush::config::QUEUE_INITIALIZED;
use qrush::job::Job;
use qrush::config::{set_basic_auth, QrushBasicAuthConfig};
use crate::jobs::notify_user::NotifyUser;

pub async fn initiate(basic_auth: Option<QrushBasicAuthConfig>) {
    let queueNotify = Arc::new(Notify::new());
    let basic_auth = basic_auth.or_else(|| {
        std::env::var("QRUSH_BASIC_AUTH").ok().and_then(|auth| {
            let parts: Vec<&str> = auth.splitn(2, ':').collect();
            if parts.len() == 2 {
                Some(QrushBasicAuthConfig {
                    username: parts[0].to_string(),
                    password: parts[1].to_string(),
                })
            } else {
                None
            }
        })
    });

    let _ = set_basic_auth(basic_auth);

    let _ = QUEUE_INITIALIZED.set(queueNotify.clone());

    register_job(NotifyUser::name(), NotifyUser::handler);

    tokio::spawn({
        let queueNotify = queueNotify.clone();
        async move {
            let redis_url = std::env::var("REDIS_URL")
                .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());

            let queues = vec![
                QueueConfig::new("default", 5, 1),
                QueueConfig::new("critical", 10, 0),
            ];

            if let Err(err) = QueueConfig::initialize(redis_url, queues).await {
                eprintln!("❌ Failed to initialize qrush: {:?}", err);
            } else {
                println!("✅ qrush started successfully");
                queueNotify.notify_waiters();
            }
        }
    });

    queueNotify.notified().await;
    println!("🚀 Queue initialization complete. Continuing main logic...");
}
```

---

### 2. Call `initiate()` in `main.rs`

```rust
use actix_web::{web, App, HttpServer};
use qrush::routes::metrics_route::qrush_metrics_routes;
use crate::jobs::qrush::initiate as qrush_initiate;
use qrush::config::QrushBasicAuthConfig;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let basic_auth = Some(QrushBasicAuthConfig {
        username: "qrush".into(),
        password: "qrush".into(),
    });

    qrush_initiate(basic_auth).await;

    HttpServer::new(|| {
        App::new()
            .service(web::scope("/qrush").configure(qrush_metrics_routes))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

---

### 3. Define a Job

Create `src/jobs/workers/notify_user.rs`:

```rust
use qrush::job::Job;
use async_trait::async_trait;
use serde::{Serialize, Deserialize};
use anyhow::{Result, Error};
use futures::future::{BoxFuture, FutureExt};

#[derive(Debug, Serialize, Deserialize)]
pub struct NotifyUser {
    pub user_id: String,
    pub message: String,
}

#[async_trait]
impl Job for NotifyUser {
    fn name(&self) -> &'static str {
        "NotifyUser"
    }

    fn queue(&self) -> &'static str {
        "default"
    }

    async fn before(&self) -> Result<()> {
        println!("⏳ Before NotifyUser job for user: {}", self.user_id);
        Ok(())
    }

    async fn perform(&self) -> Result<()> {
        println!("📬 Performing NotifyUser: '{}' to user {}", self.message, self.user_id);
        Ok(())
    }

    async fn after(&self) {
        println!("✅ After NotifyUser job for user: {}", self.user_id);
    }

    async fn on_error(&self, err: &Error) {
        eprintln!("❌ Error in NotifyUser job for user {}: {:?}", self.user_id, err);
    }

    async fn always(&self) {
        println!("🔁 Always block executed for NotifyUser job");
    }
}

impl NotifyUser {
    pub fn name() -> &'static str {
        "notify_user"
    }

    pub fn handler(payload: String) -> BoxFuture<'static, Result<Box<dyn Job>>> {
        async move {
            let job: NotifyUser = serde_json::from_str(&payload)?;
            Ok(Box::new(job) as Box<dyn Job>)
        }.boxed()
    }
}
```

---

### 4. Enqueue a Job Anywhere

```rust
use qrush::queue::{enqueue, enqueue_in};
use crate::jobs::notify_user::NotifyUser;

let _ = enqueue(NotifyUser {
    user_id: "abc".into(),
    message: "Hello from Qrush!".into(),
}).await;

let _ = enqueue_in(NotifyUser {
    user_id: "abc".into(),
    message: "Delayed job after 60s".into(),
}, 60).await;
```

---

### 5. Metrics Route

Visit:

```
http://localhost:8080/qrush/metrics
```

---

## ⚙️ Integration Guide for Version <= 0.1.2

### 1. Initialize Qrush (Legacy)

Create `src/jobs/qrush.rs`:

```rust
use std::sync::Arc;
use tokio::sync::Notify;
use qrush::config::{QueueConfig, set_basic_auth, QUEUE_INITIALIZED, QrushBasicAuthConfig};
use qrush::registry::register_jobs;
use qrush::job::Job;
use crate::jobs::workers::notify_user_job::NotifyUser;

pub async fn initiate(basic_auth: Option<QrushBasicAuthConfig>) {
    let queue_notify = Arc::new(Notify::new());
    let _ = set_basic_auth(basic_auth);
    let _ = QUEUE_INITIALIZED.set(queue_notify.clone());

    register_jobs(<NotifyUser as Job>::name(), NotifyUser::handler);

    tokio::spawn({
        let queue_notify = queue_notify.clone();
        async move {
            let redis_url = std::env::var("REDIS_URL")
                .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());

            let queues = vec![
                QueueConfig::new("default", 5, 1),
                QueueConfig::new("critical", 10, 0),
            ];

            if let Err(err) = QueueConfig::initialize(redis_url, queues).await {
                eprintln!("Failed to initialize Qrush: {:?}", err);
            } else {
                println!("Qrush started successfully");
                queue_notify.notify_waiters();
            }
        }
    });

    queue_notify.notified().await;
}
```

### 2. Call `initiate()` in `main.rs`

```rust
use actix_web::{web, App, HttpServer};
use qrush::routes::metrics_route::qrush_metrics_routes;
use crate::jobs::qrush::initiate as qrush_initiate;
use qrush::config::QrushBasicAuthConfig;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let basic_auth = Some(QrushBasicAuthConfig {
        username: "qrush".into(),
        password: "qrush".into(),
    });

    qrush_initiate(basic_auth).await;

    HttpServer::new(|| {
        App::new()
            .service(web::scope("/qrush").configure(qrush_metrics_routes))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

### 3. Define a Job (Legacy Style)

Create `src/jobs/workers/notify_user_job.rs`:

```rust
use qrush::job::Job;
use async_trait::async_trait;
use serde::{Serialize, Deserialize};
use anyhow::Result;
use futures::future::BoxFuture;

#[derive(Debug, Serialize, Deserialize)]
pub struct NotifyUser {
    pub user_id: String,
    pub message: String,
}

#[async_trait]
impl Job for NotifyUser {
    async fn perform(&self) -> Result<()> {
        println!("Performing NotifyUser: '{}' to user {}", self.message, self.user_id);
        Ok(())
    }

    fn name() -> &'static str {
        "NotifyUser"
    }

    fn queue() -> &'static str {
        "default"
    }
}

impl NotifyUser {
    pub fn handler(payload: String) -> BoxFuture<'static, Result<()>> {
        Box::pin(async move {
            let job: NotifyUser = serde_json::from_str(&payload)?;
            job.perform().await
        })
    }
}
```

### 4. Enqueue a Job

```rust
use qrush::queue::{enqueue, enqueue_in};
use crate::jobs::workers::notify_user_job::NotifyUser;

let _ = enqueue(NotifyUser {
    user_id: "abc".into(),
    message: "Hello from Qrush!".into(),
}).await;

let _ = enqueue_in(NotifyUser {
    user_id: "abc".into(),
    message: "Delayed job after 60s".into(),
}, 60).await;
```

### 5. Metrics Route

Visit:

```
http://localhost:8080/qrush/metrics
```

---

## 📈 Optional Environment Variables

| Variable           | Description               | Default                  |
| ------------------ | ------------------------- | ------------------------ |
| `REDIS_URL`        | Redis connection string   | `redis://127.0.0.1:6379` |
| `QRUSH_BASIC_AUTH` | Basic Auth as `user:pass` | *Optional*               |

---

## 💪 TODO / Roadmap

* 💀 Dead Letter Queues
* 📜 Persistent Job Logs
* 🌐 Web UI for Monitoring

---

## 👨‍💼 Author

Built with ❤️ by **[SNM Maurya](https://snmmaurya.com/solutions/qrush)**

---

## 🖼️ Screenshots

### Qrush Metrics Example

[https://snmmaurya.com/qrush/metrics.png](https://snmmaurya.com/qrush/metrics.png)

[https://snmmaurya.com/qrush/summary.png](https://snmmaurya.com/qrush/summary.png)

---

## 🪪 License

MIT

---

## 🔧 Optional Enhancements

*

Feel free to open issues or PRs with feature requests.