UNPKG

1.91 kBJavaScriptView Raw
1// Copyright © 2017, 2018 IBM Corp. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14'use strict';
15
16const BasePlugin = require('./base.js');
17
18/**
19 * Retry plugin.
20 */
21class RetryPlugin extends BasePlugin {
22 constructor(client, cfg) {
23 cfg = Object.assign({
24 retryDelayMultiplier: 2,
25 retryErrors: true,
26 retryInitialDelayMsecs: 500,
27 retryStatusCodes: [
28 429, // 429 Too Many Requests
29 500, // 500 Internal Server Error
30 501, // 501 Not Implemented
31 502, // 502 Bad Gateway
32 503, // 503 Service Unavailable
33 504 // 504 Gateway Timeout
34 ]
35 }, cfg);
36 super(client, cfg);
37 }
38
39 onResponse(state, response, callback) {
40 if (this._cfg.retryStatusCodes.indexOf(response.statusCode) !== -1) {
41 state.retry = true;
42 if (state.attempt === 1) {
43 state.retryDelayMsecs = this._cfg.retryInitialDelayMsecs;
44 } else {
45 state.retryDelayMsecs *= this._cfg.retryDelayMultiplier;
46 }
47 }
48 callback(state);
49 }
50
51 onError(state, error, callback) {
52 if (this._cfg.retryErrors) {
53 state.retry = true;
54 if (state.attempt === 1) {
55 state.retryDelayMsecs = this._cfg.retryInitialDelayMsecs;
56 } else {
57 state.retryDelayMsecs *= this._cfg.retryDelayMultiplier;
58 }
59 }
60 callback(state);
61 }
62}
63
64RetryPlugin.id = 'retry';
65
66module.exports = RetryPlugin;