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
use crate::{Commit, EntityId, EntityName, Store, StoreMsg};
use async_trait::async_trait;
use chrono::prelude::*;
use futures::lock::Mutex;
use riker::actors::*;
use std::fmt;
use std::sync::Arc;

/// An Aggregate is the projected data of a series of events of an entity,
/// given an initial state update events are applied to it until it reaches the desired state.
pub trait Model: Message {
    type Change: Message;
    fn id(&self) -> EntityId;
    fn apply_change(&mut self, change: Self::Change);
}

// Dummy data model for tests
impl Model for () {
    type Change = ();
    fn id(&self) -> EntityId {
        "dummy".into()
    }
    fn apply_change(&mut self, _update: Self::Change) {}
}

pub type StoreRef<A> = ActorRef<StoreMsg<A>>;
pub trait Sys: TmpActorRefFactory + Run + Send + Sync {}
impl<T: TmpActorRefFactory + Run + Send + Sync> Sys for T {}

/// Implement this trait to allow your entity handle external commands
#[async_trait]
pub trait ES: EntityName + fmt::Debug + Send + Sync + 'static {
    type Args: ActorArgs;
    type Model: Model;
    type Cmd: Message;
    type Error: fmt::Debug;

    fn new(cx: &Context<CQRS<Self::Cmd>>, args: Self::Args) -> Self;

    async fn handle_command(&mut self, _cmd: Self::Cmd)
        -> Result<Commit<Self::Model>, Self::Error>;
}

/// Entity is an actor that dispatches commands and manages aggregates that are being queried
pub struct Entity<E: ES> {
    store: Option<StoreRef<E::Model>>,
    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>;

    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::Model>>(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 store = self.store.as_ref().unwrap().clone();
                let es = self.es.clone();
                ctx.system.exec.spawn_ok(async move {
                    let cmd_dbg = format!("{:?}", cmd);
                    debug!("processing command {}", cmd_dbg);
                    let commit = es
                        .unwrap()
                        .lock()
                        .await
                        .handle_command(cmd)
                        .await
                        .expect("Failed handling command");
                    let entity_id = commit.entity_id();
                    store.tell(commit, None);

                    if let Some(sender) = sender {
                        let _ = sender
                            .try_tell(entity_id, None)
                            .map_err(|_| warn!("Couldn't signal completion of {}", cmd_dbg));
                    }
                });
            }
        };
    }
}

impl<E: ES> Receive<Query> for Entity<E> {
    type Msg = CQRS<E::Cmd>;
    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> {
    Cmd(C),
    Query(Query),
}
impl<C> From<Query> for CQRS<C> {
    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;

    #[derive(Debug)]
    struct Test {
        sys: ActorSystem,
        entity: ActorRef<CQRS<<Self as ES>::Cmd>>,
        _foo: String,
    }
    impl EntityName for Test {
        const NAME: &'static str = "test-entity";
    }
    #[async_trait]
    impl ES for Test {
        type Args = (u8, String);
        type Model = TestCount;
        type Cmd = TestCmd;
        type Error = String;

        fn new(cx: &Context<CQRS<Self::Cmd>>, (num, txt): Self::Args) -> Self {
            Test {
                _foo: format!("{}{}", num, txt),
                sys: cx.system.clone(),
                entity: cx.myself(),
            }
        }

        async fn handle_command(
            &mut self,
            cmd: Self::Cmd,
        ) -> Result<Commit<Self::Model>, Self::Error> {
            let event = match cmd {
                TestCmd::Create42 => Event::Create(TestCount::new(42)),
                TestCmd::Create99 => Event::Create(TestCount::new(99)),
                TestCmd::Double(id) => {
                    let res: Option<TestCount> = ask(&self.sys, &self.entity, Query::One(id)).await;
                    let res = res.ok_or("Not found")?;
                    Event::Change(res.id(), Op::Add(res.count))
                }
            };
            Ok(event.into())
        }
    }
    #[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();

        let _: EntityId = block_on(ask(&sys, &entity, CQRS::Cmd(TestCmd::Create42)));
        let _: EntityId = block_on(ask(&sys, &entity, CQRS::Cmd(TestCmd::Create99)));
        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();
        let _: EntityId = block_on(ask(&sys, &entity, CQRS::Cmd(TestCmd::Double(id))));
        let result: Option<TestCount> = block_on(ask(&sys, &entity, Query::One(id)));
        assert_eq!(result.unwrap().count, 84);
    }
}