-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
bulkhead.clj
208 lines (177 loc) · 6.28 KB
/
bulkhead.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) Andrey Antukh <niwi@niwi.nz>
(ns promesa.exec.bulkhead
"Bulkhead pattern: limiter of concurrent executions."
(:refer-clojure :exclude [run!])
(:require
[promesa.core :as p]
[promesa.exec :as px]
[promesa.exec.semaphore :as psm]
[promesa.impl :as pi]
[promesa.protocols :as pt]
[promesa.util :as pu])
(:import
java.util.concurrent.BlockingQueue
java.util.concurrent.CompletableFuture
java.util.concurrent.Executor
java.util.concurrent.LinkedBlockingQueue
java.util.concurrent.Semaphore
java.util.concurrent.atomic.AtomicLong))
(set! *warn-on-reflection* true)
;; (set! *unchecked-math* :warn-on-boxed)
(defmacro log!
[& params]
;; `(locking prn
;; (prn ~@params))
)
(declare ^:private instant)
(defprotocol IQueue
(-poll! [_])
(-offer! [_ _]))
(defprotocol IBulkhead
"Bulkhead main API"
(-get-stats [_] "Get internal statistics of the bulkhead instance")
(-invoke! [_ f] "Call synchronously a function under bulkhead context"))
(extend-type BlockingQueue
IQueue
(-poll! [this] (.poll ^BlockingQueue this))
(-offer! [this o] (.offer ^BlockingQueue this o)))
(defn- instant
[]
(System/currentTimeMillis))
(deftype ExecutorBulkheadTask [bulkhead f inst]
clojure.core/Inst
(inst-ms* [_] inst)
Runnable
(run [this]
(let [^Semaphore semaphore (:semaphore bulkhead)
^Executor executor (:executor bulkhead)]
(log! "cmd:" "Task/run" "f:" (hash f) "task:" (hash this) "START")
(try
(.run ^Runnable f)
(finally
(psm/release! semaphore :permits 1)
(log! "cmd:" "Task/run" "f:" (hash f) "task:" (hash this) "END" "permits:" (.availablePermits semaphore))
(pt/-run! executor bulkhead))))))
(ns-unmap *ns* '->ExecutorBulkheadTask)
(defrecord ExecutorBulkhead [^Executor executor
^Semaphore semaphore
^BlockingQueue queue
max-permits
max-queue]
IBulkhead
(-get-stats [_]
(let [permits (.availablePermits semaphore)]
{:permits (.availablePermits semaphore)
:queue (.size queue)
:max-permits max-permits
:max-queue max-queue}))
(-invoke! [this f]
(p/await! (pt/-submit! this f)))
Executor
(execute [this f]
(log! "cmd:" "Bulkhead/execute" "f:" (hash f))
(-offer! this f))
IQueue
(-offer! [this f]
(let [task (ExecutorBulkheadTask. this f (instant))]
(when-not (-offer! queue task)
(let [size (.size queue)
hint (str "queue max capacity reached: " size)
props {:type :bulkhead-error
:code :capacity-limit-reached
:size size}]
(throw (ex-info hint props))))
(log! "cmd:" "Bulkhead/-offer!" "queue" (.size queue))
(.run ^Runnable this)))
(-poll! [this]
(when (pt/-try-acquire! semaphore)
(if-let [task (-poll! queue)]
task
(pt/-release! semaphore))))
Runnable
(run [this]
(log! "cmd:" "Bulkhead/run" "queue:" (.size queue) "permits:" (.availablePermits semaphore))
(loop []
(log! "cmd:" "Bulkhead/run$loop1" "queue:" (.size queue) "permits:" (.availablePermits semaphore))
(when-let [task (-poll! this)]
(log! "cmd:" "Bulkhead/run$loop2" "task:" (hash task) "available-permits:" (.availablePermits semaphore))
(pt/-exec! executor task)
(recur)))))
(ns-unmap *ns* '->ExecutorBulkhead)
(ns-unmap *ns* 'map->ExecutorBulkhead)
(defrecord SemaphoreBulkhead [^Semaphore semaphore
^AtomicLong counter
max-permits
max-queue
timeout]
IBulkhead
(-get-stats [_]
{:permits (.availablePermits semaphore)
:queue (+ (long counter) (long max-permits))
:max-permits max-permits
:max-queue max-queue})
Executor
(execute [this f]
(let [nqueued (.incrementAndGet counter)]
(when (> (long nqueued) (long max-queue))
(let [hint (str "bulkhead: queue max capacity reached (" max-queue ")")
props {:type :bulkhead-error
:code :capacity-limit-reached
:size max-queue}]
(.decrementAndGet counter)
(throw (ex-info hint props))))
(try
(if (psm/acquire! semaphore :permits 1 :timeout timeout)
(try
(.run ^Runnable f)
(finally (psm/release! semaphore)))
(let [props {:type :bulkhead-error
:code :timeout
:timeout timeout}]
(throw (ex-info "bulkhead: timeout" props))))
(finally
(.decrementAndGet counter)))))
(-invoke! [this f]
(p/await! (pt/-submit! this f))))
(ns-unmap *ns* '->SemaphoreBulkhead)
(ns-unmap *ns* 'map->SemaphoreBulkhead)
(defn- create-with-executor
[{:keys [executor permits queue on-run on-queue]}]
(let [executor (px/resolve-executor executor)
max-queue (or queue Integer/MAX_VALUE)
max-permits (or permits 1)
queue (LinkedBlockingQueue. (int max-queue))
semaphore (Semaphore. (int permits))]
(ExecutorBulkhead. executor semaphore queue max-permits max-queue)))
(defn- create-with-semaphore
[{:keys [permits queue timeout]}]
(let [max-queue (or queue Integer/MAX_VALUE)
max-permits (or permits 1)
counter (AtomicLong. (- (long permits)))
semaphore (Semaphore. (int max-permits))]
(SemaphoreBulkhead. semaphore
counter
max-permits
max-queue
timeout)))
;; --- PUBLIC API
(defn create
[& {:keys [type] :as params}]
(case type
:executor (create-with-executor params)
:semaphore (create-with-semaphore params)
(throw (UnsupportedOperationException. "invalid bulkhead type provided"))))
(defn get-stats
[instance]
(-get-stats instance))
(defn invoke!
[instance f]
(-invoke! instance f))
(defn bulkhead?
"Check if the provided object is instance of Bulkhead type."
[o]
(satisfies? IBulkhead o))