ddd-toolkit-core 0.2.2

Traits and reference implementations for Domain-Driven Design building blocks: entities, value objects, aggregates, repositories, and event dispatch.
Documentation
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
use std::{collections::HashMap, sync::Mutex};

use crate::{
    domain::AggregateRoot,
    port::{
        PortError,
        repository::{Delete, Load, Save},
    },
};

#[derive(Debug)]
struct StoreState<A: AggregateRoot> {
    aggregates: HashMap<A::Id, A>,
    events: Vec<A::Event>,
}

/// A [`Load`]/[`Save`]/[`Delete`] implementation backed by an in-memory
/// `HashMap`, with last-write-wins semantics (see [`Save`]'s docs for what
/// that means for `PortErrorKind::Conflict`).
///
/// # Examples
///
/// See [`Save`](Save#examples) for a worked example of saving and loading
/// through an `InMemoryStore`. The example below covers the store's own
/// inspection methods, useful for asserting on what a use case persisted.
///
/// ```
/// use ddd_toolkit_core::domain::{AggregateRoot, DomainEvent, Entity, EntityId, ValueObject};
/// use ddd_toolkit_core::mock::repository::InMemoryStore;
/// use ddd_toolkit_core::port::repository::Save;
/// use std::fmt::Display;
///
/// # fn block_on<F: std::future::Future>(future: F) -> F::Output {
/// #     let mut future = std::pin::pin!(future);
/// #     let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
/// #     loop {
/// #         if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
/// #             return output;
/// #         }
/// #     }
/// # }
/// #
/// # #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// # struct OrderId(u32);
/// # impl ValueObject for OrderId {}
/// # impl Display for OrderId {
/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// #         write!(f, "order-{}", self.0)
/// #     }
/// # }
/// # impl EntityId for OrderId {}
/// # #[derive(Debug, Clone, PartialEq)]
/// # struct OrderPlaced;
/// # impl DomainEvent for OrderPlaced {}
/// # #[derive(Debug, Clone)]
/// # struct Order {
/// #     id: OrderId,
/// #     events: Vec<OrderPlaced>,
/// # }
/// # impl Entity for Order {
/// #     type Id = OrderId;
/// #     fn id(&self) -> &Self::Id {
/// #         &self.id
/// #     }
/// # }
/// # impl AggregateRoot for Order {
/// #     type Event = OrderPlaced;
/// #     fn record(&mut self, event: Self::Event) {
/// #         self.events.push(event);
/// #     }
/// #     fn take_events(&mut self) -> Vec<Self::Event> {
/// #         std::mem::take(&mut self.events)
/// #     }
/// # }
/// let store = InMemoryStore::new();
/// assert!(store.is_empty());
///
/// let mut order = Order { id: OrderId(1), events: vec![OrderPlaced] };
/// block_on(store.save(&mut order))?;
///
/// assert_eq!(store.len(), 1);
///
/// // events recorded across every save() call so far, for asserting a use
/// // case published what it was supposed to
/// assert_eq!(store.take_recorded_events(), vec![OrderPlaced]);
/// assert_eq!(store.take_recorded_events(), vec![]); // drained
/// # Ok::<(), ddd_toolkit_core::port::PortError>(())
/// ```
#[derive(Debug)]
pub struct InMemoryStore<A: AggregateRoot> {
    state: Mutex<StoreState<A>>,
}

impl<A: AggregateRoot> InMemoryStore<A> {
    /// Creates a new, empty store.
    pub fn new() -> Self {
        Self {
            state: Mutex::new(StoreState {
                aggregates: HashMap::new(),
                events: Vec::new(),
            }),
        }
    }

    /// Returns and clears every event recorded by a `save` call so far.
    pub fn take_recorded_events(&self) -> Vec<A::Event> {
        std::mem::take(&mut self.state.lock().unwrap_or_else(|e| e.into_inner()).events)
    }

    /// The number of aggregates currently stored.
    pub fn len(&self) -> usize {
        self.state
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .aggregates
            .len()
    }

