chainmq 1.3.0

A Redis-backed, type-safe job queue for Rust. Provides job registration and execution, delayed jobs, retries with backoff, and scalable workers.
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
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
//! Mount the dashboard on an existing Actix [`web::ServiceConfig`] (no `HttpServer` in this crate).

use std::sync::Arc;

use actix_session::SessionExt;
use actix_session::config::CookieContentSecurity;
use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use actix_web::{
    Error, HttpRequest, HttpResponse, Result as ActixResult,
    body::BoxBody,
    cookie::{Key, SameSite},
    dev::{ServiceRequest, ServiceResponse},
    http::header::LOCATION,
    middleware::{DefaultHeaders, Next, from_fn},
    web::{self, Bytes, ServiceConfig},
};
use futures::StreamExt;

fn map_http_status(s: http::StatusCode) -> actix_web::http::StatusCode {
    actix_web::http::StatusCode::from_u16(s.as_u16())
        .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR)
}
use tokio::sync::Mutex;

use crate::Queue;

use super::core::{
    self, CleanQueueRequest, DeleteJobRequest, JobLogsQuery, LoginRequest, SESSION_AUTH_KEY,
    UiAssets, WebUIMountConfig, embedded_asset_rel_key, embedded_content_type,
    is_ui_auth_public_route, json_reauth_value, normalize_static_url_prefix, session_cookie_path,
    session_signing_key_material, verify_credentials,
};

#[derive(Clone)]
struct AppState {
    queue: Arc<Mutex<Queue>>,
    auth: Option<Arc<core::UiLoginRuntime>>,
}

/// Register dashboard routes on `cfg`. Call this from `App::configure`.
///
/// Pass a shared [`Arc`]`<`[`Mutex`]`<`[`Queue`]`>>` so every Actix worker uses the same queue handle
/// (for example clone the arc in your `HttpServer::new` closure).
///
/// ```ignore
/// use actix_web::{App, HttpServer};
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
///
/// let queue = Arc::new(Mutex::new(queue));
/// HttpServer::new({
///     let queue = queue.clone();
///     let config = config.clone();
///     move || {
///         App::new().configure(|cfg| {
///             chainmq::configure_chainmq_web_ui(cfg, queue.clone(), config.clone()).unwrap()
///         })
///     }
/// })
/// ```
pub fn configure_chainmq_web_ui(
    cfg: &mut ServiceConfig,
    queue: Arc<Mutex<Queue>>,
    config: WebUIMountConfig,
) -> std::io::Result<()> {
    let auth: Option<Arc<core::UiLoginRuntime>> = match &config.auth {
        Some(a) => Some(core::build_login_runtime(a)?),
        None => None,
    };

    let app_state = AppState { queue, auth };

    let session_key = Key::from(&session_signing_key_material(&config)[..]);
    let cookie_path = session_cookie_path(&config.ui_path);
    let cookie_secure = config.cookie_secure;

    let static_url_prefix = normalize_static_url_prefix(&config.ui_path);
    let api_path = if static_url_prefix == "/" {
        "/api".to_string()
    } else {
        format!("{}/api", static_url_prefix)
    };

    let static_url_prefix_data = static_url_prefix.clone();
    let api_path_for_scope = api_path.clone();

    let no_store =
        DefaultHeaders::new().add(("Cache-Control", "no-store, max-age=0, must-revalidate"));

    cfg.app_data(web::Data::new(app_state));
    cfg.app_data(web::Data::new(static_url_prefix_data.clone()));

    cfg.service(
        web::scope(&api_path_for_scope)
            .wrap(no_store.clone())
            .wrap(from_fn(require_ui_session_login_actix))
            .wrap(from_fn(ui_internal_json_only_actix))
            .wrap({
                let mut session_builder =
                    SessionMiddleware::builder(CookieSessionStore::default(), session_key.clone())
                        .cookie_name("chainmq_ui".into())
                        .cookie_secure(cookie_secure)
                        .cookie_same_site(SameSite::Lax)
                        .cookie_content_security(CookieContentSecurity::Signed);
                if cookie_path != "/" {
                    session_builder = session_builder.cookie_path(cookie_path.clone());
                }
                session_builder.build()
            })
            .route("/auth/session", web::get().to(get_auth_session_actix))
            .route("/auth/login", web::post().to(post_auth_login_actix))
            .route("/auth/logout", web::post().to(post_auth_logout_actix))
            .route("/queues", web::get().to(get_queues_actix))
            .route(
                "/queues/{queue_name}/stats",
                web::get().to(get_queue_stats_actix),
            )
            .route(
                "/queues/{queue_name}/events/live",
                web::get().to(get_queue_events_live_actix),
            )
            .route(
                "/queues/{queue_name}/events",
                web::get().to(get_queue_events_actix),
            )
            .route("/redis/stats", web::get().to(get_redis_stats_actix))
            .route(
                "/queues/{queue_name}/jobs/{state}",
                web::get().to(list_jobs_actix),
            )
            .route("/jobs/{job_id}/logs", web::get().to(get_job_logs_actix))
            .route("/jobs/{job_id}", web::get().to(get_job_actix))
            .route("/jobs/{job_id}/retry", web::post().to(retry_job_actix))
            .route("/jobs/{job_id}/delete", web::delete().to(delete_job_actix))
            .route("/queues/clean", web::post().to(clean_queue_actix))
            .route(
                "/queues/{queue_name}/recover-stalled",
                web::post().to(recover_stalled_actix),
            )
            .route(
                "/queues/{queue_name}/process-delayed",
                web::post().to(process_delayed_actix),
            ),
    );

    if static_url_prefix == "/" {
        cfg.service(
            web::resource("/")
                .wrap(no_store.clone())
                .route(web::get().to(serve_embedded_actix)),
        );
        cfg.service(
            web::resource("/{path:.*}")
                .wrap(no_store)
                .route(web::get().to(serve_embedded_actix)),
        );
    } else {
        cfg.service(
            web::scope(static_url_prefix.as_str())
                .wrap(no_store)
                .service(web::resource("").route(web::get().to(serve_embedded_actix)))
                .service(web::resource("/").route(web::get().to(serve_embedded_actix)))
                .service(web::resource("/{path:.*}").route(web::get().to(serve_embedded_actix))),
        );
    }

    Ok(())
}

