qml-rs 1.1.0

A Rust implementation of QML background job processing
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
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
use axum::{Router, http::StatusCode, middleware, response::Html, routing::get};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;

use crate::dashboard::{
    auth::{self, DashboardAuth},
    routes::create_router,
    service::DashboardService,
    websocket::{WebSocketManager, websocket_handler},
};
use crate::storage::MonitoringApi;

#[cfg(feature = "metrics")]
use crate::processing::PrometheusMetrics;
#[cfg(feature = "metrics")]
use axum::{
    extract::State as AxumState,
    http::header::CONTENT_TYPE,
    response::{IntoResponse, Response},
};

#[derive(Debug, Clone)]
pub struct DashboardConfig {
    pub host: String,
    pub port: u16,
    pub statistics_update_interval: u64,
    /// Optional authentication guard applied to every dashboard route.
    ///
    /// If `None` and the dashboard is bound to a non-loopback interface
    /// (anything other than `localhost`, `127.0.0.1`, or `::1`),
    /// [`DashboardServer::start`] refuses to start. This prevents the
    /// common footgun of exposing an unauthenticated retry/delete API to
    /// the network.
    pub auth: Option<DashboardAuth>,
    /// Optional Prometheus metrics handle. When set, the dashboard exposes
    /// a `GET /metrics` endpoint returning the Prometheus text exposition
    /// format over the shared [`PrometheusMetrics`] registry. The route
    /// inherits the same auth guard as the rest of the dashboard — scrapers
    /// that can't authenticate should scrape via a sidecar on the loopback.
    ///
    /// Requires the `metrics` cargo feature.
    #[cfg(feature = "metrics")]
    pub metrics: Option<Arc<PrometheusMetrics>>,
}

impl Default for DashboardConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_string(),
            port: 8080,
            statistics_update_interval: 5, // Update every 5 seconds
            auth: None,
            #[cfg(feature = "metrics")]
            metrics: None,
        }
    }
}

pub struct DashboardServer {
    config: DashboardConfig,
    dashboard_service: Arc<DashboardService>,
    websocket_manager: Arc<WebSocketManager>,
}

impl DashboardServer {
    pub fn new(storage: Arc<dyn MonitoringApi>, config: DashboardConfig) -> Self {
        let dashboard_service = Arc::new(DashboardService::new(storage));
        let websocket_manager = Arc::new(WebSocketManager::new(Arc::clone(&dashboard_service)));

        Self {
            config,
            dashboard_service,
            websocket_manager,
        }
    }

    /// Start the dashboard server
    pub async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if self.config.auth.is_none() && !auth::is_loopback_host(&self.config.host) {
            return Err(format!(
                "refusing to start dashboard on non-loopback host '{}' without \
                 DashboardConfig::auth — set an auth guard or bind to localhost",
                self.config.host
            )
            .into());
        }

        let addr: SocketAddr = format!("{}:{}", self.config.host, self.config.port).parse()?;

        // Create the main router
        let app = self.create_app().await;

        // Start periodic statistics updates
        self.websocket_manager
            .start_periodic_updates(self.config.statistics_update_interval)
            .await;

        tracing::info!("Starting QML Dashboard server on http://{}", addr);
        tracing::info!("Dashboard available at: http://{}", addr);

        let listener = TcpListener::bind(addr).await?;
        axum::serve(listener, app).await?;

        Ok(())
    }

    /// Create the main application router
    async fn create_app(&self) -> Router {
        // Create API router
        let api_router = create_router(Arc::clone(&self.dashboard_service));

        // Create WebSocket route
        let ws_router = Router::new()
            .route("/ws", get(websocket_handler))
            .with_state(Arc::clone(&self.websocket_manager));

        // Main dashboard UI route
        let ui_router = Router::new()
            .route("/", get(dashboard_ui))
            .route("/dashboard", get(dashboard_ui))
            .route("/jobs", get(dashboard_ui))
            .route("/queues", get(dashboard_ui))
            .route("/statistics", get(dashboard_ui));

        let mut app = Router::new()
            .merge(api_router)
            .merge(ws_router)
            .merge(ui_router);

        #[cfg(feature = "metrics")]
        if let Some(metrics) = self.config.metrics.clone() {
            let metrics_router = Router::new()
                .route("/metrics", get(metrics_handler))
                .with_state(metrics);
            app = app.merge(metrics_router);
        }

        // DB4: same-origin guard on state-changing methods. Applied before
        // auth so cross-site mutation attempts are rejected without leaking
        // an auth challenge.
        app = app.layer(middleware::from_fn(auth::csrf_guard));

        // DB2: optional auth guard on every route.
        if let Some(auth) = &self.config.auth {
            app = app.layer(middleware::from_fn_with_state(
                Arc::new(auth.clone()),
                auth::require_auth,
            ));
        }

        app.layer(
            ServiceBuilder::new()
                .layer(CorsLayer::permissive()) // Allow all origins for development
                .into_inner(),
        )
    }

    /// Get the WebSocket manager for external use
    pub fn websocket_manager(&self) -> Arc<WebSocketManager> {
        Arc::clone(&self.websocket_manager)
    }

    /// Get the dashboard service for external use
    pub fn dashboard_service(&self) -> Arc<DashboardService> {
        Arc::clone(&self.dashboard_service)
    }
}

