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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! # cqrs-todo-core
//!
//! `cqrs-todo-core` is a demonstration crate, showing how to construct an aggregate, with the associated events
//! and commands, using the CQRS system.

#![warn(unused_import_braces, unused_imports, unused_qualifications)]
#![deny(
    missing_debug_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unused_must_use,
    missing_docs
)]

use cqrs_core::{
    Aggregate, AggregateEvent, AggregateId, DeserializableEvent, Event, SerializableEvent,
};
use serde::{Deserialize, Serialize};

pub mod commands;
pub mod domain;
pub mod error;
pub mod events;

/// An aggregate representing the view of a to-do item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TodoAggregate {
    /// A to-do item that has been properly initialized.
    Created(TodoData),

    /// An uninitialized to-do item.
    Uninitialized,
}

impl Default for TodoAggregate {
    fn default() -> Self {
        TodoAggregate::Uninitialized
    }
}

impl TodoAggregate {
    /// Get the underlying to-do data if the aggregate has been initialized.
    pub fn get_data(&self) -> Option<&TodoData> {
        match *self {
            TodoAggregate::Uninitialized => None,
            TodoAggregate::Created(ref x) => Some(x),
        }
    }
}

impl Aggregate for TodoAggregate {
    #[inline(always)]
    fn aggregate_type() -> &'static str
    where
        Self: Sized,
    {
        "todo"
    }
}

/// An identifier for an item to be done.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TodoId(pub String);

impl AggregateId<TodoAggregate> for TodoId {
    fn as_str(&self) -> &str {
        &self.0
    }
}

/// An identifier for an item to be done.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TodoIdRef<'a>(pub &'a str);

impl<'a> AsRef<str> for TodoIdRef<'a> {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl<'a> AggregateId<TodoAggregate> for TodoIdRef<'a> {
    fn as_str(&self) -> &str {
        self.0
    }
}

/// Metadata about events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TodoMetadata {
    /// The actor that caused this event to be added to the event stream.
    pub initiated_by: String,
}

/// Data relating to a to-do item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TodoData {
    /// The to-do item description.
    pub description: domain::Description,

    /// The reminder time for this to-do item.
    pub reminder: Option<domain::Reminder>,

    /// The current status of this item.
    pub status: TodoStatus,
}

impl TodoData {
    fn with_description(description: domain::Description) -> Self {
        TodoData {
            description,
            reminder: None,
            status: TodoStatus::NotCompleted,
        }
    }
}

/// The completion status of a to-do item.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum TodoStatus {
    /// The item has been completed.
    Completed,

    /// The item has not been completed.
    NotCompleted,
}

/// A combined roll-up of the events that can be applied to a [TodoAggregate].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TodoEvent {
    /// Created
    Created(events::Created),

    /// Description updated
    DescriptionUpdated(events::DescriptionUpdated),

    /// Reminder updated
    ReminderUpdated(events::ReminderUpdated),

    /// Item completed
    Completed(events::Completed),

    /// Item completion undone
    Uncompleted(events::Uncompleted),
}

impl Event for TodoEvent {
    fn event_type(&self) -> &'static str {
        match *self {
            TodoEvent::Created(ref evt) => evt.event_type(),
            TodoEvent::DescriptionUpdated(ref evt) => evt.event_type(),
            TodoEvent::ReminderUpdated(ref evt) => evt.event_type(),
            TodoEvent::Completed(ref evt) => evt.event_type(),
            TodoEvent::Uncompleted(ref evt) => evt.event_type(),
        }
    }
}

impl AggregateEvent<TodoAggregate> for events::Created {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        if TodoAggregate::Uninitialized == *aggregate {
            *aggregate =
                TodoAggregate::Created(TodoData::with_description(self.initial_description))
        }
    }
}

impl AggregateEvent<TodoAggregate> for events::DescriptionUpdated {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        if let TodoAggregate::Created(ref mut data) = aggregate {
            data.description = self.new_description;
        }
    }
}

impl AggregateEvent<TodoAggregate> for events::ReminderUpdated {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        if let TodoAggregate::Created(ref mut data) = aggregate {
            data.reminder = self.new_reminder;
        }
    }
}

impl AggregateEvent<TodoAggregate> for events::Completed {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        if let TodoAggregate::Created(ref mut data) = aggregate {
            data.status = TodoStatus::Completed;
        }
    }
}

