tsuzuri 0.1.285

Tsuzuri is a Event Sourcing framework for Rust, designed to be simple and easy to use.
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
535
536
537
538
539
540
541
542
543
544
545
use crate::{
    aggregate::AggregateRoot,
    domain_event::SerializedDomainEvent,
    event::{SequenceSelect, Stream},
    event_store::{AggregateEventStreamer, Persister, SnapshotGetter, SnapshotIntervalProvider},
    integration_event::SerializedIntegrationEvent,
    inverted_index_store::{AggregateIdsLoader, InvertedIndexCommiter, InvertedIndexRemover},
    persist::PersistenceError,
    snapshot::PersistedSnapshot,
};
use async_trait::async_trait;
use futures::stream;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

/// Memory-based event store for testing and development
#[derive(Clone)]
pub struct MemoryEventStore {
    snapshot_interval: usize,
    events: Arc<RwLock<HashMap<String, Vec<SerializedDomainEvent>>>>,
    snapshots: Arc<RwLock<HashMap<String, PersistedSnapshot>>>,
    integration_events: Arc<RwLock<Vec<SerializedIntegrationEvent>>>,
}

impl MemoryEventStore {
    pub fn new(snapshot_interval: usize) -> Self {
        Self {
            snapshot_interval,
            events: Arc::new(RwLock::new(HashMap::new())),
            snapshots: Arc::new(RwLock::new(HashMap::new())),
            integration_events: Arc::new(RwLock::new(Vec::new())),
        }
    }
}

impl SnapshotIntervalProvider for MemoryEventStore {
    fn snapshot_interval(&self) -> usize {
        self.snapshot_interval
    }
}

impl AggregateEventStreamer for MemoryEventStore {
    fn stream_events<T: AggregateRoot>(
        &self,
        id: &str,
        select: SequenceSelect,
    ) -> Stream<'_, SerializedDomainEvent, PersistenceError> {
        let events = self.events.read().unwrap();
        let aggregate_events = events.get(id).cloned().unwrap_or_default();

        let filtered_events: Vec<SerializedDomainEvent> = match select {
            SequenceSelect::All => aggregate_events,
            SequenceSelect::From(seq) => aggregate_events.into_iter().filter(|e| e.seq_nr >= seq).collect(),
        };

        Box::pin(stream::iter(filtered_events.into_iter().map(Ok)))
    }
}

#[async_trait]
impl Persister for MemoryEventStore {
    async fn persist(
        &self,
        domain_events: &[SerializedDomainEvent],
        integration_events: Option<&[SerializedIntegrationEvent]>,
        snapshot_update: Option<&PersistedSnapshot>,
    ) -> Result<(), PersistenceError> {
        // Store domain events
        if !domain_events.is_empty() {
            let mut events = self.events.write().unwrap();
            let aggregate_id = &domain_events[0].aggregate_id;
            events
                .entry(aggregate_id.clone())
                .or_default()
                .extend(domain_events.iter().cloned());
        }

        // Store integration events
        if let Some(events) = integration_events {
            if !events.is_empty() {
                let mut int_events = self.integration_events.write().unwrap();
                int_events.extend(events.iter().cloned());
            }
        }

        // Update snapshot if provided
        if let Some(snapshot) = snapshot_update {
            let mut snapshots = self.snapshots.write().unwrap();
            snapshots.insert(
                snapshot.aggregate_id.clone(),
                PersistedSnapshot {
                    aggregate_type: snapshot.aggregate_type.clone(),
                    aggregate_id: snapshot.aggregate_id.clone(),
                    aggregate: snapshot.aggregate.clone(),
                    seq_nr: snapshot.seq_nr,
                    version: snapshot.version,
                },
            );
        }

        Ok(())
    }
}

#[async_trait]
impl SnapshotGetter for MemoryEventStore {
    async fn get_snapshot<T>(&self, id: &str) -> Result<Option<PersistedSnapshot>, PersistenceError>
    where
        T: AggregateRoot,
    {
        let snapshots = self.snapshots.read().unwrap();
        Ok(snapshots.get(id).map(|s| PersistedSnapshot {
            aggregate_type: s.aggregate_type.clone(),
            aggregate_id: s.aggregate_id.clone(),
            aggregate: s.aggregate.clone(),
            seq_nr: s.seq_nr,
            version: s.version,
        }))
    }
}

