reinhardt-tasks 0.1.0-rc.15

Background task execution and scheduling
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Task metrics and monitoring
//!
//! This module provides metrics collection and monitoring capabilities for background tasks.
//!
//! ## Features
//!
//! - Task execution time tracking with percentile calculation (P50, P95, P99)
//! - Success/failure rate metrics
//! - Queue depth monitoring
//! - Worker utilization metrics
//! - Snapshot capabilities for metrics reporting
//!
//! ## Example
//!
//! ```rust,no_run
//! use reinhardt_tasks::{TaskMetrics, TaskId};
//! use std::time::Duration;
//!
//! # async fn example() {
//! let metrics = TaskMetrics::new();
//!
//! // Record task execution
//! let task_id = TaskId::new();
//! metrics.record_task_start(&task_id).await.unwrap();
//! metrics.record_task_success(&task_id, Duration::from_millis(100)).await.unwrap();
//!
//! // Get snapshot
//! let snapshot = metrics.snapshot().await;
//! assert_eq!(snapshot.task_counts.total, 1);
//! assert_eq!(snapshot.task_counts.successful, 1);
//! # }
//! ```

use crate::{TaskId, TaskResult};
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Maximum number of execution times to retain in the ring buffer.
/// Prevents unbounded memory growth in long-running services.
const MAX_EXECUTION_TIMES: usize = 10_000;

/// Task count metrics
///
/// # Example
///
/// ```rust
/// use reinhardt_tasks::TaskCounts;
///
/// let counts = TaskCounts {
///     total: 100,
///     successful: 95,
///     failed: 5,
///     pending: 10,
///     running: 3,
/// };
/// assert_eq!(counts.total, 100);
/// ```
#[derive(Debug, Clone, Default)]
pub struct TaskCounts {
	/// Total number of tasks processed
	pub total: u64,
	/// Number of successful tasks
	pub successful: u64,
	/// Number of failed tasks
	pub failed: u64,
	/// Number of pending tasks
	pub pending: u64,
	/// Number of running tasks
	pub running: u64,
}

/// Worker statistics
///
/// # Example
///
/// ```rust
/// use reinhardt_tasks::WorkerStats;
/// use std::time::Duration;
///
/// let stats = WorkerStats {
///     tasks_processed: 50,
///     average_execution_time: Duration::from_millis(100),
///     idle_time: Duration::from_secs(10),
/// };
/// assert_eq!(stats.tasks_processed, 50);
/// ```
#[derive(Debug, Clone)]
pub struct WorkerStats {
	/// Number of tasks processed by this worker
	pub tasks_processed: u64,
	/// Average execution time for tasks
	pub average_execution_time: Duration,
	/// Total idle time
	pub idle_time: Duration,
}

impl Default for WorkerStats {
	fn default() -> Self {
		Self {
			tasks_processed: 0,
			average_execution_time: Duration::ZERO,
			idle_time: Duration::ZERO,
		}
	}
}

/// Snapshot of current metrics
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_tasks::{TaskMetrics, MetricsSnapshot};
///
/// # async fn example() {
/// let metrics = TaskMetrics::new();
/// let snapshot = metrics.snapshot().await;
/// assert_eq!(snapshot.task_counts.total, 0);
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
	/// Task count metrics
	pub task_counts: TaskCounts,
	/// Average execution time
	pub average_execution_time: Duration,
	/// 50th percentile execution time
	pub p50_execution_time: Duration,
	/// 95th percentile execution time
	pub p95_execution_time: Duration,
	/// 99th percentile execution time
	pub p99_execution_time: Duration,
	/// Queue depths by queue name
	pub queue_depths: HashMap<String, usize>,
	/// Worker statistics by worker ID
	pub worker_stats: HashMap<String, WorkerStats>,
}

/// Task metrics collector
///
/// Collects and aggregates metrics for task execution, queue depths, and worker performance.
///
/// # Example
///
/// ```rust,no_run
/// use reinhardt_tasks::{TaskMetrics, TaskId};
/// use std::time::Duration;
///
/// # async fn example() {
/// let metrics = TaskMetrics::new();
///
/// // Track a task
/// let task_id = TaskId::new();
/// metrics.record_task_start(&task_id).await.unwrap();
/// metrics.record_task_success(&task_id, Duration::from_millis(150)).await.unwrap();
///
/// // Get metrics
/// let snapshot = metrics.snapshot().await;
/// assert_eq!(snapshot.task_counts.total, 1);
/// # }
/// ```
#[derive(Clone)]
pub struct TaskMetrics {
	task_counts: Arc<RwLock<TaskCounts>>,
	execution_times: Arc<RwLock<VecDeque<Duration>>>,
	queue_depths: Arc<RwLock<HashMap<String, usize>>>,
	worker_stats: Arc<RwLock<HashMap<String, WorkerStats>>>,
}

