forked from yammer/circuit-breaker-js
-
Notifications
You must be signed in to change notification settings - Fork 4
/
circuit-breaker.js
187 lines (146 loc) · 4.94 KB
/
circuit-breaker.js
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
// CircuitBreaker
// ==============
//
// Hystrix-like circuit breaker for JavaScript.
(function() {
var CircuitBreaker = function(opts) {
opts = opts || {};
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._lastUpdate = now();
this._totalBucketsUsed = 0;
};
CircuitBreaker.OPEN = 0;
CircuitBreaker.HALF_OPEN = 1;
CircuitBreaker.CLOSED = 2;
// Public API
// ----------
CircuitBreaker.prototype.run = function(command, fallback) {
this._updateBuckets();
if (this.isOpen()) {
this._executeFallback(fallback || function() {});
}
else {
this._executeCommand(command);
}
};
CircuitBreaker.prototype.forceClose = function() {
this._forced = this._state;
this._state = CircuitBreaker.CLOSED;
};
CircuitBreaker.prototype.forceOpen = function() {
this._forced = this._state;
this._state = CircuitBreaker.OPEN;
};
CircuitBreaker.prototype.unforce = function() {
this._state = this._forced;
this._forced = null;
};
CircuitBreaker.prototype.isOpen = function() {
return this._state == CircuitBreaker.OPEN;
};
// Private API
// -----------
CircuitBreaker.prototype._updateBuckets = function() {
var timeSinceLastBucket = now() - this._lastUpdate,
bucketDuration = this.windowDuration / this.numBuckets,
bucketsNeeded = Math.floor(timeSinceLastBucket / bucketDuration);
for (var i = 0; i < bucketsNeeded; i++) {
this._pushBucket();
}
};
CircuitBreaker.prototype._pushBucket = function() {
// add the bucket
this._buckets.push(this._createBucket());
if (this._buckets.length > this.numBuckets) {
this._buckets.shift();
}
// handle half-opening every once in a while
this._totalBucketsUsed++;
if (this.isOpen() && (this._totalBucketsUsed % this.numBuckets === 0)) {
this._state = CircuitBreaker.HALF_OPEN;
}
};
CircuitBreaker.prototype._createBucket = function() {
return { failures: 0, successes: 0, timeouts: 0, shortCircuits: 0 };
};
CircuitBreaker.prototype._lastBucket = function() {
return this._buckets[this._buckets.length - 1];
};
CircuitBreaker.prototype._executeCommand = function(command) {
var self = this;
var timeout;
var increment = function(prop) {
return function() {
if (!timeout) { return; }
var bucket = self._lastBucket();
bucket[prop]++;
if (self._forced == null) {
self._updateState();
}
clearTimeout(timeout);
timeout = null;
};
};
timeout = setTimeout(increment('timeouts'), this.timeoutDuration);
command(increment('successes'), increment('failures'));
};
CircuitBreaker.prototype._executeFallback = function(fallback) {
fallback();
var bucket = this._lastBucket();
bucket.shortCircuits++;
};
CircuitBreaker.prototype._calculateMetrics = function() {
var totalCount = 0, errorCount = 0, errorPercentage = 0;
for (var i = 0, l = this._buckets.length; i < l; i++) {
var bucket = this._buckets[i];
var 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 };
};
CircuitBreaker.prototype._updateState = function() {
var metrics = this._calculateMetrics();
if (this._state == CircuitBreaker.HALF_OPEN) {
var lastCommandFailed = !this._lastBucket().successes && metrics.errorCount > 0;
if (lastCommandFailed) {
this._state = CircuitBreaker.OPEN;
}
else {
this._state = CircuitBreaker.CLOSED;
this.onCircuitClose(metrics);
}
}
else {
var overErrorThreshold = metrics.errorPercentage > this.errorThreshold;
var overVolumeThreshold = metrics.totalCount > this.volumeThreshold;
var overThreshold = overVolumeThreshold && overErrorThreshold;
if (overThreshold) {
this._state = CircuitBreaker.OPEN;
this.onCircuitOpen(metrics);
}
}
};
var assign = function(name, obj) {
var commonJS = typeof module != 'undefined' && module.exports;
if (commonJS) {
module.exports = obj;
}
else {
window[name] = obj;
}
};
var now = function() {
return (new Date()).getTime();
};
assign('CircuitBreaker', CircuitBreaker);
})();