async fn ui_internal_json_only_actix(
    req: ServiceRequest,
    next: Next<BoxBody>,
) -> Result<ServiceResponse<BoxBody>, Error> {
    let site = req
        .headers()
        .get("sec-fetch-site")
        .and_then(|h| h.to_str().ok());
    let allowed = matches!(site, Some("same-origin") | Some("same-site"));
    if allowed {
        Ok(next.call(req).await?.map_into_boxed_body())
    } else {
        let (req, _pl) = req.into_parts();
        let res = HttpResponse::Forbidden()
            .json(serde_json::json!({
                "error": "This JSON API is internal to the web UI. Open the dashboard in a browser."
            }))
            .map_into_boxed_body();
        Ok(ServiceResponse::new(req, res))
    }
}

async fn require_ui_session_login_actix(
    req: ServiceRequest,
    next: Next<BoxBody>,
) -> Result<ServiceResponse<BoxBody>, Error> {
    let state = req
        .app_data::<web::Data<AppState>>()
        .map(|d| d.get_ref().clone());

    let Some(state) = state else {
        return Err(actix_web::error::ErrorInternalServerError(
            "missing AppState",
        ));
    };

    if state.auth.is_none() {
        return Ok(next.call(req).await?.map_into_boxed_body());
    }

    let path = req.path().to_string();
    let method = req.method().as_str();

    if is_ui_auth_public_route(method, &path) {
        return Ok(next.call(req).await?.map_into_boxed_body());
    }

    let session = req.get_session();
    let authenticated = session
        .get::<bool>(SESSION_AUTH_KEY)
        .map_err(actix_web::error::ErrorInternalServerError)?
        .unwrap_or(false);

    if !authenticated {
        let (req, _pl) = req.into_parts();
        let res = HttpResponse::build(actix_web::http::StatusCode::UNAUTHORIZED)
            .json(json_reauth_value("Not authenticated"))
            .map_into_boxed_body();
        return Ok(ServiceResponse::new(req, res));
    }

    Ok(next.call(req).await?.map_into_boxed_body())
}

async fn get_auth_session_actix(
    state: web::Data<AppState>,
    session: Session,
) -> ActixResult<HttpResponse> {
    let auth_enabled = state.auth.is_some();
    let authenticated = if auth_enabled {
        session
            .get::<bool>(SESSION_AUTH_KEY)
            .map_err(actix_web::error::ErrorInternalServerError)?
            .unwrap_or(false)
    } else {
        true
    };
    Ok(HttpResponse::Ok().json(core::AuthSessionResponse {
        auth_enabled,
        authenticated,
    }))
}

async fn post_auth_login_actix(
    state: web::Data<AppState>,
    session: Session,
    body: web::Json<LoginRequest>,
) -> ActixResult<HttpResponse> {
    let Some(auth) = state.auth.as_ref() else {
        return Ok(HttpResponse::NotFound().json(serde_json::json!({
            "error": "Authentication is not enabled for this server"
        })));
    };

    if !verify_credentials(auth, &body.username, &body.password) {
        return Ok(
            HttpResponse::build(actix_web::http::StatusCode::UNAUTHORIZED)
                .json(json_reauth_value("Invalid username or password")),
        );
    }

    session
        .insert(SESSION_AUTH_KEY, true)
        .map_err(actix_web::error::ErrorInternalServerError)?;
    session.renew();

    Ok(HttpResponse::Ok().json(serde_json::json!({ "success": true })))
}

async fn post_auth_logout_actix(session: Session) -> ActixResult<HttpResponse> {
    session.purge();
    Ok(HttpResponse::Ok().json(serde_json::json!({ "success": true })))
}

