Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
(ns net.higher-order.integration.circuit-breaker.atomic
(:use net.higher-order.integration.circuit-breaker.states))
(def default-policy (TransitionPolicy 5 5000))
(def initial-state (ClosedState default-policy 0))
(defn make-circuit-breaker
([] (atom initial-state))
([s] (atom s)))
(def transition-by!)
(defn wrap-with [f state]
(fn [& args]
(let [s (transition-by! on-before-call state)]
(if (proceed s)
(try
(let [res (apply f args)]
(do (transition-by! on-success state)
res))
(catch Exception e
(do
(transition-by! on-error state)
(throw e))))
(throw (RuntimeException. "OpenCircuit"))))))
(defn wrap [f]
(let [state (make-circuit-breaker)]
[(wrap-with f state) state]))
(defn transition-by! [f state]
(loop [s @state
t (f s)]
(if (or (identical? s t)
(compare-and-set! state s t))
t
(let [s1 @state]
(recur s1 (f s1))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment