1use crate::{
2 domain::entities::Event,
3 error::Result,
4 infrastructure::{
5 hash_state::{FastDashMap, fast_dashmap},
6 memory::ledger::{Owner, ShardSlots, Tally},
7 observability::heap::{StructureSize, hash_entry_bytes},
8 },
9};
10use dashmap::mapref::entry::Entry;
11use std::{mem::size_of, sync::Arc};
12use uuid::Uuid;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct ValidWindow {
18 pub from: chrono::DateTime<chrono::Utc>,
19 pub to: Option<chrono::DateTime<chrono::Utc>>,
20}
21
22impl ValidWindow {
23 pub fn of(event: &Event) -> Self {
24 Self {
25 from: event.effective_valid_from(),
26 to: event.valid_to,
27 }
28 }
29}
30
31#[derive(Debug, Clone)]
33pub struct IndexEntry {
34 pub event_id: Uuid,
35 pub offset: usize,
36 pub timestamp: chrono::DateTime<chrono::Utc>,
37 pub valid: ValidWindow,
38}
39
40pub struct EventIndex {
42 entity_index: Arc<FastDashMap<String, Vec<IndexEntry>>>,
44
45 type_index: Arc<FastDashMap<String, Vec<IndexEntry>>>,
47
48 id_index: Arc<FastDashMap<Uuid, usize>>,
50
51 total_events: parking_lot::RwLock<usize>,
53
54 entity_entries: Tally,
55 entity_table: Tally,
56 entity_slots: ShardSlots,
57 type_entries: Tally,
58 type_table: Tally,
59 type_slots: ShardSlots,
60 id_table: Tally,
61 id_slots: ShardSlots,
62}
63
64impl EventIndex {
65 pub fn new() -> Self {
66 Self {
67 entity_index: Arc::new(fast_dashmap()),
68 type_index: Arc::new(fast_dashmap()),
69 id_index: Arc::new(fast_dashmap()),
70 total_events: parking_lot::RwLock::new(0),
71 entity_entries: Tally::new(Owner::IndexEntity),
72 entity_table: Tally::new(Owner::IndexEntity),
73 entity_slots: ShardSlots::new(),
74 type_entries: Tally::new(Owner::IndexType),
75 type_table: Tally::new(Owner::IndexType),
76 type_slots: ShardSlots::new(),
77 id_table: Tally::new(Owner::IndexId),
78 id_slots: ShardSlots::new(),
79 }
80 }
81
82 #[cfg_attr(feature = "hotpath", hotpath::measure)]
84 pub fn index_event(
85 &self,
86 event_id: Uuid,
87 entity_id: &str,
88 event_type: &str,
89 timestamp: chrono::DateTime<chrono::Utc>,
90 valid: ValidWindow,
91 offset: usize,
92 ) -> Result<()> {
93 let entry = IndexEntry {
94 event_id,
95 offset,
96 timestamp,
97 valid,
98 };
99
100 let entity_new = push_entry(
101 &self.entity_index,
102 &self.entity_entries,
103 entity_id,
104 entry.clone(),
105 );
106 if entity_new {
107 self.entity_slots.charge_key(
108 &self.entity_index,
109 entity_id,
110 &self.entity_table,
111 size_of::<(String, Vec<IndexEntry>)>(),
112 );
113 }
114
115 let type_new = push_entry(&self.type_index, &self.type_entries, event_type, entry);
116 if type_new {
117 self.type_slots.charge_key(
118 &self.type_index,
119 event_type,
120 &self.type_table,
121 size_of::<(String, Vec<IndexEntry>)>(),
122 );
123 }
124
125 if self.id_index.insert(event_id, offset).is_none() {
126 self.id_slots.charge_key(
127 &self.id_index,
128 &event_id,
129 &self.id_table,
130 size_of::<(Uuid, usize)>(),
131 );
132 }
133
134 let mut total = self.total_events.write();
135 *total += 1;
136
137 Ok(())
138 }
139
140 #[cfg_attr(feature = "hotpath", hotpath::measure)]
142 pub fn get_by_entity(&self, entity_id: &str) -> Option<Vec<IndexEntry>> {
143 self.entity_index
144 .get(entity_id)
145 .map(|entries| entries.clone())
146 }
147
148 pub fn entity_capacity(&self, entity_id: &str) -> usize {
150 self.entity_index
151 .get(entity_id)
152 .map_or(0, |entries| entries.capacity())
153 }
154
155 pub(crate) fn get_by_entity_bounded(
157 &self,
158 entity_id: &str,
159 max: usize,
160 ) -> Result<Vec<IndexEntry>> {
161 let Some(entries) = self.entity_index.get(entity_id) else {
162 return Ok(Vec::new());
163 };
164 if entries.len() > max {
165 return Err(crate::error::AllSourceError::StorageError(
166 "Strict retained entity exceeds its event budget".into(),
167 ));
168 }
169 Ok(entries.clone())
170 }
171
172 #[cfg_attr(feature = "hotpath", hotpath::measure)]
174 pub fn get_by_type(&self, event_type: &str) -> Option<Vec<IndexEntry>> {
175 self.type_index
176 .get(event_type)
177 .map(|entries| entries.clone())
178 }
179
180 #[cfg_attr(feature = "hotpath", hotpath::measure)]
182 pub fn get_by_id(&self, event_id: &Uuid) -> Option<usize> {
183 self.id_index.get(event_id).map(|offset| *offset)
184 }
185
186 #[cfg_attr(feature = "hotpath", hotpath::measure)]
188 pub fn get_by_type_prefix(&self, prefix: &str) -> Vec<IndexEntry> {
189 let mut entries = Vec::new();
190 for item in self.type_index.iter() {
191 if item.key().starts_with(prefix) {
192 entries.extend(item.value().clone());
193 }
194 }
195 entries
196 }
197
198 pub fn get_all_entities(&self) -> Vec<String> {
200 self.entity_index.iter().map(|e| e.key().clone()).collect()
201 }
202
203 pub fn get_all_types(&self) -> Vec<String> {
205 self.type_index.iter().map(|e| e.key().clone()).collect()
206 }
207
208 pub fn stats(&self) -> IndexStats {
210 IndexStats {
211 total_events: *self.total_events.read(),
212 total_entities: self.entity_index.len(),
213 total_event_types: self.type_index.len(),
214 }
215 }
216
217 pub fn resident_structures(&self) -> [StructureSize; 3] {
220 let list_map = |name, map: &FastDashMap<String, Vec<IndexEntry>>| {
221 let bytes: usize = map
222 .iter()
223 .map(|item| {
224 hash_entry_bytes::<String, Vec<IndexEntry>>()
225 + item.key().len()
226 + item.value().capacity() * size_of::<IndexEntry>()
227 })
228 .sum();
229 StructureSize {
230 name,
231 entries: map.len() as u64,
232 bytes: Some(bytes as u64),
233 }
234 };
235 let ids = self.id_index.len();
236 [
237 list_map("entity_index", &self.entity_index),
238 list_map("type_index", &self.type_index),
239 StructureSize {
240 name: "id_index",
241 entries: ids as u64,
242 bytes: Some((ids * hash_entry_bytes::<Uuid, usize>()) as u64),
243 },
244 ]
245 }
246
247 pub fn clear(&self) {
252 self.entity_index.clear();
253 self.entity_entries.take();
254 self.type_index.clear();
255 self.type_entries.take();
256 self.id_index.clear();
257 let mut total = self.total_events.write();
258 *total = 0;
259 }
260}
261
262fn push_entry(
265 map: &FastDashMap<String, Vec<IndexEntry>>,
266 entries: &Tally,
267 key: &str,
268 entry: IndexEntry,
269) -> bool {
270 match map.entry(key.to_string()) {
271 Entry::Occupied(mut occupied) => {
272 let vec = occupied.get_mut();
273 let before = vec.capacity();
274 vec.push(entry);
275 entries.grow(before, vec.capacity(), size_of::<IndexEntry>());
276 false
277 }
278 Entry::Vacant(vacant) => {
279 let key_bytes = vacant.key().len() as u64;
280 let vec = vacant.insert(vec![entry]);
281 entries.add(key_bytes + (vec.capacity() * size_of::<IndexEntry>()) as u64);
282 true
283 }
284 }
285}
286
287impl Default for EventIndex {
288 fn default() -> Self {
289 Self::new()
290 }
291}
292
293#[derive(Debug, Clone, serde::Serialize)]
294pub struct IndexStats {
295 pub total_events: usize,
296 pub total_entities: usize,
297 pub total_event_types: usize,
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 fn open(from: chrono::DateTime<chrono::Utc>) -> ValidWindow {
305 ValidWindow { from, to: None }
306 }
307
308 #[test]
309 fn test_index_event() {
310 let index = EventIndex::new();
311 let event_id = Uuid::new_v4();
312 let timestamp = chrono::Utc::now();
313
314 index
315 .index_event(
316 event_id,
317 "user-123",
318 "user.created",
319 timestamp,
320 open(timestamp),
321 0,
322 )
323 .unwrap();
324
325 assert_eq!(index.stats().total_events, 1);
326 assert_eq!(index.stats().total_entities, 1);
327 assert_eq!(index.stats().total_event_types, 1);
328 }
329
330 #[test]
331 fn test_get_by_entity() {
332 let index = EventIndex::new();
333 let event_id = Uuid::new_v4();
334 let timestamp = chrono::Utc::now();
335
336 index
337 .index_event(
338 event_id,
339 "user-123",
340 "user.created",
341 timestamp,
342 open(timestamp),
343 0,
344 )
345 .unwrap();
346
347 let entries = index.get_by_entity("user-123").unwrap();
348 assert_eq!(entries.len(), 1);
349 assert_eq!(entries[0].event_id, event_id);
350 }
351
352 #[test]
353 fn test_get_by_type() {
354 let index = EventIndex::new();
355 let event_id = Uuid::new_v4();
356 let timestamp = chrono::Utc::now();
357
358 index
359 .index_event(
360 event_id,
361 "user-123",
362 "user.created",
363 timestamp,
364 open(timestamp),
365 0,
366 )
367 .unwrap();
368
369 let entries = index.get_by_type("user.created").unwrap();
370 assert_eq!(entries.len(), 1);
371 assert_eq!(entries[0].event_id, event_id);
372 }
373
374 #[test]
375 fn test_get_by_type_prefix() {
376 let index = EventIndex::new();
377 let ts = chrono::Utc::now();
378
379 index
380 .index_event(Uuid::new_v4(), "e-1", "index.created", ts, open(ts), 0)
381 .unwrap();
382 index
383 .index_event(Uuid::new_v4(), "e-2", "index.updated", ts, open(ts), 1)
384 .unwrap();
385 index
386 .index_event(Uuid::new_v4(), "e-3", "trade.created", ts, open(ts), 2)
387 .unwrap();
388
389 let entries = index.get_by_type_prefix("index.");
390 assert_eq!(entries.len(), 2);
391
392 let entries = index.get_by_type_prefix("trade.");
393 assert_eq!(entries.len(), 1);
394
395 let entries = index.get_by_type_prefix("nonexistent.");
396 assert_eq!(entries.len(), 0);
397
398 let entries = index.get_by_type_prefix("");
400 assert_eq!(entries.len(), 3);
401 }
402}