Skip to content

Instantly share code, notes, and snippets.

@nomisRev
Created April 15, 2020 10:11
Show Gist options
  • Save nomisRev/d46ed792944c2bcaecfcf946e2e78a51 to your computer and use it in GitHub Desktop.
Save nomisRev/d46ed792944c2bcaecfcf946e2e78a51 to your computer and use it in GitHub Desktop.
Simple CircuitBreaker example with Kotlin & Arrow Fx
import arrow.fx.extensions.io.applicative.map
import arrow.fx.extensions.io.monad.flatMap
import arrow.fx.extensions.io.monadDefer.monadDefer
import java.lang.RuntimeException
enum class CBState {
CLOSED, OPEN, DISABLED;
}
class CallNotPermitedException(val state: CBState):
RuntimeException("CircuitBreaker was closed with state: $state")
class CircuitBreaker private constructor(val ref: Ref<ForIO, CBState>) {
fun <A> decorateIO(io: IO<A>): IO<A> =
ref.get().flatMap { state ->
when(state) {
CBState.OPEN -> io
CBState.DISABLED -> io
CBState.CLOSED -> IO.raiseError(CallNotPermitedException(state))
}
}
companion object {
operator fun invoke(initial: CBState = CBState.OPEN): IO<CircuitBreaker> =
Ref.invoke(IO.monadDefer(), initial).map { ref -> CircuitBreaker(ref) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment