rust-task-queue 0.1.5

Production-ready Redis task queue with intelligent auto-scaling, Actix Web integration, and enterprise-grade observability for high-performance async Rust applications.
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
//! Comprehensive tracing utilities for the Rust Task Queue system
//!
//! This module provides structured tracing utilities for observability, debugging,
//! and production monitoring of task queue operations.

use crate::{TaskId, TaskPriority};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Task lifecycle events for comprehensive observability
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TaskLifecycleEvent {
    /// Task has been enqueued
    Enqueued {
        queue: String,
        priority: TaskPriority,
        payload_size_bytes: usize,
        max_retries: u32,
        timeout_seconds: u64,
    },
    /// Task has been dequeued by a worker
    Dequeued {
        worker_id: String,
        queue: String,
        wait_time_ms: u64,
        payload_size_bytes: usize,
    },
    /// Task execution has started
    ExecutionStarted {
        worker_id: String,
        attempt: u32,
        max_retries: u32,
    },
    /// Task execution completed successfully
    ExecutionCompleted {
        worker_id: String,
        duration_ms: u64,
        result_size_bytes: usize,
        attempt: u32,
    },
    /// Task execution failed
    ExecutionFailed {
        worker_id: String,
        duration_ms: u64,
        error: String,
        error_source: Option<String>,
        attempt: u32,
    },
    /// Task is being retried
    Retrying {
        attempt: u32,
        max_retries: u32,
        delay_ms: u64,
        reason: String,
    },
    /// Task has permanently failed
    PermanentlyFailed {
        total_attempts: u32,
        final_error: String,
        total_duration_ms: u64,
    },
    /// Task has been scheduled for delayed execution
    Scheduled {
        execute_at: chrono::DateTime<chrono::Utc>,
        delay_ms: i64,
        queue: String,
    },
    /// Scheduled task moved to regular queue
    MovedToRegularQueue {
        from_scheduled: bool,
        delay_from_scheduled_ms: i64,
        queue: String,
    },
}

/// Performance metrics for task execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskPerformanceMetrics {
    pub task_name: String,
    pub execution_count: u64,
    pub total_duration_ms: u64,
    pub average_duration_ms: f64,
    pub min_duration_ms: u64,
    pub max_duration_ms: u64,
    pub success_count: u64,
    pub failure_count: u64,
    pub success_rate: f64,
    pub last_execution: chrono::DateTime<chrono::Utc>,
}

/// Queue performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueuePerformanceMetrics {
    pub queue_name: String,
    pub current_depth: i64,
    pub peak_depth: i64,
    pub total_processed: u64,
    pub total_failed: u64,
    pub average_processing_time_ms: f64,
    pub throughput_per_minute: f64,
    pub last_activity: chrono::DateTime<chrono::Utc>,
}

/// Worker performance metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerPerformanceMetrics {
    pub worker_id: String,
    pub tasks_processed: u64,
    pub tasks_failed: u64,
    pub total_processing_time_ms: u64,
    pub average_processing_time_ms: f64,
    pub current_active_tasks: usize,
    pub max_concurrent_tasks: usize,
    pub uptime_seconds: u64,
    pub last_heartbeat: chrono::DateTime<chrono::Utc>,
}

