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,
) -> Result<()>
where
T: IntoTaskName,
C: Serialize,
{
let compensation_task = compensation_task.into_task_name();
let compensation_bytes = serde_json::to_vec(&compensation_input).map_err(|e| {
Error::Serialization(format!(
"input for compensation '{compensation_task}' could not be serialized: {e}"
))
})?;
self.steps_executed += 1;
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"
);
Ok(())
}
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 failed: Vec<String> = Vec::new();
let mut successful_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.push(entry.compensation_task.to_string());
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.len(),
"Saga compensation complete"
);
match first_error {
Some(error) => Err(Error::Workflow(
crate::error::WorkflowError::CompensationFailed {
failed,
reason: error.to_string(),
step_failure: None,
},
)),
None => 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"
);
match self.saga.compensate(self.ctx).await {
Ok(()) => Err(e),
Err(comp_error) if comp_error.is_suspend() => Err(comp_error),
Err(Error::Workflow(crate::error::WorkflowError::CompensationFailed {
failed,
reason,
..
})) => Err(Error::Workflow(
crate::error::WorkflowError::CompensationFailed {
failed,
reason,
step_failure: Some(e.to_string()),
},
)),
Err(comp_error) => Err(comp_error),
}
}
}
}
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");
struct Unserializable;
impl Serialize for Unserializable {
fn serialize<S: serde::Serializer>(&self, _: S) -> std::result::Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom("deliberately unserializable"))
}
}
#[test]
fn add_compensation_reports_an_input_that_cannot_be_serialized() {
let mut saga = Saga::new();
let err = saga
.add_compensation("cancel_hotel", Unserializable)
.unwrap_err();
match err {
Error::Serialization(message) => {
assert!(message.contains("cancel_hotel"), "{message}");
assert!(message.contains("deliberately unserializable"), "{message}");
}
other => panic!("expected a serialization error, got {other:?}"),
}
assert_eq!(saga.steps_executed(), 0);
assert_eq!(saga.pending_compensations(), 0);
}
#[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").unwrap();
assert_eq!(saga.steps_executed(), 1);
assert_eq!(saga.pending_compensations(), 1);
saga.add_compensation("cancel_flight", "flight-456")
.unwrap();
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").unwrap();
assert_eq!(saga.steps_executed(), 1);
assert_eq!(saga.pending_compensations(), 1);
saga.add_compensation("cancel_flight", "flight-456")
.unwrap();
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").unwrap();
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").unwrap();
assert_eq!(saga.steps_executed(), 1);
saga.add_compensation("cancel_flight", "booking-456")
.unwrap();
assert_eq!(saga.steps_executed(), 2);
assert_eq!(saga.pending_compensations(), 2);
}
}