oximedia-distributed 0.1.9

Distributed encoding coordinator for OxiMedia
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
//! Distributed metrics collection and aggregation.
//!
//! Provides time-series metric recording, windowed queries, statistical
//! aggregation, and alert evaluation for the distributed encoding cluster.

#![allow(dead_code)]

use std::collections::HashMap;

/// A single metric measurement.
#[derive(Debug, Clone)]
pub struct MetricPoint {
    /// Name of the metric (e.g., "`cpu_usage`", "`frames_encoded`").
    pub name: String,
    /// Numeric value.
    pub value: f64,
    /// Key-value tags for dimensionality (e.g., `worker_id`, codec).
    pub tags: HashMap<String, String>,
    /// Unix epoch timestamp in milliseconds.
    pub timestamp_ms: u64,
}

impl MetricPoint {
    /// Create a new metric point.
    pub fn new(name: impl Into<String>, value: f64, timestamp_ms: u64) -> Self {
        Self {
            name: name.into(),
            value,
            tags: HashMap::new(),
            timestamp_ms,
        }
    }

    /// Create a metric point with tags.
    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.insert(key.into(), value.into());
        self
    }
}

/// Aggregation function to apply over a set of values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregationFn {
    /// Sum of all values.
    Sum,
    /// Arithmetic mean.
    Mean,
    /// Minimum value.
    Min,
    /// Maximum value.
    Max,
    /// 50th percentile (median).
    P50,
    /// 95th percentile.
    P95,
    /// 99th percentile.
    P99,
}

/// Collects and aggregates distributed metrics.
#[derive(Debug, Default)]
pub struct MetricAggregator {
    /// All recorded metric points, grouped by metric name.
    points: HashMap<String, Vec<MetricPoint>>,
}

impl MetricAggregator {
    /// Create a new aggregator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            points: HashMap::new(),
        }
    }

    /// Record a metric point.
    pub fn record(&mut self, point: MetricPoint) {
        self.points
            .entry(point.name.clone())
            .or_default()
            .push(point);
    }

    /// Return all values for a metric within the given time window ending at
    /// the most recent recorded timestamp (or the largest timestamp seen).
    ///
    /// `window_ms` is the duration in milliseconds to look back.  Points are
    /// included when `now_max - window_ms <= timestamp_ms <= now_max`.
    #[must_use]
    pub fn query(&self, name: &str, window_ms: u64) -> Vec<f64> {
        let pts = match self.points.get(name) {
            Some(v) => v,
            None => return Vec::new(),
        };

        let now_max = pts.iter().map(|p| p.timestamp_ms).max().unwrap_or(0);
        let start = now_max.saturating_sub(window_ms);

        pts.iter()
            .filter(|p| p.timestamp_ms >= start)
            .map(|p| p.value)
            .collect()
    }

    /// Compute an aggregation over values in a time window.
    ///
    /// Returns `None` if there are no values in the window.
    #[must_use]
    pub fn aggregate(&self, name: &str, window_ms: u64, agg: AggregationFn) -> Option<f64> {
        let mut values = self.query(name, window_ms);
        if values.is_empty() {
            return None;
        }
        values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let result = match agg {
            AggregationFn::Sum => values.iter().sum(),
            AggregationFn::Mean => values.iter().sum::<f64>() / values.len() as f64,
            AggregationFn::Min => *values.first().unwrap_or(&0.0),
            AggregationFn::Max => *values.last().unwrap_or(&0.0),
            AggregationFn::P50 => percentile(&values, 50.0),
            AggregationFn::P95 => percentile(&values, 95.0),
            AggregationFn::P99 => percentile(&values, 99.0),
        };

        Some(result)
    }
}

/// Compute the p-th percentile of a pre-sorted slice.
fn percentile(sorted: &[f64], p: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let idx = ((p / 100.0) * (sorted.len() - 1) as f64).round() as usize;
    sorted[idx.min(sorted.len() - 1)]
}

/// A snapshot of cluster-wide metrics.
#[derive(Debug, Clone)]
pub struct ClusterMetrics {
    /// Number of worker nodes.
    pub worker_count: u32,
    /// Total tasks ever submitted.
    pub total_tasks: u64,
    /// Tasks currently running.
    pub running_tasks: u32,
    /// Total failed tasks.
    pub failed_tasks: u64,
    /// Average throughput (tasks/sec or frames/sec depending on context).
    pub avg_throughput: f64,
}

