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
//! ### UnitOfWork
//! [UnitOfWork][UOW] is to a unit that manages atomic transaction.
//!
//! Its [executor][Exec] is supposed to be shared with its sub type [Repository][TRepository].
//!
//! `commit`, and `rollback`, is governed by this implementation.
//!
//! When events are collected in `Repository`[TRepository], you can collect them
//!
//! automatically thanks to `_commit_hook` method.
//!
//! [UOW]: crate::unit_of_work::UnitOfWork
//! [TRepository]: crate::repository::TRepository
//! [Exec]: crate::unit_of_work::Executor
//! [Handler]: crate::unit_of_work::Handler
//!
//! #### Usage Pattern
//!
//! ```ignore
//! // Intialize Uow, start transaction
//! let mut uow = UnitOfWork::<Repository<TaskAggregate>, Executor,TaskAggregate>::new(context).await;
//!
//! // Fetch data
//! let mut aggregate = uow.repository().get(&cmd.aggregate_id).await?;
//!
//! // Process business logic
//! aggregate.process_business_logic(cmd)?;
//!
//! // Apply changes
//! uow.repository().update(&mut aggregate).await?;
//!
//! // Commit transaction
//! uow.commit().await?;
//! ```
//!
//!
//!
//! ### Handler
//! [Handler] is what orchestrates operations from data fetching, business logic operation and store
//! changes back to db. This is where tranasction occurs.
//!
//! ### Example
//! ```ignore
//! struct ApplicationHandler;
//! impl Handler for ApplicationHandler{
//! type E = ApplicationExecutor;
//! type R = ApplicationRepository<Aggregate>
//! }
//!
//! impl ApplicationHandler{
//! pub async fn serve_request(
//! cmd: Command1,
//! context: AtomicContextManager,
//! ) -> Result<(),ServiceError> {
//! let mut uow = TaskHandler::uow(context).await;
//! }
//! ```
use crate::{
prelude::{AtomicContextManager, BaseError},
repository::TRepository,
};
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::RwLock;
/// Executor is abstract implementation of whatever storage layer you use.
/// Among examples are RDBMS, Queue, NoSQLs.
#[async_trait]
pub trait Executor: Sync + Send {
async fn begin(&mut self) -> Result<(), BaseError>;
async fn commit(&mut self) -> Result<(), BaseError>;
async fn rollback(&mut self) -> Result<(), BaseError>;
}
#[async_trait]
pub trait TUnitOfWork: Send + Sync {
/// Creeate UOW object with context manager.
async fn begin(&mut self) -> Result<(), BaseError>;
async fn commit(&mut self) -> Result<(), BaseError>;
async fn rollback(self) -> Result<(), BaseError>;
}
pub trait TClone {
fn clone(&self) -> Self;
}
pub trait TRepositoyCallable<R>
where
R: TRepository,
{
fn repository(&mut self) -> &mut R;
}
#[derive(Clone)]
pub struct UnitOfWork<R, E>
where
R: TRepository,
E: Executor,
{
/// real transaction executor
executor: Arc<RwLock<E>>,
/// global event event_queue
context: AtomicContextManager,
/// event local repository for Executor
pub repository: R,
}
impl<R, E> UnitOfWork<R, E>
where
R: TRepository,
E: Executor,
{
pub fn new(context: AtomicContextManager, executor: Arc<RwLock<E>>, repository: R) -> Self {
Self { repository, context, executor }
}
async fn _commit(&mut self) -> Result<(), BaseError> {
let mut executor = self.executor.write().await;
executor.commit().await
}
/// commit_hook is invoked right before the calling for commit
/// which sorts out and processes outboxes and internally processable events.
async fn _commit_hook(&mut self) -> Result<(), BaseError> {
let cxt = self.clone_context();
let event_queue = &mut cxt.write().await;
let mut outboxes = vec![];
for e in self.repository.get_events() {
if e.externally_notifiable() {
outboxes.push(e.outbox());
};
if e.internally_notifiable() {
event_queue.push_back(e.message_clone());
}
}
if !outboxes.is_empty() {
self.repository().save_outbox(outboxes).await;
}
Ok(())
}
}
#[async_trait]
impl<R, E> TUnitOfWork for UnitOfWork<R, E>
where
R: TRepository,
E: Executor,
{
/// Begin transaction.
async fn begin(&mut self) -> Result<(), BaseError> {
let mut executor = self.executor.write().await;
executor.begin().await
}
/// Commit transaction.
async fn commit(&mut self) -> Result<(), BaseError> {
// To drop uow itself!
// run commit hook
self._commit_hook().await?;
// commit
self._commit().await
}
/// Rollback transaction.
async fn rollback(self) -> Result<(), BaseError> {
let mut executor = self.executor.write().await;
executor.rollback().await
}
}
impl<R, E> TRepositoyCallable<R> for UnitOfWork<R, E>
where
R: TRepository,
E: Executor,
{
fn repository(&mut self) -> &mut R {
&mut self.repository
}
}
pub trait TCloneContext {
fn clone_context(&self) -> AtomicContextManager;
}
impl<R, E> TCloneContext for UnitOfWork<R, E>
where
R: TRepository,
E: Executor,
{
fn clone_context(&self) -> AtomicContextManager {
Arc::clone(&self.context)
}
}
impl<R, E> TClone for UnitOfWork<R, E>
where
R: TRepository + TClone,
E: Executor,
{
fn clone(&self) -> Self {
Self {
executor: self.executor.clone(),
context: self.context.clone(),
repository: self.repository.clone(),
}
}
}