/// Trace a task lifecycle event with structured logging
pub fn trace_task_lifecycle_event(task_id: TaskId, task_name: &str, event: TaskLifecycleEvent) {
    match event {
        TaskLifecycleEvent::Enqueued {
            queue,
            priority,
            payload_size_bytes,
            max_retries,
            timeout_seconds,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                queue = queue,
                priority = ?priority,
                payload_size_bytes = payload_size_bytes,
                max_retries = max_retries,
                timeout_seconds = timeout_seconds,
                event = "enqueued",
                "Task enqueued"
            );
        }
        TaskLifecycleEvent::Dequeued {
            worker_id,
            queue,
            wait_time_ms,
            payload_size_bytes,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                worker_id = worker_id,
                queue = queue,
                wait_time_ms = wait_time_ms,
                payload_size_bytes = payload_size_bytes,
                event = "dequeued",
                "Task dequeued"
            );
        }
        TaskLifecycleEvent::ExecutionStarted {
            worker_id,
            attempt,
            max_retries,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                worker_id = worker_id,
                attempt = attempt,
                max_retries = max_retries,
                event = "execution_started",
                "Task execution started"
            );
        }
        TaskLifecycleEvent::ExecutionCompleted {
            worker_id,
            duration_ms,
            result_size_bytes,
            attempt,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                worker_id = worker_id,
                duration_ms = duration_ms,
                result_size_bytes = result_size_bytes,
                attempt = attempt,
                success = true,
                event = "execution_completed",
                "Task execution completed successfully"
            );
        }
        TaskLifecycleEvent::ExecutionFailed {
            worker_id,
            duration_ms,
            error,
            error_source,
            attempt,
        } => {
            tracing::error!(
                task_id = %task_id,
                task_name = task_name,
                worker_id = worker_id,
                duration_ms = duration_ms,
                error = error,
                error_source = error_source,
                attempt = attempt,
                success = false,
                event = "execution_failed",
                "Task execution failed"
            );
        }
        TaskLifecycleEvent::Retrying {
            attempt,
            max_retries,
            delay_ms,
            reason,
        } => {
            tracing::warn!(
                task_id = %task_id,
                task_name = task_name,
                attempt = attempt,
                max_retries = max_retries,
                delay_ms = delay_ms,
                reason = reason,
                event = "retrying",
                "Task being retried"
            );
        }
        TaskLifecycleEvent::PermanentlyFailed {
            total_attempts,
            final_error,
            total_duration_ms,
        } => {
            tracing::error!(
                task_id = %task_id,
                task_name = task_name,
                total_attempts = total_attempts,
                final_error = final_error,
                total_duration_ms = total_duration_ms,
                event = "permanently_failed",
                "Task permanently failed"
            );
        }
        TaskLifecycleEvent::Scheduled {
            execute_at,
            delay_ms,
            queue,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                execute_at = %execute_at,
                delay_ms = delay_ms,
                queue = queue,
                event = "scheduled",
                "Task scheduled for delayed execution"
            );
        }
        TaskLifecycleEvent::MovedToRegularQueue {
            from_scheduled,
            delay_from_scheduled_ms,
            queue,
        } => {
            tracing::info!(
                task_id = %task_id,
                task_name = task_name,
                from_scheduled = from_scheduled,
                delay_from_scheduled_ms = delay_from_scheduled_ms,
                queue = queue,
                event = "moved_to_regular_queue",
                "Scheduled task moved to regular queue"
            );
        }
    }
}

/// Trace task error with detailed context and error chain
pub fn trace_task_error(
    task_id: TaskId,
    task_name: &str,
    error: &dyn std::error::Error,
    context: &str,
    worker_id: Option<&str>,
    attempt: Option<u32>,
) {
    tracing::error!(
        task_id = %task_id,
        task_name = task_name,
        error = %error,
        error_source = error.source().map(|e| e.to_string()).as_deref(),
        context = context,
        worker_id = worker_id,
        attempt = attempt,
        "Task error occurred"
    );

    // Log error chain for debugging
    let mut source = error.source();
    let mut depth = 1;
    while let Some(err) = source {
        tracing::debug!(
            task_id = %task_id,
            error_depth = depth,
            error = %err,
            "Error chain"
        );
        source = err.source();
        depth += 1;
    }
}

/// Simple performance tracker for measuring operation durations
pub struct PerformanceTracker {
    start_time: Instant,
    operation_name: String,
    context: HashMap<String, String>,
}

impl PerformanceTracker {
    pub fn new(operation_name: &str) -> Self {
        Self {
            start_time: Instant::now(),
            operation_name: operation_name.to_string(),
            context: HashMap::new(),
        }
    }

    pub fn with_context(mut self, key: &str, value: &str) -> Self {
        self.context.insert(key.to_string(), value.to_string());
        self
    }

    pub fn add_context(&mut self, key: &str, value: &str) {
        self.context.insert(key.to_string(), value.to_string());
    }

