allsource-core 0.19.1

High-performance event store core built in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use crate::{
    domain::value_objects::{EntityId, EventType, TenantId},
    error::Result,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Domain Entity: Event
///
/// Core event structure representing a domain event in the event store.
/// This is an immutable, timestamped record of something that happened.
///
/// Domain Rules:
/// - Events are immutable once created
/// - Event type must follow naming convention (enforced by EventType value object)
/// - Entity ID cannot be empty (enforced by EntityId value object)
/// - Tenant ID cannot be empty (enforced by TenantId value object)
/// - Timestamp must not be in the future
/// - Version starts at 1
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Event {
    pub id: Uuid,
    pub event_type: EventType,
    pub entity_id: EntityId,
    #[serde(default = "default_tenant_id")]
    pub tenant_id: TenantId,
    pub payload: serde_json::Value,
    pub timestamp: DateTime<Utc>,
    pub metadata: Option<serde_json::Value>,
    pub version: i64,
}

fn default_tenant_id() -> TenantId {
    TenantId::default_tenant()
}

impl Event {
    /// Create a new Event with value objects (recommended)
    pub fn new(
        event_type: EventType,
        entity_id: EntityId,
        tenant_id: TenantId,
        payload: serde_json::Value,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            event_type,
            entity_id,
            tenant_id,
            payload,
            timestamp: Utc::now(),
            metadata: None,
            version: 1,
        }
    }

    /// Create event with optional metadata
    pub fn with_metadata(
        event_type: EventType,
        entity_id: EntityId,
        tenant_id: TenantId,
        payload: serde_json::Value,
        metadata: serde_json::Value,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            event_type,
            entity_id,
            tenant_id,
            payload,
            timestamp: Utc::now(),
            metadata: Some(metadata),
            version: 1,
        }
    }

    /// Create event with default tenant (for single-tenant use)
    pub fn with_default_tenant(
        event_type: EventType,
        entity_id: EntityId,
        payload: serde_json::Value,
    ) -> Self {
        Self::new(event_type, entity_id, TenantId::default_tenant(), payload)
    }

    /// Create event from strings (for backward compatibility)
    ///
    /// This validates the strings and creates value objects.
    /// Use the value object constructor for new code.
    pub fn from_strings(
        event_type: String,
        entity_id: String,
        tenant_id: String,
        payload: serde_json::Value,
        metadata: Option<serde_json::Value>,
    ) -> Result<Self> {
        let event_type = EventType::new(event_type)?;
        let entity_id = EntityId::new(entity_id)?;
        let tenant_id = TenantId::new(tenant_id)?;

        Ok(Self {
            id: Uuid::new_v4(),
            event_type,
            entity_id,
            tenant_id,
            payload,
            timestamp: Utc::now(),
            metadata,
            version: 1,
        })
    }

    /// Reconstruct an Event from storage (bypasses validation for stored events)
    pub fn reconstruct(
        id: Uuid,
        event_type: EventType,
        entity_id: EntityId,
        tenant_id: TenantId,
        payload: serde_json::Value,
        timestamp: DateTime<Utc>,
        metadata: Option<serde_json::Value>,
        version: i64,
    ) -> Self {
        Self {
            id,
            event_type,
            entity_id,
            tenant_id,
            payload,
            timestamp,
            metadata,
            version,
        }
    }

    /// Reconstruct from raw strings (for loading from old storage)
    pub fn reconstruct_from_strings(
        id: Uuid,
        event_type: String,
        entity_id: String,
        tenant_id: String,
        payload: serde_json::Value,
        timestamp: DateTime<Utc>,
        metadata: Option<serde_json::Value>,
        version: i64,
    ) -> Self {
        Self {
            id,
            event_type: EventType::new_unchecked(event_type),
            entity_id: EntityId::new_unchecked(entity_id),
            tenant_id: TenantId::new_unchecked(tenant_id),
            payload,
            timestamp,
            metadata,
            version,
        }
    }

    // Getters (Events are immutable)

    pub fn id(&self) -> Uuid {
        self.id
    }

    pub fn event_type(&self) -> &EventType {
        &self.event_type
    }

    pub fn event_type_str(&self) -> &str {
        self.event_type.as_str()
    }

    pub fn entity_id(&self) -> &EntityId {
        &self.entity_id
    }

    pub fn entity_id_str(&self) -> &str {
        self.entity_id.as_str()
    }

    pub fn tenant_id(&self) -> &TenantId {
        &self.tenant_id
    }

    pub fn tenant_id_str(&self) -> &str {
        self.tenant_id.as_str()
    }

    pub fn payload(&self) -> &serde_json::Value {
        &self.payload
    }

    pub fn timestamp(&self) -> DateTime<Utc> {
        self.timestamp
    }

    pub fn metadata(&self) -> Option<&serde_json::Value> {
        self.metadata.as_ref()
    }

    pub fn version(&self) -> i64 {
        self.version
    }

    // Domain behavior methods

    /// Check if this event belongs to a specific tenant
    pub fn belongs_to_tenant(&self, tenant_id: &TenantId) -> bool {
        &self.tenant_id == tenant_id
    }

    /// Check if this event belongs to a tenant (by string)
    pub fn belongs_to_tenant_str(&self, tenant_id: &str) -> bool {
        self.tenant_id.as_str() == tenant_id
    }

    /// Check if this event relates to a specific entity
    pub fn relates_to_entity(&self, entity_id: &EntityId) -> bool {
        &self.entity_id == entity_id
    }

    /// Check if this event relates to an entity (by string)
    pub fn relates_to_entity_str(&self, entity_id: &str) -> bool {
        self.entity_id.as_str() == entity_id
    }

    /// Check if this event is of a specific type
    pub fn is_type(&self, event_type: &EventType) -> bool {
        &self.event_type == event_type
    }

    /// Check if this event is of a type (by string)
    pub fn is_type_str(&self, event_type: &str) -> bool {
        self.event_type.as_str() == event_type
    }

    /// Check if this event is in a specific namespace
    pub fn is_in_namespace(&self, namespace: &str) -> bool {
        self.event_type.is_in_namespace(namespace)
    }

    /// Check if this event occurred within a time range
    pub fn occurred_between(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> bool {
        self.timestamp >= start && self.timestamp <= end
    }

    /// Check if event occurred before a specific time
    pub fn occurred_before(&self, time: DateTime<Utc>) -> bool {
        self.timestamp < time
    }

    /// Check if event occurred after a specific time
    pub fn occurred_after(&self, time: DateTime<Utc>) -> bool {
        self.timestamp > time
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn test_event_type() -> EventType {
        EventType::new("user.created".to_string()).unwrap()
    }

    fn test_entity_id() -> EntityId {
        EntityId::new("user-123".to_string()).unwrap()
    }

    fn test_tenant_id() -> TenantId {
        TenantId::new("tenant-1".to_string()).unwrap()
    }

    #[test]
    fn test_event_creation_with_value_objects() {
        let event = Event::new(
            test_event_type(),
            test_entity_id(),
            test_tenant_id(),
            json!({"name": "Alice"}),
        );

        assert_eq!(event.event_type_str(), "user.created");
        assert_eq!(event.entity_id_str(), "user-123");
        assert_eq!(event.tenant_id_str(), "tenant-1");
        assert_eq!(event.version(), 1);
    }

    #[test]
    fn test_event_creation_from_strings() {
        let event = Event::from_strings(
            "user.created".to_string(),
            "user-123".to_string(),
            "tenant-1".to_string(),
            json!({"name": "Alice"}),
            None,
        );

        assert!(event.is_ok());
        let event = event.unwrap();
        assert_eq!(event.event_type_str(), "user.created");
        assert_eq!(event.entity_id_str(), "user-123");
        assert_eq!(event.tenant_id_str(), "tenant-1");
    }

    #[test]
    fn test_event_with_metadata() {
        let event = Event::with_metadata(
            test_event_type(),
            test_entity_id(),
            test_tenant_id(),
            json!({"name": "Bob"}),
            json!({"source": "api"}),
        );

        assert!(event.metadata().is_some());
        assert_eq!(event.metadata().unwrap(), &json!({"source": "api"}));
    }

    #[test]
    fn test_event_with_default_tenant() {
        let event = Event::with_default_tenant(test_event_type(), test_entity_id(), json!({}));

        assert_eq!(event.tenant_id_str(), "default");
    }

    #[test]
    fn test_from_strings_validates_event_type() {
        // Invalid: uppercase
        let result = Event::from_strings(
            "User.Created".to_string(),
            "e1".to_string(),
            "t1".to_string(),
            json!({}),
            None,
        );
        assert!(result.is_err());

        // Invalid: empty
        let result = Event::from_strings(
            String::new(),
            "e1".to_string(),
            "t1".to_string(),
            json!({}),
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_from_strings_validates_entity_id() {
        // Invalid: empty entity_id
        let result = Event::from_strings(
            "user.created".to_string(),
            String::new(),
            "t1".to_string(),
            json!({}),
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_from_strings_validates_tenant_id() {
        // Invalid: empty tenant_id
        let result = Event::from_strings(
            "user.created".to_string(),
            "e1".to_string(),
            String::new(),
            json!({}),
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_belongs_to_tenant() {
        let tenant1 = TenantId::new("tenant-1".to_string()).unwrap();
        let tenant2 = TenantId::new("tenant-2".to_string()).unwrap();

        let event = Event::new(
            test_event_type(),
            test_entity_id(),
            tenant1.clone(),
            json!({}),
        );

        assert!(event.belongs_to_tenant(&tenant1));
        assert!(!event.belongs_to_tenant(&tenant2));
    }

    #[test]
    fn test_belongs_to_tenant_str() {
        let event = Event::new(
            test_event_type(),
            test_entity_id(),
            test_tenant_id(),
            json!({}),
        );

        assert!(event.belongs_to_tenant_str("tenant-1"));
        assert!(!event.belongs_to_tenant_str("tenant-2"));
    }

    #[test]
    fn test_relates_to_entity() {
        let entity1 = EntityId::new("order-456".to_string()).unwrap();
        let entity2 = EntityId::new("order-789".to_string()).unwrap();

        let event = Event::new(
            EventType::new("order.placed".to_string()).unwrap(),
            entity1.clone(),
            test_tenant_id(),
            json!({}),
        );

        assert!(event.relates_to_entity(&entity1));
        assert!(!event.relates_to_entity(&entity2));
    }

    #[test]
    fn test_relates_to_entity_str() {
        let event = Event::new(
            EventType::new("order.placed".to_string()).unwrap(),
            EntityId::new("order-456".to_string()).unwrap(),
            test_tenant_id(),
            json!({}),
        );

        assert!(event.relates_to_entity_str("order-456"));
        assert!(!event.relates_to_entity_str("order-789"));
    }

    #[test]
    fn test_is_type() {
        let type1 = EventType::new("order.placed".to_string()).unwrap();
        let type2 = EventType::new("order.cancelled".to_string()).unwrap();

        let event = Event::new(type1.clone(), test_entity_id(), test_tenant_id(), json!({}));

        assert!(event.is_type(&type1));
        assert!(!event.is_type(&type2));
    }

    #[test]
    fn test_is_type_str() {
        let event = Event::new(
            EventType::new("order.placed".to_string()).unwrap(),
            test_entity_id(),
            test_tenant_id(),
            json!({}),
        );

        assert!(event.is_type_str("order.placed"));
        assert!(!event.is_type_str("order.cancelled"));
    }

    #[test]
    fn test_is_in_namespace() {
        let event = Event::new(
            EventType::new("order.placed".to_string()).unwrap(),
            test_entity_id(),
            test_tenant_id(),
            json!({}),
        );

        assert!(event.is_in_namespace("order"));
        assert!(!event.is_in_namespace("user"));
    }

    #[test]
    fn test_time_range_queries() {
        let event = Event::new(
            test_event_type(),
            test_entity_id(),
            test_tenant_id(),
            json!({}),
        );

        let past = Utc::now() - chrono::Duration::hours(1);
        let future = Utc::now() + chrono::Duration::hours(1);

        assert!(event.occurred_after(past));
        assert!(event.occurred_before(future));
        assert!(event.occurred_between(past, future));
    }

    #[test]
    fn test_serde_serialization() {
        let event = Event::new(
            test_event_type(),
            test_entity_id(),
            test_tenant_id(),
            json!({"test": "data"}),
        );

        // Should be able to serialize
        let json = serde_json::to_string(&event);
        assert!(json.is_ok());

        // Should be able to deserialize
        let deserialized = serde_json::from_str::<Event>(&json.unwrap());
        assert!(deserialized.is_ok());

        let deserialized = deserialized.unwrap();
        assert_eq!(deserialized.event_type_str(), "user.created");
        assert_eq!(deserialized.entity_id_str(), "user-123");
    }

    #[test]
    fn test_reconstruct_from_strings() {
        let id = Uuid::new_v4();
        let timestamp = Utc::now();

        let event = Event::reconstruct_from_strings(
            id,
            "order.placed".to_string(),
            "order-123".to_string(),
            "tenant-1".to_string(),
            json!({"amount": 100}),
            timestamp,
            Some(json!({"source": "api"})),
            1,
        );

        assert_eq!(event.id(), id);
        assert_eq!(event.event_type_str(), "order.placed");
        assert_eq!(event.entity_id_str(), "order-123");
        assert_eq!(event.tenant_id_str(), "tenant-1");
        assert_eq!(event.version(), 1);
    }
}