sagaExecutor

fun <C, R> sagaExecutor(configure: SagaBuilder<C, R>.() -> Unit): SagaExecutor<C, R>

Factory function for creating sagas with DSL.

This function provides a convenient way to create saga executors using Kotlin's DSL syntax.

Usage Example

val saga = sagaExecutor<OrderContext, OrderResult> {
step("reserve-inventory") { context ->
val reservationId = inventoryService.reserve(context.items) // Can be suspend
ReservationResult(reservationId)
}
compensate { result ->
inventoryService.release(result.reservationId) // Can be suspend
}

step("charge-payment") { context ->
val transactionId = paymentService.charge(context.amount) // Can be suspend
PaymentResult(transactionId)
}
compensate { result ->
paymentService.refund(result.transactionId) // Can be suspend
}
}

// Execute within a coroutine
runBlocking {
val result = saga.execute(OrderContext(items = listOf("item1"), amount = 99.99))
when (result) {
is SagaResult.Completed -> println("Success: ${result.value}")
is SagaResult.Aborted -> println("Aborted: ${result.error.message}")
is SagaResult.CompensationFailure -> println("Critical failure")
}
}

Return

A configured SagaExecutor ready for execution

Parameters

C

The type of context passed to saga steps

R

The type of result produced by saga steps

configure

Configuration block for the saga builder


fun <C, R, S : Any> sagaExecutor(initialState: S, configure: StatefulSagaBuilder<C, R, S>.() -> Unit): StatefulSagaExecutor<C, R, S>

Factory function for creating stateful sagas with typed state management.

This overload of sagaExecutor creates a saga with shared state that is accessible in both forward actions and compensation logic. The state type is inferred from the initialState parameter.

Usage Example

data class PaymentState(
val paymentAmount: Long = 0L,
val escrowCaptured: Boolean = false
)

val saga = sagaExecutor<Cart, Order>(PaymentState()) {
first `do` "take-payment" with { cart ->
updateState { it.copy(paymentAmount = payment.amount) }
createOrder(cart)
} and undo {
if (state.escrowCaptured) refund() else returnEscrow()
}

then `do` "capture-escrow" with { cart ->
cashManager.captureEscrow()
updateState { it.copy(escrowCaptured = true) }
result!!
}
}

Return

A configured StatefulSagaExecutor ready for execution

Parameters

C

The type of context passed to saga steps

R

The type of result produced by saga steps

S

The type of shared saga state (inferred from initialState)

initialState

Initial value for the saga state

configure

Configuration block for the saga builder