Saga Monitor
Monitor for observing saga execution lifecycle events.
Implement this interface to log, track metrics, or react to saga events. Monitors are notified of all saga lifecycle events, enabling observability and monitoring without coupling saga logic to specific logging frameworks.
Async Operations
This is a suspend function interface, enabling monitors to perform asynchronous operations such as:
Sending metrics to remote services
Logging to distributed systems
Triggering webhooks or notifications
Async database writes
Functional Interface
This is a functional interface (SAM - Single Abstract Method), which means you can use lambda expressions to create monitors:
val monitor = SagaMonitor { event ->
// Can use suspend functions!
metricsService.recordEvent(event)
when (event) {
is SagaEvent.StepStarted -> logger.info("Step started: ${event.stepName}")
is SagaEvent.StepFailed -> logger.error("Step failed: ${event.stepName}")
else -> logger.debug("Event: $event")
}
}Usage Example
class MetricsCollector(private val metricsService: MetricsService) : SagaMonitor {
override suspend fun onSagaEvent(event: SagaEvent) {
when (event) {
is SagaEvent.StepCompleted<*> -> {
val duration = event.timestamp - startTime
// Async metric recording
metricsService.recordStepDuration(event.stepName, duration)
}
is SagaEvent.CompensationStarted -> {
// Async counter increment
metricsService.incrementCompensationCount(event.stepName)
}
}
}
}
saga.addMonitor(MetricsCollector(metricsService))Error Handling
Exceptions thrown by monitors are caught and logged but do not affect saga execution. This ensures that monitoring failures don't impact business logic.