1use crate::{
2 domain::entities::Event,
3 error::{AllSourceError, Result},
4 store::EventStore,
5};
6use chrono::{DateTime, Datelike, Duration, Timelike, Utc};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
12#[serde(rename_all = "lowercase")]
13pub enum TimeWindow {
14 Minute,
15 Hour,
16 Day,
17 Week,
18 Month,
19}
20
21impl TimeWindow {
22 pub fn duration(&self) -> Duration {
23 match self {
24 TimeWindow::Minute => Duration::minutes(1),
25 TimeWindow::Hour => Duration::hours(1),
26 TimeWindow::Day => Duration::days(1),
27 TimeWindow::Week => Duration::weeks(1),
28 TimeWindow::Month => Duration::days(30),
29 }
30 }
31
32 pub fn truncate(&self, timestamp: DateTime<Utc>) -> DateTime<Utc> {
33 match self {
34 TimeWindow::Minute => timestamp
35 .with_second(0)
36 .unwrap()
37 .with_nanosecond(0)
38 .unwrap(),
39 TimeWindow::Hour => timestamp
40 .with_minute(0)
41 .unwrap()
42 .with_second(0)
43 .unwrap()
44 .with_nanosecond(0)
45 .unwrap(),
46 TimeWindow::Day => timestamp
47 .with_hour(0)
48 .unwrap()
49 .with_minute(0)
50 .unwrap()
51 .with_second(0)
52 .unwrap()
53 .with_nanosecond(0)
54 .unwrap(),
55 TimeWindow::Week => {
56 let days_from_monday = timestamp.weekday().num_days_from_monday();
57 (timestamp - Duration::days(i64::from(days_from_monday)))
58 .with_hour(0)
59 .unwrap()
60 .with_minute(0)
61 .unwrap()
62 .with_second(0)
63 .unwrap()
64 .with_nanosecond(0)
65 .unwrap()
66 }
67 TimeWindow::Month => timestamp
68 .with_day(1)
69 .unwrap()
70 .with_hour(0)
71 .unwrap()
72 .with_minute(0)
73 .unwrap()
74 .with_second(0)
75 .unwrap()
76 .with_nanosecond(0)
77 .unwrap(),
78 }
79 }
80}
81
82#[derive(Debug, Deserialize)]
84pub struct EventFrequencyRequest {
85 pub entity_id: Option<String>,
87
88 pub event_type: Option<String>,
90
91 pub since: DateTime<Utc>,
93
94 pub until: Option<DateTime<Utc>>,
96
97 pub window: TimeWindow,
99}
100
101#[derive(Debug, Clone, Serialize)]
103pub struct TimeBucket {
104 pub timestamp: DateTime<Utc>,
105 pub count: usize,
106 pub event_types: HashMap<String, usize>,
107}
108
109#[derive(Debug, Serialize)]
111pub struct EventFrequencyResponse {
112 pub buckets: Vec<TimeBucket>,
113 pub total_events: usize,
114 pub window: TimeWindow,
115 pub time_range: TimeRange,
116}
117
118#[derive(Debug, Serialize)]
119pub struct TimeRange {
120 pub from: DateTime<Utc>,
121 pub to: DateTime<Utc>,
122}
123
124#[derive(Debug, Deserialize)]
126pub struct StatsSummaryRequest {
127 pub entity_id: Option<String>,
129
130 pub event_type: Option<String>,
132
133 pub since: Option<DateTime<Utc>>,
135
136 pub until: Option<DateTime<Utc>>,
138}
139
140#[derive(Debug, Serialize)]
142pub struct StatsSummaryResponse {
143 pub total_events: usize,
144 pub unique_entities: usize,
145 pub unique_event_types: usize,
146 pub time_range: TimeRange,
147 pub events_per_day: f64,
148 pub top_event_types: Vec<EventTypeCount>,
149 pub top_entities: Vec<EntityCount>,
150 pub first_event: Option<DateTime<Utc>>,
151 pub last_event: Option<DateTime<Utc>>,
152}
153
154#[derive(Debug, Serialize)]
155pub struct EventTypeCount {
156 pub event_type: String,
157 pub count: usize,
158 pub percentage: f64,
159}
160
161#[derive(Debug, Serialize)]
162pub struct EntityCount {
163 pub entity_id: String,
164 pub count: usize,
165 pub percentage: f64,
166}
167
168#[derive(Debug, Deserialize)]
170pub struct CorrelationRequest {
171 pub event_type_a: String,
173
174 pub event_type_b: String,
176
177 pub time_window_seconds: i64,
179
180 pub since: Option<DateTime<Utc>>,
182
183 pub until: Option<DateTime<Utc>>,
185}
186
187#[derive(Debug, Serialize)]
189pub struct CorrelationResponse {
190 pub event_type_a: String,
191 pub event_type_b: String,
192 pub total_a: usize,
193 pub total_b: usize,
194 pub correlated_pairs: usize,
195 pub correlation_percentage: f64,
196 pub avg_time_between_seconds: f64,
197 pub examples: Vec<CorrelationExample>,
198}
199
200#[derive(Debug, Serialize)]
201pub struct CorrelationExample {
202 pub entity_id: String,
203 pub event_a_timestamp: DateTime<Utc>,
204 pub event_b_timestamp: DateTime<Utc>,
205 pub time_between_seconds: i64,
206}
207
208pub struct AnalyticsEngine;
210
211impl AnalyticsEngine {
212 pub fn event_frequency(
214 store: &EventStore,
215 request: &EventFrequencyRequest,
216 ) -> Result<EventFrequencyResponse> {
217 let until = request.until.unwrap_or_else(Utc::now);
218
219 let events = store.query(&crate::application::dto::QueryEventsRequest {
221 as_of_valid: None,
222 since_valid: None,
223 until_valid: None,
224 entity_id: request.entity_id.clone(),
225 event_type: request.event_type.clone(),
226 tenant_id: None,
227 as_of: None,
228 since: Some(request.since),
229 until: Some(until),
230 limit: None,
231 event_type_prefix: None,
232 exclude_event_type_prefix: None,
233 payload_filter: None,
234 })?;
235
236 if events.is_empty() {
237 return Ok(EventFrequencyResponse {
238 buckets: Vec::new(),
239 total_events: 0,
240 window: request.window,
241 time_range: TimeRange {
242 from: request.since,
243 to: until,
244 },
245 });
246 }
247
248 let mut buckets_map: HashMap<DateTime<Utc>, HashMap<String, usize>> = HashMap::new();
250
251 for event in &events {
252 let bucket_time = request.window.truncate(event.timestamp);
253 let bucket = buckets_map.entry(bucket_time).or_default();
254 *bucket
255 .entry(event.event_type_str().to_string())
256 .or_insert(0) += 1;
257 }
258
259 let mut buckets: Vec<TimeBucket> = buckets_map
261 .into_iter()
262 .map(|(timestamp, event_types)| {
263 let count = event_types.values().sum();
264 TimeBucket {
265 timestamp,
266 count,
267 event_types,
268 }
269 })
270 .collect();
271
272 buckets.sort_by_key(|b| b.timestamp);
273
274 let filled_buckets = Self::fill_time_gaps(&buckets, request.since, until, request.window);
276
277 Ok(EventFrequencyResponse {
278 total_events: events.len(),
279 buckets: filled_buckets,
280 window: request.window,
281 time_range: TimeRange {
282 from: request.since,
283 to: until,
284 },
285 })
286 }
287
288 fn fill_time_gaps(
290 buckets: &[TimeBucket],
291 start: DateTime<Utc>,
292 end: DateTime<Utc>,
293 window: TimeWindow,
294 ) -> Vec<TimeBucket> {
295 if buckets.is_empty() {
296 return Vec::new();
297 }
298
299 let mut filled = Vec::new();
300 let mut current = window.truncate(start);
301 let end = window.truncate(end);
302
303 let bucket_map: HashMap<DateTime<Utc>, &TimeBucket> =
304 buckets.iter().map(|b| (b.timestamp, b)).collect();
305
306 while current <= end {
307 if let Some(bucket) = bucket_map.get(¤t) {
308 filled.push((**bucket).clone());
309 } else {
310 filled.push(TimeBucket {
311 timestamp: current,
312 count: 0,
313 event_types: HashMap::new(),
314 });
315 }
316 current += window.duration();
317 }
318
319 filled
320 }
321
322 pub fn stats_summary(
324 store: &EventStore,
325 request: &StatsSummaryRequest,
326 ) -> Result<StatsSummaryResponse> {
327 let events = store.query(&crate::application::dto::QueryEventsRequest {
329 as_of_valid: None,
330 since_valid: None,
331 until_valid: None,
332 entity_id: request.entity_id.clone(),
333 event_type: request.event_type.clone(),
334 tenant_id: None,
335 as_of: None,
336 since: request.since,
337 until: request.until,
338 limit: None,
339 event_type_prefix: None,
340 exclude_event_type_prefix: None,
341 payload_filter: None,
342 })?;
343
344 if events.is_empty() {
345 return Err(AllSourceError::ValidationError(
346 "No events found for the specified criteria".to_string(),
347 ));
348 }
349
350 let first_event = events.first().map(|e| e.timestamp);
352 let last_event = events.last().map(|e| e.timestamp);
353
354 let mut entity_counts: HashMap<String, usize> = HashMap::new();
355 let mut event_type_counts: HashMap<String, usize> = HashMap::new();
356
357 for event in &events {
358 *entity_counts
359 .entry(event.entity_id_str().to_string())
360 .or_insert(0) += 1;
361 *event_type_counts
362 .entry(event.event_type_str().to_string())
363 .or_insert(0) += 1;
364 }
365
366 let time_span = if let (Some(first), Some(last)) = (first_event, last_event) {
368 (last - first).num_days().max(1) as f64
369 } else {
370 1.0
371 };
372
373 let events_per_day = events.len() as f64 / time_span;
374
375 let mut top_event_types: Vec<EventTypeCount> = event_type_counts
377 .into_iter()
378 .map(|(event_type, count)| EventTypeCount {
379 event_type,
380 count,
381 percentage: (count as f64 / events.len() as f64) * 100.0,
382 })
383 .collect();
384 top_event_types.sort_by_key(|x| std::cmp::Reverse(x.count));
385 top_event_types.truncate(10);
386
387 let mut top_entities: Vec<EntityCount> = entity_counts
389 .into_iter()
390 .map(|(entity_id, count)| EntityCount {
391 entity_id,
392 count,
393 percentage: (count as f64 / events.len() as f64) * 100.0,
394 })
395 .collect();
396 top_entities.sort_by_key(|x| std::cmp::Reverse(x.count));
397 top_entities.truncate(10);
398
399 let time_range = TimeRange {
400 from: first_event.unwrap_or_else(Utc::now),
401 to: last_event.unwrap_or_else(Utc::now),
402 };
403
404 Ok(StatsSummaryResponse {
405 total_events: events.len(),
406 unique_entities: top_entities.len(),
407 unique_event_types: top_event_types.len(),
408 time_range,
409 events_per_day,
410 top_event_types,
411 top_entities,
412 first_event,
413 last_event,
414 })
415 }
416
417 pub fn analyze_correlation(
419 store: &EventStore,
420 request: CorrelationRequest,
421 ) -> Result<CorrelationResponse> {
422 let events_a = store.query(&crate::application::dto::QueryEventsRequest {
424 as_of_valid: None,
425 since_valid: None,
426 until_valid: None,
427 entity_id: None,
428 event_type: Some(request.event_type_a.clone()),
429 tenant_id: None,
430 as_of: None,
431 since: request.since,
432 until: request.until,
433 limit: None,
434 event_type_prefix: None,
435 exclude_event_type_prefix: None,
436 payload_filter: None,
437 })?;
438
439 let events_b = store.query(&crate::application::dto::QueryEventsRequest {
440 as_of_valid: None,
441 since_valid: None,
442 until_valid: None,
443 entity_id: None,
444 event_type: Some(request.event_type_b.clone()),
445 tenant_id: None,
446 as_of: None,
447 since: request.since,
448 until: request.until,
449 limit: None,
450 event_type_prefix: None,
451 exclude_event_type_prefix: None,
452 payload_filter: None,
453 })?;
454
455 let mut entity_events_a: HashMap<String, Vec<&Event>> = HashMap::new();
457 let mut entity_events_b: HashMap<String, Vec<&Event>> = HashMap::new();
458
459 for event in &events_a {
460 entity_events_a
461 .entry(event.entity_id_str().to_string())
462 .or_default()
463 .push(event);
464 }
465
466 for event in &events_b {
467 entity_events_b
468 .entry(event.entity_id_str().to_string())
469 .or_default()
470 .push(event);
471 }
472
473 let mut correlated_pairs = 0;
475 let mut total_time_between = 0i64;
476 let mut examples = Vec::new();
477
478 for (entity_id, a_events) in &entity_events_a {
479 if let Some(b_events) = entity_events_b.get(entity_id) {
480 for a_event in a_events {
481 for b_event in b_events {
482 let time_diff = (b_event.timestamp - a_event.timestamp).num_seconds().abs();
483
484 if time_diff <= request.time_window_seconds {
485 correlated_pairs += 1;
486 total_time_between += time_diff;
487
488 if examples.len() < 5 {
489 examples.push(CorrelationExample {
490 entity_id: entity_id.clone(),
491 event_a_timestamp: a_event.timestamp,
492 event_b_timestamp: b_event.timestamp,
493 time_between_seconds: time_diff,
494 });
495 }
496 }
497 }
498 }
499 }
500 }
501
502 let correlation_percentage = if events_a.is_empty() {
503 0.0
504 } else {
505 (correlated_pairs as f64 / events_a.len() as f64) * 100.0
506 };
507
508 let avg_time_between = if correlated_pairs > 0 {
509 total_time_between as f64 / correlated_pairs as f64
510 } else {
511 0.0
512 };
513
514 Ok(CorrelationResponse {
515 event_type_a: request.event_type_a,
516 event_type_b: request.event_type_b,
517 total_a: events_a.len(),
518 total_b: events_b.len(),
519 correlated_pairs,
520 correlation_percentage,
521 avg_time_between_seconds: avg_time_between,
522 examples,
523 })
524 }
525}
526
527#[cfg(test)]
528mod tests {
529 use super::*;
530
531 #[test]
539 fn event_frequency_without_a_filter_still_respects_its_time_range() {
540 use crate::store::EventStore;
541
542 let store = EventStore::new();
543 let base = Utc::now() - chrono::Duration::hours(24);
544 for i in 0..6i64 {
545 let mut event = crate::domain::entities::Event::from_strings(
546 "user.created".to_string(),
547 format!("e-{i}"),
548 "default".to_string(),
549 serde_json::json!({}),
550 None,
551 )
552 .unwrap();
553 event.timestamp = base + chrono::Duration::hours(i);
554 event.version = i + 1;
555 store.ingest(&event).unwrap();
556 }
557
558 let response = AnalyticsEngine::event_frequency(
560 &store,
561 &EventFrequencyRequest {
562 entity_id: None,
563 event_type: None,
564 since: base + chrono::Duration::hours(2),
565 until: Some(base + chrono::Duration::hours(4)),
566 window: TimeWindow::Hour,
567 },
568 )
569 .unwrap();
570
571 assert_eq!(
572 response.total_events, 3,
573 "events at T+2, T+3 and T+4 are inside the range; the 6-event \
574 history is not"
575 );
576 let counted: usize = response.buckets.iter().map(|b| b.count).sum();
577 assert_eq!(
578 counted, 3,
579 "the buckets must add up to the events in the range"
580 );
581 assert!(
582 response.buckets.iter().all(|b| b.timestamp
583 >= TimeWindow::Hour.truncate(response.time_range.from)
584 && b.timestamp <= response.time_range.to),
585 "no bucket may fall outside the reported time_range"
586 );
587 }
588
589 #[test]
590 fn test_time_window_truncation() {
591 let timestamp = chrono::Utc::now();
592
593 let minute_truncated = TimeWindow::Minute.truncate(timestamp);
594 assert_eq!(minute_truncated.second(), 0);
595
596 let hour_truncated = TimeWindow::Hour.truncate(timestamp);
597 assert_eq!(hour_truncated.minute(), 0);
598 assert_eq!(hour_truncated.second(), 0);
599
600 let day_truncated = TimeWindow::Day.truncate(timestamp);
601 assert_eq!(day_truncated.hour(), 0);
602 assert_eq!(day_truncated.minute(), 0);
603 }
604}