wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
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
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import { IncomingHttpHeaders } from "http";
import { Constants, Logger } from "@azure/msal-common/node";
import { IHttpRetryPolicy } from "./IHttpRetryPolicy.js";
import { LinearRetryStrategy } from "./LinearRetryStrategy.js";
 
export const DEFAULT_MANAGED_IDENTITY_MAX_RETRIES: number = 3; // referenced in unit test
const DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS: number = 1000;
const DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON: Array<number> = [
    Constants.HTTP_NOT_FOUND,
    Constants.HTTP_REQUEST_TIMEOUT,
    Constants.HTTP_TOO_MANY_REQUESTS,
    Constants.HTTP_SERVER_ERROR,
    Constants.HTTP_SERVICE_UNAVAILABLE,
    Constants.HTTP_GATEWAY_TIMEOUT,
];
 
export class DefaultManagedIdentityRetryPolicy implements IHttpRetryPolicy {
    /*
     * this is defined here as a static variable despite being defined as a constant outside of the
     * class because it needs to be overridden in the unit tests so that the unit tests run faster
     */
    static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS(): number {
        return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS;
    }
 
    private linearRetryStrategy: LinearRetryStrategy =
        new LinearRetryStrategy();
 
    async pauseForRetry(
        httpStatusCode: number,
        currentRetry: number,
        logger: Logger,
        retryAfterHeader: IncomingHttpHeaders["retry-after"]
    ): Promise<boolean> {
        if (
            DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes(
                httpStatusCode
            ) &&
            currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES
        ) {
            const retryAfterDelay: number =
                this.linearRetryStrategy.calculateDelay(
                    retryAfterHeader,
                    DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS
                );
 
            logger.verbose(
                `Retrying request in ${retryAfterDelay}ms (retry attempt: ${
                    currentRetry + 1
                })`,
                ""
            );
 
            // pause execution for the calculated delay
            await new Promise((resolve) => {
                // retryAfterHeader value of 0 evaluates to false, and DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS will be used
                return setTimeout(resolve, retryAfterDelay);
            });
 
            return true;
        }
 
        // if the status code is not retriable or max retries have been reached, do not retry
        return false;
    }
}