Created
April 15, 2020 10:11
-
-
Save nomisRev/d46ed792944c2bcaecfcf946e2e78a51 to your computer and use it in GitHub Desktop.
Simple CircuitBreaker example with Kotlin & Arrow Fx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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