use crate::error::{Error, Result};
use crate::task::IntoTaskName;
use crate::workflow::WorkflowContext;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::VecDeque;
pub struct Saga {
compensations: VecDeque<CompensationEntry>,
completed: bool,
steps_executed: usize,
}
#[derive(Debug, Clone)]
struct CompensationEntry {
compensation_task: &'static str,
compensation_input: Vec<u8>,
step_number: usize,
}
pub struct SagaStepBuilder<'a, I> {
saga: &'a mut Saga,
ctx: &'a WorkflowContext,
action_task: &'static str,
action_input: I,
compensation_task: Option<&'static str>,
}
impl Saga {
pub fn new() -> Self {
Self {
compensations: VecDeque::new(),
completed: false,
steps_executed: 0,
}
}
pub fn add_step<'a, T, I>(
&'a mut self,
ctx: &'a WorkflowContext,
action_task: T,
action_input: I,
) -> SagaStepBuilder<'a, I>
where
T: IntoTaskName,
I: Serialize,
{
SagaStepBuilder {
saga: self,
ctx,
action_task: action_task.into_task_name(),
action_input,
compensation_task: None,
}
}
pub fn add_compensation<T, C>(&mut self, compensation_task: T, compensation_input: C)
where
T: IntoTaskName,
C: Serialize,
{
let compensation_task = compensation_task.into_task_name();
self.steps_executed += 1;
let compensation_bytes = serde_json::to_vec(&compensation_input).unwrap_or_else(|_| vec![]);
self.compensations.push_back(CompensationEntry {
compensation_task,
compensation_input: compensation_bytes,
step_number: self.steps_executed,
});
tracing::debug!(
step = %self.steps_executed,
compensation = %compensation_task,
"Registered saga compensation"
);
}
pub async fn compensate(&mut self, ctx: &WorkflowContext) -> Result<()> {
if self.completed {
tracing::warn!("Saga already completed, skipping compensation");
return Ok(());
}
self.completed = true;
if self.compensations.is_empty() {
tracing::info!("No compensations to execute");
return Ok(());
}
tracing::info!(
total_compensations = %self.compensations.len(),
"Starting saga compensation (reverse order)"
);
let mut first_error: Option<Error> = None;
let mut successful_compensations = 0;
let mut failed_compensations = 0;
while let Some(entry) = self.compensations.pop_back() {
tracing::info!(
step = %entry.step_number,
task = %entry.compensation_task,
"Executing compensation"
);
let input_result: Result<serde_json::Value> =
serde_json::from_slice(&entry.compensation_input).map_err(|e| {
Error::Serialization(format!("Failed to deserialize compensation input: {}", e))
});
let compensation_result: Result<serde_json::Value> = match input_result {
Ok(input) => ctx.execute_task(entry.compensation_task, input).await,
Err(e) => Err(e),
};
match compensation_result {
Ok(_) => {
successful_compensations += 1;
tracing::info!(
step = %entry.step_number,
task = %entry.compensation_task,
"Compensation successful"
);
}
Err(e) if e.is_suspend() => return Err(e),
Err(e) => {
failed_compensations += 1;
tracing::error!(
step = %entry.step_number,
task = %entry.compensation_task,
error = %e,
"Compensation failed"
);
if first_error.is_none() {
first_error = Some(e);
}
}
}
}
tracing::info!(
successful = %successful_compensations,
failed = %failed_compensations,
"Saga compensation complete"
);
if let Some(error) = first_error {
Err(Error::Workflow(crate::error::WorkflowError::StateError(
format!("Saga compensation failed: {}", error),
)))
} else {
Ok(())
}
}
pub fn steps_executed(&self) -> usize {
self.steps_executed
}
pub fn pending_compensations(&self) -> usize {
self.compensations.len()
}
pub fn is_completed(&self) -> bool {
self.completed
}
pub fn commit(&mut self) {
self.completed = true;
tracing::info!(
steps = %self.steps_executed,
"Saga committed successfully"
);
}
}
impl Default for Saga {
fn default() -> Self {
Self::new()
}
}
impl<'a, I> SagaStepBuilder<'a, I>
where
I: Serialize + Send + Sync + Clone + 'static,
{
pub fn with_compensation<T>(mut self, compensation_task: T) -> Self
where
T: IntoTaskName,
{
self.compensation_task = Some(compensation_task.into_task_name());
self
}
pub async fn execute<O>(self) -> Result<O>
where
O: DeserializeOwned + Send + Sync + 'static,
{
let action_input_owned = self.action_input.clone();
let action_result: Result<O> = self
.ctx
.execute_task(self.action_task, action_input_owned)
.await;
match action_result {
Ok(result) => {
if let Some(compensation_task) = self.compensation_task {
self.saga
.add_compensation(compensation_task, self.action_input);
}
tracing::info!(
step = %(self.saga.steps_executed + 1),
action = %self.action_task,
"Saga step completed successfully"
);
Ok(result)
}
Err(e) if e.is_suspend() => {
Err(e)
}
Err(e) => {
tracing::error!(
step = %(self.saga.steps_executed + 1),
action = %self.action_task,
error = %e,
"Saga step failed, starting compensation"
);
if let Err(comp_error) = self.saga.compensate(self.ctx).await {
if comp_error.is_suspend() {
return Err(comp_error);
}
tracing::error!(
compensation_error = %comp_error,
"Saga compensation encountered errors"
);
}
Err(e)
}
}
}
pub async fn execute_without_compensation<O>(self) -> Result<O>
where
O: DeserializeOwned + Send + Sync + 'static,
{
let action_input_owned = self.action_input.clone();
self.ctx
.execute_task(self.action_task, action_input_owned)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::task::TaskReference;
#[derive(Debug, Clone, Copy)]
struct MockTaskRef(&'static str);
impl TaskReference for MockTaskRef {
fn task_name(&self) -> &'static str {
self.0
}
}
#[allow(dead_code)]
const BOOK_HOTEL: MockTaskRef = MockTaskRef("book_hotel");
const CANCEL_HOTEL: MockTaskRef = MockTaskRef("cancel_hotel");
#[test]
fn test_saga_new() {
let saga = Saga::new();
assert_eq!(saga.steps_executed(), 0);
assert_eq!(saga.pending_compensations(), 0);
assert!(!saga.is_completed());
}
#[test]
fn test_saga_add_compensation() {
let mut saga = Saga::new();
saga.add_compensation("cancel_hotel", "hotel-123");
assert_eq!(saga.steps_executed(), 1);
assert_eq!(saga.pending_compensations(), 1);
saga.add_compensation("cancel_flight", "flight-456");
assert_eq!(saga.steps_executed(), 2);
assert_eq!(saga.pending_compensations(), 2);
}
#[test]
fn test_saga_add_compensation_with_task_reference() {
let mut saga = Saga::new();
saga.add_compensation(CANCEL_HOTEL, "hotel-123");
assert_eq!(saga.steps_executed(), 1);
assert_eq!(saga.pending_compensations(), 1);
saga.add_compensation("cancel_flight", "flight-456");
assert_eq!(saga.steps_executed(), 2);
assert_eq!(saga.pending_compensations(), 2);
}
#[test]
fn test_saga_commit() {
let mut saga = Saga::new();
saga.add_compensation("cancel_hotel", "hotel-123");
saga.commit();
assert!(saga.is_completed());
}
#[test]
fn test_saga_default() {
let saga = Saga::default();
assert_eq!(saga.steps_executed(), 0);
assert!(!saga.is_completed());
}
#[test]
fn test_saga_accepts_task_references() {
let mut saga = Saga::new();
saga.add_compensation(CANCEL_HOTEL, "booking-123");
assert_eq!(saga.steps_executed(), 1);
saga.add_compensation("cancel_flight", "booking-456");
assert_eq!(saga.steps_executed(), 2);
assert_eq!(saga.pending_compensations(), 2);
}
}