Skip to main content

allsource_core/application/use_cases/
query_events.rs

1use crate::{
2    application::dto::{EventDto, QueryEventsRequest, QueryEventsResponse},
3    domain::repositories::EventRepository,
4    error::Result,
5};
6use std::sync::Arc;
7
8/// Use Case: Query Events
9///
10/// This use case handles querying events from the event store with various filters.
11///
12/// Responsibilities:
13/// - Validate query parameters
14/// - Determine query strategy (by entity, by type, by time range, etc.)
15/// - Execute query via repository
16/// - Transform domain events to DTOs
17/// - Apply limits and pagination
18pub struct QueryEventsUseCase {
19    repository: Arc<dyn EventRepository>,
20}
21
22impl QueryEventsUseCase {
23    pub fn new(repository: Arc<dyn EventRepository>) -> Self {
24        Self { repository }
25    }
26
27    pub async fn execute(&self, request: QueryEventsRequest) -> Result<QueryEventsResponse> {
28        // Determine tenant_id (default to "default" if not provided)
29        let tenant_id = request.tenant_id.unwrap_or_else(|| "default".to_string());
30
31        // Determine query strategy based on filters
32        let mut events = if let Some(entity_id) = request.entity_id {
33            // Query by entity (most specific)
34            if let Some(as_of) = request.as_of {
35                // Time-travel query
36                self.repository
37                    .find_by_entity_as_of(&entity_id, &tenant_id, as_of)
38                    .await?
39            } else {
40                self.repository
41                    .find_by_entity(&entity_id, &tenant_id)
42                    .await?
43            }
44        } else if let Some(event_type) = request.event_type {
45            // Query by type
46            self.repository
47                .find_by_type(&event_type, &tenant_id)
48                .await?
49        } else if let (Some(since), Some(until)) = (request.since, request.until) {
50            // Query by time range
51            self.repository
52                .find_by_time_range(&tenant_id, since, until)
53                .await?
54        } else {
55            // No specific filter - this could be expensive!
56            // In production, you might want to require at least one filter
57            return Err(crate::error::Error::InvalidInput(
58                "Query requires at least one filter (entity_id, event_type, or time range)"
59                    .to_string(),
60            ));
61        };
62
63        // Bounds are inclusive, matching the store's filters.
64        if let Some(since) = request.since {
65            events.retain(|e| e.timestamp() >= since);
66        }
67        if let Some(until) = request.until {
68            events.retain(|e| e.timestamp() <= until);
69        }
70        if let Some(as_of_valid) = request.as_of_valid {
71            events.retain(|e| {
72                e.effective_valid_from() <= as_of_valid
73                    && e.valid_to.is_none_or(|to| to > as_of_valid)
74            });
75        }
76        if let Some(since_valid) = request.since_valid {
77            events.retain(|e| e.effective_valid_from() >= since_valid);
78        }
79        if let Some(until_valid) = request.until_valid {
80            events.retain(|e| e.effective_valid_from() <= until_valid);
81        }
82
83        // Capture total before applying limit
84        let total_count = events.len();
85
86        // Apply limit
87        if let Some(limit) = request.limit {
88            events.truncate(limit);
89        }
90
91        // Convert to DTOs
92        let event_dtos: Vec<EventDto> = events.iter().map(EventDto::from).collect();
93        let count = event_dtos.len();
94        let has_more = count < total_count;
95
96        Ok(QueryEventsResponse {
97            events: event_dtos,
98            count,
99            total_count,
100            has_more,
101            entity_version: None,
102            archive_integrity: None,
103        })
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::domain::{
111        entities::Event,
112        value_objects::{EntityId, EventType, TenantId},
113    };
114    use async_trait::async_trait;
115    use chrono::Utc;
116    use serde_json::json;
117    use uuid::Uuid;
118
119    // Mock repository for testing
120    struct MockEventRepository {
121        events: Vec<Event>,
122    }
123
124    impl MockEventRepository {
125        fn with_events(events: Vec<Event>) -> Self {
126            Self { events }
127        }
128    }
129
130    #[async_trait]
131    impl EventRepository for MockEventRepository {
132        async fn save(&self, _event: &Event) -> Result<()> {
133            Ok(())
134        }
135
136        async fn save_batch(&self, _events: &[Event]) -> Result<()> {
137            Ok(())
138        }
139
140        async fn find_by_id(&self, id: Uuid) -> Result<Option<Event>> {
141            Ok(self.events.iter().find(|e| e.id() == id).cloned())
142        }
143
144        async fn find_by_entity(&self, entity_id: &str, tenant_id: &str) -> Result<Vec<Event>> {
145            Ok(self
146                .events
147                .iter()
148                .filter(|e| e.entity_id_str() == entity_id && e.tenant_id_str() == tenant_id)
149                .cloned()
150                .collect())
151        }
152
153        async fn find_by_type(&self, event_type: &str, tenant_id: &str) -> Result<Vec<Event>> {
154            Ok(self
155                .events
156                .iter()
157                .filter(|e| e.event_type_str() == event_type && e.tenant_id_str() == tenant_id)
158                .cloned()
159                .collect())
160        }
161
162        async fn find_by_time_range(
163            &self,
164            tenant_id: &str,
165            start: chrono::DateTime<Utc>,
166            end: chrono::DateTime<Utc>,
167        ) -> Result<Vec<Event>> {
168            Ok(self
169                .events
170                .iter()
171                .filter(|e| e.tenant_id_str() == tenant_id && e.occurred_between(start, end))
172                .cloned()
173                .collect())
174        }
175
176        async fn find_by_entity_as_of(
177            &self,
178            entity_id: &str,
179            tenant_id: &str,
180            as_of: chrono::DateTime<Utc>,
181        ) -> Result<Vec<Event>> {
182            Ok(self
183                .events
184                .iter()
185                .filter(|e| {
186                    e.entity_id_str() == entity_id
187                        && e.tenant_id_str() == tenant_id
188                        && e.occurred_before(as_of)
189                })
190                .cloned()
191                .collect())
192        }
193
194        async fn count(&self, tenant_id: &str) -> Result<usize> {
195            Ok(self
196                .events
197                .iter()
198                .filter(|e| e.tenant_id_str() == tenant_id)
199                .count())
200        }
201
202        async fn health_check(&self) -> Result<()> {
203            Ok(())
204        }
205    }
206
207    fn create_test_events() -> Vec<Event> {
208        vec![
209            Event::from_strings(
210                "user.created".to_string(),
211                "user-1".to_string(),
212                "tenant-1".to_string(),
213                json!({"name": "Alice"}),
214                None,
215            )
216            .unwrap(),
217            Event::from_strings(
218                "user.created".to_string(),
219                "user-2".to_string(),
220                "tenant-1".to_string(),
221                json!({"name": "Bob"}),
222                None,
223            )
224            .unwrap(),
225            Event::from_strings(
226                "order.placed".to_string(),
227                "order-1".to_string(),
228                "tenant-1".to_string(),
229                json!({"amount": 100}),
230                None,
231            )
232            .unwrap(),
233        ]
234    }
235
236    #[tokio::test]
237    async fn test_query_by_entity() {
238        let events = create_test_events();
239        let entity_id = events[0].entity_id().to_string();
240        let repo = Arc::new(MockEventRepository::with_events(events));
241        let use_case = QueryEventsUseCase::new(repo);
242
243        let request = QueryEventsRequest {
244            as_of_valid: None,
245            since_valid: None,
246            until_valid: None,
247            entity_id: Some(entity_id),
248            event_type: None,
249            tenant_id: Some("tenant-1".to_string()),
250            as_of: None,
251            since: None,
252            until: None,
253            limit: None,
254            event_type_prefix: None,
255            exclude_event_type_prefix: None,
256            payload_filter: None,
257        };
258
259        let response = use_case.execute(request).await;
260        assert!(response.is_ok());
261
262        let response = response.unwrap();
263        assert_eq!(response.count, 1);
264    }
265
266    #[tokio::test]
267    async fn test_query_by_type() {
268        let events = create_test_events();
269        let repo = Arc::new(MockEventRepository::with_events(events));
270        let use_case = QueryEventsUseCase::new(repo);
271
272        let request = QueryEventsRequest {
273            as_of_valid: None,
274            since_valid: None,
275            until_valid: None,
276            entity_id: None,
277            event_type: Some("user.created".to_string()),
278            tenant_id: Some("tenant-1".to_string()),
279            as_of: None,
280            since: None,
281            until: None,
282            limit: None,
283            event_type_prefix: None,
284            exclude_event_type_prefix: None,
285            payload_filter: None,
286        };
287
288        let response = use_case.execute(request).await;
289        assert!(response.is_ok());
290
291        let response = response.unwrap();
292        assert_eq!(response.count, 2);
293    }
294
295    #[tokio::test]
296    async fn test_query_with_limit() {
297        let events = create_test_events();
298        let repo = Arc::new(MockEventRepository::with_events(events));
299        let use_case = QueryEventsUseCase::new(repo);
300
301        let request = QueryEventsRequest {
302            as_of_valid: None,
303            since_valid: None,
304            until_valid: None,
305            entity_id: None,
306            event_type: Some("user.created".to_string()),
307            tenant_id: Some("tenant-1".to_string()),
308            as_of: None,
309            since: None,
310            until: None,
311            limit: Some(1),
312            event_type_prefix: None,
313            exclude_event_type_prefix: None,
314            payload_filter: None,
315        };
316
317        let response = use_case.execute(request).await;
318        assert!(response.is_ok());
319
320        let response = response.unwrap();
321        assert_eq!(response.count, 1);
322    }
323
324    #[tokio::test]
325    async fn test_query_requires_filter() {
326        let events = create_test_events();
327        let repo = Arc::new(MockEventRepository::with_events(events));
328        let use_case = QueryEventsUseCase::new(repo);
329
330        let request = QueryEventsRequest {
331            as_of_valid: None,
332            since_valid: None,
333            until_valid: None,
334            entity_id: None,
335            event_type: None,
336            tenant_id: Some("tenant-1".to_string()),
337            as_of: None,
338            since: None,
339            until: None,
340            limit: None,
341            event_type_prefix: None,
342            exclude_event_type_prefix: None,
343            payload_filter: None,
344        };
345
346        let response = use_case.execute(request).await;
347        assert!(response.is_err());
348    }
349
350    fn event_at(offset_secs: i64, base: chrono::DateTime<Utc>) -> Event {
351        Event::reconstruct(
352            Uuid::new_v4(),
353            EventType::new("order.placed".to_string()).unwrap(),
354            EntityId::new("order-1".to_string()).unwrap(),
355            TenantId::new("tenant-1".to_string()).unwrap(),
356            json!({}),
357            base + chrono::Duration::seconds(offset_secs),
358            None,
359            1,
360        )
361    }
362
363    #[tokio::test]
364    async fn since_and_until_are_inclusive_on_type_and_time_range_strategies() {
365        let base = Utc::now();
366        let repo = Arc::new(MockEventRepository::with_events(vec![
367            event_at(-1, base),
368            event_at(0, base),
369            event_at(5, base),
370            event_at(10, base),
371            event_at(11, base),
372        ]));
373        let use_case = QueryEventsUseCase::new(repo);
374        let window = |event_type: Option<&str>| QueryEventsRequest {
375            as_of_valid: None,
376            since_valid: None,
377            until_valid: None,
378            entity_id: None,
379            event_type: event_type.map(str::to_string),
380            tenant_id: Some("tenant-1".to_string()),
381            as_of: None,
382            since: Some(base),
383            until: Some(base + chrono::Duration::seconds(10)),
384            limit: None,
385            event_type_prefix: None,
386            exclude_event_type_prefix: None,
387            payload_filter: None,
388        };
389
390        let by_type = use_case
391            .execute(window(Some("order.placed")))
392            .await
393            .unwrap();
394        let by_range = use_case.execute(window(None)).await.unwrap();
395
396        assert_eq!(
397            by_type.count, 3,
398            "type strategy must keep both boundary events"
399        );
400        assert_eq!(
401            by_range.count, 3,
402            "time-range strategy must keep both boundary events"
403        );
404    }
405
406    #[tokio::test]
407    async fn valid_time_bounds_filter_on_the_fact_interval() {
408        let base = Utc::now();
409        let at = |secs: i64| base + chrono::Duration::seconds(secs);
410        let recorded_later = event_at(5, base)
411            .with_valid_time(Some(at(1)), None)
412            .unwrap();
413        let closed = event_at(10, base)
414            .with_valid_time(Some(at(3)), Some(at(4)))
415            .unwrap();
416        let repo = Arc::new(MockEventRepository::with_events(vec![
417            event_at(0, base),
418            recorded_later,
419            closed,
420        ]));
421        let use_case = QueryEventsUseCase::new(repo);
422        let by_valid = |as_of_valid: Option<i64>, since_valid: Option<i64>| QueryEventsRequest {
423            as_of_valid: as_of_valid.map(at),
424            since_valid: since_valid.map(at),
425            until_valid: None,
426            entity_id: None,
427            event_type: Some("order.placed".to_string()),
428            tenant_id: Some("tenant-1".to_string()),
429            ..QueryEventsRequest::default()
430        };
431
432        let inside_both = use_case.execute(by_valid(Some(2), None)).await.unwrap();
433        assert_eq!(
434            inside_both.count, 2,
435            "a fact filed at 5s but true from 1s is visible at 2s; the one not yet true is not"
436        );
437
438        let at_its_end = use_case.execute(by_valid(Some(4), None)).await.unwrap();
439        assert_eq!(
440            at_its_end.count, 2,
441            "valid_to is exclusive: the closed fact is gone at 4s"
442        );
443
444        let since = use_case.execute(by_valid(None, Some(3))).await.unwrap();
445        assert_eq!(
446            since.count, 1,
447            "since_valid bounds valid_from only, inclusive"
448        );
449    }
450}