forked from microsoftgraph/msgraph-sdk-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRetryHandler.ts
208 lines (191 loc) · 6.86 KB
/
RetryHandler.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
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module RetryHandler
*/
import { Context } from "../IContext";
import { FetchOptions } from "../IFetchOptions";
import { RequestMethod } from "../RequestMethod";
import { Middleware } from "./IMiddleware";
import { MiddlewareControl } from "./MiddlewareControl";
import { getRequestHeader, setRequestHeader } from "./MiddlewareUtil";
import { RetryHandlerOptions } from "./options/RetryHandlerOptions";
import { FeatureUsageFlag, TelemetryHandlerOptions } from "./options/TelemetryHandlerOptions";
/**
* @class
* @implements Middleware
* Class for RetryHandler
*/
export class RetryHandler implements Middleware {
/**
* @private
* @static
* A list of status codes that needs to be retried
*/
private static RETRY_STATUS_CODES: number[] = [
429, // Too many requests
503, // Service unavailable
504, // Gateway timeout
];
/**
* @private
* @static
* A member holding the name of retry attempt header
*/
private static RETRY_ATTEMPT_HEADER = "Retry-Attempt";
/**
* @private
* @static
* A member holding the name of retry after header
*/
private static RETRY_AFTER_HEADER = "Retry-After";
/**
* @private
* A member to hold next middleware in the middleware chain
*/
private nextMiddleware: Middleware;
/**
* @private
* A member holding the retry handler options
*/
private options: RetryHandlerOptions;
/**
* @public
* @constructor
* To create an instance of RetryHandler
* @param {RetryHandlerOptions} [options = new RetryHandlerOptions()] - The retry handler options value
* @returns An instance of RetryHandler
*/
public constructor(options: RetryHandlerOptions = new RetryHandlerOptions()) {
this.options = options;
}
/**
*
* @private
* To check whether the response has the retry status code
* @param {Response} response - The response object
* @returns Whether the response has retry status code or not
*/
private isRetry(response: Response): boolean {
return RetryHandler.RETRY_STATUS_CODES.indexOf(response.status) !== -1;
}
/**
* @private
* To check whether the payload is buffered or not
* @param {RequestInfo} request - The url string or the request object value
* @param {FetchOptions} options - The options of a request
* @returns Whether the payload is buffered or not
*/
private isBuffered(request: RequestInfo, options: FetchOptions | undefined): boolean {
const method = typeof request === "string" ? options.method : (request as Request).method;
const isPutPatchOrPost: boolean = method === RequestMethod.PUT || method === RequestMethod.PATCH || method === RequestMethod.POST;
if (isPutPatchOrPost) {
const isStream = getRequestHeader(request, options, "Content-Type") === "application/octet-stream";
if (isStream) {
return false;
}
}
return true;
}
/**
* @private
* To get the delay for a retry
* @param {Response} response - The response object
* @param {number} retryAttempts - The current attempt count
* @param {number} delay - The delay value in seconds
* @returns A delay for a retry
*/
private getDelay(response: Response, retryAttempts: number, delay: number): number {
const getRandomness = () => Number(Math.random().toFixed(3));
const retryAfter = response.headers !== undefined ? response.headers.get(RetryHandler.RETRY_AFTER_HEADER) : null;
let newDelay: number;
if (retryAfter !== null) {
if (Number.isNaN(Number(retryAfter))) {
newDelay = Math.round((new Date(retryAfter).getTime() - Date.now()) / 1000);
} else {
newDelay = Number(retryAfter);
}
} else {
// Adding randomness to avoid retrying at a same
newDelay = retryAttempts >= 2 ? this.getExponentialBackOffTime(retryAttempts) + delay + getRandomness() : delay + getRandomness();
}
return Math.min(newDelay, this.options.getMaxDelay() + getRandomness());
}
/**
* @private
* To get an exponential back off value
* @param {number} attempts - The current attempt count
* @returns An exponential back off value
*/
private getExponentialBackOffTime(attempts: number): number {
return Math.round((1 / 2) * (2 ** attempts - 1));
}
/**
* @private
* @async
* To add delay for the execution
* @param {number} delaySeconds - The delay value in seconds
* @returns Nothing
*/
private async sleep(delaySeconds: number): Promise<void> {
const delayMilliseconds = delaySeconds * 1000;
return new Promise((resolve) => setTimeout(resolve, delayMilliseconds));
}
private getOptions(context: Context): RetryHandlerOptions {
let options: RetryHandlerOptions;
if (context.middlewareControl instanceof MiddlewareControl) {
options = context.middlewareControl.getMiddlewareOptions(this.options.constructor) as RetryHandlerOptions;
}
if (typeof options === "undefined") {
options = Object.assign(new RetryHandlerOptions(), this.options);
}
return options;
}
/**
* @private
* @async
* To execute the middleware with retries
* @param {Context} context - The context object
* @param {number} retryAttempts - The current attempt count
* @param {RetryHandlerOptions} options - The retry middleware options instance
* @returns A Promise that resolves to nothing
*/
private async executeWithRetry(context: Context, retryAttempts: number, options: RetryHandlerOptions): Promise<void> {
await this.nextMiddleware.execute(context);
if (retryAttempts < options.maxRetries && this.isRetry(context.response) && this.isBuffered(context.request, context.options) && options.shouldRetry(options.delay, retryAttempts, context.request, context.options, context.response)) {
++retryAttempts;
setRequestHeader(context.request, context.options, RetryHandler.RETRY_ATTEMPT_HEADER, retryAttempts.toString());
const delay = this.getDelay(context.response, retryAttempts, options.delay);
await this.sleep(delay);
return await this.executeWithRetry(context, retryAttempts, options);
} else {
return;
}
}
/**
* @public
* @async
* To execute the current middleware
* @param {Context} context - The context object of the request
* @returns A Promise that resolves to nothing
*/
public async execute(context: Context): Promise<void> {
const retryAttempts = 0;
const options: RetryHandlerOptions = this.getOptions(context);
TelemetryHandlerOptions.updateFeatureUsageFlag(context, FeatureUsageFlag.RETRY_HANDLER_ENABLED);
return await this.executeWithRetry(context, retryAttempts, options);
}
/**
* @public
* To set the next middleware in the chain
* @param {Middleware} next - The middleware instance
* @returns Nothing
*/
public setNext(next: Middleware): void {
this.nextMiddleware = next;
}
}