impl TaskMetrics {
	/// Create a new TaskMetrics instance
	///
	/// # Example
	///
	/// ```rust
	/// use reinhardt_tasks::TaskMetrics;
	///
	/// let metrics = TaskMetrics::new();
	/// ```
	pub fn new() -> Self {
		Self {
			task_counts: Arc::new(RwLock::new(TaskCounts::default())),
			execution_times: Arc::new(RwLock::new(VecDeque::new())),
			queue_depths: Arc::new(RwLock::new(HashMap::new())),
			worker_stats: Arc::new(RwLock::new(HashMap::new())),
		}
	}

	/// Record a task start
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, TaskId};
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	/// let task_id = TaskId::new();
	/// metrics.record_task_start(&task_id).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.task_counts.running, 1);
	/// # }
	/// ```
	pub async fn record_task_start(&self, _task_id: &TaskId) -> TaskResult<()> {
		let mut counts = self.task_counts.write().await;
		counts.running += 1;
		counts.total += 1;
		Ok(())
	}

	/// Record a successful task completion
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, TaskId};
	/// use std::time::Duration;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	/// let task_id = TaskId::new();
	/// metrics.record_task_start(&task_id).await.unwrap();
	/// metrics.record_task_success(&task_id, Duration::from_millis(100)).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.task_counts.successful, 1);
	/// assert_eq!(snapshot.task_counts.running, 0);
	/// # }
	/// ```
	pub async fn record_task_success(
		&self,
		_task_id: &TaskId,
		duration: Duration,
	) -> TaskResult<()> {
		let mut counts = self.task_counts.write().await;
		counts.successful += 1;
		counts.running = counts.running.saturating_sub(1);

		let mut times = self.execution_times.write().await;
		if times.len() >= MAX_EXECUTION_TIMES {
			times.pop_front();
		}
		times.push_back(duration);

		Ok(())
	}

	/// Record a failed task
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, TaskId};
	/// use std::time::Duration;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	/// let task_id = TaskId::new();
	/// metrics.record_task_start(&task_id).await.unwrap();
	/// metrics.record_task_failure(&task_id, Duration::from_millis(50)).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.task_counts.failed, 1);
	/// assert_eq!(snapshot.task_counts.running, 0);
	/// # }
	/// ```
	pub async fn record_task_failure(
		&self,
		_task_id: &TaskId,
		duration: Duration,
	) -> TaskResult<()> {
		let mut counts = self.task_counts.write().await;
		counts.failed += 1;
		counts.running = counts.running.saturating_sub(1);

		let mut times = self.execution_times.write().await;
		if times.len() >= MAX_EXECUTION_TIMES {
			times.pop_front();
		}
		times.push_back(duration);

		Ok(())
	}

	/// Record queue depth for a specific queue
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::TaskMetrics;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	/// metrics.record_queue_depth("default".to_string(), 42).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.queue_depths.get("default"), Some(&42));
	/// # }
	/// ```
	pub async fn record_queue_depth(&self, queue_name: String, depth: usize) -> TaskResult<()> {
		let mut depths = self.queue_depths.write().await;
		depths.insert(queue_name, depth);
		Ok(())
	}

	/// Record worker statistics
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, WorkerStats};
	/// use std::time::Duration;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	/// let stats = WorkerStats {
	///     tasks_processed: 10,
	///     average_execution_time: Duration::from_millis(100),
	///     idle_time: Duration::from_secs(5),
	/// };
	/// metrics.record_worker_stats("worker-1".to_string(), stats).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.worker_stats.get("worker-1").unwrap().tasks_processed, 10);
	/// # }
	/// ```
	pub async fn record_worker_stats(
		&self,
		worker_id: String,
		stats: WorkerStats,
	) -> TaskResult<()> {
		let mut worker_stats = self.worker_stats.write().await;
		worker_stats.insert(worker_id, stats);
		Ok(())
	}

	/// Get a snapshot of current metrics
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, TaskId};
	/// use std::time::Duration;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	///
	/// let task_id = TaskId::new();
	/// metrics.record_task_start(&task_id).await.unwrap();
	/// metrics.record_task_success(&task_id, Duration::from_millis(100)).await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.task_counts.total, 1);
	/// assert_eq!(snapshot.task_counts.successful, 1);
	/// assert!(snapshot.average_execution_time >= Duration::from_millis(100));
	/// # }
	/// ```
	pub async fn snapshot(&self) -> MetricsSnapshot {
		let counts = self.task_counts.read().await.clone();
		let times_deque = self.execution_times.read().await.clone();
		let depths = self.queue_depths.read().await.clone();
		let workers = self.worker_stats.read().await.clone();

		let times: Vec<Duration> = times_deque.into_iter().collect();
		let (average, p50, p95, p99) = Self::calculate_percentiles(&times);

		MetricsSnapshot {
			task_counts: counts,
			average_execution_time: average,
			p50_execution_time: p50,
			p95_execution_time: p95,
			p99_execution_time: p99,
			queue_depths: depths,
			worker_stats: workers,
		}
	}

	/// Reset all metrics
	///
	/// # Example
	///
	/// ```rust,no_run
	/// use reinhardt_tasks::{TaskMetrics, TaskId};
	/// use std::time::Duration;
	///
	/// # async fn example() {
	/// let metrics = TaskMetrics::new();
	///
	/// let task_id = TaskId::new();
	/// metrics.record_task_start(&task_id).await.unwrap();
	/// metrics.record_task_success(&task_id, Duration::from_millis(100)).await.unwrap();
	///
	/// metrics.reset().await.unwrap();
	///
	/// let snapshot = metrics.snapshot().await;
	/// assert_eq!(snapshot.task_counts.total, 0);
	/// # }
	/// ```
	pub async fn reset(&self) -> TaskResult<()> {
		let mut counts = self.task_counts.write().await;
		*counts = TaskCounts::default();

		let mut times = self.execution_times.write().await;
		times.clear();

		let mut depths = self.queue_depths.write().await;
		depths.clear();

		let mut workers = self.worker_stats.write().await;
		workers.clear();

		Ok(())
	}

	/// Calculate percentiles from execution times
	///
	/// Returns (average, p50, p95, p99)
	fn calculate_percentiles(times: &[Duration]) -> (Duration, Duration, Duration, Duration) {
		if times.is_empty() {
			return (
				Duration::ZERO,
				Duration::ZERO,
				Duration::ZERO,
				Duration::ZERO,
			);
		}

		let mut sorted = times.to_vec();
		sorted.sort();

		let total: Duration = sorted.iter().sum();
		let average = total / times.len() as u32;

		let p50 = Self::percentile(&sorted, 0.50);
		let p95 = Self::percentile(&sorted, 0.95);
		let p99 = Self::percentile(&sorted, 0.99);

		(average, p50, p95, p99)
	}

	/// Calculate a specific percentile
	fn percentile(sorted: &[Duration], percentile: f64) -> Duration {
		if sorted.is_empty() {
			return Duration::ZERO;
		}

		let index = ((sorted.len() as f64 - 1.0) * percentile) as usize;
		sorted[index.min(sorted.len() - 1)]
	}
}

