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
//! Module containing support for Domain [Command]s.
//!
//! Following the Domain-driven Design definition, a [Command] expresses the
//! intent of an Actor (e.g. a Customer, a User, a System, etc.) to modify
//! the state of the system in some way.
//!
//! To modify the state of the system through a [Command], you must
//! implement a Command [Handler] which, in an Event-sourced system,
//! should make use of an [Aggregate] to evaluate the validity of the Command
//! submitted, and emit Domain [Event]s as a result (through the Event [Store]).
//!
//! Check out the type documentation exported in this module.

pub mod test;

use std::future::Future;

use async_trait::async_trait;

use crate::message;

/// A Command represents an intent by an Actor (e.g. a User, or a System)
/// to mutate the state of the system.
///
/// In an event-sourced system, a Command is represented as a [Message].
pub type Envelope<T> = message::Envelope<T>;

/// A software component that is able to handle [Command]s of a certain type,
/// and mutate the state as a result of the command handling, or fail.
///
/// In an event-sourced system, the [Command] Handler
/// should use an [Aggregate][crate::aggregate::Aggregate] to evaluate
/// a [Command] to ensure business invariants are respected.
#[async_trait]
pub trait Handler<T>: Send + Sync
where
    T: message::Message,
{
    /// The error type returned by the Handler while handling a [Command].
    type Error: Send + Sync;

    /// Handles a [Command] and returns an error if the handling has failed.
    ///
    /// Since [Command]s are solely modifying the state of the system,
    /// they do not return anything to the caller but the result of the operation
    /// (expressed by a [Result] type).
    async fn handle(&self, command: Envelope<T>) -> Result<(), Self::Error>;
}

#[async_trait]
impl<T, Err, F, Fut> Handler<T> for F
where
    T: message::Message + Send + Sync + 'static,
    Err: Send + Sync,
    F: Send + Sync + Fn(Envelope<T>) -> Fut,
    Fut: Send + Sync + Future<Output = Result<(), Err>>,
{
    type Error = Err;

    async fn handle(&self, command: Envelope<T>) -> Result<(), Self::Error> {
        self(command).await
    }
}

#[cfg(test)]
mod test_user_domain {
    use std::sync::Arc;

    use async_trait::async_trait;

    use crate::aggregate::test_user_domain::{User, UserEvent};
    use crate::{aggregate, command, event, message};

    struct UserService(Arc<dyn aggregate::Repository<User>>);

    impl<R> From<R> for UserService
    where
        R: aggregate::Repository<User> + 'static,
    {
        fn from(repository: R) -> Self {
            Self(Arc::new(repository))
        }
    }

    struct CreateUser {
        email: String,
        password: String,
    }

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

    #[async_trait]
    impl command::Handler<CreateUser> for UserService {
        type Error = anyhow::Error;

        async fn handle(&self, command: command::Envelope<CreateUser>) -> Result<(), Self::Error> {
            let command = command.message;
            let mut user = aggregate::Root::<User>::create(command.email, command.password)?;

            self.0.save(&mut user).await?;

            Ok(())
        }
    }

    struct ChangeUserPassword {
        email: String,
        password: String,
    }

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

    #[async_trait]
    impl command::Handler<ChangeUserPassword> for UserService {
        type Error = anyhow::Error;

        async fn handle(
            &self,
            command: command::Envelope<ChangeUserPassword>,
        ) -> Result<(), Self::Error> {
            let command = command.message;

            let mut user = self.0.get(&command.email).await?;

            user.change_password(command.password)?;

            self.0.save(&mut user).await?;

            Ok(())
        }
    }

    #[tokio::test]
    async fn it_creates_a_new_user_successfully() {
        command::test::Scenario
            .when(command::Envelope::from(CreateUser {
                email: "test@test.com".to_owned(),
                password: "not-a-secret".to_owned(),
            }))
            .then(vec![event::Persisted {
                stream_id: "test@test.com".to_owned(),
                version: 1,
                event: event::Envelope::from(UserEvent::WasCreated {
                    email: "test@test.com".to_owned(),
                    password: "not-a-secret".to_owned(),
                }),
            }])
            .assert_on(|event_store| {
                UserService::from(aggregate::EventSourcedRepository::from(event_store))
            })
            .await;
    }

    #[tokio::test]
    async fn it_fails_to_create_an_user_if_it_still_exists() {
        command::test::Scenario
            .given(vec![event::Persisted {
                stream_id: "test@test.com".to_owned(),
                version: 1,
                event: event::Envelope::from(UserEvent::WasCreated {
                    email: "test@test.com".to_owned(),
                    password: "not-a-secret".to_owned(),
                }),
            }])
            .when(command::Envelope::from(CreateUser {
                email: "test@test.com".to_owned(),
                password: "not-a-secret".to_owned(),
            }))
            .then_fails()
            .assert_on(|event_store| {
                UserService::from(aggregate::EventSourcedRepository::from(event_store))
            })
            .await;
    }

    #[tokio::test]
    async fn it_updates_the_password_of_an_existing_user() {
        command::test::Scenario
            .given(vec![event::Persisted {
                stream_id: "test@test.com".to_owned(),
                version: 1,
                event: event::Envelope::from(UserEvent::WasCreated {
                    email: "test@test.com".to_owned(),
                    password: "not-a-secret".to_owned(),
                }),
            }])
            .when(command::Envelope::from(ChangeUserPassword {
                email: "test@test.com".to_owned(),
                password: "new-password".to_owned(),
            }))
            .then(vec![event::Persisted {
                stream_id: "test@test.com".to_owned(),
                version: 2,
                event: event::Envelope::from(UserEvent::PasswordWasChanged {
                    password: "new-password".to_owned(),
                }),
            }])
            .assert_on(|event_store| {
                UserService::from(aggregate::EventSourcedRepository::from(event_store))
            })
            .await;
    }

    #[tokio::test]
    async fn it_fails_to_update_the_password_if_the_user_does_not_exist() {
        command::test::Scenario
            .when(command::Envelope::from(ChangeUserPassword {
                email: "test@test.com".to_owned(),
                password: "new-password".to_owned(),
            }))
            .then_fails()
            .assert_on(|event_store| {
                UserService::from(aggregate::EventSourcedRepository::from(event_store))
            })
            .await;
    }
}