peat-protocol 0.9.0-rc.7

Peat Coordination Protocol — hierarchical capability composition over CRDTs for heterogeneous mesh networks
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
//! Summary Strategies for Event Aggregation (ADR-027 Phase 2)
//!
//! Different event types require different summarization strategies.
//! This module provides a trait and implementations for generating
//! summaries from aggregated events.
//!
//! ## Strategy Pattern
//!
//! ```text
//! Events → SummaryStrategy → Summary Payload (bytes)
//!//!    ┌─────────┴─────────┐
//!    │  Detection: counts, histogram │
//!    │  Telemetry: min/max/avg      │
//!    │  Custom: user-defined        │
//!    └───────────────────────────────┘
//! ```

use peat_schema::event::v1::PeatEvent;
use std::collections::HashMap;
use std::fmt::Debug;

/// Strategy for summarizing events of a given type
///
/// Implementations should be stateless and thread-safe.
pub trait SummaryStrategy: Send + Sync + Debug {
    /// Event type this strategy handles (e.g., "detection", "telemetry")
    fn event_type(&self) -> &str;

    /// Generate summary payload from collected events
    ///
    /// Returns a byte vector containing the summarized data.
    /// The format is application-specific but should be consistent.
    fn summarize(&self, events: &[PeatEvent]) -> Vec<u8>;
}

/// Default summary strategy for events without a specific strategy
///
/// Generates a simple count-based summary.
#[derive(Debug)]
pub struct DefaultSummaryStrategy {
    event_type: String,
}

impl DefaultSummaryStrategy {
    /// Create a new default strategy for an event type
    pub fn new(event_type: &str) -> Self {
        Self {
            event_type: event_type.to_string(),
        }
    }
}

impl SummaryStrategy for DefaultSummaryStrategy {
    fn event_type(&self) -> &str {
        &self.event_type
    }

    fn summarize(&self, events: &[PeatEvent]) -> Vec<u8> {
        // Simple JSON summary with counts
        let summary = serde_json::json!({
            "event_type": self.event_type,
            "event_count": events.len(),
            "source_nodes": events.iter()
                .map(|e| e.source_node_id.clone())
                .collect::<std::collections::HashSet<_>>()
                .into_iter()
                .collect::<Vec<_>>(),
        });

        serde_json::to_vec(&summary).unwrap_or_default()
    }
}

/// Detection event summary strategy
///
/// Generates summaries with:
/// - Counts by detection type
/// - Confidence histogram (10 buckets)
/// - Total detection count
#[derive(Debug, Default)]
pub struct DetectionSummaryStrategy;

impl DetectionSummaryStrategy {
    /// Create a new detection summary strategy
    pub fn new() -> Self {
        Self
    }
}

impl SummaryStrategy for DetectionSummaryStrategy {
    fn event_type(&self) -> &str {
        "detection"
    }

    fn summarize(&self, events: &[PeatEvent]) -> Vec<u8> {
        let mut counts_by_type: HashMap<String, u32> = HashMap::new();
        let mut confidence_histogram = [0u32; 10];
        let mut total_detections = 0u32;

        for event in events {
            total_detections += 1;

            // Parse event type for detection subtype
            let subtype = event
                .event_type
                .strip_prefix("detection.")
                .or_else(|| event.event_type.strip_prefix("product.detection."))
                .unwrap_or("unknown");

            *counts_by_type.entry(subtype.to_string()).or_default() += 1;

            // Try to extract confidence from payload if present
            if !event.payload_value.is_empty() {
                // Attempt to parse confidence from JSON payload
                if let Ok(payload) =
                    serde_json::from_slice::<serde_json::Value>(&event.payload_value)
                {
                    if let Some(conf) = payload.get("confidence").and_then(|v| v.as_f64()) {
                        let bucket = ((conf * 10.0).clamp(0.0, 9.0)) as usize;
                        confidence_histogram[bucket] += 1;
                    }
                }
            }
        }

        let summary = DetectionSummary {
            counts_by_type,
            confidence_histogram: confidence_histogram.to_vec(),
            total_detections,
        };

        serde_json::to_vec(&summary).unwrap_or_default()
    }
}

