saga Executor
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
The type of context passed to saga steps
The type of result produced by saga steps
Configuration block for the saga builder
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
The type of context passed to saga steps
The type of result produced by saga steps
The type of shared saga state (inferred from initialState)
Initial value for the saga state
Configuration block for the saga builder