-
Notifications
You must be signed in to change notification settings - Fork 4
/
upcasting.rs
215 lines (177 loc) · 6.35 KB
/
upcasting.rs
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
//! This example demonstrates how it is possible to use the schema mechanism for upcasting.
//!
//! The module `before_upcasting` represents the code in the system before the upcasting of an
//! event. The first part of the example shows the state of the system before the event is
//! upcasted.
//!
//! The module `after_upcasting` represents the code in the system after the upcasting of an
//! schema. Similarly, the second part of the example shows how the upcasting of the event will
//! play out in a running system.
//!
//! Note the only place that still required to reference the original shape of the event is in the
//! schema itself and the rest of the system can simply operate as if the event has always been of
//! this shape.
use esrs::manager::AggregateManager;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;
use esrs::store::postgres::{PgStore, PgStoreBuilder};
use esrs::store::EventStore;
use esrs::AggregateState;
use crate::common::CommonError;
pub(crate) enum Command {}
mod before_upcasting {
//! This module represents the code of the initial iteration of the system.
use super::*;
pub(crate) struct Aggregate;
impl esrs::Aggregate for Aggregate {
const NAME: &'static str = "schema_upcasting";
type State = State;
type Command = Command;
type Event = Event;
type Error = CommonError;
fn handle_command(_state: &Self::State, command: Self::Command) -> Result<Vec<Self::Event>, Self::Error> {
match command {}
}
fn apply_event(state: Self::State, payload: Self::Event) -> Self::State {
let mut events = state.events;
events.push(payload);
Self::State { events }
}
}
#[derive(Default)]
pub(crate) struct State {
pub(crate) events: Vec<Event>,
}
pub enum Event {
A,
B { contents: String },
C { count: u64 },
}
#[derive(Deserialize, Serialize)]
pub enum Schema {
A,
B { contents: String },
C { count: u64 },
}
#[cfg(feature = "upcasting")]
impl esrs::event::Upcaster for Schema {}
impl esrs::store::postgres::Schema<Event> for Schema {
fn from_event(value: Event) -> Self {
match value {
Event::A => Schema::A,
Event::B { contents } => Schema::B { contents },
Event::C { count } => Schema::C { count },
}
}
fn to_event(self) -> Option<Event> {
match self {
Self::A => Some(Event::A),
Self::B { contents } => Some(Event::B { contents }),
Self::C { count } => Some(Event::C { count }),
}
}
}
}
mod after_upcasting {
//! This module represents the code after the upcasting has been implemented
use super::*;
pub(crate) struct Aggregate;
impl esrs::Aggregate for Aggregate {
const NAME: &'static str = "schema_upcasting";
type State = State;
type Command = Command;
type Event = Event;
type Error = CommonError;
fn handle_command(_state: &Self::State, command: Self::Command) -> Result<Vec<Self::Event>, Self::Error> {
match command {}
}
fn apply_event(state: Self::State, payload: Self::Event) -> Self::State {
let mut events = state.events;
events.push(payload);
Self::State { events }
}
}
#[derive(Default)]
pub(crate) struct State {
pub(crate) events: Vec<Event>,
}
pub enum Event {
A,
B { contents: String, count: u64 },
C { count: u64 },
}
#[derive(Deserialize, Serialize)]
pub enum Schema {
A,
B { contents: String },
C { count: u64 },
D { contents: String, count: u64 },
}
#[cfg(feature = "upcasting")]
impl esrs::event::Upcaster for Schema {}
impl esrs::store::postgres::Schema<Event> for Schema {
fn from_event(value: Event) -> Self {
match value {
Event::A => Schema::A,
Event::C { count } => Schema::C { count },
Event::B { contents, count } => Schema::D { contents, count },
}
}
fn to_event(self) -> Option<Event> {
match self {
Schema::A => Some(Event::A),
Schema::B { contents } => Some(Event::B { contents, count: 1 }),
Schema::C { count } => Some(Event::C { count }),
Schema::D { contents, count } => Some(Event::B { contents, count }),
}
}
}
}
pub(crate) async fn example(pool: PgPool) {
let aggregate_id: Uuid = Uuid::new_v4();
// Initial state of the system
{
use before_upcasting::{Aggregate, Event, Schema};
let store: PgStore<Aggregate, _> = PgStoreBuilder::new(pool.clone())
.with_schema::<Schema>()
.try_build()
.await
.unwrap();
let events = vec![
Event::A,
Event::B {
contents: "goodbye world".to_owned(),
},
Event::C { count: 42 },
];
let mut state = AggregateState::with_id(aggregate_id);
let events = store.persist(&mut state, events).await.unwrap();
assert_eq!(events.len(), 3);
}
// After upcasting before_upcasting::Event::B to after_upcasting::Event::B
{
use after_upcasting::{Aggregate, Event, Schema};
let store: PgStore<Aggregate, _> = PgStoreBuilder::new(pool.clone())
.with_schema::<Schema>()
.try_build()
.await
.unwrap();
let events = vec![
Event::A,
Event::C { count: 42 },
Event::B {
contents: "this is the new events".to_owned(),
count: 21,
},
];
let manager = AggregateManager::new(store.clone());
let mut state = manager.load(aggregate_id).await.unwrap().unwrap();
let _ = store.persist(&mut state, events).await.unwrap();
let persisted_events = manager.load(aggregate_id).await.unwrap().unwrap().into_inner().events;
// All the events are visible
assert_eq!(persisted_events.len(), 6);
// The events have been upcasted
assert!(matches!(persisted_events[1], Event::B { count: 1, .. }));
}
}