fmodel-rust 0.9.1

Accelerate development of compositional, safe, and ergonomic applications/information systems by effectively implementing Event Sourcing and CQRS patterns in Rust.
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
use std::future::Future;
use std::marker::PhantomData;

use crate::decider::{Decider, EventComputation, StateComputation};
use crate::saga::{ActionComputation, Saga};
use crate::Identifier;

/// Event Repository trait
///
/// Generic parameters:
///
/// - `C` - Command
/// - `E` - Event
/// - `Version` - Version/Offset/Sequence number
/// - `Error` - Error
#[cfg(not(feature = "not-send-futures"))]
pub trait EventRepository<C, E, Version, Error> {
    /// Fetches current events, based on the command.
    /// Desugared `async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error>;` to a normal `fn` that returns `impl Future`, and adds bound `Send`.
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls. This is true even when one form has a Send bound.
    fn fetch_events(
        &self,
        command: &C,
    ) -> impl Future<Output = Result<Vec<(E, Version)>, Error>> + Send;
    /// Saves events.
    /// Desugared `async fn save(&self, events: &[E], latest_version: &Option<Version>) -> Result<Vec<(E, Version)>, Error>;` to a normal `fn` that returns `impl Future`, and adds bound `Send`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls. This is true even when one form has a Send bound.
    fn save(&self, events: &[E]) -> impl Future<Output = Result<Vec<(E, Version)>, Error>> + Send;

    /// Version provider. It is used to provide the version/sequence of the stream to wich this event belongs to. Optimistic locking is useing this version to check if the event is already saved.
    /// Desugared `async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error>;` to a normal `fn` that returns `impl Future`, and adds bound `Send`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls. This is true even when one form has a Send bound.
    fn version_provider(
        &self,
        event: &E,
    ) -> impl Future<Output = Result<Option<Version>, Error>> + Send;
}

/// Event Repository trait
///
/// Generic parameters:
///
/// - `C` - Command
/// - `E` - Event
/// - `Version` - Version/Offset/Sequence number
/// - `Error` - Error
#[cfg(feature = "not-send-futures")]
pub trait EventRepository<C, E, Version, Error> {
    /// Fetches current events, based on the command.
    /// Desugared `async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error>;` to a normal `fn` that returns `impl Future`.
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls.
    fn fetch_events(&self, command: &C) -> impl Future<Output = Result<Vec<(E, Version)>, Error>>;
    /// Saves events.
    /// Desugared `async fn save(&self, events: &[E], latest_version: &Option<Version>) -> Result<Vec<(E, Version)>, Error>;` to a normal `fn` that returns `impl Future`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls.
    fn save(&self, events: &[E]) -> impl Future<Output = Result<Vec<(E, Version)>, Error>>;

    /// Version provider. It is used to provide the version/sequence of the stream to wich this event belongs to. Optimistic locking is useing this version to check if the event is already saved.
    /// Desugared `async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error>;` to a normal `fn` that returns `impl Future`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls.
    fn version_provider(&self, event: &E) -> impl Future<Output = Result<Option<Version>, Error>>;
}

/// Event Sourced Aggregate.
///
/// It is using a `Decider` / [EventComputation] to compute new events based on the current events and the command.
/// It is using a [EventRepository] to fetch the current events and to save the new events.
///
/// Generic parameters:
///
/// - `C` - Command
/// - `S` - State
/// - `E` - Event
/// - `Repository` - Event repository
/// - `Decider` - Event computation
/// - `Version` - Version/Offset/Sequence number
/// - `Error` - Error
pub struct EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
    Decider: EventComputation<C, S, E, Error>,
{
    repository: Repository,
    decider: Decider,
    _marker: PhantomData<(C, S, E, Version, Error)>,
}