/// Memory-based inverted index store for testing and development
#[derive(Clone)]
pub struct MemoryInvertedIndexStore {
    indexes: Arc<RwLock<HashMap<String, HashSet<String>>>>,
}

impl MemoryInvertedIndexStore {
    pub fn new() -> Self {
        Self {
            indexes: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

impl Default for MemoryInvertedIndexStore {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl AggregateIdsLoader for MemoryInvertedIndexStore {
    async fn get_aggregate_ids(&self, keyword: &str) -> Result<Vec<String>, PersistenceError> {
        let indexes = self.indexes.read().unwrap();
        Ok(indexes
            .get(keyword)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default())
    }
}

#[async_trait]
impl InvertedIndexCommiter for MemoryInvertedIndexStore {
    async fn commit(&self, aggregate_id: &str, keyword: &str) -> Result<(), PersistenceError> {
        let mut indexes = self.indexes.write().unwrap();
        indexes
            .entry(keyword.to_string())
            .or_default()
            .insert(aggregate_id.to_string());
        Ok(())
    }
}

#[async_trait]
impl InvertedIndexRemover for MemoryInvertedIndexStore {
    async fn remove(&self, aggregate_id: &str, keyword: &str) -> Result<(), PersistenceError> {
        let mut indexes = self.indexes.write().unwrap();
        if let Some(set) = indexes.get_mut(keyword) {
            set.remove(aggregate_id);
            if set.is_empty() {
                indexes.remove(keyword);
            }
        }
        Ok(())
    }
}

/// Combined memory store that implements both EventStore and InvertedIndexStore
#[derive(Clone)]
pub struct MemoryStore {
    event_store: MemoryEventStore,
    inverted_index_store: MemoryInvertedIndexStore,
}

impl MemoryStore {
    pub fn new(snapshot_interval: usize) -> Self {
        Self {
            event_store: MemoryEventStore::new(snapshot_interval),
            inverted_index_store: MemoryInvertedIndexStore::new(),
        }
    }

    /// Get reference to the event store component
    pub fn event_store(&self) -> &MemoryEventStore {
        &self.event_store
    }

    /// Get reference to the inverted index store component
    pub fn inverted_index_store(&self) -> &MemoryInvertedIndexStore {
        &self.inverted_index_store
    }
}

// Implement all EventStore traits by delegating to event_store
impl SnapshotIntervalProvider for MemoryStore {
    fn snapshot_interval(&self) -> usize {
        self.event_store.snapshot_interval()
    }
}

impl AggregateEventStreamer for MemoryStore {
    fn stream_events<T: AggregateRoot>(
        &self,
        id: &str,
        select: SequenceSelect,
    ) -> Stream<'_, SerializedDomainEvent, PersistenceError> {
        self.event_store.stream_events::<T>(id, select)
    }
}

#[async_trait]
impl Persister for MemoryStore {
    async fn persist(
        &self,
        domain_events: &[SerializedDomainEvent],
        integration_events: Option<&[SerializedIntegrationEvent]>,
        snapshot_update: Option<&PersistedSnapshot>,
    ) -> Result<(), PersistenceError> {
        self.event_store
            .persist(domain_events, integration_events, snapshot_update)
            .await
    }
}

#[async_trait]
impl SnapshotGetter for MemoryStore {
    async fn get_snapshot<T>(&self, id: &str) -> Result<Option<PersistedSnapshot>, PersistenceError>
    where
        T: AggregateRoot,
    {
        self.event_store.get_snapshot::<T>(id).await
    }
}

// Implement all InvertedIndexStore traits by delegating to inverted_index_store
#[async_trait]
impl AggregateIdsLoader for MemoryStore {
    async fn get_aggregate_ids(&self, keyword: &str) -> Result<Vec<String>, PersistenceError> {
        self.inverted_index_store.get_aggregate_ids(keyword).await
    }
}

#[async_trait]
impl InvertedIndexCommiter for MemoryStore {
    async fn commit(&self, aggregate_id: &str, keyword: &str) -> Result<(), PersistenceError> {
        self.inverted_index_store.commit(aggregate_id, keyword).await
    }
}

#[async_trait]
impl InvertedIndexRemover for MemoryStore {
    async fn remove(&self, aggregate_id: &str, keyword: &str) -> Result<(), PersistenceError> {
        self.inverted_index_store.remove(aggregate_id, keyword).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        aggregate_id::{AggregateId, HasIdPrefix},
        command::Command,
        domain_event::DomainEvent,
        event_id::EventIdType,
        integration_event::IntegrationEvent,
        message,
    };
    use serde_json::json;

    // Test ID type
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    struct TestId;

    impl HasIdPrefix for TestId {
        const PREFIX: &'static str = "test";
    }

    // Test command
    #[derive(Debug, Clone)]
    struct TestCommand {
        id: AggregateId<TestId>,
    }

    impl message::Message for TestCommand {
        fn name(&self) -> &'static str {
            "TestCommand"
        }
    }

    impl Command for TestCommand {
        type ID = TestId;

        fn id(&self) -> AggregateId<Self::ID> {
            self.id
        }
    }

    // Test event
    #[derive(Debug, Clone)]
    struct TestEvent {
        id: EventIdType,
    }

    impl message::Message for TestEvent {
        fn name(&self) -> &'static str {
            "TestEvent"
        }
    }

    impl DomainEvent for TestEvent {
        fn id(&self) -> EventIdType {
            self.id
        }

        fn event_type(&self) -> &'static str {
            "TestEvent"
        }
    }