    /// Whether the store currently holds no aggregates.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<A: AggregateRoot> Default for InMemoryStore<A> {
    fn default() -> Self {
        Self::new()
    }
}

impl<A: AggregateRoot + Clone> Load<A> for InMemoryStore<A> {
    async fn load(&self, id: &A::Id) -> Result<Option<A>, PortError> {
        Ok(self
            .state
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .aggregates
            .get(id)
            .cloned())
    }
}

impl<A: AggregateRoot + Clone> Save<A> for InMemoryStore<A> {
    // Intentionally last-write-wins: this double has no stored version to
    // compare against, so it never returns PortErrorKind::Conflict. See the
    // `Save` trait's doc comment for what a real, version-checked backend
    // should do instead.
    async fn save(&self, aggregate: &mut A) -> Result<(), PortError> {
        let events = aggregate.take_events();
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.events.extend(events);
        state
            .aggregates
            .insert(aggregate.id().clone(), aggregate.clone());
        Ok(())
    }
}

impl<A: AggregateRoot + Clone> Delete<A> for InMemoryStore<A> {
    async fn delete(&self, id: &A::Id) -> Result<(), PortError> {
        self.state
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .aggregates
            .remove(id);
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use std::fmt::Display;

    use crate::{
        domain::{DomainEvent, Entity, EntityId, ValueObject},
        testing::block_on,
    };

    use super::*;

    #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
    struct FooId(String);

    impl ValueObject for FooId {}

    impl Display for FooId {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl EntityId for FooId {}

    #[derive(Debug, Clone, PartialEq)]
    struct FooEvent {
        name: String,
    }

    impl DomainEvent for FooEvent {}

    fn event(name: &str) -> FooEvent {
        FooEvent {
            name: name.to_string(),
        }
    }

    #[derive(Debug, Clone)]
    struct Foo {
        id: FooId,
        name: String,
        events: Vec<FooEvent>,
    }

    impl Foo {
        fn new(id: &str, name: &str) -> Self {
            Self {
                id: FooId(id.to_string()),
                name: name.to_string(),
                events: Vec::new(),
            }
        }
    }

    impl Entity for Foo {
        type Id = FooId;

        fn id(&self) -> &Self::Id {
            &self.id
        }
    }

    impl AggregateRoot for Foo {
        type Event = FooEvent;

        fn record(&mut self, event: Self::Event) {
            self.events.push(event);
        }

        fn take_events(&mut self) -> Vec<Self::Event> {
            std::mem::take(&mut self.events)
        }
    }

    #[test]
    fn new_store_is_empty() {
        let store = InMemoryStore::<Foo>::new();

        assert_eq!(store.len(), 0);
        assert!(store.is_empty());
    }

    #[test]
    fn default_store_is_empty() {
        let store = InMemoryStore::<Foo>::default();

        assert_eq!(store.len(), 0);
        assert!(store.is_empty());
    }

    #[test]
    fn save_new_aggregate_load_returns_stored_state() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");

        block_on(store.save(&mut foo)).expect("save should succeed");

        let loaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should succeed")
            .expect("saved aggregate should be found");
        assert_eq!(loaded.id(), &FooId("foo-1".to_string()));
        assert_eq!(loaded.name, "alice");
    }

    #[test]
    fn load_missing_id_returns_none() {
        let store = InMemoryStore::<Foo>::new();

        let loaded =
            block_on(store.load(&FooId("missing".to_string()))).expect("load should succeed");

        assert!(loaded.is_none());
    }

    #[test]
    fn load_returns_clone_detached_from_store() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        block_on(store.save(&mut foo)).expect("save should succeed");

        let mut loaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should succeed")
            .expect("saved aggregate should be found");
        loaded.name = "bob".to_string();

        let reloaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should succeed")
            .expect("saved aggregate should be found");
        assert_eq!(reloaded.name, "alice");
    }

    #[test]
    fn save_existing_id_overwrites_state() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        block_on(store.save(&mut foo)).expect("first save should succeed");

        foo.name = "bob".to_string();
        block_on(store.save(&mut foo)).expect("second save should succeed");

