forked from yammer/circuit-breaker-js
-
Notifications
You must be signed in to change notification settings - Fork 4
/
circuit-breaker.ts
243 lines (198 loc) · 5.83 KB
/
circuit-breaker.ts
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
export type Bucket = {
failures: number
successes: number
timeouts: number
shortCircuits: number
}
export type Metrics = {
totalCount: number
errorCount: number
errorPercentage: number
}
export type Command<T> = () => Promise<T> | T
export type Fallback = () => void
export enum CircuitBreakerStatus {
OPEN = 0,
HALF_OPEN = 1,
CLOSED = 2,
}
export class CircuitOpenError extends Error {
name = 'CIRCUIT_OPEN'
constructor(msg: string = 'Circuit Open') {
super(msg)
}
}
class CircuitWorkerTimeout extends Error {
name = 'CIRCUIT_WORKER_TIMEOUT'
constructor(msg: string = 'Circuit worker timeout') {
super(msg)
}
}
function wrapPromise<T>(fn: () => T | Promise<T>): Promise<T> {
try {
const ret = fn()
return Promise.resolve(ret)
} catch (e) {
return Promise.reject(e)
}
}
export default class CircuitBreaker {
static readonly OPEN = CircuitBreakerStatus.OPEN
static readonly HALF_OPEN = CircuitBreakerStatus.HALF_OPEN
static readonly CLOSED = CircuitBreakerStatus.CLOSED
windowDuration: number
numBuckets: number
timeoutDuration: number
errorThreshold: number
volumeThreshold: number
onCircuitOpen: (metrics: Metrics) => void
onCircuitClose: (metrics: Metrics) => void
_buckets: Bucket[]
_state: CircuitBreakerStatus | null
_forced: CircuitBreakerStatus | null
_interval: number
constructor(opts: {
windowDuration?: number
numBuckets?: number
timeoutDuration?: number
errorThreshold?: number
volumeThreshold?: number
onCircuitOpen?: (metrics: Metrics) => void
onCircuitClose?: (metrics: Metrics) => void
} = {}) {
this.windowDuration = opts.windowDuration || 10000 // milliseconds
this.numBuckets = opts.numBuckets || 10 // number
this.timeoutDuration = opts.timeoutDuration || 3000 // milliseconds
this.errorThreshold = opts.errorThreshold || 50 // percentage
this.volumeThreshold = opts.volumeThreshold || 5 // number
this.onCircuitOpen = opts.onCircuitOpen || function () { }
this.onCircuitClose = opts.onCircuitClose || function () { }
this._buckets = [this._createBucket()]
this._state = CircuitBreaker.CLOSED
this._startTicker()
}
async run<T>(command: Command<T>): Promise<T> {
if (this.isOpen()) {
this._incrementShortCircuits()
throw new CircuitOpenError()
}
else {
return this._executeCommand(command)
}
}
forceClose(): void {
this._forced = this._state
this._state = CircuitBreaker.CLOSED
}
forceOpen(): void {
this._forced = this._state
this._state = CircuitBreaker.OPEN
}
unforce(): void {
this._state = this._forced
this._forced = null
}
isOpen(): boolean {
return this._state == CircuitBreaker.OPEN
}
destroy(): void {
clearInterval(this._interval);
}
_startTicker(): void {
const self = this
let bucketIndex = 0
const bucketDuration = this.windowDuration / this.numBuckets
function tick() {
if (self._buckets.length > self.numBuckets) {
self._buckets.shift()
}
bucketIndex++
if (bucketIndex > self.numBuckets) {
bucketIndex = 0
if (self.isOpen()) {
self._state = CircuitBreaker.HALF_OPEN
}
}
self._buckets.push(self._createBucket())
}
this._interval = setInterval(tick, bucketDuration)
}
_createBucket(): Bucket {
return { failures: 0, successes: 0, timeouts: 0, shortCircuits: 0 }
}
_lastBucket(): Bucket {
return this._buckets[this._buckets.length - 1]
}
_executeCommand<T>(command: Command<T>): Promise<T> {
const self = this
let timeout: number | null
function increment<P extends 'successes' | 'failures' | 'timeouts'>(prop: P) {
return function() {
const bucket = self._lastBucket()
bucket[prop]++
if (self._forced == null) {
self._updateState()
}
clearTimeout(timeout!)
timeout = null
}
}
return new Promise((resolve, reject) => {
wrapPromise(command).then(
(result: T) => {
if (!timeout) return
increment('successes')()
resolve(result)
},
(reason: any) => {
if (!timeout) return
increment('failures')()
reject(reason)
},
)
timeout = setTimeout(() => {
if (!timeout) return
increment('timeouts')()
reject(new CircuitWorkerTimeout())
}, this.timeoutDuration)
})
}
_incrementShortCircuits(): void {
const bucket = this._lastBucket()
bucket.shortCircuits++
}
_calculateMetrics(): Metrics {
let totalCount = 0, errorCount = 0, errorPercentage = 0
for (let i = 0, l = this._buckets.length; i < l; i++) {
const bucket = this._buckets[i]
const errors = (bucket.failures + bucket.timeouts)
errorCount += errors
totalCount += (errors + bucket.successes)
}
errorPercentage = (errorCount / (totalCount > 0 ? totalCount : 1)) * 100
return { totalCount: totalCount, errorCount: errorCount, errorPercentage: errorPercentage }
}
_updateState(): void {
const metrics = this._calculateMetrics()
if (this._state == CircuitBreaker.HALF_OPEN) {
const lastCommandFailed = !this._lastBucket().successes && metrics.errorCount > 0
if (lastCommandFailed) {
this._state = CircuitBreaker.OPEN
this.onCircuitOpen(metrics)
}
else {
this._state = CircuitBreaker.CLOSED
this.onCircuitClose(metrics)
}
}
else {
const overErrorThreshold = metrics.errorPercentage > this.errorThreshold
const overVolumeThreshold = metrics.totalCount > this.volumeThreshold
const overThreshold = overVolumeThreshold && overErrorThreshold
if (overThreshold) {
this._state = CircuitBreaker.OPEN
this.onCircuitOpen(metrics)
}
}
}
}