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
455
456
457
458
459
460
461
use crate::{domain::AggregateRoot, port::PortError};

/// Loads an aggregate by id.
///
/// # Examples
///
/// See [`Save`](Save#examples) for a worked example of saving and loading
/// an aggregate.
#[trait_variant::make(Send)]
pub trait Load<A: AggregateRoot> {
    /// Returns the aggregate with the given id, or `None` if it doesn't exist.
    async fn load(&self, id: &A::Id) -> Result<Option<A>, PortError>;
}

/// Persists an aggregate.
///
/// # Examples
///
/// ```
/// use ddd_toolkit_core::domain::{AggregateRoot, DomainEvent, Entity, EntityId, ValueObject};
/// use ddd_toolkit_core::mock::repository::InMemoryStore;
/// use ddd_toolkit_core::port::repository::{Load, 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();
/// let mut order = Order { id: OrderId(1), events: vec![OrderPlaced] };
///
/// block_on(store.save(&mut order))?;
///
/// // save() drains the aggregate's recorded events as a side effect
/// assert!(order.take_events().is_empty());
///
/// let loaded = block_on(store.load(&OrderId(1)))?.expect("just-saved order should be found");
/// assert_eq!(loaded.id, OrderId(1));
/// # Ok::<(), ddd_toolkit_core::port::PortError>(())
/// ```
///
/// Implementations backed by optimistic concurrency control (e.g. a
/// stored version/etag compared against the aggregate's current state)
/// should return `Err` with [`PortErrorKind::Conflict`] when the
/// stored version has moved on since the aggregate was loaded, so the
/// caller can reload and retry. The in-memory reference implementations
/// in this crate (`mock::repository::InMemoryStore` and the doctest
/// fixtures) intentionally do not: they have no notion of a stored
/// version and always last-write-wins, so they never produce
/// `Conflict`. A real backend copying them as a starting point should
/// add its own version check rather than assume last-write-wins is
/// the port's default behavior.
///
/// [`PortErrorKind::Conflict`]: crate::port::PortErrorKind::Conflict
#[trait_variant::make(Send)]
pub trait Save<A: AggregateRoot> {
    /// Persists the aggregate, draining and recording any events it has
    /// accumulated via [`AggregateRoot::take_events`]. See the trait-level
    /// docs for the `Conflict` contract.
    async fn save(&self, aggregate: &mut A) -> Result<(), PortError>;
}

/// Deletes an aggregate.
///
/// Deleting an id that does not exist is **not** an error: it is
/// idempotent and returns `Ok(())`, the same as if the delete had just
/// run again after already succeeding. Implementations must not return
/// `Err` solely because the id was already absent.
///
/// # Examples
///
/// ```
/// use ddd_toolkit_core::domain::{AggregateRoot, DomainEvent, Entity, EntityId, ValueObject};
/// use ddd_toolkit_core::mock::repository::InMemoryStore;
/// use ddd_toolkit_core::port::repository::Delete;
/// 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::<Order>::new();
///
/// // deleting an id that was never there is not an error
/// assert!(block_on(store.delete(&OrderId(404))).is_ok());
/// ```
#[trait_variant::make(Send)]
pub trait Delete<A: AggregateRoot> {
    /// Deletes the aggregate with the given id. See the trait-level docs
    /// for why deleting a missing id is not an error.
    async fn delete(&self, id: &A::Id) -> Result<(), PortError>;
}

#[cfg(test)]
mod test {
    use std::{collections::HashMap, fmt::Display, sync::Mutex};

