kerf 0.1.2

Simple tokio-based trace event collector
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::{Event, Level};

/// COMPLETE snapshot of ALL stats data - no fucking abbreviations
#[derive(Debug, Clone)]
pub struct StatsSnapshot {
    // Every single location with all its data
    pub location_stats: HashMap<Location, LocationStats>,
    // Every single module with all its data
    pub module_stats: HashMap<String, ModuleStats>,
    // Every single level/event type combination with counts
    pub level_event_counts: HashMap<(Level, EventType), u64>,
    // Raw stat entries with full keys and counts
    pub raw_stats: HashMap<StatKey, StatEntrySnapshot>,
    // Total counters for each event type and level
    pub total_counters: HashMap<(EventType, Level), u64>,
    // Configuration
    pub config: StatsConfig,
    // Meta info
    pub total_entries: usize,
    pub location_count: usize,
    pub module_count: usize,
    pub snapshot_time: SystemTime,
}

/// Complete snapshot of a stat entry with all data
#[derive(Debug, Clone)]
pub struct StatEntrySnapshot {
    pub key: StatKey,
    pub count: u64,
    pub last_seen: SystemTime,
}

/// Stats configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatsConfig {
    pub track_by_location: bool,
    pub track_by_module: bool,
    pub track_by_level: bool,
    pub max_locations: usize,
    pub max_modules: usize,
}

impl Default for StatsConfig {
    fn default() -> Self {
        Self {
            track_by_location: true,
            track_by_module: true,
            track_by_level: true,
            max_locations: 10_000,
            max_modules: 1_000,
        }
    }
}

/// Location identifier (file:line)
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Location {
    pub file: String,
    pub line: u32,
}

impl Location {
    pub fn from_trace_data(data: &Event) -> Option<Self> {
        if let (Some(file), Some(line)) = (&data.file, data.line) {
            Some(Location {
                file: file.clone(),
                line,
            })
        } else {
            None
        }
    }
}

impl std::fmt::Display for Location {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.file, self.line)
    }
}

/// Event type for stats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventType {
    Captured,
    Silenced,
    Dropped,
}

impl std::fmt::Display for EventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EventType::Captured => write!(f, "Captured"),
            EventType::Silenced => write!(f, "Silenced"),
            EventType::Dropped => write!(f, "Dropped"),
        }
    }
}

/// Thread-safe atomic counter
#[derive(Debug)]
pub struct AtomicCounter {
    count: AtomicU64,
}

impl AtomicCounter {
    pub fn new() -> Self {
        Self {
            count: AtomicU64::new(0),
        }
    }

    pub fn increment(&self) -> u64 {
        self.count.fetch_add(1, Ordering::Relaxed)
    }

    pub fn get(&self) -> u64 {
        self.count.load(Ordering::Relaxed)
    }

    pub fn reset(&self) {
        self.count.store(0, Ordering::Relaxed);
    }
}

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

/// Stats for a specific combination of location/module/level/event_type
#[derive(Debug)]
pub struct StatEntry {
    pub counter: AtomicCounter,
    pub last_seen: AtomicU64,
}

impl StatEntry {
    pub fn new() -> Self {
        Self {
            counter: AtomicCounter::new(),
            last_seen: AtomicU64::new(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos() as u64,
            ),
        }
    }

    pub fn record_event(&self) {
        self.counter.increment();
        self.last_seen.store(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos() as u64,
            Ordering::Relaxed,
        );
    }

    pub fn get_count(&self) -> u64 {
        self.counter.get()
    }

    pub fn get_last_seen(&self) -> SystemTime {
        let nanos = self.last_seen.load(Ordering::Relaxed);
        UNIX_EPOCH + std::time::Duration::from_nanos(nanos)
    }
}

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

/// Composite key for stats tracking
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct StatKey {
    pub location: Option<Location>,
    pub module: Option<String>,
    pub level: Level,
    pub event_type: EventType,
}

/// High-performance stats tracker
#[derive(Debug)]
pub struct StatsTracker {
    config: StatsConfig,
    stats: RwLock<HashMap<StatKey, Arc<StatEntry>>>,
    total_counters: HashMap<(EventType, Level), AtomicCounter>,
    location_count: AtomicU64,
    module_count: AtomicU64,
}

impl StatsTracker {
    pub fn new(config: StatsConfig) -> Self {
        let mut total_counters = HashMap::new();

        for event_type in [EventType::Captured, EventType::Silenced, EventType::Dropped] {
            for level in [
                Level(tracing::Level::ERROR),
                Level(tracing::Level::WARN),
                Level(tracing::Level::INFO),
                Level(tracing::Level::DEBUG),
                Level(tracing::Level::TRACE),
            ] {
                total_counters.insert((event_type, level), AtomicCounter::new());
            }
        }

        Self {
            config,
            stats: RwLock::new(HashMap::new()),
            total_counters,
            location_count: AtomicU64::new(0),
            module_count: AtomicU64::new(0),
        }
    }

