Stateful Saga Builder
DSL builder for creating stateful saga executors with typed state management.
StatefulSagaBuilder provides a fluent API for defining saga steps that can share typed state across the execution. This enables "smart compensation" where compensation logic can make decisions based on execution progress from later steps.
Usage Example
data class PaymentState(
val paymentAmount: Long = 0L,
val escrowCaptured: Boolean = false
)
val saga = sagaExecutor<OrderContext, OrderResult>(PaymentState()) {
step("take-payment") { context ->
val payment = paymentService.takePayment(context.amount)
updateState { it.copy(paymentAmount = payment.amount) }
OrderResult(payment.id)
}
compensate {
// Smart compensation using state from later steps
if (state.escrowCaptured) {
paymentService.refund(result.paymentId)
} else {
paymentService.returnEscrow()
}
}
step("capture-escrow") { context ->
paymentService.captureEscrow()
updateState { it.copy(escrowCaptured = true) }
result!! // Pass through previous result
}
compensate {
paymentService.refund(state.paymentAmount)
}
}Parameters
The type of context passed to saga steps
The type of result produced by saga steps
The type of shared saga state (must be non-null)
Functions
Marks the last step as idempotent using simple syntax.
Marks the last step as non-idempotent.
Define compensation logic for the current step.
Adds compensation to the last defined step using simple syntax.
Mark the current step as idempotent (safe to retry).
Add a monitor to observe saga events.
Add a monitor using a lambda.
Adds a saga monitor instance.
Set retry policy for current step.
Define a saga step with forward logic using explicit outcome control.
Define a saga step with string name (convenience overload).