allsource_core/infrastructure/persistence/
index.rs1use crate::{domain::entities::Event, error::Result};
2use dashmap::DashMap;
3use std::sync::Arc;
4use uuid::Uuid;
5
6#[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#[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
32pub struct EventIndex {
34 entity_index: Arc<DashMap<String, Vec<IndexEntry>>>,
36
37 type_index: Arc<DashMap<String, Vec<IndexEntry>>>,
39
40 id_index: Arc<DashMap<Uuid, usize>>,
42
43 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 #[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 self.entity_index
77 .entry(entity_id.to_string())
78 .or_default()
79 .push(entry.clone());
80
81 self.type_index
83 .entry(event_type.to_string())
84 .or_default()
85 .push(entry.clone());
86
87 self.id_index.insert(event_id, offset);
89
90 let mut total = self.total_events.write();
92 *total += 1;
93
94 Ok(())
95 }
96
97 #[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 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 #[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 #[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 #[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 pub fn get_all_entities(&self) -> Vec<String> {
150 self.entity_index.iter().map(|e| e.key().clone()).collect()
151 }
152
153 pub fn get_all_types(&self) -> Vec<String> {
155 self.type_index.iter().map(|e| e.key().clone()).collect()
156 }
157
158 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 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 let entries = index.get_by_type_prefix("");
290 assert_eq!(entries.len(), 3);
291 }
292}