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
//! Foundation traits for creating Domain abstractions //! using [the `Aggregate` pattern](https://martinfowler.com/bliki/DDD_Aggregate.html). use std::sync::Arc; use futures::future::BoxFuture; /// A trait for data structures that can be identified by an id. pub trait Identifiable { /// Type of the data id. /// An id must support total equality. type Id: Eq; /// Data structure id accessor. fn id(&self) -> Self::Id; } impl<State> Identifiable for Option<State> where State: Identifiable, State::Id: Default, { type Id = State::Id; #[inline] fn id(&self) -> Self::Id { self.as_ref().map_or_else(Self::Id::default, |id| id.id()) } } /// A short extractor type for the Aggregate id, found in the Aggregate [`State`]. /// /// [`State`]: trait.Aggregate.html#associatedtype.State pub type AggregateId<A> = <<A as Aggregate>::State as Identifiable>::Id; /// An Aggregate manages a domain entity [`State`], acting as a _transaction boundary_. /// /// It allows **state mutations** through the use of [`Command`]s, which the /// Aggregate instance handles and emits a number of Domain [`Event`]s. /// /// [`Event`]: trait.Aggregate.html#associatedtype.Event /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Command`]: trait.Aggregate.html#associatedtype.Command pub trait Aggregate { /// State of the Aggregate: this should represent the Domain Entity data structure. type State: Identifiable; /// Represents a specific, domain-related change to the Aggregate [`State`]. /// /// [`State`]: trait.Aggregate.html#associatedtype.State type Event; /// Commands are all the possible operations available on an Aggregate. /// Use Commands to model business use-cases or [`State`] mutations. /// /// [`State`]: trait.Aggregate.html#associatedtype.State type Command; /// Possible failures while [`apply`]ing [`Event`]s or handling [`Command`]s. /// /// [`apply`]: trait.Aggregate.html#method.apply /// [`Event`]: trait.Aggregate.html#associatedtype.Event /// [`Command`]: trait.Aggregate.html#associatedtype.Command type Error; /// Applies an [`Event`] to the current Aggregate [`State`]. /// /// To enforce immutability, this method takes ownership of the previous [`State`] /// and the current [`Event`] to apply, and returns the new version of the [`State`] /// or an error. /// /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Event`]: trait.Aggregate.html#associatedtype.Event fn apply(state: Self::State, event: Self::Event) -> Result<Self::State, Self::Error>; /// Handles the requested [`Command`] and returns a list of [`Event`]s /// to apply the [`State`] mutation based on the current representation of the State. /// /// [`Event`]: trait.Aggregate.html#associatedtype.Event /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Command`]: trait.Aggregate.html#associatedtype.Command fn handle<'a, 's: 'a>( &'a self, state: &'s Self::State, command: Self::Command, ) -> BoxFuture<'a, Result<Vec<Self::Event>, Self::Error>> where Self: Sized; } impl<T> Aggregate for Arc<T> where T: Aggregate, { type State = T::State; type Event = T::Event; type Command = T::Command; type Error = T::Error; fn apply(state: Self::State, event: Self::Event) -> Result<Self::State, Self::Error> { T::apply(state, event) } fn handle<'agg, 'st: 'agg>( &'agg self, state: &'st Self::State, command: Self::Command, ) -> BoxFuture<'agg, Result<Vec<Self::Event>, Self::Error>> where Self: Sized, { T::handle(self, state, command) } } /// Extension trait with some handy methods to use with [`Aggregate`]s. /// /// [`Aggregate`]: trait.Aggregate.html pub trait AggregateExt: Aggregate { /// Constructs a new, empty [`AggregateRoot`] using the current [`Aggregate`]. /// /// [`Aggregate`]: trait.Aggregate.html /// [`AggregateRoot`]: struct.AggregateRoot.html #[inline] fn root(&self) -> AggregateRoot<Self> where Self: Sized + Clone, Self::State: Default, { AggregateRoot::from(self.clone()) } /// Applies a list of [`Event`]s from an `Iterator` /// to the current Aggregate [`State`]. /// /// Useful to recreate the [`State`] of an Aggregate when the [`Event`]s /// are located in-memory. /// /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Event`]: trait.Aggregate.html#associatedtype.Event #[inline] fn fold<I>(state: Self::State, mut events: I) -> Result<Self::State, Self::Error> where I: Iterator<Item = Self::Event>, { events.try_fold(state, Self::apply) } } impl<T> AggregateExt for T where T: Aggregate {} /// An `AggregateRoot` represents an handler to the [`Aggregate`] it's managing, /// such as: /// /// * Owning the current, local Aggregate [`State`], /// * Proxying [`Command`]s to the [`Aggregate`] using the current [`State`], /// * Keeping a list of [`Event`]s to commit after [`Command`] execution. /// /// ## Initialize /// /// `AggregateRoot` can be initialized in two ways: /// /// 1. Using the `From<Aggregate>` method: /// ```text /// let root = AggregateRoot::from(aggregate); /// ``` /// /// 2. Using the [`AggregateExt`] extension trait to call [`root()`] on the [`Aggregate`] /// instance: /// ```text /// // This will result in a Clone of the Aggregate instance. /// let root = aggregate.root(); /// ``` /// /// [`Aggregate`]: trait.Aggregate.html /// [`AggregateExt`]: trait.AggregateExt.html /// [`root()`]: trait.AggregateExt.html#method.root /// [`Event`]: trait.Aggregate.html#associatedtype.Event /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Command`]: trait.Aggregate.html#associatedtype.Event #[derive(Debug)] pub struct AggregateRoot<T> where T: Aggregate + 'static, { pub(crate) state: T::State, aggregate: T, pub(crate) to_commit: Option<Vec<T::Event>>, } impl<T> Identifiable for AggregateRoot<T> where T: Aggregate, { type Id = AggregateId<T>; #[inline] fn id(&self) -> Self::Id { self.state.id() } } impl<T> PartialEq for AggregateRoot<T> where T: Aggregate, { #[inline] fn eq(&self, other: &Self) -> bool { self.id() == other.id() } } impl<T> From<T> for AggregateRoot<T> where T: Aggregate, T::State: Default, { #[inline] fn from(aggregate: T) -> Self { Self::new(aggregate, Default::default()) } } impl<T> AggregateRoot<T> where T: Aggregate, { /// Returns a reference to the current Aggregate [`State`]. /// /// [`State`]: trait.Aggregate.html#associatedtype.State #[inline] pub fn state(&self) -> &T::State { &self.state } } impl<T> AggregateRoot<T> where T: Aggregate, { /// Creates a new `AggregateRoot` instance wrapping the specified [`State`]. /// /// [`State`]: trait.Aggregate.html#associatedtype.State #[inline] pub fn new(aggregate: T, state: T::State) -> Self { Self { state, aggregate, to_commit: None, } } } impl<T> AggregateRoot<T> where T: AggregateExt, T::Event: Clone, T::State: Clone, { /// Handles the submitted [`Command`] using the [`Aggregate::handle`] method /// and updates the Aggregate [`State`]. /// /// Returns a `&mut self` reference to allow for _method chaining_. /// /// [`State`]: trait.Aggregate.html#associatedtype.State /// [`Command`]: trait.Aggregate.html#associatedtype.Command /// [`Aggregate::handle`]: trait.Aggregate.html#method.handle pub async fn handle(&mut self, command: T::Command) -> Result<&mut Self, T::Error> { let mut events = self.aggregate.handle(self.state(), command).await?; self.state = T::fold(self.state.clone(), events.clone().into_iter())?; self.to_commit = Some(match self.to_commit.take() { None => events, Some(mut list) => { list.append(&mut events); list } }); Ok(self) } }