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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use log::{
    debug,
    error,
    trace,
};
use std::{
    collections::HashMap,
    marker::PhantomData,
};

use cqrs_es2::{
    AggregateContext,
    Error,
    EventContext,
    IAggregate,
    ICommand,
    IEvent,
};

use super::{
    i_event_dispatcher::IEventDispatcher,
    i_event_store::IEventStore,
};

/// This is the base framework for applying commands to produce
/// events.
///
/// In [Domain Driven Design](https://en.wikipedia.org/wiki/Domain-driven_design)
/// we require that changes are made only after loading the entire
/// `Aggregate` in order to ensure that the full context is
/// understood. With event-sourcing this means:
/// 1. loading all previous events for the aggregate instance
/// 2. applying these events, in order, to a new `Aggregate`
/// 3. using the recreated `Aggregate` to handle an inbound `Command`
/// 4. persisting any generated events or rolling back on an error
///
/// To manage these tasks we use a `Repository`.
pub struct Repository<
    C: ICommand,
    E: IEvent,
    A: IAggregate<C, E>,
    ES: IEventStore<C, E, A>,
> {
    store: ES,
    dispatchers: Vec<Box<dyn IEventDispatcher<C, E>>>,
    with_snapshots: bool,
    _phantom: PhantomData<A>,
}

impl<
        C: ICommand,
        E: IEvent,
        A: IAggregate<C, E>,
        ES: IEventStore<C, E, A>,
    > Repository<C, E, A, ES>
{
    /// Creates new framework for dispatching commands using the
    /// provided elements.
    pub fn new(
        store: ES,
        dispatchers: Vec<Box<dyn IEventDispatcher<C, E>>>,
        with_snapshots: bool,
    ) -> Self {
        let x = Self {
            store,
            dispatchers,
            with_snapshots,
            _phantom: PhantomData,
        };

        trace!("Created new Repository");

        x
    }

    /// This applies a command to an aggregate. Executing a command
    /// in this way is the only way to make any change to
    /// the state of an aggregate.
    ///
    /// An error while processing will result in no events committed
    /// and an Error being returned.
    ///
    /// If successful the events produced will be applied to the
    /// configured `QueryProcessor`s.
    ///
    /// # Error
    /// If an error is generated while processing the command this
    /// will be returned.
    pub fn execute(
        &mut self,
        aggregate_id: &str,
        command: C,
    ) -> Result<(), Error> {
        self.execute_with_metadata(
            aggregate_id,
            command,
            HashMap::new(),
        )
    }

    /// This applies a command to an aggregate along with associated
    /// metadata. Executing a command in this way to make any
    /// change to the state of an aggregate.
    ///
    /// A `Hashmap<String,String>` is supplied with any contextual
    /// information that should be associated with this change.
    /// This metadata will be attached to any produced events and is
    /// meant to assist in debugging and auditing. Common information
    /// might include:
    /// - time of commit
    /// - user making the change
    /// - application version
    ///
    /// An error while processing will result in no events committed
    /// and an Error being returned.
    ///
    /// If successful the events produced will be applied to the
    /// configured `QueryProcessor`s.
    pub fn execute_with_metadata(
        &mut self,
        aggregate_id: &str,
        command: C,
        metadata: HashMap<String, String>,
    ) -> Result<(), Error> {
        trace!(
            "Applying command '{:?}' to aggregate '{}' with \
             metadata '{:?}'",
            &command,
            &aggregate_id,
            &metadata
        );

        let stored_context = match self.load_aggregate(&aggregate_id)
        {
            Ok(x) => x,
            Err(e) => {
                error!(
                    "Loading aggregate '{}' returned error '{}'",
                    &aggregate_id,
                    e.to_string()
                );
                return Err(e);
            },
        };

        let events = match stored_context
            .payload
            .handle(command.clone())
        {
            Ok(x) => x,
            Err(e) => {
                error!(
                    "Handling command '{:?}' for aggregate '{}' \
                     returned error '{}'",
                    &command,
                    &aggregate_id,
                    e.to_string()
                );
                return Err(e);
            },
        };

        if events.len() == 0 {
            return Ok(());
        }

        let event_contexts = match self.save_events(
            events,
            stored_context,
            metadata,
        ) {
            Ok(x) => x,
            Err(e) => {
                error!(
                    "Committing events returned error '{}'",
                    e.to_string()
                );
                return Err(e);
            },
        };

        for x in &mut self.dispatchers {
            match x.dispatch(&aggregate_id, &event_contexts) {
                Ok(_) => {},
                Err(e) => {
                    error!(
                        "dispatcher returned error '{}'",
                        e.to_string()
                    );
                    return Err(e);
                },
            }
        }

        debug!(
            "Successfully applied command '{:?}' to aggregate '{}'",
            &command, &aggregate_id
        );

        Ok(())
    }

    fn load_aggregate(
        &mut self,
        aggregate_id: &str,
    ) -> Result<AggregateContext<C, E, A>, Error> {
        match self.with_snapshots {
            true => {
                self.store
                    .load_aggregate_from_snapshot(aggregate_id)
            },
            false => self.load_aggregate_from_events(aggregate_id),
        }
    }

    fn save_events(
        &mut self,
        events: Vec<E>,
        stored_context: AggregateContext<C, E, A>,
        metadata: HashMap<String, String>,
    ) -> Result<Vec<EventContext<C, E>>, Error> {
        let aggregate_id = stored_context.aggregate_id;

        let contexts = self.wrap_events(
            &aggregate_id,
            stored_context.version,
            events,
            metadata,
        );

        match self.store.save_events(&contexts) {
            Ok(_) => {},
            Err(e) => {
                error!(
                    "save events returned error '{}'",
                    e.to_string()
                );
                return Err(e);
            },
        };

        if self.with_snapshots {
            let mut aggregate = stored_context.payload;

            contexts
                .iter()
                .map(|x| &x.payload)
                .for_each(|x| aggregate.apply(&x));

            match self.store.save_aggregate_snapshot(
                AggregateContext::new(
                    aggregate_id,
                    contexts.last().unwrap().sequence,
                    aggregate,
                ),
            ) {
                Ok(_) => {},
                Err(e) => {
                    error!(
                        "save aggregate snapshot returned error '{}'",
                        e.to_string()
                    );
                    return Err(e);
                },
            };
        }

        Ok(contexts)
    }

    /// Wrap a set of events with the additional metadata
    /// needed for persistence and publishing
    fn wrap_events(
        &self,
        aggregate_id: &str,
        current_sequence: i64,
        events: Vec<E>,
        metadata: HashMap<String, String>,
    ) -> Vec<EventContext<C, E>> {
        let mut sequence = current_sequence;

        let mut result = Vec::new();

        for x in events {
            sequence += 1;

            result.push(EventContext::new(
                aggregate_id.to_string(),
                sequence,
                x,
                metadata.clone(),
            ));
        }

        result
    }

    /// Load aggregate at current state from events stream
    fn load_aggregate_from_events(
        &mut self,
        aggregate_id: &str,
    ) -> Result<AggregateContext<C, E, A>, Error> {
        let contexts = self.store.load_events(&aggregate_id)?;

        if contexts.len() == 0 {
            return Ok(AggregateContext::new(
                aggregate_id.to_string(),
                0,
                A::default(),
            ));
        }

        let mut aggregate = A::default();

        contexts
            .iter()
            .map(|x| &x.payload)
            .for_each(|x| aggregate.apply(&x));

        Ok(AggregateContext::new(
            aggregate_id.to_string(),
            contexts.last().unwrap().sequence,
            aggregate,
        ))
    }
}