fmodel_rust/lib.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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
#![deny(missing_docs)]
//! # FModel Rust
//!
//! When you’re developing an information system to automate the activities of the business, you are modeling the business.
//! The abstractions that you design, the behaviors that you implement, and the UI interactions that you build all reflect
//! the business — together, they constitute the model of the domain.
//!
//! 
//!
//! ## `IOR<Library, Inspiration>`
//!
//! This crate can be used as a library, or as an inspiration, or both. It provides just enough tactical Domain-Driven
//! Design patterns, optimised for Event Sourcing and CQRS.
//!
//! 
//!
//!## Decider
//!
//! `Decider` is a datatype/struct that represents the main decision-making algorithm. It belongs to the Domain layer. It
//! has three
//! generic parameters `C`, `S`, `E` , representing the type of the values that `Decider` may contain or use.
//! `Decider` can be specialized for any type `C` or `S` or `E` because these types do not affect its
//! behavior. `Decider` behaves the same for `C`=`Int` or `C`=`YourCustomType`, for example.
//!
//! `Decider` is a pure domain component.
//!
//! - `C` - Command
//! - `S` - State
//! - `E` - Event
//!
//! ```rust
//! pub type DecideFunction<'a, C, S, E> = Box<dyn Fn(&C, &S) -> Vec<E> + 'a + Send + Sync>;
//! pub type EvolveFunction<'a, S, E> = Box<dyn Fn(&S, &E) -> S + 'a + Send + Sync>;
//! pub type InitialStateFunction<'a, S> = Box<dyn Fn() -> S + 'a + Send + Sync>;
//!
//! pub struct Decider<'a, C: 'a, S: 'a, E: 'a> {
//! pub decide: DecideFunction<'a, C, S, E>,
//! pub evolve: EvolveFunction<'a, S, E>,
//! pub initial_state: InitialStateFunction<'a, S>,
//! }
//! ```
//!
//! Additionally, `initialState` of the Decider is introduced to gain more control over the initial state of the Decider.
//!
//! ### Event-sourcing aggregate
//!
//! [aggregate::EventSourcedAggregate] is using/delegating a `Decider` to handle commands and produce new events.
//!
//! It belongs to the Application layer.
//!
//! In order to handle the command, aggregate needs to fetch the current state (represented as a list/vector of events)
//! via `EventRepository.fetchEvents` async function, and then delegate the command to the decider which can produce new
//! events as
//! a result. Produced events are then stored via `EventRepository.save` async function.
//!
//! It is a formalization of the event sourced information system.
//!
//! ### State-stored aggregate
//!
//! [aggregate::StateStoredAggregate] is using/delegating a `Decider` to handle commands and produce new state.
//!
//! It belongs to the Application layer.
//!
//! In order to handle the command, aggregate needs to fetch the current state via `StateRepository.fetchState` async function first,
//! and then
//! delegate the command to the decider which can produce new state as a result. New state is then stored
//! via `StateRepository.save` async function.
//!
//! ## View
//!
//! `View` is a datatype that represents the event handling algorithm, responsible for translating the events into
//! denormalized state, which is more adequate for querying. It belongs to the Domain layer. It is usually used to create
//! the view/query side of the CQRS pattern. Obviously, the command side of the CQRS is usually event-sourced aggregate.
//!
//! It has two generic parameters `S`, `E`, representing the type of the values that `View` may contain or use.
//! `View` can be specialized for any type of `S`, `E` because these types do not affect its behavior.
//! `View` behaves the same for `E`=`Int` or `E`=`YourCustomType`, for example.
//!
//! `View` is a pure domain component.
//!
//! - `S` - State
//! - `E` - Event
//!
//! ```rust
//! pub type EvolveFunction<'a, S, E> = Box<dyn Fn(&S, &E) -> S + 'a + Send + Sync>;
//! pub type InitialStateFunction<'a, S> = Box<dyn Fn() -> S + 'a + Send + Sync>;
//!
//! pub struct View<'a, S: 'a, E: 'a> {
//! pub evolve: EvolveFunction<'a, S, E>,
//! pub initial_state: InitialStateFunction<'a, S>,
//! }
//! ```
//!
//! ### Materialized View
//!
//! [materialized_view::MaterializedView] is using/delegating a `View` to handle events of type `E` and to maintain
//! a state of denormalized
//! projection(s) as a
//! result. Essentially, it represents the query/view side of the CQRS pattern.
//!
//! It belongs to the Application layer.
//!
//! In order to handle the event, materialized view needs to fetch the current state via `ViewStateRepository.fetchState`
//! suspending function first, and then delegate the event to the view, which can produce new state as a result. New state
//! is then stored via `ViewStateRepository.save` suspending function.
//!
//!
//! ## Saga
//!
//! `Saga` is a datatype that represents the central point of control, deciding what to execute next (`A`), based on the action result (`AR`).
//! It has two generic parameters `AR`/Action Result, `A`/Action , representing the type of the values that Saga 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.
//!
//! `Saga` is a pure domain component.
//!
//! - `AR` - Action Result/Event
//! - `A` - Action/Command
//!
//! ```rust
//! pub type ReactFunction<'a, AR, A> = Box<dyn Fn(&AR) -> Vec<A> + 'a + Send + Sync>;
//! pub struct Saga<'a, AR: 'a, A: 'a> {
//! pub react: ReactFunction<'a, AR, A>,
//! }
//! ```
//!
//! ### Saga Manager
//!
//! [saga_manager::SagaManager] is using/delegating a `Saga` to react to the action result and to publish the new actions.
//!
//! It belongs to the Application layer.
//!
//! It is using a [saga::Saga] to react to the action result and to publish the new actions.
//! It is using an [saga_manager::ActionPublisher] to publish the new actions.
//!
//! ## Clear separation between data and behaviour
//!
//!```rust
//! use fmodel_rust::decider::Decider;
//! // ## Algebraic Data Types
//! //
//! // In Rust, we can use ADTs to model our application's domain entities and relationships in a functional way, clearly defining the set of possible values and states.
//! // Rust has two main types of ADTs: `enum` and `struct`.
//! //
//! // - `enum` is used to define a type that can take on one of several possible variants - modeling a `sum/OR` type.
//! // - `struct` is used to express a type that has named fields - modeling a `product/AND` type.
//! //
//! // ADTs will help with
//! //
//! // - representing the business domain in the code accurately
//! // - enforcing correctness
//! // - reducing the likelihood of bugs.
//!
//!
//! // ### `C` / Command / Intent to change the state of the system
//!
//! // models Sum/Or type / multiple possible variants
//! pub enum OrderCommand {
//! Create(CreateOrderCommand),
//! Update(UpdateOrderCommand),
//! Cancel(CancelOrderCommand),
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct CreateOrderCommand {
//! pub order_id: u32,
//! pub customer_name: String,
//! pub items: Vec<String>,
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct UpdateOrderCommand {
//! pub order_id: u32,
//! pub new_items: Vec<String>,
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct CancelOrderCommand {
//! pub order_id: u32,
//! }
//!
//! // ### `E` / Event / Fact
//!
//! // models Sum/Or type / multiple possible variants
//! pub enum OrderEvent {
//! Created(OrderCreatedEvent),
//! Updated(OrderUpdatedEvent),
//! Cancelled(OrderCancelledEvent),
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct OrderCreatedEvent {
//! pub order_id: u32,
//! pub customer_name: String,
//! pub items: Vec<String>,
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct OrderUpdatedEvent {
//! pub order_id: u32,
//! pub updated_items: Vec<String>,
//! }
//! // models Product/And type / a concrete variant, consisting of named fields
//! pub struct OrderCancelledEvent {
//! pub order_id: u32,
//! }
//!
//! // ### `S` / State / Current state of the system/aggregate/entity
//! #[derive(Clone)]
//! struct OrderState {
//! order_id: u32,
//! customer_name: String,
//! items: Vec<String>,
//! is_cancelled: bool,
//! }
//!
//! // ## Modeling the Behaviour of our domain
//! //
//! // - algebraic data types form the structure of our entities (commands, state, and events).
//! // - functions/lambda offers the algebra of manipulating the entities in a compositional manner, effectively modeling the behavior.
//! //
//! // This leads to modularity in design and a clear separation of the entity’s structure and functions/behaviour of the entity.
//! //
//! // Fmodel library offers generic and abstract components to specialize in for your specific case/expected behavior
//!
//! fn decider<'a>() -> Decider<'a, OrderCommand, OrderState, OrderEvent> {
//! Decider {
//! // Your decision logic goes here.
//! decide: Box::new(|command, state| match command {
//! // Exhaustive pattern matching on the 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) => {
//! // Your validation logic goes here
//! 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 {
//! // In case of validation failure, return empty list of events or error event
//! vec![]
//! }
//! }
//! OrderCommand::Cancel(cancel_cmd) => {
//! // Your validation logic goes here
//! if state.order_id == cancel_cmd.order_id {
//! vec![OrderEvent::Cancelled(OrderCancelledEvent {
//! order_id: cancel_cmd.order_id,
//! })]
//! } else {
//! // In case of validation failure, return empty list of events or error event
//! vec![]
//! }
//! }
//! }),
//! // Evolve the state based on the event(s)
//! evolve: Box::new(|state, event| {
//! let mut new_state = state.clone();
//! // Exhaustive pattern matching on the event
//! 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
//! initial_state: Box::new(|| OrderState {
//! order_id: 0,
//! customer_name: "".to_string(),
//! items: Vec::new(),
//! is_cancelled: false,
//! }),
//! }
//! }
//! ```
//!
//! ## Examples
//!
//! - [Gift Card Demo - with Axon](https://!github.com/AxonIQ/axon-rust/tree/main/gift-card-rust)
//! - [FModel Rust Tests](https://!github.com/fraktalio/fmodel-rust/tree/main/tests)
//!
//! ## GitHub
//!
//! - [FModel Rust](https://!github.com/fraktalio/fmodel-rust)
//!
//! ## FModel in other languages
//!
//! - [FModel Kotlin](https://!github.com/fraktalio/fmodel/)
//! - [FModel TypeScript](https://!github.com/fraktalio/fmodel-ts/)
//! - [FModel Java](https://!github.com/fraktalio/fmodel-java/)
//!
//! ## Credits
//!
//! Special credits to `Jérémie Chassaing` for sharing his [research](https://!www.youtube.com/watch?v=kgYGMVDHQHs)
//! and `Adam Dymitruk` for hosting the meetup.
//!
//! ---
//! Created with `love` by [Fraktalio](https://!fraktalio.com/)
use serde::{Deserialize, Serialize};
/// Aggregate module - belongs to the `Application` layer - composes pure logic and effects (fetching, storing)
pub mod aggregate;
/// Decider module - belongs to the `Domain` layer - pure decision making component - pure logic
pub mod decider;
/// Materialized View module - belongs to the `Application` layer - composes pure event handling algorithm and effects (fetching, storing)
pub mod materialized_view;
/// Saga module - belongs to the `Domain` layer - pure mapper of action results/events into new actions/commands
pub mod saga;
/// Saga Manager module - belongs to the `Application` layer - composes pure saga and effects (publishing)
pub mod saga_manager;
/// View module - belongs to the `Domain` layer - pure event handling algorithm
pub mod view;
/// The [DecideFunction] function is used to decide which events to produce based on the command and the current state.
pub type DecideFunction<'a, C, S, E> = Box<dyn Fn(&C, &S) -> Vec<E> + 'a + Send + Sync>;
/// The [EvolveFunction] function is used to evolve the state based on the current state and the event.
pub type EvolveFunction<'a, S, E> = Box<dyn Fn(&S, &E) -> S + 'a + Send + Sync>;
/// The [InitialStateFunction] function is used to produce the initial state.
pub type InitialStateFunction<'a, S> = Box<dyn Fn() -> S + 'a + Send + Sync>;
/// The [ReactFunction] function is used to decide what actions/A to execute next based on the action result/AR.
pub type ReactFunction<'a, AR, A> = Box<dyn Fn(&AR) -> Vec<A> + 'a + Send + Sync>;
/// Define the generic Combined/Sum Enum
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Sum<A, B> {
/// First variant
First(A),
/// Second variant
Second(B),
}