go_zoom_kinesis/monitoring/
metrics.rs

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
use super::types::{IteratorEventType, ProcessingEvent, ProcessingEventType, ShardEventType};
use std::collections::HashMap;

use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tokio::time::interval;
use tracing::trace;
use tracing::{debug, info, warn};

#[derive(Debug, Default)]
pub struct ProcessingMetrics {}

#[derive(Debug, Clone)]
pub struct BatchMetrics {
    pub total_records: usize,
    pub successful_count: usize,
    pub failed_count: usize,
    pub processing_duration: Duration,
    pub has_more: bool,
}

/// Holds aggregated metrics for a single shard
#[derive(Debug, Clone)]
pub struct ShardMetrics {
    // Record processing metrics
    pub records_processed: u64,
    pub records_failed: u64,
    pub retry_attempts: u64,
    pub processing_time: Duration,

    // Checkpoint metrics
    pub checkpoints_succeeded: u64,
    pub checkpoints_failed: u64,

    // Iterator metrics
    pub iterator_renewals: u64,
    pub iterator_failures: u64,

    // Error tracking
    pub soft_errors: u64,
    pub hard_errors: u64,

    // Performance metrics
    pub avg_processing_time: Duration,
    pub max_processing_time: Duration,

    // Window information
    pub window_start: Instant,
    pub last_updated: Instant,
}

impl Default for ShardMetrics {
    fn default() -> Self {
        let now = Instant::now();
        Self {
            records_processed: 0,
            records_failed: 0,
            retry_attempts: 0,
            processing_time: Duration::default(),
            checkpoints_succeeded: 0,
            checkpoints_failed: 0,
            iterator_renewals: 0,
            iterator_failures: 0,
            soft_errors: 0,
            hard_errors: 0,
            avg_processing_time: Duration::default(),
            max_processing_time: Duration::default(),
            window_start: now,
            last_updated: now,
        }
    }
}

/// Aggregates monitoring events into metrics
pub struct MetricsAggregator {
    metrics: Arc<RwLock<HashMap<String, ShardMetrics>>>,
    window_duration: Duration,
    monitoring_rx: tokio::sync::mpsc::Receiver<ProcessingEvent>,
}

impl MetricsAggregator {
    /// Create a new metrics aggregator
    pub fn new(
        window_duration: Duration,
        monitoring_rx: tokio::sync::mpsc::Receiver<ProcessingEvent>,
    ) -> Self {
        Self {
            metrics: Arc::new(RwLock::new(HashMap::new())),
            window_duration,
            monitoring_rx,
        }
    }

    /// Start processing events and emitting metrics
    pub async fn run(mut self) {
        let mut interval = interval(self.window_duration);

        loop {
            tokio::select! {
                // Process incoming events
                Some(event) = self.monitoring_rx.recv() => {
                    self.process_event(event).await;
                }

                // Emit metrics at regular intervals
                _ = interval.tick() => {
                    self.emit_metrics().await;
                }
            }
        }
    }