impl AggregateEvent<TodoAggregate> for events::Uncompleted {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        if let TodoAggregate::Created(ref mut data) = aggregate {
            data.status = TodoStatus::NotCompleted;
        }
    }
}
impl AggregateEvent<TodoAggregate> for TodoEvent {
    fn apply_to(self, aggregate: &mut TodoAggregate) {
        match self {
            TodoEvent::Created(evt) => evt.apply_to(aggregate),
            TodoEvent::DescriptionUpdated(evt) => evt.apply_to(aggregate),
            TodoEvent::ReminderUpdated(evt) => evt.apply_to(aggregate),
            TodoEvent::Completed(evt) => evt.apply_to(aggregate),
            TodoEvent::Uncompleted(evt) => evt.apply_to(aggregate),
        }
    }
}

impl SerializableEvent for TodoEvent {
    type Error = serde_json::Error;

    fn serialize_event_to_buffer(&self, buffer: &mut Vec<u8>) -> Result<(), Self::Error> {
        buffer.clear();
        buffer.reserve(128);
        match *self {
            TodoEvent::Created(ref inner) => {
                serde_json::to_writer(buffer, inner)?;
            }
            TodoEvent::ReminderUpdated(ref inner) => {
                serde_json::to_writer(buffer, inner)?;
            }
            TodoEvent::DescriptionUpdated(ref inner) => {
                serde_json::to_writer(buffer, inner)?;
            }
            TodoEvent::Completed(ref inner) => {
                serde_json::to_writer(buffer, inner)?;
            }
            TodoEvent::Uncompleted(ref inner) => {
                serde_json::to_writer(buffer, inner)?;
            }
        }
        Ok(())
    }
}

impl DeserializableEvent for TodoEvent {
    type Error = serde_json::Error;

    fn deserialize_event_from_buffer(
        data: &[u8],
        event_type: &str,
    ) -> Result<Option<Self>, Self::Error> {
        let deserialized = match event_type {
            "todo_created" => TodoEvent::Created(serde_json::from_slice(data)?),
            "todo_reminder_updated" => TodoEvent::ReminderUpdated(serde_json::from_slice(data)?),
            "todo_description_updated" => {
                TodoEvent::DescriptionUpdated(serde_json::from_slice(data)?)
            }
            "todo_completed" => TodoEvent::Completed(serde_json::from_slice(data)?),
            "todo_uncompleted" => TodoEvent::Uncompleted(serde_json::from_slice(data)?),
            _ => return Ok(None),
        };
        Ok(Some(deserialized))
    }
}

#[cfg(test)]
mod tests {
    pub use super::*;
    use arrayvec::ArrayVec;
    use chrono::{Duration, TimeZone, Utc};
    use pretty_assertions::assert_eq;

    fn create_basic_aggregate() -> TodoAggregate {
        let now = Utc.ymd(1970, 1, 1).and_hms(0, 0, 0);
        let reminder = now + Duration::seconds(10000);

        let events = ArrayVec::from([
            TodoEvent::Completed(events::Completed {}),
            TodoEvent::Created(events::Created {
                initial_description: domain::Description::new("Hello!").unwrap(),
            }),
            TodoEvent::ReminderUpdated(events::ReminderUpdated {
                new_reminder: Some(domain::Reminder::new(reminder, now).unwrap()),
            }),
            TodoEvent::DescriptionUpdated(events::DescriptionUpdated {
                new_description: domain::Description::new("New text").unwrap(),
            }),
            TodoEvent::Created(events::Created {
                initial_description: domain::Description::new("Ignored!").unwrap(),
            }),
            TodoEvent::ReminderUpdated(events::ReminderUpdated { new_reminder: None }),
        ]);

        let mut agg = TodoAggregate::default();
        for event in events {
            agg.apply(event);
        }
        agg
    }

    #[test]
    fn example_event_sequence() {
        let expected_data = TodoData {
            description: domain::Description::new("New text").unwrap(),
            reminder: None,
            status: TodoStatus::NotCompleted,
        };
        let expected_state = TodoAggregate::Created(expected_data);

        let agg = create_basic_aggregate();

        assert_eq!(expected_state, agg);
    }

    #[test]
    fn cancel_reminder_on_default_aggregate() {
        let agg = TodoAggregate::default();

        let cmd = commands::CancelReminder;

        let result = agg.execute(cmd).unwrap_err();

        assert_eq!(error::CommandError::NotInitialized, result);
    }