async fn get_queues_actix(state: web::Data<AppState>) -> ActixResult<HttpResponse> {
    let q = state.queue.lock().await;
    let (st, json) = core::api_get_queues(&*q).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_queue_stats_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> ActixResult<HttpResponse> {
    let queue_name = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_get_queue_stats(&*q, &queue_name).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_queue_events_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<core::QueueEventsQuery>,
) -> ActixResult<HttpResponse> {
    let queue_name = path.into_inner();
    let limit = query.limit.unwrap_or(100).clamp(1, 500);
    let q = state.queue.lock().await;
    let (st, json) = core::api_list_queue_events(&*q, &queue_name, limit).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_redis_stats_actix(state: web::Data<AppState>) -> ActixResult<HttpResponse> {
    let q = state.queue.lock().await;
    let (st, json) = core::api_get_redis_server_stats(&*q).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_queue_events_live_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> ActixResult<HttpResponse> {
    let queue_name = path.into_inner();
    let (client_res, channel) = {
        let g = state.queue.lock().await;
        (g.redis_pubsub_client(), g.redis_events_channel(&queue_name))
    };
    let Ok(client) = client_res else {
        return Ok(
            HttpResponse::ServiceUnavailable().json(serde_json::json!({
                "error": "Live queue events require Redis URL or Client (not ConnectionManager). Use GET …/events for history."
            })),
        );
    };
    let mut pubsub = client
        .get_async_pubsub()
        .await
        .map_err(actix_web::error::ErrorBadGateway)?;
    pubsub
        .subscribe(&channel)
        .await
        .map_err(actix_web::error::ErrorBadGateway)?;
    let stream = pubsub.into_on_message().map(|msg| {
        let s: String = msg.get_payload().unwrap_or_default();
        Ok::<Bytes, Error>(Bytes::from(format!("data: {s}\n\n")))
    });
    Ok(HttpResponse::Ok()
        .insert_header(("Content-Type", "text/event-stream"))
        .insert_header(("Cache-Control", "no-cache"))
        .streaming(stream))
}

async fn list_jobs_actix(
    state: web::Data<AppState>,
    path: web::Path<(String, String)>,
    query: web::Query<std::collections::HashMap<String, String>>,
) -> ActixResult<HttpResponse> {
    let (queue_name, state_str) = path.into_inner();
    let limit = query
        .get("limit")
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(100);
    let q = state.queue.lock().await;
    let (st, json) = core::api_list_jobs(&*q, &queue_name, &state_str, limit).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_job_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> ActixResult<HttpResponse> {
    let job_id = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_get_job(&*q, &job_id).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn get_job_logs_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<JobLogsQuery>,
) -> ActixResult<HttpResponse> {
    let job_id = path.into_inner();
    let limit = query.limit.unwrap_or(200).clamp(1, 500);
    let q = state.queue.lock().await;
    let (st, json) = core::api_get_job_logs(&*q, &job_id, limit).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn retry_job_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
    body: web::Json<core::RetryJobRequest>,
) -> ActixResult<HttpResponse> {
    let job_id = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_retry_job(&*q, &job_id, &body.queue_name).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn delete_job_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
    query: web::Query<DeleteJobRequest>,
) -> ActixResult<HttpResponse> {
    let job_id = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_delete_job(&*q, &job_id, &query.queue_name).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn clean_queue_actix(
    state: web::Data<AppState>,
    body: web::Json<CleanQueueRequest>,
) -> ActixResult<HttpResponse> {
    let q = state.queue.lock().await;
    let (st, json) = core::api_clean_queue(&*q, &body).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn recover_stalled_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> ActixResult<HttpResponse> {
    let queue_name = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_recover_stalled(&*q, &queue_name).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn process_delayed_actix(
    state: web::Data<AppState>,
    path: web::Path<String>,
) -> ActixResult<HttpResponse> {
    let queue_name = path.into_inner();
    let q = state.queue.lock().await;
    let (st, json) = core::api_process_delayed(&*q, &queue_name).await;
    Ok(HttpResponse::build(map_http_status(st)).json(json))
}

async fn serve_embedded_actix(
    req: HttpRequest,
    prefix: web::Data<String>,
) -> ActixResult<HttpResponse> {
    let prefix_str = prefix.get_ref().as_str();
    if prefix_str != "/" {
        let canonical_prefix = prefix_str.trim_end_matches('/');
        if req.path() == canonical_prefix {
            let mut loc = format!("{}/", canonical_prefix);
            if let Some(q) = req.uri().query() {
                loc.push('?');
                loc.push_str(q);
            }
            return Ok(HttpResponse::Found()
                .insert_header((LOCATION, loc))
                .finish());
        }
    }
    let Some(rel) = embedded_asset_rel_key(req.path(), prefix_str) else {
        return Ok(HttpResponse::NotFound().finish());
    };
    let Some(file) = UiAssets::get(&rel) else {
        return Ok(HttpResponse::NotFound().finish());
    };
    Ok(HttpResponse::Ok()
        .content_type(embedded_content_type(&rel))
        .body(file.data))
}