/// Summary data for detection events
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DetectionSummary {
    /// Counts of detections by type
    pub counts_by_type: HashMap<String, u32>,

    /// Confidence histogram (10 buckets: 0.0-0.1, 0.1-0.2, ..., 0.9-1.0)
    pub confidence_histogram: Vec<u32>,

    /// Total number of detections
    pub total_detections: u32,
}

/// Telemetry event summary strategy
///
/// Generates summaries with:
/// - Min/max/avg for each metric
/// - Sample count
#[derive(Debug, Default)]
pub struct TelemetrySummaryStrategy;

impl TelemetrySummaryStrategy {
    /// Create a new telemetry summary strategy
    pub fn new() -> Self {
        Self
    }
}

impl SummaryStrategy for TelemetrySummaryStrategy {
    fn event_type(&self) -> &str {
        "telemetry"
    }

    fn summarize(&self, events: &[PeatEvent]) -> Vec<u8> {
        let mut metrics: HashMap<String, MetricStats> = HashMap::new();

        for event in events {
            // Try to parse metrics from payload
            if !event.payload_value.is_empty() {
                if let Ok(payload) =
                    serde_json::from_slice::<serde_json::Value>(&event.payload_value)
                {
                    // Look for metrics in the payload
                    if let Some(obj) = payload.as_object() {
                        for (key, value) in obj {
                            if let Some(v) = value.as_f64() {
                                let stats = metrics.entry(key.clone()).or_default();
                                stats.update(v);
                            }
                        }
                    }
                }
            }

            // Also track by event type (e.g., "telemetry.cpu" -> "cpu")
            let metric_name = event
                .event_type
                .strip_prefix("telemetry.")
                .unwrap_or(&event.event_type);

            // Track at least the count for this metric type
            let stats = metrics.entry(metric_name.to_string()).or_default();
            if stats.count == 0 {
                stats.count = 1;
            } else {
                stats.count += 1;
            }
        }

        let summary = TelemetrySummary {
            metrics: metrics
                .into_iter()
                .map(|(k, v)| (k, v.finalize()))
                .collect(),
            sample_count: events.len() as u32,
        };

        serde_json::to_vec(&summary).unwrap_or_default()
    }
}

/// Summary data for telemetry events
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TelemetrySummary {
    /// Statistics for each metric
    pub metrics: HashMap<String, MetricSummaryStats>,

    /// Total number of samples
    pub sample_count: u32,
}

/// Statistics for a single metric
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MetricStats {
    min: f64,
    max: f64,
    sum: f64,
    count: u32,
}

impl MetricStats {
    /// Update stats with a new value
    pub fn update(&mut self, value: f64) {
        if self.count == 0 {
            self.min = value;
            self.max = value;
        } else {
            self.min = self.min.min(value);
            self.max = self.max.max(value);
        }
        self.sum += value;
        self.count += 1;
    }

    /// Finalize into a summary stats structure
    pub fn finalize(&self) -> MetricSummaryStats {
        MetricSummaryStats {
            min: self.min,
            max: self.max,
            avg: if self.count > 0 {
                self.sum / self.count as f64
            } else {
                0.0
            },
            count: self.count,
        }
    }
}

/// Final statistics for a metric
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MetricSummaryStats {
    /// Minimum value
    pub min: f64,

    /// Maximum value
    pub max: f64,

    /// Average value
    pub avg: f64,

    /// Sample count
    pub count: u32,
}

/// Anomaly event summary strategy
///
/// Generates summaries with:
/// - Counts by severity
/// - List of unique anomaly types
/// - Total anomaly count
#[derive(Debug, Default)]
pub struct AnomalySummaryStrategy;