    // Test integration event
    #[allow(dead_code)]
    #[derive(Debug, Clone)]
    struct TestIntegrationEvent;

    impl message::Message for TestIntegrationEvent {
        fn name(&self) -> &'static str {
            "TestIntegrationEvent"
        }
    }

    impl IntegrationEvent for TestIntegrationEvent {
        fn id(&self) -> String {
            ulid::Ulid::new().to_string()
        }

        fn event_type(&self) -> &'static str {
            "test.integration.event"
        }
    }

    // Test error
    #[derive(Debug, thiserror::Error)]
    #[allow(dead_code)]
    enum TestError {
        #[error("Test error")]
        TestError,
    }

    // Test aggregate
    #[derive(Debug)]
    struct TestAggregate {
        id: AggregateId<TestId>,
    }

    impl AggregateRoot for TestAggregate {
        const TYPE: &'static str = "TestAggregate";
        type ID = TestId;
        type Command = TestCommand;
        type DomainEvent = TestEvent;
        type Error = TestError;

        fn init(id: AggregateId<Self::ID>) -> Self {
            Self { id }
        }

        fn id(&self) -> &AggregateId<Self::ID> {
            &self.id
        }

        fn handle(&mut self, _cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error> {
            Ok(vec![TestEvent { id: EventIdType::new() }])
        }

        fn apply(&mut self, _event: Self::DomainEvent) {}
    }

    #[tokio::test]
    async fn test_memory_event_store_basic_operations() {
        let store = MemoryEventStore::new(10);

        // Test persisting events
        let events = vec![
            SerializedDomainEvent::new(
                "evt-1".to_string(),
                "agg-1".to_string(),
                1,
                "TestAggregate".to_string(),
                "TestEvent".to_string(),
                vec![],
                json!({}),
            ),
            SerializedDomainEvent::new(
                "evt-2".to_string(),
                "agg-1".to_string(),
                2,
                "TestAggregate".to_string(),
                "TestEvent".to_string(),
                vec![],
                json!({}),
            ),
        ];

        let result = store.persist(&events, None, None).await;
        assert!(result.is_ok());

        // Test streaming events
        use futures::StreamExt;
        let mut stream = store.stream_events::<TestAggregate>("agg-1", SequenceSelect::All);
        let mut count = 0;
        while let Some(result) = stream.next().await {
            let event = result.unwrap();
            count += 1;
            assert_eq!(event.seq_nr, count);
        }
        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn test_memory_inverted_index_store() {
        let store = MemoryInvertedIndexStore::new();

        // Test commit
        store.commit("agg-1", "user:john").await.unwrap();
        store.commit("agg-2", "user:john").await.unwrap();
        store.commit("agg-3", "user:jane").await.unwrap();

        // Test get_aggregate_ids
        let john_aggs = store.get_aggregate_ids("user:john").await.unwrap();
        assert_eq!(john_aggs.len(), 2);
        assert!(john_aggs.contains(&"agg-1".to_string()));
        assert!(john_aggs.contains(&"agg-2".to_string()));

        // Test remove
        store.remove("agg-1", "user:john").await.unwrap();
        let john_aggs = store.get_aggregate_ids("user:john").await.unwrap();
        assert_eq!(john_aggs.len(), 1);
        assert!(john_aggs.contains(&"agg-2".to_string()));
    }

    #[tokio::test]
    async fn test_memory_store_combined() {
        let store = MemoryStore::new(5);

        // Test event store functionality
        let events = vec![SerializedDomainEvent::new(
            "evt-1".to_string(),
            "agg-1".to_string(),
            1,
            "TestAggregate".to_string(),
            "TestEvent".to_string(),
            vec![],
            json!({"test": true}),
        )];

        store.persist(&events, None, None).await.unwrap();

        // Test inverted index functionality
        store.commit("agg-1", "type:test").await.unwrap();
        let result = store.get_aggregate_ids("type:test").await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0], "agg-1");

        // Test snapshot functionality
        let snapshot = PersistedSnapshot {
            aggregate_type: "TestAggregate".to_string(),
            aggregate_id: "agg-1".to_string(),
            aggregate: vec![1, 2, 3],
            seq_nr: 1,
            version: 1,
        };

        store.persist(&[], None, Some(&snapshot)).await.unwrap();
        let retrieved = store.get_snapshot::<TestAggregate>("agg-1").await.unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().version, 1);
    }

    #[tokio::test]
    async fn test_snapshot_interval_calculation() {
        let store = MemoryStore::new(10);

        // Test various snapshot interval calculations
        use crate::event_store::EventStore;
        assert_eq!(store.commit_snapshot_with_addl_events(0, 5), 0);
        assert_eq!(store.commit_snapshot_with_addl_events(0, 10), 10);
        assert_eq!(store.commit_snapshot_with_addl_events(5, 5), 5);
        assert_eq!(store.commit_snapshot_with_addl_events(8, 12), 12);
    }

    #[tokio::test]
    async fn test_integration_events() {
        let store = MemoryEventStore::new(10);

        let integration_events = vec![
            SerializedIntegrationEvent::new(
                "int-evt-1".to_string(),
                "agg-1".to_string(),
                "TestAggregate".to_string(),
                "test.event".to_string(),
                vec![],
            ),
            SerializedIntegrationEvent::new(
                "int-evt-2".to_string(),
                "agg-1".to_string(),
                "TestAggregate".to_string(),
                "test.event".to_string(),
                vec![],
            ),
        ];

        let result = store.persist(&[], Some(&integration_events), None).await;
        assert!(result.is_ok());

        // Verify integration events were stored
        let stored_events = store.integration_events.read().unwrap();
        assert_eq!(stored_events.len(), 2);
    }

    #[tokio::test]
    async fn test_empty_keyword_removal() {
        let store = MemoryInvertedIndexStore::new();

        // Add and remove to test empty set cleanup
        store.commit("agg-1", "temp:keyword").await.unwrap();
        assert_eq!(store.get_aggregate_ids("temp:keyword").await.unwrap().len(), 1);

        store.remove("agg-1", "temp:keyword").await.unwrap();
        assert_eq!(store.get_aggregate_ids("temp:keyword").await.unwrap().len(), 0);

        // Verify the keyword was completely removed from the map
        let indexes = store.indexes.read().unwrap();
        assert!(!indexes.contains_key("temp:keyword"));
    }
}