Add `retry.delay` option to control the time between retries (#533)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Russell Clarey · committed by GitHub · parent 577dd4c · Browse files · 7 files·+106 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+106 added−35 removed
- tests:+92 added−32 removed
- other:+14 added−3 removed
Provenance
- Commit
c6181ef- Tree
164bd9f- Author
Russell Clarey <r.e.clarey@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
577dd4c
7 files changed+106 added−35 removed
modified:source/core/Ky.ts+2 added-2 removed
232 unmodified lines233 return 0;234 }235 }236 237- const BACKOFF_FACTOR = 0.3;238- return Math.min(this._options.retry.backoffLimit, BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000);237+ const retryDelay = this._options.retry.delay(this._retryCount);238+ return Math.min(this._options.retry.backoffLimit, retryDelay);239 }240 241 return 0;242 }118 unmodified linesmodified:source/types/options.ts+1 added-1 removed
136 unmodified lines137 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.138 139 If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`. If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.140 141- Delays between retries is calculated with the function `0.3 * (2 ** (retry - 1)) * 1000`, where `retry` is the attempt number (starts from 1).141+ By default, delays between retries are calculated with the function `0.3 * (2 ** (attemptCount - 1)) * 1000`, where `attemptCount` is the attempt number (starts from 1), however this can be changed by passing a `delay` function.142 143 Retries are not triggered following a timeout.144 145 @example105 unmodified linesmodified:source/types/retry.ts+7 added
47 unmodified lines48495051525354555657585947 unmodified lines
@default Infinity */ backoffLimit?: number;
/** A function to calculate the delay between retries given `attemptCount` (starts from 1).
@default attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000 */ delay?: (attemptCount: number) => number;};modified:source/utils/normalize.ts+1 added
16 unmodified lines17181920212223242520 unmodified lines16 unmodified lines statusCodes: retryStatusCodes, afterStatusCodes: retryAfterStatusCodes, maxRetryAfter: Number.POSITIVE_INFINITY, backoffLimit: Number.POSITIVE_INFINITY, delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,};
export const normalizeRetryOptions = (retry: number | RetryOptions = {}): Required<RetryOptions> => { if (typeof retry === 'number') {20 unmodified linesadded:test/helpers/with-performance-observer.ts+42 added
123456789101112131415161718192021222324252627282930313233343536373839404142import {performance, PerformanceObserver} from 'node:perf_hooks';import process from 'node:process';import type {ExecutionContext} from 'ava';
type Arg = { name: string; expectedDuration: number; t: ExecutionContext; test: () => Promise<void>;};
// We allow the tests to take more time on CI than locally, to reduce flakinessconst allowedOffset = process.env.CI ? 1000 : 300;
export async function withPerformanceObserver({ name, expectedDuration, t, test,}: Arg) { // Register observer that asserts on duration when a measurement is performed const obs = new PerformanceObserver(items => { const measurements = items.getEntries();
const duration = measurements[0].duration ?? Number.NaN;
t.true( Math.abs(duration - expectedDuration) < allowedOffset, `Duration of ${duration}ms is not close to expected duration ${expectedDuration}ms`, );
obs.disconnect(); }); obs.observe({entryTypes: ['measure']});
// Start measuring performance.mark(`start-${name}`); await test(); performance.mark(`end-${name}`);
performance.measure(name, `start-${name}`, `end-${name}`);}modified:test/retry.ts+50 added-32 removed
1-import {performance, PerformanceObserver} from 'node:perf_hooks';2-import process from 'node:process';1 import test from 'ava';2 import ky from '../source/index.js';3 import {createHttpTestServer} from './helpers/create-http-test-server.js';4+import {withPerformanceObserver} from './helpers/with-performance-observer.js';5 6 const fixture = 'fixture';7 const defaultRetryCount = 2;8 const retryAfterOn413 = 2;447 unmodified lines456 response.sendStatus(500);457 }458 });459 461- // We allow the test to take more time on CI than locally, to reduce flakiness462- const allowedOffset = process.env.CI ? 1000 : 300;460+ await withPerformanceObserver({461+ t,462+ name: 'default',463+ expectedDuration: 300 + 600 + 1200 + 2400,464+ async test() {465+ t.is(await ky(server.url, {466+ retry: retryCount,467+ }).text(), fixture);468+ },469+ });470 464- // Register observer that asserts on duration when a measurement is performed465- const obs = new PerformanceObserver(items => {466- const measurements = items.getEntries();471+ requestCount = 0;472+ await withPerformanceObserver({473+ t,474+ name: 'custom',475+ expectedDuration: 300 + 600 + 1000 + 1000,476+ async test() {477+ t.is(await ky(server.url, {478+ retry: {479+ limit: retryCount,480+ backoffLimit: 1000,481+ },482+ }).text(), fixture);483+ },484+ });485 468- const duration = measurements[0].duration ?? Number.NaN;469- const expectedDuration = {default: 300 + 600 + 1200 + 2400, custom: 300 + 600 + 1000 + 1000}[measurements[0].name] ?? Number.NaN;486+ await server.close();487+});488 471- t.true(Math.abs(duration - expectedDuration) < allowedOffset, `Duration of ${duration}ms is not close to expected duration ${expectedDuration}ms`); // Allow for 300ms difference489+test('respect custom retry.delay', async t => {490+ const retryCount = 5;491+ let requestCount = 0;492 473- if (measurements[0].name === 'custom') {474- obs.disconnect();493+ const server = await createHttpTestServer();494+ server.get('/', (_request, response) => {495+ requestCount++;496+497+ if (requestCount === retryCount) {498+ response.end(fixture);499+ } else {500+ response.sendStatus(500);501 }502 });477- obs.observe({entryTypes: ['measure']});503 479- // Start measuring480- performance.mark('start');481- t.is(await ky(server.url, {482- retry: retryCount,483- }).text(), fixture);484- performance.mark('end');485-486- performance.mark('start-custom');487- requestCount = 0;488- t.is(await ky(server.url, {489- retry: {490- limit: retryCount,491- backoffLimit: 1000,504+ await withPerformanceObserver({505+ t,506+ name: 'linear',507+ expectedDuration: 200 + 300 + 400 + 500,508+ async test() {509+ t.is(await ky(server.url, {510+ retry: {511+ limit: retryCount,512+ delay: n => 100 * (n + 1),513+ },514+ }).text(), fixture);515 },493- }).text(), fixture);516+ });517 495- performance.mark('end-custom');496-497- performance.measure('default', 'start', 'end');498- performance.measure('custom', 'start-custom', 'end-custom');499-518 await server.close();519 });modified:readme.md+3 added
194 unmodified lines195 - `methods`: `get` `put` `head` `delete` `options` `trace`196 - `statusCodes`: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)197 - `maxRetryAfter`: `undefined`198 - `backoffLimit`: `undefined`199+- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`200 201 An object representing `limit`, `methods`, `statusCodes` and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.202 203 If `retry` is a number, it will be used as `limit` and other defaults will remain in place.3 unmodified lines207 The `backoffLimit` option is the upper limit of the delay per retry in milliseconds.208 To clamp the delay, set `backoffLimit` to 1000, for example.209 By default, the delay is calculated with `0.3 * (2 ** (attemptCount - 1)) * 1000`. The delay increases exponentially.210 211+The `delay` option can be used to change how the delay between retries is calculated. The function receives one parameter, the attempt count, starting at `1`.212+213 Retries are not triggered following a [timeout](#timeout).214 215 ```js216 import ky from 'ky';468 unmodified lines