Skip to main content

allsource_core/infrastructure/persistence/
index.rs

1use crate::{domain::entities::Event, error::Result};
2use dashmap::DashMap;
3use std::sync::Arc;
4use uuid::Uuid;
5
6/// Valid-time interval of an indexed event. `from` is the effective start
7/// (`valid_from`, or record time when unset); `to` is `None` when open-ended.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct ValidWindow {
10    pub from: chrono::DateTime<chrono::Utc>,
11    pub to: Option<chrono::DateTime<chrono::Utc>>,
12}
13
14impl ValidWindow {
15    pub fn of(event: &Event) -> Self {
16        Self {
17            from: event.effective_valid_from(),
18            to: event.valid_to,
19        }
20    }
21}
22
23/// Event index entry
24#[derive(Debug, Clone)]
25pub struct IndexEntry {
26    pub event_id: Uuid,
27    pub offset: usize,
28    pub timestamp: chrono::DateTime<chrono::Utc>,
29    pub valid: ValidWindow,
30}
31
32/// High-performance concurrent index for fast event lookups
33pub struct EventIndex {
34    /// Index by entity_id -> list of event entries
35    entity_index: Arc<DashMap<String, Vec<IndexEntry>>>,
36
37    /// Index by event_type -> list of event entries
38    type_index: Arc<DashMap<String, Vec<IndexEntry>>>,
39
40    /// Index by event_id -> offset (for direct lookups)
41    id_index: Arc<DashMap<Uuid, usize>>,
42
43    /// Total indexed events
44    total_events: parking_lot::RwLock<usize>,
45}
46
47impl EventIndex {
48    pub fn new() -> Self {
49        Self {
50            entity_index: Arc::new(DashMap::new()),
51            type_index: Arc::new(DashMap::new()),
52            id_index: Arc::new(DashMap::new()),
53            total_events: parking_lot::RwLock::new(0),
54        }
55    }
56
57    /// Add an event to all relevant indices
58    #[cfg_attr(feature = "hotpath", hotpath::measure)]
59    pub fn index_event(
60        &self,
61        event_id: Uuid,
62        entity_id: &str,
63        event_type: &str,
64        timestamp: chrono::DateTime<chrono::Utc>,
65        valid: ValidWindow,
66        offset: usize,
67    ) -> Result<()> {
68        let entry = IndexEntry {
69            event_id,
70            offset,
71            timestamp,
72            valid,
73        };
74
75        // Index by entity_id
76        self.entity_index
77            .entry(entity_id.to_string())
78            .or_default()
79            .push(entry.clone());
80
81        // Index by event_type
82        self.type_index
83            .entry(event_type.to_string())
84            .or_default()
85            .push(entry.clone());
86
87        // Index by event_id
88        self.id_index.insert(event_id, offset);
89
90        // Increment total
91        let mut total = self.total_events.write();
92        *total += 1;
93
94        Ok(())
95    }
96
97    /// Get all event offsets for an entity
98    #[cfg_attr(feature = "hotpath", hotpath::measure)]
99    pub fn get_by_entity(&self, entity_id: &str) -> Option<Vec<IndexEntry>> {
100        self.entity_index
101            .get(entity_id)
102            .map(|entries| entries.clone())
103    }
104
105    /// Refuse an oversized entity before allocating its offset vector.
106    pub(crate) fn get_by_entity_bounded(
107        &self,
108        entity_id: &str,
109        max: usize,
110    ) -> Result<Vec<IndexEntry>> {
111        let Some(entries) = self.entity_index.get(entity_id) else {
112            return Ok(Vec::new());
113        };
114        if entries.len() > max {
115            return Err(crate::error::AllSourceError::StorageError(
116                "Strict retained entity exceeds its event budget".into(),
117            ));
118        }
119        Ok(entries.clone())
120    }
121
122    /// Get all event offsets for an event type
123    #[cfg_attr(feature = "hotpath", hotpath::measure)]
124    pub fn get_by_type(&self, event_type: &str) -> Option<Vec<IndexEntry>> {
125        self.type_index
126            .get(event_type)
127            .map(|entries| entries.clone())
128    }
129
130    /// Get event offset by ID
131    #[cfg_attr(feature = "hotpath", hotpath::measure)]
132    pub fn get_by_id(&self, event_id: &Uuid) -> Option<usize> {
133        self.id_index.get(event_id).map(|offset| *offset)
134    }
135
136    /// Get all event entries matching a type prefix (e.g., "index." matches "index.created")
137    #[cfg_attr(feature = "hotpath", hotpath::measure)]
138    pub fn get_by_type_prefix(&self, prefix: &str) -> Vec<IndexEntry> {
139        let mut entries = Vec::new();
140        for item in self.type_index.iter() {
141            if item.key().starts_with(prefix) {
142                entries.extend(item.value().clone());
143            }
144        }
145        entries
146    }
147
148    /// Get all entities being tracked
149    pub fn get_all_entities(&self) -> Vec<String> {
150        self.entity_index.iter().map(|e| e.key().clone()).collect()
151    }
152
153    /// Get all event types
154    pub fn get_all_types(&self) -> Vec<String> {
155        self.type_index.iter().map(|e| e.key().clone()).collect()
156    }
157
158    /// Get statistics
159    pub fn stats(&self) -> IndexStats {
160        IndexStats {
161            total_events: *self.total_events.read(),
162            total_entities: self.entity_index.len(),
163            total_event_types: self.type_index.len(),
164        }
165    }
166
167    /// Clear all indices (useful for testing)
168    pub fn clear(&self) {
169        self.entity_index.clear();
170        self.type_index.clear();
171        self.id_index.clear();
172        let mut total = self.total_events.write();
173        *total = 0;
174    }
175}
176
177impl Default for EventIndex {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183#[derive(Debug, Clone, serde::Serialize)]
184pub struct IndexStats {
185    pub total_events: usize,
186    pub total_entities: usize,
187    pub total_event_types: usize,
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn open(from: chrono::DateTime<chrono::Utc>) -> ValidWindow {
195        ValidWindow { from, to: None }
196    }
197
198    #[test]
199    fn test_index_event() {
200        let index = EventIndex::new();
201        let event_id = Uuid::new_v4();
202        let timestamp = chrono::Utc::now();
203
204        index
205            .index_event(
206                event_id,
207                "user-123",
208                "user.created",
209                timestamp,
210                open(timestamp),
211                0,
212            )
213            .unwrap();
214
215        assert_eq!(index.stats().total_events, 1);
216        assert_eq!(index.stats().total_entities, 1);
217        assert_eq!(index.stats().total_event_types, 1);
218    }
219
220    #[test]
221    fn test_get_by_entity() {
222        let index = EventIndex::new();
223        let event_id = Uuid::new_v4();
224        let timestamp = chrono::Utc::now();
225
226        index
227            .index_event(
228                event_id,
229                "user-123",
230                "user.created",
231                timestamp,
232                open(timestamp),
233                0,
234            )
235            .unwrap();
236
237        let entries = index.get_by_entity("user-123").unwrap();
238        assert_eq!(entries.len(), 1);
239        assert_eq!(entries[0].event_id, event_id);
240    }
241
242    #[test]
243    fn test_get_by_type() {
244        let index = EventIndex::new();
245        let event_id = Uuid::new_v4();
246        let timestamp = chrono::Utc::now();
247
248        index
249            .index_event(
250                event_id,
251                "user-123",
252                "user.created",
253                timestamp,
254                open(timestamp),
255                0,
256            )
257            .unwrap();
258
259        let entries = index.get_by_type("user.created").unwrap();
260        assert_eq!(entries.len(), 1);
261        assert_eq!(entries[0].event_id, event_id);
262    }
263
264    #[test]
265    fn test_get_by_type_prefix() {
266        let index = EventIndex::new();
267        let ts = chrono::Utc::now();
268
269        index
270            .index_event(Uuid::new_v4(), "e-1", "index.created", ts, open(ts), 0)
271            .unwrap();
272        index
273            .index_event(Uuid::new_v4(), "e-2", "index.updated", ts, open(ts), 1)
274            .unwrap();
275        index
276            .index_event(Uuid::new_v4(), "e-3", "trade.created", ts, open(ts), 2)
277            .unwrap();
278
279        let entries = index.get_by_type_prefix("index.");
280        assert_eq!(entries.len(), 2);
281
282        let entries = index.get_by_type_prefix("trade.");
283        assert_eq!(entries.len(), 1);
284
285        let entries = index.get_by_type_prefix("nonexistent.");
286        assert_eq!(entries.len(), 0);
287
288        // Empty prefix matches all
289        let entries = index.get_by_type_prefix("");
290        assert_eq!(entries.len(), 3);
291    }
292}