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
use crateState;
/// The `Aggregate` trait is used to manage the life-cycle of implementations of
/// `State`.
///
/// Each `Aggregate` implementation will usually have its own `State`
/// implementation that it manages.
///
/// Note that `Aggregate` is also explicitly marked as `Send + Sync` due to
/// usages of the `async-trait` crate on the `Store` trait.
///
/// Implementations of `Aggregate` must specify the type of `Identifier` used as
/// well as the type of `State` that will be managed.
///
/// An example implementation of `Aggregate` for a fictional "Order" entity is
/// provided below. This example aligns with the examples given for the other
/// core traits.
///
/// ```
/// #[derive(Error, Debug, PartialEq)]
/// enum OrderAggregateError {
/// #[error("a payment of this amount would leave a negative balance owing")]
/// Overpayment
/// }
///
/// struct OrderAggregate {
/// state: OrderState,
/// next_version: u32,
/// pending_events: Vec<Event>
/// }
///
/// impl ljprs_es::Aggregate for OrderAggregate {
/// type Identifier = u128;
/// type State = OrderState;
///
/// fn from_state(state: Self::State, next_version: u32) -> Self {
/// OrderAggregate {
/// state: state,
/// next_version: next_version,
/// pending_events: Vec::with_capacity(0)
/// }
/// }
///
/// fn clone_state(&self) -> Self::State {
/// self.state.clone()
/// }
///
/// fn take(self) -> (Self::State, u32, Vec<<Self::State as ljprs_es::State>::Event>) {
/// (self.state, self.next_version, self.pending_events)
/// }
/// }
///
/// impl OrderAggregate {
/// fn new(product_name: String, balance_owing: f64) -> Self {
/// let mut state = OrderState::default();
/// let event = Event::OrderCreated(OrderCreatedEvent {
/// id: rand::thread_rng().gen(),
/// product_name: product_name,
/// balance_owing: balance_owing
/// });
///
/// state.apply(&event);
///
/// OrderAggregate {
/// state: state,
/// next_version: 1,
/// pending_events: vec!(event)
/// }
/// }
///
/// fn make_payment(&mut self, amount: f64) -> Result<(), OrderAggregateError> {
/// if self.state.balance_owing - amount < 0f64 {
/// return Err(OrderAggregateError::Overpayment);
/// }
///
/// let event_payment = Event::OrderPayment(OrderPaymentEvent {
/// id: self.state.id,
/// amount: amount
/// });
///
/// self.state.apply(&event_payment);
/// self.pending_events.push(event_payment);
/// self.next_version += 1;
///
/// Ok(())
/// }
/// }
/// ```