    #[test]
    fn cancel_reminder_on_basic_aggregate() {
        let agg = create_basic_aggregate();

        let cmd = commands::CancelReminder;

        let result = agg.execute(cmd).unwrap();

        assert_eq!(ArrayVec::new(), result);
    }

    #[test]
    fn set_reminder_on_basic_aggregate() {
        let agg = create_basic_aggregate();

        let now = Utc.ymd(1970, 1, 1).and_hms(0, 0, 0);
        let reminder_time = now + Duration::seconds(20000);
        let new_reminder = domain::Reminder::new(reminder_time, now).unwrap();
        let cmd = commands::SetReminder { new_reminder };

        let result = agg.execute(cmd).unwrap();

        let mut expected = ArrayVec::new();
        expected.push(TodoEvent::ReminderUpdated(events::ReminderUpdated {
            new_reminder: Some(new_reminder),
        }));
        assert_eq!(expected, result);
    }

    #[test]
    fn ensure_created_event_stays_same() -> Result<(), serde_json::Error> {
        let initial_description = domain::Description::new("test description").unwrap();
        run_snapshot_test(
            "created_event",
            TodoEvent::Created(events::Created {
                initial_description,
            }),
        )
    }

    #[test]
    fn ensure_reminder_updated_event_stays_same() -> Result<(), serde_json::Error> {
        let current_time = Utc.ymd(2000, 1, 1).and_hms(0, 0, 0);
        let reminder_time = Utc.ymd(2100, 1, 1).and_hms(0, 0, 0);
        let reminder = domain::Reminder::new(reminder_time, current_time).unwrap();
        run_snapshot_test(
            "reminder_updated_event",
            TodoEvent::ReminderUpdated(events::ReminderUpdated {
                new_reminder: Some(reminder),
            }),
        )
    }

    #[test]
    fn ensure_reminder_removed_event_stays_same() -> Result<(), serde_json::Error> {
        run_snapshot_test(
            "reminder_updated_none_event",
            TodoEvent::ReminderUpdated(events::ReminderUpdated { new_reminder: None }),
        )
    }

    #[test]
    fn ensure_text_updated_event_stays_same() -> Result<(), serde_json::Error> {
        let new_description = domain::Description::new("alt test description").unwrap();
        run_snapshot_test(
            "description_updated_event",
            TodoEvent::DescriptionUpdated(events::DescriptionUpdated { new_description }),
        )
    }

    #[test]
    fn ensure_completed_event_stays_same() -> Result<(), serde_json::Error> {
        run_snapshot_test(
            "completed_event",
            TodoEvent::Completed(events::Completed {}),
        )
    }

    #[test]
    fn ensure_uncompleted_event_stays_same() -> Result<(), serde_json::Error> {
        run_snapshot_test(
            "uncompleted_event",
            TodoEvent::Uncompleted(events::Uncompleted {}),
        )
    }

    fn run_snapshot_test<E: SerializableEvent>(
        name: &'static str,
        event: E,
    ) -> Result<(), E::Error> {
        let mut buffer = Vec::default();
        event.serialize_event_to_buffer(&mut buffer)?;

        #[derive(Serialize)]
        struct RawEventWithType {
            event_type: &'static str,
            raw: String,
        }

        let data = RawEventWithType {
            event_type: event.event_type(),
            raw: String::from_utf8(buffer).unwrap(),
        };

        insta::assert_json_snapshot_matches!(name, data);
        Ok(())
    }