impl<C, S, E, Repository, Decider, Version, Error> EventComputation<C, S, E, Error>
    for EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
    Decider: EventComputation<C, S, E, Error>,
{
    /// Computes new events based on the current events and the command.
    fn compute_new_events(&self, current_events: &[E], command: &C) -> Result<Vec<E>, Error> {
        self.decider.compute_new_events(current_events, command)
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Decider, Version, Error> EventRepository<C, E, Version, Error>
    for EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error> + Sync,
    Decider: EventComputation<C, S, E, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Fetches current events, based on the command.
    async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        self.repository.fetch_events(command).await
    }
    /// Saves events.
    async fn save(&self, events: &[E]) -> Result<Vec<(E, Version)>, Error> {
        self.repository.save(events).await
    }
    /// Version provider. It is used to provide the version/sequence of the event. Optimistic locking is useing this version to check if the event is already saved.
    async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error> {
        self.repository.version_provider(event).await
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Decider, Version, Error> EventRepository<C, E, Version, Error>
    for EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
    Decider: EventComputation<C, S, E, Error>,
{
    /// Fetches current events, based on the command.
    async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        self.repository.fetch_events(command).await
    }
    /// Saves events.
    async fn save(&self, events: &[E]) -> Result<Vec<(E, Version)>, Error> {
        self.repository.save(events).await
    }
    /// Version provider. It is used to provide the version/sequence of the event. Optimistic locking is useing this version to check if the event is already saved.
    async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error> {
        self.repository.version_provider(event).await
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Decider, Version, Error>
    EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error> + Sync,
    Decider: EventComputation<C, S, E, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Creates a new instance of [EventSourcedAggregate].
    pub fn new(repository: Repository, decider: Decider) -> Self {
        EventSourcedAggregate {
            repository,
            decider,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the events from the repository, computing new events based on the current events and the command, and saving the new events to the repository.
    pub async fn handle(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        let events: Vec<(E, Version)> = self.fetch_events(command).await?;
        let mut current_events: Vec<E> = vec![];
        for (event, _) in events {
            current_events.push(event);
        }
        let new_events = self.compute_new_events(&current_events, command)?;
        let saved_events = self.save(&new_events).await?;
        Ok(saved_events)
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Decider, Version, Error>
    EventSourcedAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
    Decider: EventComputation<C, S, E, Error>,
{
    /// Creates a new instance of [EventSourcedAggregate].
    pub fn new(repository: Repository, decider: Decider) -> Self {
        EventSourcedAggregate {
            repository,
            decider,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the events from the repository, computing new events based on the current events and the command, and saving the new events to the repository.
    pub async fn handle(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        let events: Vec<(E, Version)> = self.fetch_events(command).await?;
        let mut current_events: Vec<E> = vec![];
        for (event, _) in events {
            current_events.push(event);
        }
        let new_events = self.compute_new_events(&current_events, command)?;
        let saved_events = self.save(&new_events).await?;
        Ok(saved_events)
    }
}

/// State Repository trait
///
/// Generic parameters:
///
/// - `C` - Command
/// - `S` - State
/// - `Version` - Version
/// - `Error` - Error
#[cfg(not(feature = "not-send-futures"))]
pub trait StateRepository<C, S, Version, Error> {
    /// Fetches current state, based on the command.
    /// Desugared `async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error>;` to a normal `fn` that returns `impl Future` and adds bound `Send`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls. This is true even when one form has a Send bound.
    fn fetch_state(
        &self,
        command: &C,
    ) -> impl Future<Output = Result<Option<(S, Version)>, Error>> + Send;
    /// Saves state.
    /// Desugared `async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error>;` to a normal `fn` that returns `impl Future` and adds bound `Send`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls. This is true even when one form has a Send bound.
    fn save(
        &self,
        state: &S,
        version: &Option<Version>,
    ) -> impl Future<Output = Result<(S, Version), Error>> + Send;
}

/// State Repository trait
///
/// Generic parameters:
///
/// - `C` - Command
/// - `S` - State
/// - `Version` - Version
/// - `Error` - Error
#[cfg(feature = "not-send-futures")]
pub trait StateRepository<C, S, Version, Error> {
    /// Fetches current state, based on the command.
    /// Desugared `async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error>;` to a normal `fn` that returns `impl Future`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls.
    fn fetch_state(&self, command: &C)
        -> impl Future<Output = Result<Option<(S, Version)>, Error>>;
    /// Saves state.
    /// Desugared `async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error>;` to a normal `fn` that returns `impl Future`
    /// You can freely move between the `async fn` and `-> impl Future` spelling in your traits and impls.
    fn save(
        &self,
        state: &S,
        version: &Option<Version>,
    ) -> impl Future<Output = Result<(S, Version), Error>>;
}

/// State Stored Aggregate.
///
/// It is using a `Decider` / [StateComputation] to compute new state based on the current state and the command.
/// It is using a [StateRepository] to fetch the current state and to save the new state.
///
/// Generic parameters:
///
/// - `C` - Command
/// - `S` - State
/// - `E` - Event
/// - `Repository` - State repository
/// - `Decider` - State computation
/// - `Version` - Version
/// - `Error` - Error
pub struct StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    Decider: StateComputation<C, S, E, Error>,
{
    repository: Repository,
    decider: Decider,
    _marker: PhantomData<(C, S, E, Version, Error)>,
}

impl<C, S, E, Repository, Decider, Version, Error> StateComputation<C, S, E, Error>
    for StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    Decider: StateComputation<C, S, E, Error>,
{
    /// Computes new state based on the current state and the command.
    fn compute_new_state(&self, current_state: Option<S>, command: &C) -> Result<S, Error> {
        self.decider.compute_new_state(current_state, command)
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Decider, Version, Error> StateRepository<C, S, Version, Error>
    for StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error> + Sync,
    Decider: StateComputation<C, S, E, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Fetches current state, based on the command.
    async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error> {
        self.repository.fetch_state(command).await
    }
    /// Saves state.
    async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error> {
        self.repository.save(state, version).await
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Decider, Version, Error> StateRepository<C, S, Version, Error>
    for StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    Decider: StateComputation<C, S, E, Error>,
{
    /// Fetches current state, based on the command.
    async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error> {
        self.repository.fetch_state(command).await
    }
    /// Saves state.
    async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error> {
        self.repository.save(state, version).await
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Decider, Version, Error>
    StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error> + Sync,
    Decider: StateComputation<C, S, E, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Creates a new instance of [StateStoredAggregate].
    pub fn new(repository: Repository, decider: Decider) -> Self {
        StateStoredAggregate {
            repository,
            decider,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the state from the repository, computing new state based on the current state and the command, and saving the new state to the repository.
    pub async fn handle(&self, command: &C) -> Result<(S, Version), Error> {
        let state_version = self.fetch_state(command).await?;
        match state_version {
            None => {
                let new_state = self.compute_new_state(None, command)?;
                let saved_state = self.save(&new_state, &None).await?;
                Ok(saved_state)
            }
            Some((state, version)) => {
                let new_state = self.compute_new_state(Some(state), command)?;
                let saved_state = self.save(&new_state, &Some(version)).await?;
                Ok(saved_state)
            }
        }
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Decider, Version, Error>
    StateStoredAggregate<C, S, E, Repository, Decider, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    Decider: StateComputation<C, S, E, Error>,
{
    /// Creates a new instance of [StateStoredAggregate].
    pub fn new(repository: Repository, decider: Decider) -> Self {
        StateStoredAggregate {
            repository,
            decider,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the state from the repository, computing new state based on the current state and the command, and saving the new state to the repository.
    pub async fn handle(&self, command: &C) -> Result<(S, Version), Error> {
        let state_version = self.fetch_state(command).await?;
        match state_version {
            None => {
                let new_state = self.compute_new_state(None, command)?;
                let saved_state = self.save(&new_state, &None).await?;
                Ok(saved_state)
            }
            Some((state, version)) => {
                let new_state = self.compute_new_state(Some(state), command)?;
                let saved_state = self.save(&new_state, &Some(version)).await?;
                Ok(saved_state)
            }
        }
    }
}

/// Orchestrating Event Sourced Aggregate.
/// It is using a [Decider] and [Saga] to compute new events based on the current events and the command.
/// If the `decider` is combined out of many deciders via `combine` function, a `saga` could be used to react on new events and send new commands to the `decider` recursively, in single transaction.
/// It is using a [EventRepository] to fetch the current events and to save the new events.
/// Generic parameters:
/// - `C` - Command
/// - `S` - State
/// - `E` - Event
/// - `Repository` - Event repository
/// - `Version` - Version/Offset/Sequence number
/// - `Error` - Error
pub struct EventSourcedOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
{
    repository: Repository,
    decider: Decider<'a, C, S, E, Error>,
    saga: Saga<'a, E, C>,
    _marker: PhantomData<(C, S, E, Version, Error)>,
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Version, Error> EventRepository<C, E, Version, Error>
    for EventSourcedOrchestratingAggregate<'_, C, S, E, Repository, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Fetches current events, based on the command.
    async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        self.repository.fetch_events(command).await
    }
    /// Saves events.
    async fn save(&self, events: &[E]) -> Result<Vec<(E, Version)>, Error> {
        self.repository.save(events).await
    }
    /// Version provider. It is used to provide the version/sequence of the event. Optimistic locking is useing this version to check if the event is already saved.
    async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error> {
        self.repository.version_provider(event).await
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Version, Error> EventRepository<C, E, Version, Error>
    for EventSourcedOrchestratingAggregate<'_, C, S, E, Repository, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
{
    /// Fetches current events, based on the command.
    async fn fetch_events(&self, command: &C) -> Result<Vec<(E, Version)>, Error> {
        self.repository.fetch_events(command).await
    }
    /// Saves events.
    async fn save(&self, events: &[E]) -> Result<Vec<(E, Version)>, Error> {
        self.repository.save(events).await
    }
    /// Version provider. It is used to provide the version/sequence of the event. Optimistic locking is useing this version to check if the event is already saved.
    async fn version_provider(&self, event: &E) -> Result<Option<Version>, Error> {
        self.repository.version_provider(event).await
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<'a, C, S, E, Repository, Version, Error>
    EventSourcedOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync + Clone,
    Version: Sync,
    Error: Sync,
{
    /// Creates a new instance of [EventSourcedAggregate].
    pub fn new(
        repository: Repository,
        decider: Decider<'a, C, S, E, Error>,
        saga: Saga<'a, E, C>,
    ) -> Self {
        EventSourcedOrchestratingAggregate {
            repository,
            decider,
            saga,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the events from the repository, computing new events based on the current events and the command, and saving the new events to the repository.
    pub async fn handle(&self, command: &C) -> Result<Vec<(E, Version)>, Error>
    where
        E: Identifier,
        C: Identifier,
    {
        let events: Vec<(E, Version)> = self.fetch_events(command).await?;
        let mut current_events: Vec<E> = vec![];
        for (event, _) in events {
            current_events.push(event);
        }
        let new_events = self
            .compute_new_events_dynamically(&current_events, command)
            .await?;
        let saved_events = self.save(&new_events).await?;
        Ok(saved_events)
    }
    /// Computes new events based on the current events and the command.
    /// It is using a [Decider] and [Saga] to compute new events based on the current events and the command.
    /// If the `decider` is combined out of many deciders via `combine` function, a `saga` could be used to react on new events and send new commands to the `decider` recursively, in single transaction.
    /// It is using a [EventRepository] to fetch the current events for the command that is computed by the `saga`.
    async fn compute_new_events_dynamically(
        &self,
        current_events: &[E],
        command: &C,
    ) -> Result<Vec<E>, Error>
    where
        E: Identifier,
        C: Identifier,
    {
        let current_state: S = current_events
            .iter()
            .fold((self.decider.initial_state)(), |state, event| {
                (self.decider.evolve)(&state, event)
            });

        let initial_events = (self.decider.decide)(command, &current_state)?;

        let commands: Vec<C> = initial_events
            .iter()
            .flat_map(|event: &E| self.saga.compute_new_actions(event))
            .collect();

        // Collect all events including recursively computed new events.
        let mut all_events = initial_events.clone();

        for command in commands.iter() {
            let previous_events = [
                self.repository
                    .fetch_events(command)
                    .await?
                    .iter()
                    .map(|(e, _)| e.clone())
                    .collect::<Vec<E>>(),
                initial_events
                    .clone()
                    .into_iter()
                    .filter(|e| e.identifier() == command.identifier())
                    .collect::<Vec<E>>(),
            ]
            .concat();

            // Recursively compute new events and extend the accumulated events list.
            // By wrapping the recursive call in a Box, we ensure that the future type is not self-referential.
            let new_events =
                Box::pin(self.compute_new_events_dynamically(&previous_events, command)).await?;
            all_events.extend(new_events);
        }

        Ok(all_events)
    }
}

#[cfg(feature = "not-send-futures")]
impl<'a, C, S, E, Repository, Version, Error>
    EventSourcedOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: EventRepository<C, E, Version, Error>,
    E: Clone,
{
    /// Creates a new instance of [EventSourcedAggregate].
    pub fn new(
        repository: Repository,
        decider: Decider<'a, C, S, E, Error>,
        saga: Saga<'a, E, C>,
    ) -> Self {
        EventSourcedOrchestratingAggregate {
            repository,
            decider,
            saga,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the events from the repository, computing new events based on the current events and the command, and saving the new events to the repository.
    pub async fn handle(&self, command: &C) -> Result<Vec<(E, Version)>, Error>
    where
        E: Identifier,
        C: Identifier,
    {
        let events: Vec<(E, Version)> = self.fetch_events(command).await?;
        let mut current_events: Vec<E> = vec![];
        for (event, _) in events {
            current_events.push(event);
        }
        let new_events = self
            .compute_new_events_dynamically(&current_events, command)
            .await?;
        let saved_events = self.save(&new_events).await?;
        Ok(saved_events)
    }
    /// Computes new events based on the current events and the command.
    /// It is using a [Decider] and [Saga] to compute new events based on the current events and the command.
    /// If the `decider` is combined out of many deciders via `combine` function, a `saga` could be used to react on new events and send new commands to the `decider` recursively, in single transaction.
    /// It is using a [EventRepository] to fetch the current events for the command that is computed by the `saga`.
    async fn compute_new_events_dynamically(
        &self,
        current_events: &[E],
        command: &C,
    ) -> Result<Vec<E>, Error>
    where
        E: Identifier,
        C: Identifier,
    {
        let current_state: S = current_events
            .iter()
            .fold((self.decider.initial_state)(), |state, event| {
                (self.decider.evolve)(&state, event)
            });

        let initial_events = (self.decider.decide)(command, &current_state)?;

        let commands: Vec<C> = initial_events
            .iter()
            .flat_map(|event: &E| self.saga.compute_new_actions(event))
            .collect();

        // Collect all events including recursively computed new events.
        let mut all_events = initial_events.clone();

        for command in commands.iter() {
            let previous_events = [
                self.repository
                    .fetch_events(command)
                    .await?
                    .iter()
                    .map(|(e, _)| e.clone())
                    .collect::<Vec<E>>(),
                initial_events
                    .clone()
                    .into_iter()
                    .filter(|e| e.identifier() == command.identifier())
                    .collect::<Vec<E>>(),
            ]
            .concat();

            // Recursively compute new events and extend the accumulated events list.
            // By wrapping the recursive call in a Box, we ensure that the future type is not self-referential.
            let new_events =
                Box::pin(self.compute_new_events_dynamically(&previous_events, command)).await?;
            all_events.extend(new_events);
        }

        Ok(all_events)
    }
}

/// Orchestrating State Stored Aggregate.
///
/// It is using a [Decider] and [Saga] to compute new state based on the current state and the command.
/// If the `decider` is combined out of many deciders via `combine` function, a `saga` could be used to react on new events and send new commands to the `decider` recursively, in single transaction.
/// It is using a [StateRepository] to fetch the current state and to save the new state.
///
/// Generic parameters:
///
/// - `C` - Command
/// - `S` - State
/// - `E` - Event
/// - `Repository` - State repository
/// - `Version` - Version
/// - `Error` - Error
pub struct StateStoredOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
{
    repository: Repository,
    decider: Decider<'a, C, S, E, Error>,
    saga: Saga<'a, E, C>,
    _marker: PhantomData<(C, S, E, Version, Error)>,
}

impl<C, S, E, Repository, Version, Error> StateComputation<C, S, E, Error>
    for StateStoredOrchestratingAggregate<'_, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    S: Clone,
{
    /// Computes new state based on the current state and the command.
    fn compute_new_state(&self, current_state: Option<S>, command: &C) -> Result<S, Error> {
        let effective_current_state =
            current_state.unwrap_or_else(|| (self.decider.initial_state)());
        let events = (self.decider.decide)(command, &effective_current_state)?;
        let mut new_state = events.iter().fold(effective_current_state, |state, event| {
            (self.decider.evolve)(&state, event)
        });
        let commands = events
            .iter()
            .flat_map(|event: &E| self.saga.compute_new_actions(event))
            .collect::<Vec<C>>();
        for action in commands {
            new_state = self.compute_new_state(Some(new_state.clone()), &action)?;
        }
        Ok(new_state)
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<C, S, E, Repository, Version, Error> StateRepository<C, S, Version, Error>
    for StateStoredOrchestratingAggregate<'_, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error> + Sync,
    C: Sync,
    S: Sync,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Fetches current state, based on the command.
    async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error> {
        self.repository.fetch_state(command).await
    }
    /// Saves state.
    async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error> {
        self.repository.save(state, version).await
    }
}

#[cfg(feature = "not-send-futures")]
impl<C, S, E, Repository, Version, Error> StateRepository<C, S, Version, Error>
    for StateStoredOrchestratingAggregate<'_, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
{
    /// Fetches current state, based on the command.
    async fn fetch_state(&self, command: &C) -> Result<Option<(S, Version)>, Error> {
        self.repository.fetch_state(command).await
    }
    /// Saves state.
    async fn save(&self, state: &S, version: &Option<Version>) -> Result<(S, Version), Error> {
        self.repository.save(state, version).await
    }
}

#[cfg(not(feature = "not-send-futures"))]
impl<'a, C, S, E, Repository, Version, Error>
    StateStoredOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error> + Sync,
    C: Sync,
    S: Sync + Clone,
    E: Sync,
    Version: Sync,
    Error: Sync,
{
    /// Creates a new instance of [StateStoredAggregate].
    pub fn new(
        repository: Repository,
        decider: Decider<'a, C, S, E, Error>,
        saga: Saga<'a, E, C>,
    ) -> Self {
        StateStoredOrchestratingAggregate {
            repository,
            decider,
            saga,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the state from the repository, computing new state based on the current state and the command, and saving the new state to the repository.
    pub async fn handle(&self, command: &C) -> Result<(S, Version), Error> {
        let state_version = self.fetch_state(command).await?;
        match state_version {
            None => {
                let new_state = self.compute_new_state(None, command)?;
                let saved_state = self.save(&new_state, &None).await?;
                Ok(saved_state)
            }
            Some((state, version)) => {
                let new_state = self.compute_new_state(Some(state), command)?;
                let saved_state = self.save(&new_state, &Some(version)).await?;
                Ok(saved_state)
            }
        }
    }
}

#[cfg(feature = "not-send-futures")]
impl<'a, C, S, E, Repository, Version, Error>
    StateStoredOrchestratingAggregate<'a, C, S, E, Repository, Version, Error>
where
    Repository: StateRepository<C, S, Version, Error>,
    S: Clone,
{
    /// Creates a new instance of [StateStoredAggregate].
    pub fn new(
        repository: Repository,
        decider: Decider<'a, C, S, E, Error>,
        saga: Saga<'a, E, C>,
    ) -> Self {
        StateStoredOrchestratingAggregate {
            repository,
            decider,
            saga,
            _marker: PhantomData,
        }
    }
    /// Handles the command by fetching the state from the repository, computing new state based on the current state and the command, and saving the new state to the repository.
    pub async fn handle(&self, command: &C) -> Result<(S, Version), Error> {
        let state_version = self.fetch_state(command).await?;
        match state_version {
            None => {
                let new_state = self.compute_new_state(None, command)?;
                let saved_state = self.save(&new_state, &None).await?;
                Ok(saved_state)
            }
            Some((state, version)) => {
                let new_state = self.compute_new_state(Some(state), command)?;
                let saved_state = self.save(&new_state, &Some(version)).await?;
                Ok(saved_state)
            }
        }
    }
}