impl AnomalySummaryStrategy {
    /// Create a new anomaly summary strategy
    pub fn new() -> Self {
        Self
    }
}

impl SummaryStrategy for AnomalySummaryStrategy {
    fn event_type(&self) -> &str {
        "anomaly"
    }

    fn summarize(&self, events: &[PeatEvent]) -> Vec<u8> {
        let mut counts_by_severity: HashMap<String, u32> = HashMap::new();
        let mut anomaly_types: std::collections::HashSet<String> = std::collections::HashSet::new();

        for event in events {
            // Extract severity from priority
            let severity = if let Some(routing) = &event.routing {
                match routing.priority {
                    0 => "critical",
                    1 => "high",
                    2 => "normal",
                    3 => "low",
                    _ => "unknown",
                }
            } else {
                "unknown"
            };

            *counts_by_severity.entry(severity.to_string()).or_default() += 1;

            // Extract anomaly type
            let anomaly_type = event
                .event_type
                .strip_prefix("anomaly.")
                .unwrap_or(&event.event_type);
            anomaly_types.insert(anomaly_type.to_string());
        }

        let summary = AnomalySummary {
            counts_by_severity,
            anomaly_types: anomaly_types.into_iter().collect(),
            total_anomalies: events.len() as u32,
        };

        serde_json::to_vec(&summary).unwrap_or_default()
    }
}

