1use std::sync::Arc;
2use tokio::sync::RwLock;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Serialize, Deserialize, Default)]
7pub struct QueueStats {
8 pub total_enqueued: u64,
10 pub total_processed: u64,
12 pub total_failed: u64,
14 pub total_retried: u64,
16 pub pending_count: u64,
18 pub running_count: u64,
20 pub dead_letter_count: u64,
22}
23
24#[derive(Clone)]
26pub struct StatsTracker {
27 stats: Arc<RwLock<QueueStats>>,
28}
29
30impl StatsTracker {
31 pub fn new() -> Self {
33 Self {
34 stats: Arc::new(RwLock::new(QueueStats::default())),
35 }
36 }
37
38 pub async fn increment_enqueued(&self) {
40 let mut stats = self.stats.write().await;
41 stats.total_enqueued += 1;
42 stats.pending_count += 1;
43 }
44
45 pub async fn increment_processed(&self) {
47 let mut stats = self.stats.write().await;
48 stats.total_processed += 1;
49 if stats.running_count > 0 {
50 stats.running_count -= 1;
51 }
52 }
53
54 pub async fn increment_failed(&self) {
56 let mut stats = self.stats.write().await;
57 stats.total_failed += 1;
58 if stats.running_count > 0 {
59 stats.running_count -= 1;
60 }
61 }
62
63 pub async fn increment_retried(&self) {
65 let mut stats = self.stats.write().await;
66 stats.total_retried += 1;
67 }
68
69 pub async fn increment_dead_letter(&self) {
71 let mut stats = self.stats.write().await;
72 stats.dead_letter_count += 1;
73 }
74
75 pub async fn mark_running(&self) {
77 let mut stats = self.stats.write().await;
78 if stats.pending_count > 0 {
79 stats.pending_count -= 1;
80 }
81 stats.running_count += 1;
82 }
83
84 pub async fn get_stats(&self) -> QueueStats {
86 self.stats.read().await.clone()
87 }
88
89 pub async fn reset(&self) {
91 let mut stats = self.stats.write().await;
92 *stats = QueueStats::default();
93 }
94}
95
96impl Default for StatsTracker {
97 fn default() -> Self {
98 Self::new()
99 }
100}