    #[test]
    fn roundtrip_created() {
        let original = TodoEvent::Created(events::Created {
            initial_description: domain::Description::new("test description").unwrap(),
        });
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn roundtrip_reminder_updated() {
        let original = TodoEvent::ReminderUpdated(events::ReminderUpdated {
            new_reminder: Some(
                domain::Reminder::new(
                    Utc.ymd(2100, 1, 1).and_hms(0, 0, 0),
                    Utc.ymd(2000, 1, 1).and_hms(0, 0, 0),
                )
                .unwrap(),
            ),
        });
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn roundtrip_reminder_updated_none() {
        let original = TodoEvent::ReminderUpdated(events::ReminderUpdated { new_reminder: None });
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn roundtrip_description_updated() {
        let original = TodoEvent::DescriptionUpdated(events::DescriptionUpdated {
            new_description: domain::Description::new("alt test description").unwrap(),
        });
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn roundtrip_completed() {
        let original = TodoEvent::Completed(events::Completed {});
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    #[test]
    fn roundtrip_uncompleted() {
        let original = TodoEvent::Uncompleted(events::Uncompleted {});
        let roundtrip = cqrs_proptest::roundtrip_through_serialization(&original);
        assert_eq!(original, roundtrip);
    }

    mod property_tests {
        use super::*;
        use cqrs_proptest::AggregateFromEventSequence;
        use pretty_assertions::assert_eq;
        use proptest::{prelude::*, prop_oneof, proptest, proptest_helper};
        use std::fmt;

        impl Arbitrary for domain::Description {
            type Parameters = proptest::string::StringParam;
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
                let s: &'static str = args.into();
                s.prop_filter_map("invalid description", |d| domain::Description::new(d).ok())
                    .boxed()
            }
        }

        impl Arbitrary for domain::Reminder {
            type Parameters = ();
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                let current_time = Utc.ymd(2000, 1, 1).and_hms(0, 0, 0);

                (2000..2500_i32, 1..=366_u32, 0..86400_u32)
                    .prop_filter_map("invalid date", move |(y, o, s)| {
                        let time = chrono::NaiveTime::from_num_seconds_from_midnight(s, 0);
                        let date = Utc.yo_opt(y, o).single()?.and_time(time)?;
                        domain::Reminder::new(date, current_time).ok()
                    })
                    .boxed()
            }
        }

        impl Arbitrary for events::Created {
            type Parameters = ();
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                any::<domain::Description>()
                    .prop_map(|initial_description| events::Created {
                        initial_description,
                    })
                    .boxed()
            }
        }

        impl Arbitrary for events::ReminderUpdated {
            type Parameters = ();
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                any::<Option<domain::Reminder>>()
                    .prop_map(|new_reminder| events::ReminderUpdated { new_reminder })
                    .boxed()
            }
        }

        impl Arbitrary for events::DescriptionUpdated {
            type Parameters = ();
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                any::<domain::Description>()
                    .prop_map(|new_description| events::DescriptionUpdated { new_description })
                    .boxed()
            }
        }

        impl Arbitrary for events::Completed {
            type Parameters = ();
            type Strategy = Just<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                Just(events::Completed {})
            }
        }

        impl Arbitrary for events::Uncompleted {
            type Parameters = ();
            type Strategy = Just<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                Just(events::Uncompleted {})
            }
        }

        impl Arbitrary for TodoEvent {
            type Parameters = ();
            type Strategy = BoxedStrategy<Self>;

            fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
                prop_oneof![
                    any::<events::Created>().prop_map(TodoEvent::Created),
                    any::<events::ReminderUpdated>().prop_map(TodoEvent::ReminderUpdated),
                    any::<events::DescriptionUpdated>().prop_map(TodoEvent::DescriptionUpdated),
                    any::<events::Completed>().prop_map(TodoEvent::Completed),
                    any::<events::Uncompleted>().prop_map(TodoEvent::Uncompleted),
                ]
                .boxed()
            }
        }

        fn verify_serializable_roundtrips_through_serialization<
            V: Serialize + for<'de> Deserialize<'de> + Eq + fmt::Debug,
        >(
            original: V,
        ) {
            let data = serde_json::to_string(&original).expect("serialization");
            let roundtrip: V = serde_json::from_str(&data).expect("deserialization");
            assert_eq!(original, roundtrip);
        }

        type ArbitraryTodoAggregate = AggregateFromEventSequence<TodoAggregate, TodoEvent>;

        proptest! {
            #[test]
            fn can_create_arbitrary_aggregate(_agg in any::<ArbitraryTodoAggregate>()) {
            }

            #[test]
            fn arbitrary_aggregate_roundtrips_through_serialization(arg in any::<ArbitraryTodoAggregate>()) {
                verify_serializable_roundtrips_through_serialization(arg.into_aggregate());
            }

            #[test]
            fn arbitrary_event_roundtrips_through_serialization(event in any::<TodoEvent>()) {
                let roundtrip = cqrs_proptest::roundtrip_through_serialization(&event);
                assert_eq!(event, roundtrip);
            }
        }
    }
}