Skip to content

Instantly share code, notes, and snippets.

@krukow
Created January 1, 2010 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krukow/267172 to your computer and use it in GitHub Desktop.
Save krukow/267172 to your computer and use it in GitHub Desktop.
(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