impl ClusterMetrics {
    /// Compute cluster metrics from aggregated data.
    ///
    /// Reads the following metric names:
    /// - "`worker_count`" (latest value)
    /// - "`total_tasks`" (sum over window)
    /// - "`running_tasks`" (latest value)
    /// - "`failed_tasks`" (sum over window)
    /// - "throughput" (mean over window)
    #[must_use]
    pub fn compute(aggregator: &MetricAggregator, now_ms: u64) -> Self {
        let window_ms = now_ms; // look at all recorded data

        let worker_count = aggregator
            .aggregate("worker_count", window_ms, AggregationFn::Max)
            .unwrap_or(0.0) as u32;

        let total_tasks = aggregator
            .aggregate("total_tasks", window_ms, AggregationFn::Sum)
            .unwrap_or(0.0) as u64;

        let running_tasks = aggregator
            .aggregate("running_tasks", window_ms, AggregationFn::Max)
            .unwrap_or(0.0) as u32;

        let failed_tasks = aggregator
            .aggregate("failed_tasks", window_ms, AggregationFn::Sum)
            .unwrap_or(0.0) as u64;

        let avg_throughput = aggregator
            .aggregate("throughput", window_ms, AggregationFn::Mean)
            .unwrap_or(0.0);

        Self {
            worker_count,
            total_tasks,
            running_tasks,
            failed_tasks,
            avg_throughput,
        }
    }
}

/// Comparison operator for alert rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Comparison {
    /// Alert fires when metric is above the threshold.
    Above,
    /// Alert fires when metric is below the threshold.
    Below,
    /// Alert fires when metric equals the threshold (within floating-point epsilon).
    Equal,
}

/// A rule that triggers an alert based on a metric condition.
#[derive(Debug, Clone)]
pub struct AlertRule {
    /// Name of the metric to watch.
    pub metric_name: String,
    /// Threshold value.
    pub threshold: f64,
    /// How to compare the aggregated value against the threshold.
    pub comparison: Comparison,
    /// Time window (ms) over which to aggregate the metric.
    pub window_ms: u64,
}

impl AlertRule {
    /// Create a new alert rule.
    pub fn new(
        metric_name: impl Into<String>,
        threshold: f64,
        comparison: Comparison,
        window_ms: u64,
    ) -> Self {
        Self {
            metric_name: metric_name.into(),
            threshold,
            comparison,
            window_ms,
        }
    }
}

/// A fired alert.
#[derive(Debug, Clone)]
pub struct Alert {
    /// The rule that triggered this alert.
    pub rule: AlertRule,
    /// The aggregated value that triggered the alert.
    pub current_value: f64,
    /// When the alert was triggered (Unix epoch ms).
    pub triggered_at_ms: u64,
}

/// Evaluates alert rules against recorded metrics.
pub struct AlertEvaluator;

