|
| 1 | +/* |
| 2 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | + * Licensed under the MIT License. |
| 4 | + */ |
| 5 | + |
| 6 | +import { IncomingHttpHeaders } from "http"; |
| 7 | +import { HttpStatus, Logger } from "@azure/msal-common"; |
| 8 | +import { IHttpRetryPolicy } from "./IHttpRetryPolicy.js"; |
| 9 | +import { LinearRetryStrategy } from "./LinearRetryStrategy.js"; |
| 10 | + |
| 11 | +const DEFAULT_MANAGED_IDENTITY_MAX_RETRIES: number = 3; |
| 12 | +const DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS: number = 1000; |
| 13 | +const DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON: Array<number> = [ |
| 14 | + HttpStatus.NOT_FOUND, |
| 15 | + HttpStatus.REQUEST_TIMEOUT, |
| 16 | + HttpStatus.TOO_MANY_REQUESTS, |
| 17 | + HttpStatus.SERVER_ERROR, |
| 18 | + HttpStatus.SERVICE_UNAVAILABLE, |
| 19 | + HttpStatus.GATEWAY_TIMEOUT, |
| 20 | +]; |
| 21 | + |
| 22 | +export class DefaultManagedIdentityRetryPolicy implements IHttpRetryPolicy { |
| 23 | + /* |
| 24 | + * this is defined here as a static variable despite being defined as a constant outside of the |
| 25 | + * class because it needs to be overridden in the unit tests so that the unit tests run faster |
| 26 | + */ |
| 27 | + static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS(): number { |
| 28 | + return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS; |
| 29 | + } |
| 30 | + |
| 31 | + private linearRetryStrategy: LinearRetryStrategy = |
| 32 | + new LinearRetryStrategy(); |
| 33 | + |
| 34 | + async pauseForRetry( |
| 35 | + httpStatusCode: number, |
| 36 | + currentRetry: number, |
| 37 | + logger: Logger, |
| 38 | + retryAfterHeader: IncomingHttpHeaders["retry-after"] |
| 39 | + ): Promise<boolean> { |
| 40 | + if ( |
| 41 | + DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes( |
| 42 | + httpStatusCode |
| 43 | + ) && |
| 44 | + currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES |
| 45 | + ) { |
| 46 | + const retryAfterDelay: number = |
| 47 | + this.linearRetryStrategy.calculateDelay( |
| 48 | + retryAfterHeader, |
| 49 | + DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS |
| 50 | + ); |
| 51 | + |
| 52 | + logger.verbose( |
| 53 | + `Retrying request in ${retryAfterDelay}ms (retry attempt: ${ |
| 54 | + currentRetry + 1 |
| 55 | + })` |
| 56 | + ); |
| 57 | + |
| 58 | + // pause execution for the calculated delay |
| 59 | + await new Promise((resolve) => { |
| 60 | + // retryAfterHeader value of 0 evaluates to false, and DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS will be used |
| 61 | + return setTimeout(resolve, retryAfterDelay); |
| 62 | + }); |
| 63 | + |
| 64 | + return true; |
| 65 | + } |
| 66 | + |
| 67 | + // if the status code is not retriable or max retries have been reached, do not retry |
| 68 | + return false; |
| 69 | + } |
| 70 | +} |
0 commit comments