Skip to content

Commit

Permalink
ActionComputation trait added. Saga as implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
idugalic committed Dec 2, 2023
1 parent 95a0a19 commit 7ef6d43
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
13 changes: 13 additions & 0 deletions src/saga.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,16 @@ impl<'a, AR, A> Saga<'a, AR, A> {
Saga { react: new_react }
}
}

/// Formalizes the `Action Computation` algorithm for the `saga` to handle events/action_results, and produce new commands/actions.
pub trait ActionComputation<AR, A> {
/// Computes new commands/actions based on the event/action_result.
fn compute_new_actions(&self, event: &AR) -> Vec<A>;
}

impl<'a, AR, A> ActionComputation<AR, A> for Saga<'a, AR, A> {
/// Computes new commands/actions based on the event/action_result.
fn compute_new_actions(&self, event: &AR) -> Vec<A> {
(self.react)(event).into_iter().collect()
}
}
14 changes: 8 additions & 6 deletions src/saga_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::marker::PhantomData;

use async_trait::async_trait;

use crate::saga::Saga;
use crate::saga::ActionComputation;

/// Publishes the action/command to some external system.
///
Expand All @@ -26,21 +26,23 @@ pub trait ActionPublisher<A, Error> {
/// - `AR` - Action Result / Event
/// - `Publisher` - Action Publisher
/// - `Error` - Error
pub struct SagaManager<'a, A, AR, Publisher, Error>
pub struct SagaManager<A, AR, Publisher, Saga, Error>
where
Publisher: ActionPublisher<A, Error>,
Saga: ActionComputation<AR, A>,
{
action_publisher: Publisher,
saga: Saga<'a, AR, A>,
saga: Saga,
_marker: PhantomData<(A, AR, Error)>,
}

impl<'a, A, AR, Publisher, Error> SagaManager<'a, A, AR, Publisher, Error>
impl<A, AR, Publisher, Saga, Error> SagaManager<A, AR, Publisher, Saga, Error>
where
Publisher: ActionPublisher<A, Error>,
Saga: ActionComputation<AR, A>,
{
/// Creates a new instance of [SagaManager].
pub fn new(action_publisher: Publisher, saga: Saga<'a, AR, A>) -> Self {
pub fn new(action_publisher: Publisher, saga: Saga) -> Self {
SagaManager {
action_publisher,
saga,
Expand All @@ -49,7 +51,7 @@ where
}
/// Handles the action result by publishing it to the external system.
pub async fn handle(&self, action_result: &AR) -> Result<Vec<A>, Error> {
let new_actions = (self.saga.react)(action_result);
let new_actions = self.saga.compute_new_actions(action_result);
let published_actions = self.action_publisher.publish(&new_actions).await?;
Ok(published_actions)
}
Expand Down

0 comments on commit 7ef6d43

Please sign in to comment.