fmodel_rust/
decider.rs

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
use crate::{DecideFunction, EvolveFunction, InitialStateFunction, Sum};

/// [Decider] represents the main decision-making algorithm.
/// It has three generic parameters `C`/`Command`, `S`/`State`, `E`/`Event` , representing the type of the values that Decider may contain or use.
/// `'a` is used as a lifetime parameter, indicating that all references contained within the struct (e.g., references within the function closures) must have a lifetime that is at least as long as 'a.
///
/// ## Example
/// ```
/// use fmodel_rust::decider::{Decider, EventComputation, StateComputation};
///
/// fn decider<'a>() -> Decider<'a, OrderCommand, OrderState, OrderEvent> {
///     Decider {
///         // Exhaustive pattern matching is used to handle the commands (modeled as Enum - SUM/OR type).
///         decide: Box::new(|command, state| {
///            match command {
///                 OrderCommand::Create(create_cmd) => {
///                     vec![OrderEvent::Created(OrderCreatedEvent {
///                         order_id: create_cmd.order_id,
///                         customer_name: create_cmd.customer_name.to_owned(),
///                         items: create_cmd.items.to_owned(),
///                     })]
///                 }
///                 OrderCommand::Update(update_cmd) => {
///                     if state.order_id == update_cmd.order_id {
///                         vec![OrderEvent::Updated(OrderUpdatedEvent {
///                             order_id: update_cmd.order_id,
///                             updated_items: update_cmd.new_items.to_owned(),
///                         })]
///                     } else {
///                         vec![]
///                     }
///                 }
///                 OrderCommand::Cancel(cancel_cmd) => {
///                     if state.order_id == cancel_cmd.order_id {
///                         vec![OrderEvent::Cancelled(OrderCancelledEvent {
///                             order_id: cancel_cmd.order_id,
///                         })]
///                     } else {
///                         vec![]
///                     }
///                 }
///             }
///         }),
///         // Exhaustive pattern matching is used to handle the events (modeled as Enum - SUM/OR type).
///         evolve: Box::new(|state, event| {
///             let mut new_state = state.clone();
///             match event {
///                 OrderEvent::Created(created_event) => {
///                     new_state.order_id = created_event.order_id;
///                     new_state.customer_name = created_event.customer_name.to_owned();
///                     new_state.items = created_event.items.to_owned();
///                 }
///                 OrderEvent::Updated(updated_event) => {
///                     new_state.items = updated_event.updated_items.to_owned();
///                 }
///                 OrderEvent::Cancelled(_) => {
///                     new_state.is_cancelled = true;
///                 }
///             }
///             new_state
///         }),
///         initial_state: Box::new(|| OrderState {
///             order_id: 0,
///             customer_name: "".to_string(),
///             items: Vec::new(),
///             is_cancelled: false,
///         }),
///     }
/// }
///
/// // Modeling the commands, events, and state. Enum is modeling the SUM/OR type, and struct is modeling the PRODUCT/AND type.
/// #[derive(Debug)]
/// pub enum OrderCommand {
///     Create(CreateOrderCommand),
///     Update(UpdateOrderCommand),
///     Cancel(CancelOrderCommand),
/// }
///
/// #[derive(Debug)]
/// pub struct CreateOrderCommand {
///     pub order_id: u32,
///     pub customer_name: String,
///     pub items: Vec<String>,
/// }
///
/// #[derive(Debug)]
/// pub struct UpdateOrderCommand {
///     pub order_id: u32,
///     pub new_items: Vec<String>,
/// }
///
/// #[derive(Debug)]
/// pub struct CancelOrderCommand {
///     pub order_id: u32,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum OrderEvent {
///     Created(OrderCreatedEvent),
///     Updated(OrderUpdatedEvent),
///     Cancelled(OrderCancelledEvent),
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub struct OrderCreatedEvent {
///     pub order_id: u32,
///     pub customer_name: String,
///     pub items: Vec<String>,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub struct OrderUpdatedEvent {
///     pub order_id: u32,
///     pub updated_items: Vec<String>,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub struct OrderCancelledEvent {
///     pub order_id: u32,
/// }
///
/// #[derive(Debug, Clone, PartialEq)]
/// struct OrderState {
///     order_id: u32,
///     customer_name: String,
///     items: Vec<String>,
///     is_cancelled: bool,
/// }
///
/// let decider: Decider<OrderCommand, OrderState, OrderEvent> = decider();
/// let create_order_command = OrderCommand::Create(CreateOrderCommand {
///     order_id: 1,
///     customer_name: "John Doe".to_string(),
///     items: vec!["Item 1".to_string(), "Item 2".to_string()],
/// });
/// let new_events = decider.compute_new_events(&[], &create_order_command);
///     assert_eq!(new_events, [OrderEvent::Created(OrderCreatedEvent {
///         order_id: 1,
///         customer_name: "John Doe".to_string(),
///         items: vec!["Item 1".to_string(), "Item 2".to_string()],
///     })]);
///     let new_state = decider.compute_new_state(None, &create_order_command);
///     assert_eq!(new_state, OrderState {
///         order_id: 1,
///         customer_name: "John Doe".to_string(),
///         items: vec!["Item 1".to_string(), "Item 2".to_string()],
///         is_cancelled: false,
///     });
///
/// ```
pub struct Decider<'a, C: 'a, S: 'a, E: 'a> {
    /// The `decide` function is used to decide which events to produce based on the command and the current state.
    pub decide: DecideFunction<'a, C, S, E>,
    /// The `evolve` function is used to evolve the state based on the current state and the event.
    pub evolve: EvolveFunction<'a, S, E>,
    /// The `initial_state` function is used to produce the initial state of the decider.
    pub initial_state: InitialStateFunction<'a, S>,
}

impl<'a, C, S, E> Decider<'a, C, S, E> {
    /// Maps the Decider over the S/State type parameter.
    /// Creates a new instance of [Decider]`<C, S2, E>`.
    pub fn map_state<S2, F1, F2>(self, f1: &'a F1, f2: &'a F2) -> Decider<'a, C, S2, E>
    where
        F1: Fn(&S2) -> S + Send + Sync,
        F2: Fn(&S) -> S2 + Send + Sync,
    {
        let new_decide = Box::new(move |c: &C, s2: &S2| {
            let s = f1(s2);
            (self.decide)(c, &s)
        });

        let new_evolve = Box::new(move |s2: &S2, e: &E| {
            let s = f1(s2);
            f2(&(self.evolve)(&s, e))
        });

        let new_initial_state = Box::new(move || f2(&(self.initial_state)()));

        Decider {
            decide: new_decide,
            evolve: new_evolve,
            initial_state: new_initial_state,
        }
    }

    /// Maps the Decider over the E/Event type parameter.
    /// Creates a new instance of [Decider]`<C, S, E2>`.
    pub fn map_event<E2, F1, F2>(self, f1: &'a F1, f2: &'a F2) -> Decider<'a, C, S, E2>
    where
        F1: Fn(&E2) -> E + Send + Sync,
        F2: Fn(&E) -> E2 + Send + Sync,
    {
        let new_decide = Box::new(move |c: &C, s: &S| {
            (self.decide)(c, s).into_iter().map(|e: E| f2(&e)).collect()
        });

        let new_evolve = Box::new(move |s: &S, e2: &E2| {
            let e = f1(e2);
            (self.evolve)(s, &e)
        });

        let new_initial_state = Box::new(move || (self.initial_state)());

        Decider {
            decide: new_decide,
            evolve: new_evolve,
            initial_state: new_initial_state,
        }
    }

    /// Maps the Decider over the C/Command type parameter.
    /// Creates a new instance of [Decider]`<C2, S, E>`.
    pub fn map_command<C2, F>(self, f: &'a F) -> Decider<'a, C2, S, E>
    where
        F: Fn(&C2) -> C + Send + Sync,
    {
        let new_decide = Box::new(move |c2: &C2, s: &S| {
            let c = f(c2);
            (self.decide)(&c, s)
        });

        let new_evolve = Box::new(move |s: &S, e: &E| (self.evolve)(s, e));

        let new_initial_state = Box::new(move || (self.initial_state)());

        Decider {
            decide: new_decide,
            evolve: new_evolve,
            initial_state: new_initial_state,
        }
    }

    /// Combines two deciders into one bigger decider
    /// Creates a new instance of a Decider by combining two deciders of type `C`, `S`, `E` and `C2`, `S2`, `E2` into a new decider of type `Sum<C, C2>`, `(S, S2)`, `Sum<E, E2>`
    pub fn combine<C2, S2, E2>(
        self,
        decider2: Decider<'a, C2, S2, E2>,
    ) -> Decider<'a, Sum<C, C2>, (S, S2), Sum<E, E2>>
    where
        S: Clone,
        S2: Clone,
    {
        let new_decide = Box::new(move |c: &Sum<C, C2>, s: &(S, S2)| match c {
            Sum::First(c) => {
                let s1 = &s.0;
                let events = (self.decide)(c, s1);
                events
                    .into_iter()
                    .map(|e: E| Sum::First(e))
                    .collect::<Vec<Sum<E, E2>>>()
            }
            Sum::Second(c) => {
                let s2 = &s.1;
                let events = (decider2.decide)(c, s2);
                events
                    .into_iter()
                    .map(|e: E2| Sum::Second(e))
                    .collect::<Vec<Sum<E, E2>>>()
            }
        });

        let new_evolve = Box::new(move |s: &(S, S2), e: &Sum<E, E2>| match e {
            Sum::First(e) => {
                let s1 = &s.0;
                let new_state = (self.evolve)(s1, e);
                (new_state, s.1.to_owned())
            }
            Sum::Second(e) => {
                let s2 = &s.1;
                let new_state = (decider2.evolve)(s2, e);
                (s.0.to_owned(), new_state)
            }
        });

        let new_initial_state = Box::new(move || {
            let s1 = (self.initial_state)();
            let s2 = (decider2.initial_state)();
            (s1, s2)
        });

        Decider {
            decide: new_decide,
            evolve: new_evolve,
            initial_state: new_initial_state,
        }
    }
}

/// Formalizes the `Event Computation` algorithm / event sourced system for the `decider` to handle commands based on the current events, and produce new events.
pub trait EventComputation<C, S, E> {
    /// Computes new events based on the current events and the command.
    fn compute_new_events(&self, current_events: &[E], command: &C) -> Vec<E>;
}

/// Formalizes the `State Computation` algorithm / state-stored system for the `decider` to handle commands based on the current state, and produce new state.
pub trait StateComputation<C, S, E> {
    /// Computes new state based on the current state and the command.
    fn compute_new_state(&self, current_state: Option<S>, command: &C) -> S;
}

impl<'a, C, S, E> EventComputation<C, S, E> for Decider<'a, C, S, E> {
    /// Computes new events based on the current events and the command.
    fn compute_new_events(&self, current_events: &[E], command: &C) -> Vec<E> {
        let current_state: S = current_events
            .iter()
            .fold((self.initial_state)(), |state, event| {
                (self.evolve)(&state, event)
            });
        (self.decide)(command, &current_state)
    }
}

impl<'a, C, S, E> StateComputation<C, S, E> for Decider<'a, C, S, E> {
    /// Computes new state based on the current state and the command.
    fn compute_new_state(&self, current_state: Option<S>, command: &C) -> S {
        let effective_current_state = current_state.unwrap_or_else(|| (self.initial_state)());
        let events = (self.decide)(command, &effective_current_state);
        events
            .into_iter()
            .fold(effective_current_state, |state, event| {
                (self.evolve)(&state, &event)
            })
    }
}