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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use crate::{
    aggregate_id::{AggregateId, HasIdPrefix},
    command::Command,
    domain_event::DomainEvent,
};
use std::fmt;

/// Trait that aggregates must implement to provide their ID prefix
/// and handle commands and domain events.
pub trait AggregateRoot: fmt::Debug + Send + Sync + 'static {
    const TYPE: &'static str;
    type ID: HasIdPrefix;
    type Command: Command;
    type DomainEvent: DomainEvent;
    type Error: std::error::Error;

    /// Initializes a new aggregate with the given ID.
    fn init(id: AggregateId<Self::ID>) -> Self;

    /// Returns the ID of the aggregate.
    fn id(&self) -> &AggregateId<Self::ID>;

    /// Handles a command and returns a domain event or an error.
    fn handle(&mut self, cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error>;

    /// Applies changes to the aggregate's state.
    fn apply(&mut self, event: Self::DomainEvent);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{event_id::EventIdType, message, test::TestFramework};
    use std::sync::Arc;

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

    impl HasIdPrefix for UserId {
        const PREFIX: &'static str = "usr";
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    struct OrderId;

    impl HasIdPrefix for OrderId {
        const PREFIX: &'static str = "ord";
    }

    // Commands
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    enum OrderCommand {
        Create {
            id: AggregateId<OrderId>,
            user_id: AggregateId<UserId>,
            total_amount: u64,
        },
        Confirm {
            id: AggregateId<OrderId>,
        },
        Ship {
            id: AggregateId<OrderId>,
        },
        Deliver {
            id: AggregateId<OrderId>,
        },
    }

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

    impl Command for OrderCommand {
        type ID = OrderId;

        fn id(&self) -> AggregateId<Self::ID> {
            match self {
                Self::Create { id, .. } => *id,
                Self::Confirm { id } => *id,
                Self::Ship { id } => *id,
                Self::Deliver { id } => *id,
            }
        }
    }

    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    enum UserCommand {
        Create {
            id: AggregateId<UserId>,
            name: String,
            email: String,
        },
        UpdateEmail {
            id: AggregateId<UserId>,
            email: String,
        },
    }

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

    impl Command for UserCommand {
        type ID = UserId;

        fn id(&self) -> AggregateId<Self::ID> {
            match self {
                Self::Create { id, .. } => *id,
                Self::UpdateEmail { id, .. } => *id,
            }
        }
    }

    // Domain Events
    #[derive(Debug, Clone, PartialEq)]
    #[allow(dead_code)]
    enum OrderEvent {
        Created {
            id: EventIdType,
            user_id: AggregateId<UserId>,
            total_amount: u64,
        },
        Confirmed {
            id: EventIdType,
        },
        Shipped {
            id: EventIdType,
        },
        Delivered {
            id: EventIdType,
        },
    }

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

    impl DomainEvent for OrderEvent {
        fn id(&self) -> EventIdType {
            match self {
                Self::Created { id, .. } => *id,
                Self::Confirmed { id } => *id,
                Self::Shipped { id } => *id,
                Self::Delivered { id } => *id,
            }
        }

        fn event_type(&self) -> &'static str {
            match self {
                Self::Created { .. } => "OrderCreated",
                Self::Confirmed { .. } => "OrderConfirmed",
                Self::Shipped { .. } => "OrderShipped",
                Self::Delivered { .. } => "OrderDelivered",
            }
        }
    }

    #[derive(Debug, Clone, PartialEq)]
    #[allow(dead_code)]
    enum UserEvent {
        Created {
            id: EventIdType,
            name: String,
            email: String,
        },
        EmailUpdated {
            id: EventIdType,
            old_email: String,
            new_email: String,
        },
    }

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

    impl DomainEvent for UserEvent {
        fn id(&self) -> EventIdType {
            match self {
                Self::Created { id, .. } => *id,
                Self::EmailUpdated { id, .. } => *id,
            }
        }

        fn event_type(&self) -> &'static str {
            match self {
                Self::Created { .. } => "UserCreated",
                Self::EmailUpdated { .. } => "UserEmailUpdated",
            }
        }
    }

    // Errors
    #[derive(Debug, thiserror::Error)]
    #[allow(dead_code)]
    enum OrderError {
        #[error("Invalid state transition")]
        InvalidStateTransition,
        #[error("Order already exists")]
        AlreadyExists,
    }

    #[derive(Debug, thiserror::Error)]
    #[allow(dead_code)]
    enum UserError {
        #[error("Invalid email format")]
        InvalidEmail,
        #[error("User already exists")]
        AlreadyExists,
    }

    // Test Aggregates
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct OrderAggregate {
        id: AggregateId<OrderId>,
        user_id: AggregateId<UserId>,
        total_amount: u64,
        status: OrderStatus,
    }

    #[derive(Debug, Clone, PartialEq)]
    enum OrderStatus {
        Pending,
        Confirmed,
        Shipped,
        Delivered,
    }

    impl AggregateRoot for OrderAggregate {
        const TYPE: &'static str = "Order";
        type ID = OrderId;
        type Command = OrderCommand;
        type DomainEvent = OrderEvent;
        type Error = OrderError;

        fn init(id: AggregateId<Self::ID>) -> Self {
            Self {
                id,
                user_id: AggregateId::<UserId>::new(), // Default user ID
                total_amount: 0,
                status: OrderStatus::Pending,
            }
        }

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

        fn handle(&mut self, cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error> {
            match cmd {
                OrderCommand::Create {
                    id: _,
                    user_id,
                    total_amount,
                } => Ok(vec![OrderEvent::Created {
                    id: EventIdType::new(),
                    user_id,
                    total_amount,
                }]),
                OrderCommand::Confirm { id: _ } => {
                    if self.status != OrderStatus::Pending {
                        return Err(OrderError::InvalidStateTransition);
                    }
                    Ok(vec![OrderEvent::Confirmed { id: EventIdType::new() }])
                }
                OrderCommand::Ship { id: _ } => {
                    if self.status != OrderStatus::Confirmed {
                        return Err(OrderError::InvalidStateTransition);
                    }
                    Ok(vec![OrderEvent::Shipped { id: EventIdType::new() }])
                }
                OrderCommand::Deliver { id: _ } => {
                    if self.status != OrderStatus::Shipped {
                        return Err(OrderError::InvalidStateTransition);
                    }
                    Ok(vec![OrderEvent::Delivered { id: EventIdType::new() }])
                }
            }
        }

        fn apply(&mut self, event: Self::DomainEvent) {
            match event {
                OrderEvent::Created {
                    id: _,
                    user_id,
                    total_amount,
                } => {
                    self.user_id = user_id;
                    self.total_amount = total_amount;
                    self.status = OrderStatus::Pending;
                }
                OrderEvent::Confirmed { id: _ } => {
                    self.status = OrderStatus::Confirmed;
                }
                OrderEvent::Shipped { id: _ } => {
                    self.status = OrderStatus::Shipped;
                }
                OrderEvent::Delivered { id: _ } => {
                    self.status = OrderStatus::Delivered;
                }
            }
        }
    }

    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct UserAggregate {
        id: AggregateId<UserId>,
        name: String,
        email: String,
    }

    impl AggregateRoot for UserAggregate {
        const TYPE: &'static str = "User";
        type ID = UserId;
        type Command = UserCommand;
        type DomainEvent = UserEvent;
        type Error = UserError;

        fn init(id: AggregateId<Self::ID>) -> Self {
            Self {
                id,
                name: String::new(),
                email: String::new(),
            }
        }

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

        fn handle(&mut self, cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error> {
            match cmd {
                UserCommand::Create { id: _, name, email } => {
                    if !email.contains('@') {
                        return Err(UserError::InvalidEmail);
                    }
                    Ok(vec![UserEvent::Created {
                        id: EventIdType::new(),
                        name,
                        email,
                    }])
                }
                UserCommand::UpdateEmail { id: _, email } => {
                    if !email.contains('@') {
                        return Err(UserError::InvalidEmail);
                    }
                    let old_email = self.email.clone();
                    Ok(vec![UserEvent::EmailUpdated {
                        id: EventIdType::new(),
                        old_email,
                        new_email: email,
                    }])
                }
            }
        }

        fn apply(&mut self, event: Self::DomainEvent) {
            match event {
                UserEvent::Created { id: _, name, email } => {
                    self.name = name;
                    self.email = email;
                }
                UserEvent::EmailUpdated {
                    id: _,
                    old_email: _,
                    new_email,
                } => {
                    self.email = new_email;
                }
            }
        }
    }

    #[test]
    fn test_aggregate_id_access() {
        let order = OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 10000,
            status: OrderStatus::Pending,
        };

        let order_id = order.id();
        assert!(order_id.to_string().starts_with("ord-"));
    }

    #[test]
    fn test_different_aggregate_types() {
        let order = OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 5000,
            status: OrderStatus::Confirmed,
        };

        let user = UserAggregate {
            id: AggregateId::<UserId>::new(),
            name: "Test User".to_string(),
            email: "test@example.com".to_string(),
        };

        // Ensure different ID types
        assert!(order.id().to_string().starts_with("ord-"));
        assert!(user.id().to_string().starts_with("usr-"));
    }

    #[test]
    fn test_aggregate_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}

        assert_send_sync::<OrderAggregate>();
        assert_send_sync::<UserAggregate>();
    }

    #[test]
    fn test_aggregate_static_lifetime() {
        fn assert_static<T: 'static>() {}

        assert_static::<OrderAggregate>();
        assert_static::<UserAggregate>();
    }

    #[test]
    fn test_aggregate_in_arc() {
        let order = Arc::new(OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 15000,
            status: OrderStatus::Shipped,
        });

        let order_clone = Arc::clone(&order);
        assert_eq!(order.id().to_string(), order_clone.id().to_string());
    }

    #[test]
    fn test_aggregate_with_state_changes() {
        let mut order = OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 20000,
            status: OrderStatus::Pending,
        };

        // Simulate state changes (in real CQRS, this would be through events)
        order.status = OrderStatus::Confirmed;
        assert_eq!(order.status, OrderStatus::Confirmed);

        order.status = OrderStatus::Shipped;
        assert_eq!(order.status, OrderStatus::Shipped);

        // ID should remain constant
        let id_before = order.id().to_string();
        order.status = OrderStatus::Delivered;
        let id_after = order.id().to_string();
        assert_eq!(id_before, id_after);
    }

    #[test]
    fn test_aggregate_repository_simulation() {
        use std::collections::HashMap;

        // Simulate a simple repository
        struct Repository<A: AggregateRoot> {
            storage: HashMap<String, A>,
        }

        impl<A: AggregateRoot> Repository<A> {
            fn new() -> Self {
                Self {
                    storage: HashMap::new(),
                }
            }

            fn save(&mut self, aggregate: A) {
                let id = aggregate.id().to_string();
                self.storage.insert(id, aggregate);
            }

            fn get(&self, id: &str) -> Option<&A> {
                self.storage.get(id)
            }
        }

        let mut order_repo = Repository::<OrderAggregate>::new();
        let order = OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 30000,
            status: OrderStatus::Pending,
        };

        let order_id_string = order.id().to_string();
        order_repo.save(order);

        let retrieved = order_repo.get(&order_id_string);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().total_amount, 30000);
    }

    #[test]
    fn test_order_command_handling() {
        let order_id = AggregateId::<OrderId>::new();
        let user_id = AggregateId::<UserId>::new();
        let order = OrderAggregate::init(order_id);

        // Test create command
        TestFramework::with(order.clone())
            .given_no_previous_events()
            .when(OrderCommand::Create {
                id: order_id,
                user_id,
                total_amount: 25000,
            })
            .then_verify(|result| {
                assert!(result.is_ok());
                let events = result.unwrap();
                assert_eq!(events.len(), 1);
                match &events[0] {
                    OrderEvent::Created {
                        id: _,
                        user_id: uid,
                        total_amount,
                    } => {
                        assert_eq!(uid, &user_id);
                        assert_eq!(total_amount, &25000);
                    }
                    _ => panic!("Expected OrderEvent::Created"),
                }
            });

        // Test confirm command from pending state
        TestFramework::with(order.clone())
            .given(vec![OrderEvent::Created {
                id: EventIdType::new(),
                user_id,
                total_amount: 25000,
            }])
            .when(OrderCommand::Confirm { id: order_id })
            .then_verify(|result| {
                assert!(result.is_ok());
                let events = result.unwrap();
                assert_eq!(events.len(), 1);
                assert!(matches!(events[0], OrderEvent::Confirmed { .. }));
            });

        // Test ship command from confirmed state
        TestFramework::with(order.clone())
            .given(vec![
                OrderEvent::Created {
                    id: EventIdType::new(),
                    user_id,
                    total_amount: 25000,
                },
                OrderEvent::Confirmed { id: EventIdType::new() },
            ])
            .when(OrderCommand::Ship { id: order_id })
            .then_verify(|result| {
                assert!(result.is_ok());
                let events = result.unwrap();
                assert_eq!(events.len(), 1);
                assert!(matches!(events[0], OrderEvent::Shipped { .. }));
            });

        // Test invalid state transition - trying to confirm when already shipped
        TestFramework::with(order)
            .given(vec![
                OrderEvent::Created {
                    id: EventIdType::new(),
                    user_id,
                    total_amount: 25000,
                },
                OrderEvent::Confirmed { id: EventIdType::new() },
                OrderEvent::Shipped { id: EventIdType::new() },
            ])
            .when(OrderCommand::Confirm { id: order_id })
            .then_expect_error_matches(|e| matches!(e, OrderError::InvalidStateTransition));
    }

    #[test]
    fn test_user_command_handling() {
        let user_id = AggregateId::<UserId>::new();
        let user = UserAggregate::init(user_id);

        // Test create command with valid email
        TestFramework::with(user.clone())
            .given_no_previous_events()
            .when(UserCommand::Create {
                id: user_id,
                name: "John Doe".to_string(),
                email: "john@example.com".to_string(),
            })
            .then_verify(|result| {
                assert!(result.is_ok());
                let events = result.unwrap();
                assert_eq!(events.len(), 1);
                match &events[0] {
                    UserEvent::Created { id: _, name, email } => {
                        assert_eq!(name, "John Doe");
                        assert_eq!(email, "john@example.com");
                    }
                    _ => panic!("Expected UserEvent::Created"),
                }
            });

        // Test email update with valid email
        TestFramework::with(user.clone())
            .given(vec![UserEvent::Created {
                id: EventIdType::new(),
                name: "John Doe".to_string(),
                email: "john@example.com".to_string(),
            }])
            .when(UserCommand::UpdateEmail {
                id: user_id,
                email: "john.doe@example.com".to_string(),
            })
            .then_verify(|result| {
                assert!(result.is_ok());
                let events = result.unwrap();
                assert_eq!(events.len(), 1);
                match &events[0] {
                    UserEvent::EmailUpdated {
                        id: _,
                        old_email,
                        new_email,
                    } => {
                        assert_eq!(old_email, "john@example.com");
                        assert_eq!(new_email, "john.doe@example.com");
                    }
                    _ => panic!("Expected UserEvent::EmailUpdated"),
                }
            });

        // Test create command with invalid email
        TestFramework::with(user.clone())
            .given_no_previous_events()
            .when(UserCommand::Create {
                id: user_id,
                name: "John Doe".to_string(),
                email: "invalid-email".to_string(),
            })
            .then_expect_error_matches(|e| matches!(e, UserError::InvalidEmail));

        // Test email update with invalid email
        TestFramework::with(user)
            .given(vec![UserEvent::Created {
                id: EventIdType::new(),
                name: "John Doe".to_string(),
                email: "john@example.com".to_string(),
            }])
            .when(UserCommand::UpdateEmail {
                id: user_id,
                email: "invalid-email".to_string(),
            })
            .then_expect_error_matches(|e| matches!(e, UserError::InvalidEmail));
    }

    #[test]
    fn test_command_and_event_traits() {
        fn assert_command<T: Command>() {}
        fn assert_domain_event<T: DomainEvent>() {}

        assert_command::<OrderCommand>();
        assert_command::<UserCommand>();
        assert_domain_event::<OrderEvent>();
        assert_domain_event::<UserEvent>();
    }

    #[test]
    fn test_aggregate_init() {
        // Test OrderAggregate init
        let order_id = AggregateId::<OrderId>::new();
        let order = OrderAggregate::init(order_id);

        assert_eq!(order.id, order_id);
        assert_eq!(order.total_amount, 0);
        assert_eq!(order.status, OrderStatus::Pending);
        assert!(order.user_id.to_string().starts_with("usr-"));

        // Test UserAggregate init
        let user_id = AggregateId::<UserId>::new();
        let user = UserAggregate::init(user_id);

        assert_eq!(user.id, user_id);
        assert_eq!(user.name, "");
        assert_eq!(user.email, "");
    }

    #[test]
    fn test_apply_method() {
        // Test OrderAggregate apply
        let mut order = OrderAggregate {
            id: AggregateId::<OrderId>::new(),
            user_id: AggregateId::<UserId>::new(),
            total_amount: 0,
            status: OrderStatus::Pending,
        };

        // Apply Created event
        let user_id = AggregateId::<UserId>::new();
        order.apply(OrderEvent::Created {
            id: EventIdType::new(),
            user_id,
            total_amount: 10000,
        });
        assert_eq!(order.user_id, user_id);
        assert_eq!(order.total_amount, 10000);
        assert_eq!(order.status, OrderStatus::Pending);

        // Apply Confirmed event
        order.apply(OrderEvent::Confirmed { id: EventIdType::new() });
        assert_eq!(order.status, OrderStatus::Confirmed);

        // Apply Shipped event
        order.apply(OrderEvent::Shipped { id: EventIdType::new() });
        assert_eq!(order.status, OrderStatus::Shipped);

        // Apply Delivered event
        order.apply(OrderEvent::Delivered { id: EventIdType::new() });
        assert_eq!(order.status, OrderStatus::Delivered);

        // Test UserAggregate apply
        let mut user = UserAggregate {
            id: AggregateId::<UserId>::new(),
            name: String::new(),
            email: String::new(),
        };

        // Apply Created event
        user.apply(UserEvent::Created {
            id: EventIdType::new(),
            name: "John Doe".to_string(),
            email: "john@example.com".to_string(),
        });
        assert_eq!(user.name, "John Doe");
        assert_eq!(user.email, "john@example.com");

        // Apply EmailUpdated event
        user.apply(UserEvent::EmailUpdated {
            id: EventIdType::new(),
            old_email: "john@example.com".to_string(),
            new_email: "john.doe@example.com".to_string(),
        });
        assert_eq!(user.email, "john.doe@example.com");
        assert_eq!(user.name, "John Doe"); // Name should remain unchanged
    }
}