/// Dashboard UI handler - serves the main HTML page
async fn dashboard_ui() -> Result<Html<&'static str>, StatusCode> {
    Ok(Html(DASHBOARD_HTML))
}

/// Prometheus scrape handler. Encodes the registry as text exposition
/// format on each request. Sits behind the same auth / CSRF layers as the
/// rest of the dashboard; `GET` is a safe method so CSRF is a no-op.
#[cfg(feature = "metrics")]
async fn metrics_handler(AxumState(metrics): AxumState<Arc<PrometheusMetrics>>) -> Response {
    match metrics.encode_text() {
        Ok(body) => (
            StatusCode::OK,
            [(CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")],
            body,
        )
            .into_response(),
        Err(err) => {
            tracing::error!("failed to encode prometheus metrics: {}", err);
            (StatusCode::INTERNAL_SERVER_ERROR, "metrics encode failed").into_response()
        }
    }
}

/// Embedded HTML for the dashboard UI
const DASHBOARD_HTML: &str = r#"
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QML Dashboard</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            background: #2c3e50;
            color: white;
            padding: 1rem 0;
            margin-bottom: 2rem;
        }

        header h1 {
            text-align: center;
            font-size: 2rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-card h3 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 1.2rem;
        }

        .stat-card .number {
            font-size: 2rem;
            font-weight: bold;
            color: #3498db;
        }

        .section {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .section h2 {
            color: #2c3e50;
            margin-bottom: 15px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        .status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: bold;
            text-transform: uppercase;
        }

        .status.succeeded { background: #d4edda; color: #155724; }
        .status.failed { background: #f8d7da; color: #721c24; }
        .status.processing { background: #d1ecf1; color: #0c5460; }
        .status.enqueued { background: #fff3cd; color: #856404; }
        .status.scheduled { background: #e2e3e5; color: #383d41; }
        .status.awaiting_retry { background: #fce4ec; color: #c2185b; }

        .connection-status {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 15px;
            border-radius: 5px;
            font-weight: bold;
            z-index: 1000;
        }

        .connection-status.connected {
            background: #d4edda;
            color: #155724;
        }

        .connection-status.disconnected {
            background: #f8d7da;
            color: #721c24;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            margin: 2px;
        }

        .btn-primary { background: #3498db; color: white; }
        .btn-success { background: #27ae60; color: white; }
        .btn-danger { background: #e74c3c; color: white; }

        .btn:hover {
            opacity: 0.9;
        }

        .refresh-indicator {
            display: inline-block;
            margin-left: 10px;
            color: #3498db;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .spinning {
            animation: spin 1s linear infinite;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>🔥 QML Dashboard</h1>
        </div>
    </header>

    <div class="connection-status" id="connectionStatus">
        Connecting...
    </div>

    <div class="container">
        <div class="stats-grid" id="statsGrid">
            <!-- Statistics will be populated here -->
        </div>

        <div class="section">
            <h2>Recent Jobs <span class="refresh-indicator" id="refreshIndicator">🔄</span></h2>
            <table id="jobsTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Method</th>
                        <th>Queue</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Attempts</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Jobs will be populated here -->
                </tbody>
            </table>
        </div>

        <div class="section">
            <h2>Queue Statistics</h2>
            <table id="queuesTable">
                <thead>
                    <tr>
                        <th>Queue Name</th>
                        <th>Enqueued</th>
                        <th>Processing</th>
                        <th>Scheduled</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Queues will be populated here -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        let ws = null;
        let reconnectInterval = null;

        function connectWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/ws`;
            
            ws = new WebSocket(wsUrl);

            ws.onopen = function() {
                console.log('WebSocket connected');
                updateConnectionStatus(true);
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                    reconnectInterval = null;
                }
            };

            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                console.log('Received message:', message);
                
                switch (message.type) {
                    case 'statistics_update':
                        updateStatistics(message.data);
                        updateRefreshIndicator();
                        break;
                    case 'job_update':
                        console.log('Job update:', message);
                        break;
                    case 'connection_info':
                        console.log('Connection info:', message);
                        break;
                }
            };

            ws.onclose = function() {
                console.log('WebSocket disconnected');
                updateConnectionStatus(false);
                if (!reconnectInterval) {
                    reconnectInterval = setInterval(connectWebSocket, 5000);
                }
            };

            ws.onerror = function(error) {
                console.error('WebSocket error:', error);
                updateConnectionStatus(false);
            };
        }

        function updateConnectionStatus(connected) {
            const status = document.getElementById('connectionStatus');
            if (connected) {
                status.textContent = 'Connected';
                status.className = 'connection-status connected';
            } else {
                status.textContent = 'Disconnected';
                status.className = 'connection-status disconnected';
            }
        }

        function updateStatistics(data) {
            const statsGrid = document.getElementById('statsGrid');
            statsGrid.innerHTML = `
                <div class="stat-card">
                    <h3>Total Jobs</h3>
                    <div class="number">${data.jobs.total_jobs}</div>
                </div>
                <div class="stat-card">
                    <h3>Succeeded</h3>
                    <div class="number" style="color: #27ae60;">${data.jobs.succeeded}</div>
                </div>
                <div class="stat-card">
                    <h3>Failed</h3>
                    <div class="number" style="color: #e74c3c;">${data.jobs.failed}</div>
                </div>
                <div class="stat-card">
                    <h3>Processing</h3>
                    <div class="number" style="color: #3498db;">${data.jobs.processing}</div>
                </div>
                <div class="stat-card">
                    <h3>Enqueued</h3>
                    <div class="number" style="color: #f39c12;">${data.jobs.enqueued}</div>
                </div>
                <div class="stat-card">
                    <h3>Scheduled</h3>
                    <div class="number" style="color: #9b59b6;">${data.jobs.scheduled}</div>
                </div>
            `;

            updateJobsTable(data.recent_jobs);
            updateQueuesTable(data.queues);
        }

        function updateJobsTable(jobs) {
            const tbody = document.querySelector('#jobsTable tbody');
            tbody.innerHTML = jobs.map(job => `
                <tr>
                    <td>${job.id.substring(0, 8)}...</td>
                    <td>${job.method_name}</td>
                    <td>${job.queue}</td>
                    <td><span class="status ${job.state.toLowerCase()}">${job.state}</span></td>
                    <td>${new Date(job.created_at).toLocaleString()}</td>
                    <td>${job.attempts}/${job.max_attempts}</td>
                    <td>
                        ${job.state === 'Failed' ? `<button class="btn btn-success" onclick="retryJob('${job.id}')">Retry</button>` : ''}
                        <button class="btn btn-danger" onclick="deleteJob('${job.id}')">Delete</button>
                    </td>
                </tr>
            `).join('');
        }

        function updateQueuesTable(queues) {
            const tbody = document.querySelector('#queuesTable tbody');
            tbody.innerHTML = queues.map(queue => `
                <tr>
                    <td>${queue.queue_name}</td>
                    <td>${queue.enqueued_count}</td>
                    <td>${queue.processing_count}</td>
                    <td>${queue.scheduled_count}</td>
                </tr>
            `).join('');
        }

        function updateRefreshIndicator() {
            const indicator = document.getElementById('refreshIndicator');
            indicator.classList.add('spinning');
            setTimeout(() => {
                indicator.classList.remove('spinning');
            }, 1000);
        }

        async function retryJob(jobId) {
            try {
                const response = await fetch(`/api/jobs/${jobId}/retry`, {
                    method: 'POST',
                });
                const result = await response.json();
                if (result.success) {
                    console.log('Job retried successfully');
                } else {
                    console.error('Failed to retry job:', result.error);
                }
            } catch (error) {
                console.error('Error retrying job:', error);
            }
        }

        async function deleteJob(jobId) {
            if (confirm('Are you sure you want to delete this job?')) {
                try {
                    const response = await fetch(`/api/jobs/${jobId}`, {
                        method: 'DELETE',
                    });
                    const result = await response.json();
                    if (result.success) {
                        console.log('Job deleted successfully');
                    } else {
                        console.error('Failed to delete job:', result.error);
                    }
                } catch (error) {
                    console.error('Error deleting job:', error);
                }
            }
        }

        // Initialize
        connectWebSocket();
    </script>
</body>
</html>
"#;

#[cfg(all(test, feature = "metrics"))]
mod metrics_route_tests {
    use super::*;
    use axum::{
        Router,
        body::{Body, to_bytes},
        http::{Request, StatusCode},
        routing::get,
    };
    use tower::ServiceExt;

    fn test_app(metrics: Arc<PrometheusMetrics>) -> Router {
        Router::new()
            .route("/metrics", get(metrics_handler))
            .with_state(metrics)
    }

    #[tokio::test]
    async fn metrics_route_returns_text_exposition() {
        let metrics = PrometheusMetrics::new().expect("registry");
        metrics.record_enqueued("default");

        let app = test_app(metrics);
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .to_string();
        assert!(
            content_type.starts_with("text/plain"),
            "unexpected content-type: {content_type}"
        );
        let body_bytes = to_bytes(response.into_body(), 65536).await.unwrap();
        let body = std::str::from_utf8(&body_bytes).unwrap();
        assert!(body.contains("qml_jobs_enqueued_total"));
        assert!(body.contains("queue=\"default\""));
    }
}