impl Default for TaskMetrics {
	fn default() -> Self {
		Self::new()
	}
}

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

	#[tokio::test]
	async fn test_record_task_start() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		metrics.record_task_start(&task_id).await.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.task_counts.total, 1);
		assert_eq!(snapshot.task_counts.running, 1);
	}

	#[tokio::test]
	async fn test_record_task_success() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		metrics.record_task_start(&task_id).await.unwrap();
		metrics
			.record_task_success(&task_id, Duration::from_millis(100))
			.await
			.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.task_counts.total, 1);
		assert_eq!(snapshot.task_counts.successful, 1);
		assert_eq!(snapshot.task_counts.running, 0);
		assert_eq!(snapshot.average_execution_time, Duration::from_millis(100));
	}

	#[tokio::test]
	async fn test_record_task_failure() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		metrics.record_task_start(&task_id).await.unwrap();
		metrics
			.record_task_failure(&task_id, Duration::from_millis(50))
			.await
			.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.task_counts.total, 1);
		assert_eq!(snapshot.task_counts.failed, 1);
		assert_eq!(snapshot.task_counts.running, 0);
	}

	#[tokio::test]
	async fn test_record_queue_depth() {
		let metrics = TaskMetrics::new();

		metrics
			.record_queue_depth("default".to_string(), 42)
			.await
			.unwrap();
		metrics
			.record_queue_depth("priority".to_string(), 10)
			.await
			.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.queue_depths.get("default"), Some(&42));
		assert_eq!(snapshot.queue_depths.get("priority"), Some(&10));
	}

	#[tokio::test]
	async fn test_record_worker_stats() {
		let metrics = TaskMetrics::new();

		let stats = WorkerStats {
			tasks_processed: 10,
			average_execution_time: Duration::from_millis(100),
			idle_time: Duration::from_secs(5),
		};

		metrics
			.record_worker_stats("worker-1".to_string(), stats.clone())
			.await
			.unwrap();

		let snapshot = metrics.snapshot().await;
		let worker = snapshot.worker_stats.get("worker-1").unwrap();
		assert_eq!(worker.tasks_processed, 10);
		assert_eq!(worker.average_execution_time, Duration::from_millis(100));
		assert_eq!(worker.idle_time, Duration::from_secs(5));
	}

	#[tokio::test]
	async fn test_percentile_calculation() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		// Use 100 data points for accurate percentile calculation
		for i in 1..=100 {
			metrics.record_task_start(&task_id).await.unwrap();
			metrics
				.record_task_success(&task_id, Duration::from_millis(i))
				.await
				.unwrap();
		}

		let snapshot = metrics.snapshot().await;

		// Average: (1+2+...+100)/100 = 5050/100 = 50.5 (rounds down to 50 in Duration)
		// Note: Duration division truncates, not rounds
		let avg = snapshot.average_execution_time;
		assert!(
			avg >= Duration::from_millis(50) && avg <= Duration::from_millis(51),
			"Expected average around 50-51ms, got {:?}",
			avg
		);
		// P50: (100-1) * 0.50 = 49.5, index 49 (50th element in 0-indexed)
		assert_eq!(snapshot.p50_execution_time, Duration::from_millis(50));
		// P95: (100-1) * 0.95 = 94.05, index 94 (95th element in 0-indexed)
		assert_eq!(snapshot.p95_execution_time, Duration::from_millis(95));
		// P99: (100-1) * 0.99 = 98.01, index 98 (99th element in 0-indexed)
		assert_eq!(snapshot.p99_execution_time, Duration::from_millis(99));
	}

	#[tokio::test]
	async fn test_reset() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		metrics.record_task_start(&task_id).await.unwrap();
		metrics
			.record_task_success(&task_id, Duration::from_millis(100))
			.await
			.unwrap();
		metrics
			.record_queue_depth("default".to_string(), 42)
			.await
			.unwrap();

		metrics.reset().await.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.task_counts.total, 0);
		assert_eq!(snapshot.task_counts.successful, 0);
		assert_eq!(snapshot.queue_depths.len(), 0);
		assert_eq!(snapshot.average_execution_time, Duration::ZERO);
	}

	#[tokio::test]
	async fn test_concurrent_access() {
		let metrics = Arc::new(TaskMetrics::new());
		let mut handles = vec![];

		for i in 0..10 {
			let metrics = Arc::clone(&metrics);
			let handle = tokio::spawn(async move {
				let task_id = TaskId::new();
				metrics.record_task_start(&task_id).await.unwrap();
				metrics
					.record_task_success(&task_id, Duration::from_millis(i * 10))
					.await
					.unwrap();
			});
			handles.push(handle);
		}

		for handle in handles {
			handle.await.unwrap();
		}

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.task_counts.total, 10);
		assert_eq!(snapshot.task_counts.successful, 10);
	}

	#[tokio::test]
	async fn test_empty_percentiles() {
		let metrics = TaskMetrics::new();
		let snapshot = metrics.snapshot().await;

		assert_eq!(snapshot.average_execution_time, Duration::ZERO);
		assert_eq!(snapshot.p50_execution_time, Duration::ZERO);
		assert_eq!(snapshot.p95_execution_time, Duration::ZERO);
		assert_eq!(snapshot.p99_execution_time, Duration::ZERO);
	}

	#[tokio::test]
	async fn test_single_value_percentiles() {
		let metrics = TaskMetrics::new();
		let task_id = TaskId::new();

		metrics.record_task_start(&task_id).await.unwrap();
		metrics
			.record_task_success(&task_id, Duration::from_millis(100))
			.await
			.unwrap();

		let snapshot = metrics.snapshot().await;
		assert_eq!(snapshot.average_execution_time, Duration::from_millis(100));
		assert_eq!(snapshot.p50_execution_time, Duration::from_millis(100));
		assert_eq!(snapshot.p95_execution_time, Duration::from_millis(100));
		assert_eq!(snapshot.p99_execution_time, Duration::from_millis(100));
	}
}