polykit_core/
metrics.rs

1//! Metrics and observability for task execution.
2
3use std::time::Duration;
4
5/// Metrics collected during task execution.
6#[derive(Debug, Clone, Default)]
7pub struct ExecutionMetrics {
8    /// Total number of packages processed.
9    pub packages_total: usize,
10    /// Number of packages that succeeded.
11    pub packages_succeeded: usize,
12    /// Number of packages that failed.
13    pub packages_failed: usize,
14    /// Total execution time.
15    pub total_duration: Duration,
16    /// Duration per package (package name -> duration).
17    pub package_durations: std::collections::HashMap<String, Duration>,
18    /// Cache hit rate (0.0 to 1.0).
19    pub cache_hit_rate: f64,
20}
21
22impl ExecutionMetrics {
23    /// Creates a new metrics instance.
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    /// Records a package execution result.
29    pub fn record_package(&mut self, package_name: String, duration: Duration, success: bool) {
30        self.packages_total += 1;
31        if success {
32            self.packages_succeeded += 1;
33        } else {
34            self.packages_failed += 1;
35        }
36        self.package_durations.insert(package_name, duration);
37    }
38
39    /// Sets the total execution duration.
40    pub fn set_total_duration(&mut self, duration: Duration) {
41        self.total_duration = duration;
42    }
43
44    /// Sets the cache hit rate.
45    pub fn set_cache_hit_rate(&mut self, rate: f64) {
46        self.cache_hit_rate = rate;
47    }
48
49    /// Returns the average duration per package.
50    pub fn average_package_duration(&self) -> Duration {
51        if self.package_durations.is_empty() {
52            return Duration::ZERO;
53        }
54        let total: Duration = self.package_durations.values().sum();
55        total / self.package_durations.len() as u32
56    }
57
58    /// Returns the success rate (0.0 to 1.0).
59    pub fn success_rate(&self) -> f64 {
60        if self.packages_total == 0 {
61            return 0.0;
62        }
63        self.packages_succeeded as f64 / self.packages_total as f64
64    }
65}