    async fn process_event(&self, event: ProcessingEvent) {
        let mut metrics = self.metrics.write().await;
        let shard_metrics = metrics
            .entry(event.shard_id.clone())
            .or_insert_with(|| ShardMetrics {
                window_start: Instant::now(),
                last_updated: Instant::now(),
                ..Default::default()
            });

        match event.event_type {
            ProcessingEventType::RecordAttempt {
                success,
                attempt_number,
                duration,
                error,
                is_final_attempt,
                ..
            } => {
                if success {
                    shard_metrics.records_processed += 1;
                } else if is_final_attempt {
                    shard_metrics.records_failed += 1;
                    if error.is_some() {
                        shard_metrics.hard_errors += 1;
                    }
                } else {
                    shard_metrics.soft_errors += 1;
                }

                if attempt_number > 1 {
                    shard_metrics.retry_attempts += 1;
                }

                // Update timing metrics
                shard_metrics.processing_time += duration;
                let avg_count = shard_metrics.records_processed + shard_metrics.records_failed;
                if avg_count > 0 {
                    shard_metrics.avg_processing_time =
                        shard_metrics.processing_time.div_f64(avg_count as f64);
                }
                if duration > shard_metrics.max_processing_time {
                    shard_metrics.max_processing_time = duration;
                }
            }

            ProcessingEventType::BatchComplete {
                successful_count,
                failed_count,
                duration,
            } => {
                shard_metrics.records_processed += successful_count as u64;
                shard_metrics.records_failed += failed_count as u64;
                shard_metrics.processing_time += duration;

                debug!(
                    shard_id = %event.shard_id,
                    successful = successful_count,
                    failed = failed_count,
                    duration_ms = ?duration.as_millis(),
                    "Batch processing completed"
                );
            }

            ProcessingEventType::BatchStart { timestamp: _ } => {
                // Just update the last activity timestamp
                shard_metrics.last_updated = Instant::now();
            }

            ProcessingEventType::BatchMetrics { metrics } => {
                // Update metrics from batch processing
                shard_metrics.records_processed += metrics.successful_count as u64;
                shard_metrics.records_failed += metrics.failed_count as u64;
                shard_metrics.processing_time += metrics.processing_duration;
            }

            ProcessingEventType::BatchError { error, duration } => {
                shard_metrics.hard_errors += 1;
                shard_metrics.processing_time += duration;

                warn!(
                    shard_id = %event.shard_id,
                    error = %error,
                    duration_ms = ?duration.as_millis(),
                    "Batch processing failed"
                );
            }

            ProcessingEventType::RecordSuccess {
                sequence_number,
                checkpoint_success,
            } => {
                shard_metrics.records_processed += 1;
                if checkpoint_success {
                    shard_metrics.checkpoints_succeeded += 1;
                }

                trace!(
                    shard_id = %event.shard_id,
                    sequence = %sequence_number,
                    checkpoint_success = checkpoint_success,
                    "Record processed successfully"
                );
            }

            ProcessingEventType::RecordFailure {
                sequence_number,
                error,
            } => {
                shard_metrics.records_failed += 1;
                shard_metrics.hard_errors += 1;

                warn!(
                    shard_id = %event.shard_id,
                    sequence = %sequence_number,
                    error = %error,
                    "Record processing failed"
                );
            }

            ProcessingEventType::CheckpointFailure {
                sequence_number,
                error,
            } => {
                shard_metrics.checkpoints_failed += 1;

                warn!(
                    shard_id = %event.shard_id,
                    sequence = %sequence_number,
                    error = %error,
                    "Checkpoint operation failed"
                );
            }

            ProcessingEventType::ShardEvent {
                event_type,
                details,
            } => match event_type {
                ShardEventType::Started => {
                    debug!(
                        shard_id = %event.shard_id,
                        "Shard processing started"
                    );
                }
                ShardEventType::Completed => {
                    debug!(
                        shard_id = %event.shard_id,
                        "Shard processing completed"
                    );
                }
                ShardEventType::Error => {
                    shard_metrics.hard_errors += 1;
                    warn!(
                        shard_id = %event.shard_id,
                        details = ?details,
                        "Shard processing error"
                    );
                }
                ShardEventType::Interrupted => {
                    info!(
                        shard_id = %event.shard_id,
                        details = ?details,
                        "Shard processing interrupted"
                    );
                }
            },

            ProcessingEventType::Iterator { event_type, error } => match event_type {
                IteratorEventType::Expired => {
                    debug!(
                        shard_id = %event.shard_id,
                        "Iterator expired"
                    );
                }
                IteratorEventType::Renewed => {
                    shard_metrics.iterator_renewals += 1;
                    trace!(
                        shard_id = %event.shard_id,
                        "Iterator renewed"
                    );
                }
                IteratorEventType::Failed => {
                    shard_metrics.iterator_failures += 1;
                    warn!(
                        shard_id = %event.shard_id,
                        error = ?error,
                        "Iterator operation failed"
                    );
                }
            },

            ProcessingEventType::Checkpoint {
                sequence_number,
                success,
                error,
            } => {
                if success {
                    shard_metrics.checkpoints_succeeded += 1;
                    trace!(
                        shard_id = %event.shard_id,
                        sequence = %sequence_number,
                        "Checkpoint successful"
                    );
                } else {
                    shard_metrics.checkpoints_failed += 1;
                    warn!(
                        shard_id = %event.shard_id,
                        sequence = %sequence_number,
                        error = ?error,
                        "Checkpoint failed"
                    );
                }
            }
        }

        shard_metrics.last_updated = Instant::now();
    }

    async fn emit_metrics(&self) {
        let metrics = self.metrics.read().await;

        for (shard_id, metrics) in metrics.iter() {
            // Skip shards with no recent activity
            if metrics.last_updated.elapsed() > self.window_duration * 2 {
                continue;
            }

            info!(
                shard_id = %shard_id,
                records_processed = metrics.records_processed,
                records_failed = metrics.records_failed,
                retry_attempts = metrics.retry_attempts,
                avg_processing_time_ms = %metrics.avg_processing_time.as_millis(),
                max_processing_time_ms = %metrics.max_processing_time.as_millis(),
                checkpoints_succeeded = metrics.checkpoints_succeeded,
                checkpoints_failed = metrics.checkpoints_failed,
                iterator_renewals = metrics.iterator_renewals,
                iterator_failures = metrics.iterator_failures,
                soft_errors = metrics.soft_errors,
                hard_errors = metrics.hard_errors,
                "Metrics for window"
            );

            // Emit warnings for concerning metrics
            if metrics.records_failed > 0 {
                warn!(
                    shard_id = %shard_id,
                    failed = metrics.records_failed,
                    hard_errors = metrics.hard_errors,
                    soft_errors = metrics.soft_errors,
                    "Records failed processing"
                );
            }

            if metrics.iterator_failures > 0 {
                warn!(
                    shard_id = %shard_id,
                    failures = metrics.iterator_failures,
                    "Iterator failures detected"
                );
            }

            if metrics.checkpoints_failed > 0 {
                warn!(
                    shard_id = %shard_id,
                    failures = metrics.checkpoints_failed,
                    "Checkpoint failures detected"
                );
            }
        }

        // Clean up old metrics
        if let Ok(mut metrics) = self.metrics.try_write() {
            metrics.retain(|_, m| m.last_updated.elapsed() <= self.window_duration * 2);
        }
    }

    /// Get current metrics for all shards
    pub async fn get_metrics(&self) -> HashMap<String, ShardMetrics> {
        self.metrics.read().await.clone()
    }

    /// Get metrics for a specific shard
    pub async fn get_shard_metrics(&self, shard_id: &str) -> Option<ShardMetrics> {
        self.metrics.read().await.get(shard_id).cloned()
    }
}