Skip to content

Commit 2d1b829

Browse files
authored
[core-amqp] only compute retry delay when retrying (Azure#19417)
* [core-amqp] only compute retry delay when retrying Add a small optimization that only compute the delay if we are retrying. * Extract method to calculate delay
1 parent 1f237f2 commit 2d1b829

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

sdk/core/core-amqp/src/retry.ts

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,28 @@ function validateRetryConfig<T>(config: RetryConfig<T>): void {
134134
}
135135
}
136136

137+
/**
138+
* Calculates delay between retries, in milliseconds.
139+
* @internal
140+
*/
141+
function calculateDelay(
142+
attemptCount: number,
143+
retryDelayInMs: number,
144+
maxRetryDelayInMs: number,
145+
mode: RetryMode
146+
): number {
147+
if (mode === RetryMode.Exponential) {
148+
const boundedRandDelta =
149+
retryDelayInMs * 0.8 +
150+
Math.floor(Math.random() * (retryDelayInMs * 1.2 - retryDelayInMs * 0.8));
151+
152+
const incrementDelta = boundedRandDelta * (Math.pow(2, attemptCount) - 1);
153+
return Math.min(incrementDelta, maxRetryDelayInMs);
154+
}
155+
156+
return retryDelayInMs;
157+
}
158+
137159
/**
138160
* Every operation is attempted at least once. Additional attempts are made if the previous attempt failed
139161
* with a retryable error. The number of additional attempts is governed by the `maxRetries` property provided
@@ -219,21 +241,14 @@ export async function retry<T>(config: RetryConfig<T>): Promise<T> {
219241
i,
220242
err
221243
);
222-
let targetDelayInMs = config.retryOptions.retryDelayInMs;
223-
if (config.retryOptions.mode === RetryMode.Exponential) {
224-
let incrementDelta = Math.pow(2, i) - 1;
225-
const boundedRandDelta =
226-
config.retryOptions.retryDelayInMs * 0.8 +
227-
Math.floor(
228-
Math.random() *
229-
(config.retryOptions.retryDelayInMs * 1.2 - config.retryOptions.retryDelayInMs * 0.8)
230-
);
231-
incrementDelta *= boundedRandDelta;
232-
233-
targetDelayInMs = Math.min(incrementDelta, config.retryOptions.maxRetryDelayInMs);
234-
}
235244

236245
if (lastError && lastError.retryable && totalNumberOfAttempts > i) {
246+
const targetDelayInMs = calculateDelay(
247+
i,
248+
config.retryOptions.retryDelayInMs,
249+
config.retryOptions.maxRetryDelayInMs,
250+
config.retryOptions.mode
251+
);
237252
logger.verbose(
238253
"[%s] Sleeping for %d milliseconds for '%s'.",
239254
config.connectionId,

0 commit comments

Comments
 (0)