/
index.js
381 lines (343 loc) · 11.8 KB
/
index.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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
const async = require("async");
const discovery = require("clever-discovery");
const kayvee = require("kayvee");
const request = require("request");
const {commandFactory} = require("hystrixjs");
const RollingNumberEvent = require("hystrixjs/lib/metrics/RollingNumberEvent");
const { Errors } = require("./types");
/**
* The exponential retry policy will retry five times with an exponential backoff.
* @alias module:swagger-test.RetryPolicies.Exponential
*/
const exponentialRetryPolicy = {
backoffs() {
const ret = [];
let next = 100.0; // milliseconds
const e = 0.05; // +/- 5% jitter
while (ret.length < 5) {
const jitter = ((Math.random() * 2) - 1) * e * next;
ret.push(next + jitter);
next *= 2;
}
return ret;
},
retry(requestOptions, err, res) {
if (err || requestOptions.method === "POST" ||
requestOptions.method === "PATCH" ||
res.statusCode < 500) {
return false;
}
return true;
},
};
/**
* Use this retry policy to retry a request once.
* @alias module:swagger-test.RetryPolicies.Single
*/
const singleRetryPolicy = {
backoffs() {
return [1000];
},
retry(requestOptions, err, res) {
if (err || requestOptions.method === "POST" ||
requestOptions.method === "PATCH" ||
res.statusCode < 500) {
return false;
}
return true;
},
};
/**
* Use this retry policy to turn off retries.
* @alias module:swagger-test.RetryPolicies.None
*/
const noRetryPolicy = {
backoffs() {
return [];
},
retry() {
return false;
},
};
/**
* Request status log is used to
* to output the status of a request returned
* by the client.
* @private
*/
function responseLog(logger, req, res, err) {
var res = res || { };
var req = req || { };
var logData = {
"backend": "swagger-test",
"method": req.method || "",
"uri": req.uri || "",
"message": err || (res.statusMessage || ""),
"status_code": res.statusCode || 0,
};
if (err) {
logger.errorD("client-request-finished", logData);
} else {
logger.infoD("client-request-finished", logData);
}
}
/**
* Takes a promise and uses the provided callback (if any) to handle promise
* resolutions and rejections
* @private
*/
function applyCallback(promise, cb) {
if (!cb) {
return promise;
}
return promise.then((result) => {
cb(null, result);
}).catch((err) => {
cb(err);
});
}
/**
* Default circuit breaker options.
* @alias module:swagger-test.DefaultCircuitOptions
*/
const defaultCircuitOptions = {
forceClosed: true,
requestVolumeThreshold: 20,
maxConcurrentRequests: 100,
requestVolumeThreshold: 20,
sleepWindow: 5000,
errorPercentThreshold: 90,
logIntervalMs: 30000
};
/**
* swagger-test client library.
* @module swagger-test
* @typicalname SwaggerTest
*/
/**
* swagger-test client
* @alias module:swagger-test
*/
class SwaggerTest {
/**
* Create a new client object.
* @param {Object} options - Options for constructing a client object.
* @param {string} [options.address] - URL where the server is located. Must provide
* this or the discovery argument
* @param {bool} [options.discovery] - Use clever-discovery to locate the server. Must provide
* this or the address argument
* @param {number} [options.timeout] - The timeout to use for all client requests,
* in milliseconds. This can be overridden on a per-request basis. Default is 5000ms.
* @param {bool} [options.keepalive] - Set keepalive to true for client requests. This sets the
* forever: true attribute in request. Defaults to true.
* @param {module:swagger-test.RetryPolicies} [options.retryPolicy=RetryPolicies.Single] - The logic to
* determine which requests to retry, as well as how many times to retry.
* @param {module:kayvee.Logger} [options.logger=logger.New("swagger-test-wagclient")] - The Kayvee
* logger to use in the client.
* @param {Object} [options.circuit] - Options for constructing the client's circuit breaker.
* @param {bool} [options.circuit.forceClosed] - When set to true the circuit will always be closed. Default: true.
* @param {number} [options.circuit.maxConcurrentRequests] - the maximum number of concurrent requests
* the client can make at the same time. Default: 100.
* @param {number} [options.circuit.requestVolumeThreshold] - The minimum number of requests needed
* before a circuit can be tripped due to health. Default: 20.
* @param {number} [options.circuit.sleepWindow] - how long, in milliseconds, to wait after a circuit opens
* before testing for recovery. Default: 5000.
* @param {number} [options.circuit.errorPercentThreshold] - the threshold to place on the rolling error
* rate. Once the error rate exceeds this percentage, the circuit opens.
* Default: 90.
*/
constructor(options) {
options = options || {};
if (options.discovery) {
try {
this.address = discovery(options.serviceName || "swagger-test", "http").url();
} catch (e) {
this.address = discovery(options.serviceName || "swagger-test", "default").url();
}
} else if (options.address) {
this.address = options.address;
} else {
throw new Error("Cannot initialize swagger-test without discovery or address");
}
if (options.keepalive !== undefined) {
this.keepalive = options.keepalive;
} else {
this.keepalive = true;
}
if (options.timeout) {
this.timeout = options.timeout;
} else {
this.timeout = 5000;
}
if (options.retryPolicy) {
this.retryPolicy = options.retryPolicy;
}
if (options.logger) {
this.logger = options.logger;
} else {
this.logger = new kayvee.logger((options.serviceName || "swagger-test") + "-wagclient");
}
const circuitOptions = Object.assign({}, defaultCircuitOptions, options.circuit);
this._hystrixCommand = commandFactory.getOrCreate(options.serviceName || "swagger-test").
errorHandler(this._hystrixCommandErrorHandler).
circuitBreakerForceClosed(circuitOptions.forceClosed).
requestVolumeRejectionThreshold(circuitOptions.maxConcurrentRequests).
circuitBreakerRequestVolumeThreshold(circuitOptions.requestVolumeThreshold).
circuitBreakerSleepWindowInMilliseconds(circuitOptions.sleepWindow).
circuitBreakerErrorThresholdPercentage(circuitOptions.errorPercentThreshold).
timeout(0).
statisticalWindowLength(10000).
statisticalWindowNumberOfBuckets(10).
run(this._hystrixCommandRun).
context(this).
build();
setInterval(() => this._logCircuitState(), circuitOptions.logIntervalMs);
}
_hystrixCommandErrorHandler(err) {
// to avoid counting 4XXs as errors, only count an error if it comes from the request library
if (err._fromRequest === true) {
return err;
}
return false;
}
_hystrixCommandRun(method, args) {
return method.apply(this, args);
}
_logCircuitState(logger) {
// code below heavily borrows from hystrix's internal HystrixSSEStream.js logic
const metrics = this._hystrixCommand.metrics;
const healthCounts = metrics.getHealthCounts()
const circuitBreaker = this._hystrixCommand.circuitBreaker;
this.logger.infoD("swagger-test", {
"requestCount": healthCounts.totalCount,
"errorCount": healthCounts.errorCount,
"errorPercentage": healthCounts.errorPercentage,
"isCircuitBreakerOpen": circuitBreaker.isOpen(),
"rollingCountFailure": metrics.getRollingCount(RollingNumberEvent.FAILURE),
"rollingCountShortCircuited": metrics.getRollingCount(RollingNumberEvent.SHORT_CIRCUITED),
"rollingCountSuccess": metrics.getRollingCount(RollingNumberEvent.SUCCESS),
"rollingCountTimeout": metrics.getRollingCount(RollingNumberEvent.TIMEOUT),
"currentConcurrentExecutionCount": metrics.getCurrentExecutionCount(),
"latencyTotalMean": metrics.getExecutionTime("mean") || 0,
});
}
/**
* @param {number} id
* @param {object} [options]
* @param {number} [options.timeout] - A request specific timeout
* @param {module:swagger-test.RetryPolicies} [options.retryPolicy] - A request specific retryPolicy
* @param {function} [cb]
* @returns {Promise}
* @fulfill {undefined}
* @reject {module:swagger-test.Errors.ExtendedError}
* @reject {module:swagger-test.Errors.NotFound}
* @reject {module:swagger-test.Errors.InternalError}
* @reject {Error}
*/
getBook(id, options, cb) {
let callback = cb;
if (!cb && typeof options === "function") {
callback = options;
}
return applyCallback(this._hystrixCommand.execute(this._getBook, arguments), callback);
}
_getBook(id, options, cb) {
const params = {};
params["id"] = id;
if (!cb && typeof options === "function") {
options = undefined;
}
return new Promise((resolve, reject) => {
if (!options) {
options = {};
}
const timeout = options.timeout || this.timeout;
const headers = {};
headers["Canonical-Resource"] = "getBook";
headers[versionHeader] = version;
if (!params.id) {
reject(new Error("id must be non-empty because it's a path parameter"));
return;
}
const query = {};
const requestOptions = {
method: "GET",
uri: this.address + "/v1/books/" + params.id + "",
gzip: true,
json: true,
timeout,
headers,
qs: query,
useQuerystring: true,
};
if (this.keepalive) {
requestOptions.forever = true;
}
const retryPolicy = options.retryPolicy || this.retryPolicy || singleRetryPolicy;
const backoffs = retryPolicy.backoffs();
const logger = this.logger;
let retries = 0;
(function requestOnce() {
request(requestOptions, (err, response, body) => {
if (retries < backoffs.length && retryPolicy.retry(requestOptions, err, response, body)) {
const backoff = backoffs[retries];
retries += 1;
setTimeout(requestOnce, backoff);
return;
}
if (err) {
err._fromRequest = true;
responseLog(logger, requestOptions, response, err)
reject(err);
return;
}
switch (response.statusCode) {
case 200:
resolve();
break;
case 400:
var err = new Errors.ExtendedError(body || {});
responseLog(logger, requestOptions, response, err);
reject(err);
return;
case 404:
var err = new Errors.NotFound(body || {});
responseLog(logger, requestOptions, response, err);
reject(err);
return;
case 500:
var err = new Errors.InternalError(body || {});
responseLog(logger, requestOptions, response, err);
reject(err);
return;
default:
var err = new Error("Received unexpected statusCode " + response.statusCode);
responseLog(logger, requestOptions, response, err);
reject(err);
return;
}
});
}());
});
}
};
module.exports = SwaggerTest;
/**
* Retry policies available to use.
* @alias module:swagger-test.RetryPolicies
*/
module.exports.RetryPolicies = {
Single: singleRetryPolicy,
Exponential: exponentialRetryPolicy,
None: noRetryPolicy,
};
/**
* Errors returned by methods.
* @alias module:swagger-test.Errors
*/
module.exports.Errors = Errors;
module.exports.DefaultCircuitOptions = defaultCircuitOptions;
const version = "0.1.0";
const versionHeader = "X-Client-Version";
module.exports.Version = version;
module.exports.VersionHeader = versionHeader;