SagaExecutor

interface SagaExecutor<C, R>

Executes saga steps with forward and compensating logic.

SagaExecutor orchestrates the execution of saga steps, handling forward execution, compensation on failure, and event notification. The executor is coroutine-friendly and uses suspend functions for async operations.

Execution Model

  1. Execute steps sequentially in order (asynchronously using coroutines)

  2. If a step fails, compensate completed steps in reverse order (LIFO)

  3. Notify monitors of all lifecycle events

  4. Return structured result (Completed/Aborted/CompensationFailure)

Coroutine Safety

SagaExecutor uses suspend functions for execution, allowing for non-blocking async operations. Each execution is isolated and maintains its own completion stack. Multiple executions can run concurrently in different coroutines.

Usage Example

val saga = sagaExecutor<OrderContext, OrderResult> {
step("reserve") { context -> /* suspend operation */}
compensate { result -> /* suspend compensation */}

step("charge") { context -> /* suspend operation */}
compensate { result -> /* suspend compensation */}
}

// Execute within a coroutine
val result = saga.execute(OrderContext(...))

Parameters

C

The type of context passed to saga steps

R

The type of result produced by saga steps

Inheritors

Functions

Link copied to clipboard
abstract fun addMonitor(monitor: SagaMonitor)

Add a monitor to observe saga events.

Link copied to clipboard

Extension function to convert a SagaExecutor to a FlowBasedSagaExecutor.

Link copied to clipboard
abstract suspend fun execute(context: C): SagaResult<R>

Execute the saga with the given context.

abstract suspend fun execute(context: C, coroutineContext: CoroutineContext = EmptyCoroutineContext, timeout: Duration? = null): SagaResult<R>

Execute the saga with the given context, coroutine context, and optional timeout.

Link copied to clipboard
fun <C, R> SagaExecutor<C, R>.executeToFlow(context: C, coroutineContext: CoroutineContext = EmptyCoroutineContext, timeout: Duration? = null): Flow<SagaEvent>

Execute saga and return a Flow that emits all events followed by a terminal result event.

Link copied to clipboard
abstract fun removeMonitor(monitor: SagaMonitor)

Remove a monitor.