    use crate::{
        domain::{DomainEvent, Entity, EntityId, ValueObject},
        port::PortErrorKind,
        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, PartialEq)]
    struct FooEvent {
        name: String,
    }

    impl DomainEvent for FooEvent {}

    #[derive(Debug)]
    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)
        }
    }

    struct InMemoryFooRepository {
        store: Mutex<HashMap<FooId, String>>,
        saved_events: Mutex<Vec<FooEvent>>,
    }

    impl InMemoryFooRepository {
        fn new() -> Self {
            Self {
                store: Mutex::new(HashMap::new()),
                saved_events: Mutex::new(Vec::new()),
            }
        }
    }

    impl Load<Foo> for InMemoryFooRepository {
        async fn load(&self, id: &FooId) -> Result<Option<Foo>, PortError> {
            Ok(self.store.lock().unwrap().get(id).map(|name| Foo {
                id: id.clone(),
                name: name.clone(),
                events: Vec::new(),
            }))
        }
    }

    impl Save<Foo> for InMemoryFooRepository {
        async fn save(&self, aggregate: &mut Foo) -> Result<(), PortError> {
            self.store
                .lock()
                .unwrap()
                .insert(aggregate.id().clone(), aggregate.name.clone());
            self.saved_events
                .lock()
                .unwrap()
                .extend(aggregate.take_events());
            Ok(())
        }
    }

    impl Delete<Foo> for InMemoryFooRepository {
        async fn delete(&self, id: &FooId) -> Result<(), PortError> {
            self.store.lock().unwrap().remove(id);
            Ok(())
        }
    }

    struct FailingRepository;

    impl Load<Foo> for FailingRepository {
        async fn load(&self, _id: &FooId) -> Result<Option<Foo>, PortError> {
            Err(PortError::unavailable("load failed"))
        }
    }

    impl Save<Foo> for FailingRepository {
        async fn save(&self, _aggregate: &mut Foo) -> Result<(), PortError> {
            Err(PortError::conflict("save failed"))
        }
    }

    impl Delete<Foo> for FailingRepository {
        async fn delete(&self, _id: &FooId) -> Result<(), PortError> {
            Err(PortError::other("delete failed"))
        }
    }

    #[test]
    fn save_new_aggregate_load_returns_some() {
        let repo = InMemoryFooRepository::new();
        let mut foo = Foo::new("foo-1", "alice");

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

        let loaded = block_on(repo.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 repo = InMemoryFooRepository::new();

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

        assert!(loaded.is_none());
    }

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

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

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

    #[test]
    fn save_can_drain_events_via_mut_ref() {
        let repo = InMemoryFooRepository::new();
        let mut foo = Foo::new("foo-1", "alice");
        foo.record(FooEvent {
            name: "created".to_string(),
        });

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

        assert_eq!(
            *repo.saved_events.lock().unwrap(),
            vec![FooEvent {
                name: "created".to_string()
            }]
        );
        assert_eq!(foo.take_events(), vec![]);
    }

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

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

        let loaded = block_on(repo.load(&FooId("foo-1".to_string()))).expect("load should succeed");
        assert!(loaded.is_none());
    }

    #[test]
    fn generic_fn_accepts_combined_repository_bounds() {
        fn roundtrip<R>(repo: &R, foo: &mut Foo) -> Option<Foo>
        where
            R: Load<Foo> + Save<Foo> + Delete<Foo>,
        {
            block_on(async {
                repo.save(foo).await.expect("save should succeed");
                let loaded = repo.load(foo.id()).await.expect("load should succeed");
                repo.delete(foo.id()).await.expect("delete should succeed");
                loaded
            })
        }

        let repo = InMemoryFooRepository::new();
        let mut foo = Foo::new("foo-1", "alice");

        let loaded = roundtrip(&repo, &mut foo);

        assert_eq!(
            loaded.expect("saved aggregate should be found").name,
            "alice"
        );
        assert!(repo.store.lock().unwrap().is_empty());
    }

    #[test]
    fn load_propagates_port_error() {
        let repo = FailingRepository;

        let error = block_on(repo.load(&FooId("foo-1".to_string()))).expect_err("load should fail");

        assert_eq!(error.kind(), PortErrorKind::Unavailable);
    }

    #[test]
    fn save_propagates_port_error() {
        let repo = FailingRepository;
        let mut foo = Foo::new("foo-1", "alice");

        let error = block_on(repo.save(&mut foo)).expect_err("save should fail");

        assert_eq!(error.kind(), PortErrorKind::Conflict);
    }

    #[test]
    fn delete_propagates_port_error() {
        let repo = FailingRepository;

        let error =
            block_on(repo.delete(&FooId("foo-1".to_string()))).expect_err("delete should fail");

        assert_eq!(error.kind(), PortErrorKind::Other);
    }

    // Compile-time only (no runtime assertion): the generic bounds accept the
    // futures as `Send` purely because `#[trait_variant::make(Send)]` promises
    // it at the trait level, not because of the concrete impl.
    #[test]
    fn repository_futures_are_send() {
        fn assert_send(_: impl Send) {}

        fn check<R>(repo: &R, id: &FooId, foo: &mut Foo)
        where
            R: Load<Foo> + Save<Foo> + Delete<Foo>,
        {
            assert_send(repo.load(id));
            assert_send(repo.save(foo));
            assert_send(repo.delete(id));
        }

        let repo = InMemoryFooRepository::new();
        let mut foo = Foo::new("foo-1", "alice");

        check(&repo, &FooId("foo-1".to_string()), &mut foo);
    }

    // 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 repo = InMemoryFooRepository::new();

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

        assert!(result.is_ok());
    }
}