Skip to content
Myr

Validate the retry options and forward every fetch-only extension

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent f446745 · Browse files · 7 files+155 added−8 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+155 added−8 removed

  • tests:+122 added−7 removed
  • other:+33 added−1 removed

7 files+155 added−8 removed

modified:source/core/Ky.ts+7 added
611 unmodified lines
612613 #calculateDelay(retry: InternalOptions['retry']): number {614 const retryDelay = retry.delay(this.#retryCount + 1);615616 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which617 // `setTimeout()` clamps to 1ms, silently disabling the configured backoff. The `jitter` function form618 // already guards its own result, so the input is checked here for every jitter form.619 if (typeof retryDelay !== 'number' || Number.isNaN(retryDelay) || retryDelay < 0) {620 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`');621 }622623 let jitteredDelay = retryDelay;624 if (retry.jitter === true) {625 jitteredDelay = Math.random() * retryDelay;626 } else if (typeof retry.jitter === 'function') {
838 unmodified lines
modified:source/utils/normalize.ts+20 added
modified:source/utils/options.ts+3 added-1 removed
modified:test/fetch.ts+21 added
888 unmodified lines
889890 t.is(await api(fixture).text(), 'ok');891 t.deepEqual(thisValues, [undefined]);892});893894// A vendor extension named after an `Object.prototype` member was silently dropped, because the lookup went through the prototype chain of the option registries.895test('unknown options named after Object.prototype members are passed to fetch', async t => {896 t.plan(4);897898 const customFetch: typeof fetch = async (request, init) => {899 t.is(init.constructor, 'fetch-constructor');900 t.is(init.toString, 'fetch-to-string');901 t.is(init.valueOf, 'fetch-value-of');902 t.is(init.hasOwnProperty, 'fetch-has-own-property');903 return new Response(request.url);904 };905906 await ky(fixture, {907 constructor: 'fetch-constructor',908 toString: 'fetch-to-string',909 valueOf: 'fetch-value-of',910 hasOwnProperty: 'fetch-has-own-property',911 fetch: customFetch,912 } as never).text();913});
modified:test/retry.ts+94 added
4789 unmodified lines
4790 }));47914792 t.is(error.message, 'rewritten: NetworkError');4793});47944795// Both limits feed `Math.min()`, so a non-number turns the retry delay into `NaN`, which `setTimeout()` clamps to4796// 1ms. A `Retry-After: 1` header would then be retried almost immediately, which is the thundering herd those4797// options exist to prevent.4798test('rejects non-numeric or negative `maxRetryAfter` and `backoffLimit`', t => {4799 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {4800 for (const value of ['1000', Number.NaN, -1, {}, null] as unknown[]) {4801 // `null` is nullish, so it selects the default instead of being rejected.4802 if (value === null) {4803 continue;4804 }48054806 const retry: Record<string, unknown> = {[key]: value};48074808 t.throws(() => {4809 void ky('https://example.com', {retry: retry as never});4810 }, {4811 instanceOf: TypeError,4812 message: `\`retry.${key}\` must be a non-negative number or \`Infinity\``,4813 }, `${key}: ${JSON.stringify(value)}`);4814 }4815 }4816});48174818// Validating up front means the misconfiguration is reported before the request is sent, instead of replacing the4819// `HTTPError` with a `TypeError` from deep inside the retry delay calculation.4820test('a rejected retry limit is reported before the request is sent', t => {4821 for (const key of ['maxRetryAfter', 'backoffLimit'] as const) {4822 let requestCount = 0;4823 const retry: Record<string, unknown> = {[key]: 'soon'};48244825 t.throws(() => {4826 void ky('https://example.com', {4827 async fetch() {4828 requestCount++;4829 return new Response(null, {status: 500});4830 },4831 retry: retry as never,4832 });4833 }, {4834 instanceOf: TypeError,4835 message: `\`retry.${key}\` must be a non-negative number or \`Infinity\``,4836 }, key);48374838 t.is(requestCount, 0, key);4839 }4840});48414842// A non-function `delay`/`shouldRetry` used to be called blindly, so the resulting `TypeError` replaced the4843// `HTTPError` that actually caused the retry. Validate the shapes up front instead.4844test('rejects non-function `retry.delay`, `retry.shouldRetry` and `retry.jitter`', t => {4845 for (const [key, value] of [4846 ['delay', 1000],4847 ['shouldRetry', true],4848 ['jitter', 'yes'],4849 ['jitter', 1],4850 ] as Array<[string, unknown]>) {4851 const retry: Record<string, unknown> = {[key]: value};48524853 t.throws(() => {4854 void ky('https://example.com', {retry: retry as never});4855 }, {4856 instanceOf: TypeError,4857 message: `\`retry.${key}\` must be ${key === 'jitter' ? 'a boolean or a function' : 'a function'}`,4858 }, `${key}: ${JSON.stringify(value)}`);4859 }4860});48614862test('a non-finite `retry.delay` result is rejected for every jitter form', async t => {4863 for (const jitter of [undefined, true, () => 1] as unknown[]) {4864 // eslint-disable-next-line no-await-in-loop4865 await t.throwsAsync(ky('https://example.com', {4866 async fetch() {4867 return new Response(null, {status: 500});4868 },4869 retry: {limit: 1, delay: () => Number.NaN, jitter: jitter as never},4870 }).text(), {4871 instanceOf: TypeError,4872 message: '`retry.delay` must return a non-negative number or `Infinity`',4873 }, `jitter: ${String(jitter)}`);4874 }4875});48764877test('a negative `retry.delay` result is rejected', async t => {4878 await t.throwsAsync(ky('https://example.com', {4879 async fetch() {4880 return new Response(null, {status: 500});4881 },4882 retry: {limit: 1, delay: () => -1},4883 }).text(), {4884 instanceOf: TypeError,4885 message: '`retry.delay` must return a non-negative number or `Infinity`',4886 });4887});
modified:test/validation.ts+7 added-7 removed
5 unmodified lines
6// `timeout` and `totalTimeout` are documented as milliseconds or `false`. Anything else used to be passed7// straight to `setTimeout()`, which clamps it to ~1ms, or was silently ignored, so the request never got the8// timeout the caller asked for. `null` is left out: it is nullish, so it selects the default.9test('rejects non-numeric and negative `timeout` values', async t => {10 for (const timeout of ['1000', Number.NaN, -1, -0.5, {}]) {10 for (const timeout of ['1000', Number.NaN, -1, -0.5, {}] as unknown[]) {11 // eslint-disable-next-line no-await-in-loop12 await t.throwsAsync(13 ky('https://example.com', {timeout: timeout as never, fetch: okFetch}).text(),14 {15 name: 'TypeError',16 message: 'The `timeout` option must be a non-negative number or `false`',17 },18 `timeout: ${String(timeout)}`,18 `timeout: ${JSON.stringify(timeout)}`,19 );20 }21});2223test('rejects non-numeric and negative `totalTimeout` values', async t => {24 for (const totalTimeout of ['1000', Number.NaN, -1, -0.5, {}]) {24 for (const totalTimeout of ['1000', Number.NaN, -1, -0.5, {}] as unknown[]) {25 // eslint-disable-next-line no-await-in-loop26 await t.throwsAsync(27 ky('https://example.com', {totalTimeout: totalTimeout as never, fetch: okFetch}).text(),28 {29 name: 'TypeError',30 message: 'The `totalTimeout` option must be a non-negative number or `false`',31 },32 `totalTimeout: ${String(totalTimeout)}`,32 `totalTimeout: ${JSON.stringify(totalTimeout)}`,33 );34 }35});36
9 unmodified lines
46 {47 instanceOf: RangeError,48 message: `The \`${option}\` option cannot be greater than 2147483647`,49 },50 option,50 `option: ${option}`,51 );52 }53});5455test('accepts `false`, `0` and finite non-negative numbers for the timeout options', async t => {55test('accepts `false`, `0` and non-negative numbers for the timeout options', async t => {56 t.is(await ky('https://example.com', {timeout: false, totalTimeout: false, fetch: okFetch}).text(), 'ok');57 t.is(await ky('https://example.com', {timeout: 0, fetch: async () => new Response('a'), totalTimeout: 5_000}).text(), 'a');57 t.is(await ky('https://example.com', {timeout: 0, totalTimeout: 5000, fetch: async () => new Response('a')}).text(), 'a');58});5960test('rejects invalid timeout values set from an `init` hook', async t => {61 await t.throwsAsync(
14 unmodified lines
modified:package.json+3 added
69 unmodified lines
70 "typescript": "^5.9.3",71 "xo": "^1.2.3"72 },73 "xo": {74 "ignores": [75 "Stuff/**"76 ],77 "rules": {78 "unicorn/filename-case": "off",79 "@typescript-eslint/ban-ts-comment": "off",80 "@typescript-eslint/no-unsafe-argument": "off",
22 unmodified lines