/// Summary data for anomaly events
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AnomalySummary {
    /// Counts by severity level
    pub counts_by_severity: HashMap<String, u32>,

    /// Unique anomaly types observed
    pub anomaly_types: Vec<String>,

    /// Total anomaly count
    pub total_anomalies: u32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use peat_schema::common::v1::Timestamp;
    use peat_schema::event::v1::{AggregationPolicy, EventClass, EventPriority, PropagationMode};

    fn make_event(event_type: &str, payload: Option<serde_json::Value>) -> PeatEvent {
        PeatEvent {
            event_id: "test-1".to_string(),
            timestamp: Some(Timestamp {
                seconds: 0,
                nanos: 0,
            }),
            source_node_id: "node-1".to_string(),
            source_formation_id: "squad-1".to_string(),
            source_instance_id: None,
            event_class: EventClass::Product as i32,
            event_type: event_type.to_string(),
            routing: Some(AggregationPolicy {
                propagation: PropagationMode::PropagationSummary as i32,
                priority: EventPriority::PriorityNormal as i32,
                ttl_seconds: 300,
                aggregation_window_ms: 1000,
            }),
            payload_type_url: String::new(),
            payload_value: payload
                .map(|p| serde_json::to_vec(&p).unwrap())
                .unwrap_or_default(),
        }
    }

    #[test]
    fn test_default_strategy() {
        let strategy = DefaultSummaryStrategy::new("test");
        assert_eq!(strategy.event_type(), "test");

        let events = vec![
            make_event("test.a", None),
            make_event("test.b", None),
            make_event("test.a", None),
        ];

        let summary_bytes = strategy.summarize(&events);
        let summary: serde_json::Value = serde_json::from_slice(&summary_bytes).unwrap();

        assert_eq!(summary["event_count"], 3);
        assert_eq!(summary["event_type"], "test");
    }

    #[test]
    fn test_detection_strategy_counts() {
        let strategy = DetectionSummaryStrategy::new();
        assert_eq!(strategy.event_type(), "detection");

        let events = vec![
            make_event("detection.vehicle", None),
            make_event("detection.person", None),
            make_event("detection.vehicle", None),
        ];

        let summary_bytes = strategy.summarize(&events);
        let summary: DetectionSummary = serde_json::from_slice(&summary_bytes).unwrap();

        assert_eq!(summary.total_detections, 3);
        assert_eq!(*summary.counts_by_type.get("vehicle").unwrap(), 2);
        assert_eq!(*summary.counts_by_type.get("person").unwrap(), 1);
    }

    #[test]
    fn test_detection_strategy_confidence() {
        let strategy = DetectionSummaryStrategy::new();

        let events = vec![
            make_event(
                "detection.vehicle",
                Some(serde_json::json!({"confidence": 0.95})),
            ),
            make_event(
                "detection.vehicle",
                Some(serde_json::json!({"confidence": 0.85})),
            ),
            make_event(
                "detection.vehicle",
                Some(serde_json::json!({"confidence": 0.35})),
            ),
        ];

        let summary_bytes = strategy.summarize(&events);
        let summary: DetectionSummary = serde_json::from_slice(&summary_bytes).unwrap();

        // Bucket 9 (0.9-1.0): 1 event with 0.95
        // Bucket 8 (0.8-0.9): 1 event with 0.85
        // Bucket 3 (0.3-0.4): 1 event with 0.35
        assert_eq!(summary.confidence_histogram[9], 1);
        assert_eq!(summary.confidence_histogram[8], 1);
        assert_eq!(summary.confidence_histogram[3], 1);
    }

    #[test]
    fn test_telemetry_strategy() {
        let strategy = TelemetrySummaryStrategy::new();
        assert_eq!(strategy.event_type(), "telemetry");

        let events = vec![
            make_event(
                "telemetry.cpu",
                Some(serde_json::json!({"cpu_percent": 50.0, "memory_mb": 1024.0})),
            ),
            make_event(
                "telemetry.cpu",
                Some(serde_json::json!({"cpu_percent": 75.0, "memory_mb": 2048.0})),
            ),
        ];

        let summary_bytes = strategy.summarize(&events);
        let summary: TelemetrySummary = serde_json::from_slice(&summary_bytes).unwrap();

        assert_eq!(summary.sample_count, 2);

        let cpu = summary.metrics.get("cpu_percent").unwrap();
        assert_eq!(cpu.min, 50.0);
        assert_eq!(cpu.max, 75.0);
        assert!((cpu.avg - 62.5).abs() < 0.01);
        assert_eq!(cpu.count, 2);

        let mem = summary.metrics.get("memory_mb").unwrap();
        assert_eq!(mem.min, 1024.0);
        assert_eq!(mem.max, 2048.0);
    }

    #[test]
    fn test_anomaly_strategy() {
        let strategy = AnomalySummaryStrategy::new();
        assert_eq!(strategy.event_type(), "anomaly");

        let events = vec![
            {
                let mut e = make_event("anomaly.intrusion", None);
                e.routing.as_mut().unwrap().priority = EventPriority::PriorityCritical as i32;
                e
            },
            {
                let mut e = make_event("anomaly.network_spike", None);
                e.routing.as_mut().unwrap().priority = EventPriority::PriorityHigh as i32;
                e
            },
            {
                let mut e = make_event("anomaly.intrusion", None);
                e.routing.as_mut().unwrap().priority = EventPriority::PriorityCritical as i32;
                e
            },
        ];

        let summary_bytes = strategy.summarize(&events);
        let summary: AnomalySummary = serde_json::from_slice(&summary_bytes).unwrap();

        assert_eq!(summary.total_anomalies, 3);
        assert_eq!(*summary.counts_by_severity.get("critical").unwrap(), 2);
        assert_eq!(*summary.counts_by_severity.get("high").unwrap(), 1);
        assert!(summary.anomaly_types.contains(&"intrusion".to_string()));
        assert!(summary.anomaly_types.contains(&"network_spike".to_string()));
    }

    #[test]
    fn test_empty_events() {
        let strategy = DetectionSummaryStrategy::new();
        let summary_bytes = strategy.summarize(&[]);
        let summary: DetectionSummary = serde_json::from_slice(&summary_bytes).unwrap();

        assert_eq!(summary.total_detections, 0);
        assert!(summary.counts_by_type.is_empty());
    }
}