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
use crate::{EntityId, Store, StoreMsg};
use async_trait::async_trait;
use chrono::prelude::*;
use futures::lock::Mutex;
use riker::actors::*;
use std::fmt;
use std::sync::Arc;
pub trait Aggregate: Message {
type Update: Message;
fn id(&self) -> EntityId;
fn apply_update(&mut self, update: Self::Update);
}
pub type StoreRef<A> = ActorRef<StoreMsg<A>>;
pub trait Sys: TmpActorRefFactory + Run + Send + Sync {}
impl<T: TmpActorRefFactory + Run + Send + Sync> Sys for T {}
#[async_trait]
pub trait ES: fmt::Debug + Send + Sync + 'static {
type Args: ActorArgs;
type Agg: Aggregate;
type Cmd: Message;
type Event: Message;
fn new(cx: &Context<CQRS<Self::Cmd, Self::Event>>, args: Self::Args) -> Self;
async fn handle_command<Ctx: Sys>(&self, cmd: Self::Cmd, ctx: Ctx, store: StoreRef<Self::Agg>);
async fn handle_event<Ctx: Sys>(
&self,
_event: Self::Event,
_ctx: Ctx,
_store: StoreRef<Self::Agg>,
) {
}
}
pub struct Entity<E: ES> {
store: Option<StoreRef<E::Agg>>,
args: E::Args,
es: Option<Arc<Mutex<E>>>,
}
impl<E, Args> ActorFactoryArgs<Args> for Entity<E>
where
Args: ActorArgs,
E: ES<Args = Args>,
{
fn create_args(args: Args) -> Self {
Entity {
store: None,
es: None,
args,
}
}
}
impl<E: ES> Actor for Entity<E> {
type Msg = CQRS<E::Cmd, E::Event>;
fn pre_start(&mut self, ctx: &Context<Self::Msg>) {
self.es = Some(Arc::new(Mutex::new(E::new(ctx, self.args.clone()))));
self.store = Some(ctx.actor_of::<Store<E::Agg>>(ctx.myself().name()).unwrap());
}
fn recv(&mut self, ctx: &Context<Self::Msg>, msg: Self::Msg, sender: Sender) {
match msg {
CQRS::Query(q) => self.receive(ctx, q, sender),
CQRS::Cmd(cmd) => {
let sys = ctx.system.clone();
let store = self.store.as_ref().unwrap().clone();
let es = self.es.clone();
ctx.system.exec.spawn_ok(async move {
debug!("processing command {:?}", cmd.clone());
es.unwrap()
.lock()
.await
.handle_command(cmd, sys, store)
.await;
});
}
CQRS::Event(event) => {
let sys = ctx.system.clone();
let store = self.store.as_ref().unwrap().clone();
let es = self.es.clone();
ctx.system.exec.spawn_ok(async move {
debug!("processing event {:?}", event.clone());
es.unwrap()
.lock()
.await
.handle_event(event, sys, store)
.await;
});
}
};
}
}
impl<E: ES> Receive<Query> for Entity<E> {
type Msg = CQRS<E::Cmd, E::Event>;
fn receive(&mut self, _ctx: &Context<Self::Msg>, q: Query, sender: Sender) {
match q {
Query::One(id) => self.store.as_ref().unwrap().tell((id, Utc::now()), sender),
Query::All => self.store.as_ref().unwrap().tell(..Utc::now(), sender),
}
}
}
#[derive(Clone, Debug)]
pub enum CQRS<C, E> {
Cmd(C),
Event(E),
Query(Query),
}
impl<C, E> From<Query> for CQRS<C, E> {
fn from(q: Query) -> Self {
CQRS::Query(q)
}
}
#[derive(Clone, Debug)]
pub enum Query {
All,
One(EntityId),
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::tests::{Op, TestCount};
use crate::Event;
use futures::executor::block_on;
use riker_patterns::ask::ask;
use std::time::Duration;
#[derive(Debug)]
struct Test {
sys: ActorSystem,
_foo: String,
}
#[async_trait]
impl ES for Test {
type Args = (u8, String);
type Agg = TestCount;
type Cmd = TestCmd;
type Event = ();
fn new(cx: &Context<CQRS<Self::Cmd, Self::Event>>, (num, txt): Self::Args) -> Self {
Test {
_foo: format!("{}{}", num, txt),
sys: cx.system.clone(),
}
}
async fn handle_command<Ctx: Sys>(
&self,
cmd: Self::Cmd,
cx: Ctx,
store: StoreRef<Self::Agg>,
) {
match cmd {
TestCmd::Create42 => store.tell(Event::Create(TestCount::new(42)), None),
TestCmd::Create99 => store.tell(Event::Create(TestCount::new(99)), None),
TestCmd::Double(id) => {
let res: TestCount = ask(&cx, &store, (id, Utc::now())).await;
store.tell(Event::Update(res.id(), Op::Add(res.count)), None)
}
}
}
}
#[derive(Clone, Debug)]
enum TestCmd {
Create42,
Create99,
Double(EntityId),
}
#[test]
fn command_n_query() {
let sys = ActorSystem::new().unwrap();
let entity = sys
.actor_of_args::<Entity<Test>, _>("counts", (42, "42".into()))
.unwrap();
entity.tell(CQRS::Cmd(TestCmd::Create42), None);
entity.tell(CQRS::Cmd(TestCmd::Create99), None);
std::thread::sleep(Duration::from_millis(20));
let counts: Vec<TestCount> = block_on(ask(&sys, &entity, Query::All));
assert_eq!(counts.len(), 2);
let count42 = counts.iter().find(|c| c.count == 42);
let count99 = counts.iter().find(|c| c.count == 99);
assert!(count42.is_some());
assert!(count99.is_some());
let id = count42.unwrap().id();
entity.tell(CQRS::Cmd(TestCmd::Double(id)), None);
std::thread::sleep(Duration::from_millis(20));
let result: TestCount = block_on(ask(&sys, &entity, Query::One(id)));
assert_eq!(result.count, 84);
}
}