        let loaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should succeed")
            .expect("saved aggregate should be found");
        assert_eq!(loaded.name, "bob");
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn save_two_aggregates_len_counts_distinct_ids() {
        let store = InMemoryStore::new();

        block_on(store.save(&mut Foo::new("foo-1", "alice"))).expect("save should succeed");
        block_on(store.save(&mut Foo::new("foo-2", "bob"))).expect("save should succeed");

        assert_eq!(store.len(), 2);
        assert!(!store.is_empty());
    }

    #[test]
    fn save_drains_events_from_aggregate_into_store() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        foo.record(event("created"));
        foo.record(event("updated"));

        block_on(store.save(&mut foo)).expect("save should succeed");

        assert_eq!(foo.take_events(), vec![]);
        assert_eq!(
            store.take_recorded_events(),
            vec![event("created"), event("updated")]
        );
    }

    // Pins the drain-before-clone order in `save`: the stored clone must not
    // carry pending events, or they would be recorded twice on the next save.
    #[test]
    fn save_stores_clone_without_pending_events() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        foo.record(event("created"));

        block_on(store.save(&mut foo)).expect("save should succeed");

        let mut loaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should succeed")
            .expect("saved aggregate should be found");
        assert_eq!(loaded.take_events(), vec![]);
    }

    #[test]
    fn saves_accumulate_events_in_order() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        let mut bar = Foo::new("foo-2", "bob");

        foo.record(event("foo-created"));
        block_on(store.save(&mut foo)).expect("save should succeed");
        bar.record(event("bar-created"));
        block_on(store.save(&mut bar)).expect("save should succeed");
        foo.record(event("foo-updated"));
        block_on(store.save(&mut foo)).expect("save should succeed");

        assert_eq!(
            store.take_recorded_events(),
            vec![
                event("foo-created"),
                event("bar-created"),
                event("foo-updated")
            ]
        );
    }

    #[test]
    fn take_recorded_events_clears_buffer() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        foo.record(event("created"));
        block_on(store.save(&mut foo)).expect("save should succeed");

        store.take_recorded_events();

        assert_eq!(store.take_recorded_events(), vec![]);
    }

    #[test]
    fn delete_existing_id_removes_aggregate() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        block_on(store.save(&mut foo)).expect("save should succeed");

        block_on(store.delete(&FooId("foo-1".to_string()))).expect("delete should succeed");

        let loaded =
            block_on(store.load(&FooId("foo-1".to_string()))).expect("load should succeed");
        assert!(loaded.is_none());
        assert_eq!(store.len(), 0);
    }

    #[test]
    fn debug_format_contains_type_name() {
        let store = InMemoryStore::<Foo>::new();

        assert!(format!("{store:?}").contains("InMemoryStore"));
    }

    #[test]
    fn take_recorded_events_on_fresh_store_returns_empty_vec() {
        let store = InMemoryStore::<Foo>::new();

        assert_eq!(store.take_recorded_events(), vec![]);
    }

    // Pins down the `Delete` port contract: deleting a missing id is
    // idempotent and must not be treated as an error.
    #[test]
    fn delete_missing_id_is_ok() {
        let store = InMemoryStore::<Foo>::new();

        let result = block_on(store.delete(&FooId("missing".to_string())));

        assert!(result.is_ok());
    }

    // A panic while the lock is held poisons the Mutex; subsequent calls
    // must recover the guard instead of panicking forever.
    #[test]
    fn store_recovers_from_poisoned_mutex() {
        let store = InMemoryStore::new();
        let mut foo = Foo::new("foo-1", "alice");
        block_on(store.save(&mut foo)).expect("save should succeed");

        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = store.state.lock().unwrap();
            panic!("simulated panic while holding the lock");
        }));
        assert!(poisoned.is_err());
        assert!(store.state.is_poisoned());

        let loaded = block_on(store.load(&FooId("foo-1".to_string())))
            .expect("load should recover from the poisoned mutex")
            .expect("aggregate should still be present");
        assert_eq!(loaded.name, "alice");
    }
}