    pub fn record_event(&self, event_type: EventType, trace_data: &Event) {
        if let Some(counter) = self.total_counters.get(&(event_type, trace_data.level)) {
            counter.increment();
        }

        if !self.config.track_by_location && !self.config.track_by_module {
            return;
        }

        let location = if self.config.track_by_location {
            Location::from_trace_data(trace_data)
        } else {
            None
        };

        let module = if self.config.track_by_module {
            trace_data.module_path.clone()
        } else {
            None
        };

        let key = StatKey {
            location,
            module,
            level: trace_data.level,
            event_type,
        };

        {
            let stats = self.stats.read().unwrap();
            if let Some(entry) = stats.get(&key) {
                entry.record_event();
                return;
            }
        }

        {
            let mut stats = self.stats.write().unwrap();

            if let Some(entry) = stats.get(&key) {
                entry.record_event();
                return;
            }

            let location_count = self.location_count.load(Ordering::Relaxed) as usize;
            let module_count = self.module_count.load(Ordering::Relaxed) as usize;

            if (key.location.is_some() && location_count >= self.config.max_locations)
                || (key.module.is_some() && module_count >= self.config.max_modules)
            {
                return;
            }

            let entry = Arc::new(StatEntry::new());
            entry.record_event();
            stats.insert(key.clone(), entry);

            if key.location.is_some() {
                self.location_count.fetch_add(1, Ordering::Relaxed);
            }
            if key.module.is_some() {
                self.module_count.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    pub fn get_total_count(&self, event_type: EventType, level: Level) -> u64 {
        self.total_counters
            .get(&(event_type, level))
            .map(|c| c.get())
            .unwrap_or(0)
    }

    pub fn get_total_count_by_type(&self, event_type: EventType) -> u64 {
        self.total_counters
            .iter()
            .filter(|((et, _), _)| *et == event_type)
            .map(|(_, counter)| counter.get())
            .sum()
    }

    /// Get COMPLETE snapshot with ALL fucking data
    pub fn get_snapshot(&self) -> StatsSnapshot {
        let stats = self.stats.read().unwrap();

        // Build location stats with ALL data
        let mut location_stats = HashMap::new();
        let mut module_stats = HashMap::new();
        let mut level_event_counts = HashMap::new();
        let mut raw_stats = HashMap::new();

        // Process every single stat entry
        for (key, entry) in stats.iter() {
            let count = entry.get_count();
            let last_seen = entry.get_last_seen();

            // Add to raw stats - EVERY SINGLE ENTRY
            raw_stats.insert(
                key.clone(),
                StatEntrySnapshot {
                    key: key.clone(),
                    count,
                    last_seen,
                },
            );

            // Build location stats
            if let Some(location) = &key.location {
                let entry = location_stats
                    .entry(location.clone())
                    .or_insert_with(|| LocationStats::new(location.clone()));
                entry.add_event(key.event_type, key.level, count, last_seen);
            }

            // Build module stats
            if let Some(module) = &key.module {
                let entry = module_stats
                    .entry(module.clone())
                    .or_insert_with(|| ModuleStats::new(module.clone()));
                entry.add_event(key.event_type, key.level, count, last_seen);
            }

            // Build level/event counts
            let entry = level_event_counts
                .entry((key.level, key.event_type))
                .or_insert(0);
            *entry += count;
        }

        // Get ALL total counters
        let mut total_counters = HashMap::new();
        for ((event_type, level), counter) in &self.total_counters {
            total_counters.insert((*event_type, *level), counter.get());
        }

        StatsSnapshot {
            location_stats,
            module_stats,
            level_event_counts,
            raw_stats,
            total_counters,
            config: self.config.clone(),
            total_entries: stats.len(),
            location_count: self.location_count.load(Ordering::Relaxed) as usize,
            module_count: self.module_count.load(Ordering::Relaxed) as usize,
            snapshot_time: SystemTime::now(),
        }
    }

    pub fn clear(&self) {
        let mut stats = self.stats.write().unwrap();
        stats.clear();

        for counter in self.total_counters.values() {
            counter.reset();
        }

        self.location_count.store(0, Ordering::Relaxed);
        self.module_count.store(0, Ordering::Relaxed);
    }
}

/// Complete stats for a specific location with ALL data
#[derive(Debug, Clone)]
pub struct LocationStats {
    pub location: Location,
    pub events_by_type_and_level: HashMap<(EventType, Level), u64>,
    pub last_activity: SystemTime,
}

impl LocationStats {
    fn new(location: Location) -> Self {
        Self {
            location,
            events_by_type_and_level: HashMap::new(),
            last_activity: UNIX_EPOCH,
        }
    }

    fn add_event(
        &mut self,
        event_type: EventType,
        level: Level,
        count: u64,
        last_seen: SystemTime,
    ) {
        *self
            .events_by_type_and_level
            .entry((event_type, level))
            .or_insert(0) += count;
        if last_seen > self.last_activity {
            self.last_activity = last_seen;
        }
    }

    pub fn get_total_for_type(&self, event_type: EventType) -> u64 {
        self.events_by_type_and_level
            .iter()
            .filter(|((et, _), _)| *et == event_type)
            .map(|(_, count)| *count)
            .sum()
    }

    pub fn get_total_events(&self) -> u64 {
        self.events_by_type_and_level.values().sum()
    }
}

/// Complete stats for a specific module with ALL data
#[derive(Debug, Clone)]
pub struct ModuleStats {
    pub module: String,
    pub events_by_type_and_level: HashMap<(EventType, Level), u64>,
    pub last_activity: SystemTime,
}

impl ModuleStats {
    fn new(module: String) -> Self {
        Self {
            module,
            events_by_type_and_level: HashMap::new(),
            last_activity: UNIX_EPOCH,
        }
    }

    fn add_event(
        &mut self,
        event_type: EventType,
        level: Level,
        count: u64,
        last_seen: SystemTime,
    ) {
        *self
            .events_by_type_and_level
            .entry((event_type, level))
            .or_insert(0) += count;
        if last_seen > self.last_activity {
            self.last_activity = last_seen;
        }
    }

    pub fn get_total_for_type(&self, event_type: EventType) -> u64 {
        self.events_by_type_and_level
            .iter()
            .filter(|((et, _), _)| *et == event_type)
            .map(|(_, count)| *count)
            .sum()
    }

    pub fn get_total_events(&self) -> u64 {
        self.events_by_type_and_level.values().sum()
    }
}