allsource-core 0.19.1

High-performance event store core built in Rust
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
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
527
528
529
530
use crate::{
    domain::entities::Event,
    error::{AllSourceError, Result},
    store::EventStore,
};
use chrono::{DateTime, Datelike, Duration, Timelike, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Time window granularity for analytics
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TimeWindow {
    Minute,
    Hour,
    Day,
    Week,
    Month,
}

impl TimeWindow {
    pub fn duration(&self) -> Duration {
        match self {
            TimeWindow::Minute => Duration::minutes(1),
            TimeWindow::Hour => Duration::hours(1),
            TimeWindow::Day => Duration::days(1),
            TimeWindow::Week => Duration::weeks(1),
            TimeWindow::Month => Duration::days(30),
        }
    }

    pub fn truncate(&self, timestamp: DateTime<Utc>) -> DateTime<Utc> {
        match self {
            TimeWindow::Minute => timestamp
                .with_second(0)
                .unwrap()
                .with_nanosecond(0)
                .unwrap(),
            TimeWindow::Hour => timestamp
                .with_minute(0)
                .unwrap()
                .with_second(0)
                .unwrap()
                .with_nanosecond(0)
                .unwrap(),
            TimeWindow::Day => timestamp
                .with_hour(0)
                .unwrap()
                .with_minute(0)
                .unwrap()
                .with_second(0)
                .unwrap()
                .with_nanosecond(0)
                .unwrap(),
            TimeWindow::Week => {
                let days_from_monday = timestamp.weekday().num_days_from_monday();
                (timestamp - Duration::days(i64::from(days_from_monday)))
                    .with_hour(0)
                    .unwrap()
                    .with_minute(0)
                    .unwrap()
                    .with_second(0)
                    .unwrap()
                    .with_nanosecond(0)
                    .unwrap()
            }
            TimeWindow::Month => timestamp
                .with_day(1)
                .unwrap()
                .with_hour(0)
                .unwrap()
                .with_minute(0)
                .unwrap()
                .with_second(0)
                .unwrap()
                .with_nanosecond(0)
                .unwrap(),
        }
    }
}

/// Request for event frequency analysis
#[derive(Debug, Deserialize)]
pub struct EventFrequencyRequest {
    /// Filter by entity ID
    pub entity_id: Option<String>,

    /// Filter by event type
    pub event_type: Option<String>,

    /// Start time for analysis
    pub since: DateTime<Utc>,

    /// End time for analysis (defaults to now)
    pub until: Option<DateTime<Utc>>,

    /// Time window granularity
    pub window: TimeWindow,
}

/// Time bucket with event count
#[derive(Debug, Clone, Serialize)]
pub struct TimeBucket {
    pub timestamp: DateTime<Utc>,
    pub count: usize,
    pub event_types: HashMap<String, usize>,
}

/// Response containing time-series frequency data
#[derive(Debug, Serialize)]
pub struct EventFrequencyResponse {
    pub buckets: Vec<TimeBucket>,
    pub total_events: usize,
    pub window: TimeWindow,
    pub time_range: TimeRange,
}

#[derive(Debug, Serialize)]
pub struct TimeRange {
    pub from: DateTime<Utc>,
    pub to: DateTime<Utc>,
}

/// Request for statistical summary
#[derive(Debug, Deserialize)]
pub struct StatsSummaryRequest {
    /// Filter by entity ID
    pub entity_id: Option<String>,

    /// Filter by event type
    pub event_type: Option<String>,

    /// Start time for analysis
    pub since: Option<DateTime<Utc>>,

    /// End time for analysis
    pub until: Option<DateTime<Utc>>,
}

/// Statistical summary response
#[derive(Debug, Serialize)]
pub struct StatsSummaryResponse {
    pub total_events: usize,
    pub unique_entities: usize,
    pub unique_event_types: usize,
    pub time_range: TimeRange,
    pub events_per_day: f64,
    pub top_event_types: Vec<EventTypeCount>,
    pub top_entities: Vec<EntityCount>,
    pub first_event: Option<DateTime<Utc>>,
    pub last_event: Option<DateTime<Utc>>,
}

#[derive(Debug, Serialize)]
pub struct EventTypeCount {
    pub event_type: String,
    pub count: usize,
    pub percentage: f64,
}

#[derive(Debug, Serialize)]
pub struct EntityCount {
    pub entity_id: String,
    pub count: usize,
    pub percentage: f64,
}

/// Request for event correlation analysis
#[derive(Debug, Deserialize)]
pub struct CorrelationRequest {
    /// First event type
    pub event_type_a: String,

    /// Second event type
    pub event_type_b: String,

    /// Maximum time window to consider events correlated
    pub time_window_seconds: i64,

    /// Start time for analysis
    pub since: Option<DateTime<Utc>>,

    /// End time for analysis
    pub until: Option<DateTime<Utc>>,
}

/// Correlation analysis response
#[derive(Debug, Serialize)]
pub struct CorrelationResponse {
    pub event_type_a: String,
    pub event_type_b: String,
    pub total_a: usize,
    pub total_b: usize,
    pub correlated_pairs: usize,
    pub correlation_percentage: f64,
    pub avg_time_between_seconds: f64,
    pub examples: Vec<CorrelationExample>,
}

#[derive(Debug, Serialize)]
pub struct CorrelationExample {
    pub entity_id: String,
    pub event_a_timestamp: DateTime<Utc>,
    pub event_b_timestamp: DateTime<Utc>,
    pub time_between_seconds: i64,
}

/// Analytics engine for time-series and statistical analysis
pub struct AnalyticsEngine;

impl AnalyticsEngine {
    /// Analyze event frequency over time windows
    pub fn event_frequency(
        store: &EventStore,
        request: &EventFrequencyRequest,
    ) -> Result<EventFrequencyResponse> {
        let until = request.until.unwrap_or_else(Utc::now);

        // Query events in the time range
        let events = store.query(&crate::application::dto::QueryEventsRequest {
            entity_id: request.entity_id.clone(),
            event_type: request.event_type.clone(),
            tenant_id: None,
            as_of: None,
            since: Some(request.since),
            until: Some(until),
            limit: None,
            event_type_prefix: None,
            payload_filter: None,
        })?;

        if events.is_empty() {
            return Ok(EventFrequencyResponse {
                buckets: Vec::new(),
                total_events: 0,
                window: request.window,
                time_range: TimeRange {
                    from: request.since,
                    to: until,
                },
            });
        }

        // Create time buckets
        let mut buckets_map: HashMap<DateTime<Utc>, HashMap<String, usize>> = HashMap::new();

        for event in &events {
            let bucket_time = request.window.truncate(event.timestamp);
            let bucket = buckets_map.entry(bucket_time).or_default();
            *bucket
                .entry(event.event_type_str().to_string())
                .or_insert(0) += 1;
        }

        // Convert to sorted vector
        let mut buckets: Vec<TimeBucket> = buckets_map
            .into_iter()
            .map(|(timestamp, event_types)| {
                let count = event_types.values().sum();
                TimeBucket {
                    timestamp,
                    count,
                    event_types,
                }
            })
            .collect();

        buckets.sort_by_key(|b| b.timestamp);

        // Fill gaps in the timeline
        let filled_buckets = Self::fill_time_gaps(&buckets, request.since, until, request.window);

        Ok(EventFrequencyResponse {
            total_events: events.len(),
            buckets: filled_buckets,
            window: request.window,
            time_range: TimeRange {
                from: request.since,
                to: until,
            },
        })
    }

    /// Fill gaps in time buckets for continuous timeline
    fn fill_time_gaps(
        buckets: &[TimeBucket],
        start: DateTime<Utc>,
        end: DateTime<Utc>,
        window: TimeWindow,
    ) -> Vec<TimeBucket> {
        if buckets.is_empty() {
            return Vec::new();
        }

        let mut filled = Vec::new();
        let mut current = window.truncate(start);
        let end = window.truncate(end);

        let bucket_map: HashMap<DateTime<Utc>, &TimeBucket> =
            buckets.iter().map(|b| (b.timestamp, b)).collect();

        while current <= end {
            if let Some(bucket) = bucket_map.get(&current) {
                filled.push((**bucket).clone());
            } else {
                filled.push(TimeBucket {
                    timestamp: current,
                    count: 0,
                    event_types: HashMap::new(),
                });
            }
            current += window.duration();
        }

        filled
    }

    /// Generate comprehensive statistical summary
    pub fn stats_summary(
        store: &EventStore,
        request: &StatsSummaryRequest,
    ) -> Result<StatsSummaryResponse> {
        // Query events based on filters
        let events = store.query(&crate::application::dto::QueryEventsRequest {
            entity_id: request.entity_id.clone(),
            event_type: request.event_type.clone(),
            tenant_id: None,
            as_of: None,
            since: request.since,
            until: request.until,
            limit: None,
            event_type_prefix: None,
            payload_filter: None,
        })?;

        if events.is_empty() {
            return Err(AllSourceError::ValidationError(
                "No events found for the specified criteria".to_string(),
            ));
        }

        // Calculate statistics
        let first_event = events.first().map(|e| e.timestamp);
        let last_event = events.last().map(|e| e.timestamp);

        let mut entity_counts: HashMap<String, usize> = HashMap::new();
        let mut event_type_counts: HashMap<String, usize> = HashMap::new();

        for event in &events {
            *entity_counts
                .entry(event.entity_id_str().to_string())
                .or_insert(0) += 1;
            *event_type_counts
                .entry(event.event_type_str().to_string())
                .or_insert(0) += 1;
        }

        // Calculate events per day
        let time_span = if let (Some(first), Some(last)) = (first_event, last_event) {
            (last - first).num_days().max(1) as f64
        } else {
            1.0
        };

        let events_per_day = events.len() as f64 / time_span;

        // Top event types
        let mut top_event_types: Vec<EventTypeCount> = event_type_counts
            .into_iter()
            .map(|(event_type, count)| EventTypeCount {
                event_type,
                count,
                percentage: (count as f64 / events.len() as f64) * 100.0,
            })
            .collect();
        top_event_types.sort_by_key(|x| std::cmp::Reverse(x.count));
        top_event_types.truncate(10);

        // Top entities
        let mut top_entities: Vec<EntityCount> = entity_counts
            .into_iter()
            .map(|(entity_id, count)| EntityCount {
                entity_id,
                count,
                percentage: (count as f64 / events.len() as f64) * 100.0,
            })
            .collect();
        top_entities.sort_by_key(|x| std::cmp::Reverse(x.count));
        top_entities.truncate(10);

        let time_range = TimeRange {
            from: first_event.unwrap_or_else(Utc::now),
            to: last_event.unwrap_or_else(Utc::now),
        };

        Ok(StatsSummaryResponse {
            total_events: events.len(),
            unique_entities: top_entities.len(),
            unique_event_types: top_event_types.len(),
            time_range,
            events_per_day,
            top_event_types,
            top_entities,
            first_event,
            last_event,
        })
    }

    /// Analyze correlation between two event types
    pub fn analyze_correlation(
        store: &EventStore,
        request: CorrelationRequest,
    ) -> Result<CorrelationResponse> {
        // Query both event types
        let events_a = store.query(&crate::application::dto::QueryEventsRequest {
            entity_id: None,
            event_type: Some(request.event_type_a.clone()),
            tenant_id: None,
            as_of: None,
            since: request.since,
            until: request.until,
            limit: None,
            event_type_prefix: None,
            payload_filter: None,
        })?;

        let events_b = store.query(&crate::application::dto::QueryEventsRequest {
            entity_id: None,
            event_type: Some(request.event_type_b.clone()),
            tenant_id: None,
            as_of: None,
            since: request.since,
            until: request.until,
            limit: None,
            event_type_prefix: None,
            payload_filter: None,
        })?;

        // Group events by entity
        let mut entity_events_a: HashMap<String, Vec<&Event>> = HashMap::new();
        let mut entity_events_b: HashMap<String, Vec<&Event>> = HashMap::new();

        for event in &events_a {
            entity_events_a
                .entry(event.entity_id_str().to_string())
                .or_default()
                .push(event);
        }

        for event in &events_b {
            entity_events_b
                .entry(event.entity_id_str().to_string())
                .or_default()
                .push(event);
        }

        // Find correlated pairs
        let mut correlated_pairs = 0;
        let mut total_time_between = 0i64;
        let mut examples = Vec::new();

        for (entity_id, a_events) in &entity_events_a {
            if let Some(b_events) = entity_events_b.get(entity_id) {
                for a_event in a_events {
                    for b_event in b_events {
                        let time_diff = (b_event.timestamp - a_event.timestamp).num_seconds().abs();

                        if time_diff <= request.time_window_seconds {
                            correlated_pairs += 1;
                            total_time_between += time_diff;

                            if examples.len() < 5 {
                                examples.push(CorrelationExample {
                                    entity_id: entity_id.clone(),
                                    event_a_timestamp: a_event.timestamp,
                                    event_b_timestamp: b_event.timestamp,
                                    time_between_seconds: time_diff,
                                });
                            }
                        }
                    }
                }
            }
        }

        let correlation_percentage = if events_a.is_empty() {
            0.0
        } else {
            (correlated_pairs as f64 / events_a.len() as f64) * 100.0
        };

        let avg_time_between = if correlated_pairs > 0 {
            total_time_between as f64 / correlated_pairs as f64
        } else {
            0.0
        };

        Ok(CorrelationResponse {
            event_type_a: request.event_type_a,
            event_type_b: request.event_type_b,
            total_a: events_a.len(),
            total_b: events_b.len(),
            correlated_pairs,
            correlation_percentage,
            avg_time_between_seconds: avg_time_between,
            examples,
        })
    }
}

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

    #[test]
    fn test_time_window_truncation() {
        let timestamp = chrono::Utc::now();

        let minute_truncated = TimeWindow::Minute.truncate(timestamp);
        assert_eq!(minute_truncated.second(), 0);

        let hour_truncated = TimeWindow::Hour.truncate(timestamp);
        assert_eq!(hour_truncated.minute(), 0);
        assert_eq!(hour_truncated.second(), 0);

        let day_truncated = TimeWindow::Day.truncate(timestamp);
        assert_eq!(day_truncated.hour(), 0);
        assert_eq!(day_truncated.minute(), 0);
    }
}