    pub fn elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    pub fn trace_completion(self) {
        let duration = self.elapsed();
        tracing::debug!(
            operation = self.operation_name,
            duration_ms = duration.as_millis(),
            context = ?self.context,
            "Operation completed"
        );
    }

    pub fn trace_completion_with_result<T, E>(self, result: &Result<T, E>)
    where
        E: std::fmt::Display,
    {
        let duration = self.elapsed();
        match result {
            Ok(_) => {
                tracing::info!(
                    operation = self.operation_name,
                    duration_ms = duration.as_millis(),
                    success = true,
                    context = ?self.context,
                    "Operation completed successfully"
                );
            }
            Err(e) => {
                tracing::error!(
                    operation = self.operation_name,
                    duration_ms = duration.as_millis(),
                    success = false,
                    error = %e,
                    context = ?self.context,
                    "Operation failed"
                );
            }
        }
    }
}

/// Trace queue operation with metrics
pub fn trace_queue_operation(
    operation: &str,
    queue: &str,
    item_count: Option<usize>,
    duration: Duration,
    success: bool,
    error: Option<&str>,
) {
    if success {
        tracing::info!(
            operation = operation,
            queue = queue,
            item_count = item_count,
            duration_ms = duration.as_millis(),
            success = true,
            "Queue operation completed"
        );
    } else {
        tracing::error!(
            operation = operation,
            queue = queue,
            item_count = item_count,
            duration_ms = duration.as_millis(),
            success = false,
            error = error,
            "Queue operation failed"
        );
    }
}

/// Trace worker operation with context
pub fn trace_worker_operation(
    worker_id: &str,
    operation: &str,
    active_tasks: Option<usize>,
    duration: Option<Duration>,
    success: bool,
    error: Option<&str>,
) {
    if success {
        tracing::info!(
            worker_id = worker_id,
            operation = operation,
            active_tasks = active_tasks,
            duration_ms = duration.map(|d| d.as_millis()),
            success = true,
            "Worker operation completed"
        );
    } else {
        tracing::error!(
            worker_id = worker_id,
            operation = operation,
            active_tasks = active_tasks,
            duration_ms = duration.map(|d| d.as_millis()),
            success = false,
            error = error,
            "Worker operation failed"
        );
    }
}

/// Helper macro for creating traced spans around async operations
#[macro_export]
macro_rules! traced_operation {
    ($span_name:expr, $($field:ident = $value:expr),* $(,)?) => {
        tracing::info_span!($span_name, $($field = $value),*)
    };
}

/// Helper macro for timing operations with automatic tracing
#[macro_export]
macro_rules! timed_operation {
    ($operation_name:expr, $code:expr) => {{
        let tracker = $crate::tracing_utils::PerformanceTracker::new($operation_name);
        let result = $code;
        tracker.trace_completion_with_result(&result);
        result
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_performance_tracker() {
        let tracker =
            PerformanceTracker::new("test_operation").with_context("test_key", "test_value");

        assert_eq!(tracker.operation_name, "test_operation");
        assert_eq!(
            tracker.context.get("test_key"),
            Some(&"test_value".to_string())
        );
        assert!(tracker.elapsed().as_nanos() > 0);
    }

    #[test]
    fn test_task_lifecycle_event_serialization() {
        let event = TaskLifecycleEvent::Enqueued {
            queue: "test_queue".to_string(),
            priority: TaskPriority::High,
            payload_size_bytes: 1024,
            max_retries: 3,
            timeout_seconds: 300,
        };

        let serialized = serde_json::to_string(&event).expect("Failed to serialize");
        let deserialized: TaskLifecycleEvent =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        match deserialized {
            TaskLifecycleEvent::Enqueued {
                queue,
                priority,
                payload_size_bytes,
                max_retries,
                timeout_seconds,
            } => {
                assert_eq!(queue, "test_queue");
                assert_eq!(priority, TaskPriority::High);
                assert_eq!(payload_size_bytes, 1024);
                assert_eq!(max_retries, 3);
                assert_eq!(timeout_seconds, 300);
            }
            _ => panic!("Unexpected event type"),
        }
    }
}