impl AlertEvaluator {
    /// Check all rules and return any that are currently firing.
    #[must_use]
    pub fn check(rules: &[AlertRule], aggregator: &MetricAggregator, now_ms: u64) -> Vec<Alert> {
        let mut alerts = Vec::new();

        for rule in rules {
            // Use Mean as default aggregation for alerts
            if let Some(value) =
                aggregator.aggregate(&rule.metric_name, rule.window_ms, AggregationFn::Mean)
            {
                let fires = match rule.comparison {
                    Comparison::Above => value > rule.threshold,
                    Comparison::Below => value < rule.threshold,
                    Comparison::Equal => (value - rule.threshold).abs() < f64::EPSILON,
                };

                if fires {
                    alerts.push(Alert {
                        rule: rule.clone(),
                        current_value: value,
                        triggered_at_ms: now_ms,
                    });
                }
            }
        }

        alerts
    }
}

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

    fn ts(ms: u64) -> u64 {
        ms
    }

    fn record_values(agg: &mut MetricAggregator, name: &str, values: &[(f64, u64)]) {
        for &(v, t) in values {
            agg.record(MetricPoint::new(name, v, ts(t)));
        }
    }

    #[test]
    fn test_record_and_query() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "cpu", &[(0.5, 1000), (0.6, 2000), (0.7, 3000)]);
        let vals = agg.query("cpu", 5000);
        assert_eq!(vals.len(), 3);
    }

    #[test]
    fn test_query_windowed() {
        let mut agg = MetricAggregator::new();
        // Points at t=100, t=500, t=1000; max=1000, window=600 → include t>=400
        record_values(&mut agg, "fps", &[(10.0, 100), (20.0, 500), (30.0, 1000)]);
        let vals = agg.query("fps", 600);
        // Should include t=500 and t=1000
        assert_eq!(vals.len(), 2);
    }

    #[test]
    fn test_aggregate_sum() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "bytes", &[(100.0, 1), (200.0, 2), (300.0, 3)]);
        let sum = agg.aggregate("bytes", 100, AggregationFn::Sum);
        assert!((sum.expect("metric computation should succeed") - 600.0).abs() < 1e-9);
    }

    #[test]
    fn test_aggregate_mean() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "lat", &[(10.0, 1), (20.0, 2), (30.0, 3)]);
        let mean = agg.aggregate("lat", 100, AggregationFn::Mean);
        assert!((mean.expect("metric computation should succeed") - 20.0).abs() < 1e-9);
    }

    #[test]
    fn test_aggregate_min_max() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "val", &[(5.0, 1), (1.0, 2), (9.0, 3)]);
        assert!(
            (agg.aggregate("val", 100, AggregationFn::Min)
                .expect("aggregation should succeed")
                - 1.0)
                .abs()
                < 1e-9
        );
        assert!(
            (agg.aggregate("val", 100, AggregationFn::Max)
                .expect("aggregation should succeed")
                - 9.0)
                .abs()
                < 1e-9
        );
    }

    #[test]
    fn test_aggregate_p50() {
        let mut agg = MetricAggregator::new();
        // sorted: 1,2,3,4,5 → p50 = 3
        record_values(
            &mut agg,
            "m",
            &[(3.0, 1), (1.0, 2), (5.0, 3), (2.0, 4), (4.0, 5)],
        );
        let p50 = agg.aggregate("m", 100, AggregationFn::P50);
        assert!((p50.expect("metric computation should succeed") - 3.0).abs() < 1e-9);
    }

    #[test]
    fn test_aggregate_empty() {
        let agg = MetricAggregator::new();
        assert!(agg
            .aggregate("nonexistent", 1000, AggregationFn::Mean)
            .is_none());
    }

    #[test]
    fn test_cluster_metrics_compute() {
        let mut agg = MetricAggregator::new();
        agg.record(MetricPoint::new("worker_count", 4.0, 1000));
        agg.record(MetricPoint::new("total_tasks", 100.0, 1000));
        agg.record(MetricPoint::new("running_tasks", 12.0, 1000));
        agg.record(MetricPoint::new("failed_tasks", 3.0, 1000));
        agg.record(MetricPoint::new("throughput", 25.0, 1000));

        let metrics = ClusterMetrics::compute(&agg, 2000);
        assert_eq!(metrics.worker_count, 4);
        assert_eq!(metrics.running_tasks, 12);
        assert!((metrics.avg_throughput - 25.0).abs() < 1e-9);
    }

    #[test]
    fn test_alert_above_fires() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "cpu", &[(0.95, 1000)]);
        let rules = vec![AlertRule::new("cpu", 0.8, Comparison::Above, 5000)];
        let alerts = AlertEvaluator::check(&rules, &agg, 1000);
        assert_eq!(alerts.len(), 1);
        assert!((alerts[0].current_value - 0.95).abs() < 1e-9);
    }

    #[test]
    fn test_alert_below_fires() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "workers", &[(2.0, 1000)]);
        let rules = vec![AlertRule::new("workers", 5.0, Comparison::Below, 5000)];
        let alerts = AlertEvaluator::check(&rules, &agg, 1000);
        assert_eq!(alerts.len(), 1);
    }

    #[test]
    fn test_alert_does_not_fire_when_ok() {
        let mut agg = MetricAggregator::new();
        record_values(&mut agg, "cpu", &[(0.5, 1000)]);
        let rules = vec![AlertRule::new("cpu", 0.8, Comparison::Above, 5000)];
        let alerts = AlertEvaluator::check(&rules, &agg, 1000);
        assert!(alerts.is_empty());
    }
}