Skip to content
Myr

Skip wrapping a body a hook read, and read a past reset epoch as a timestamp

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 d89c8c8 · Browse files · 7 files+83 added−7 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+83 added−7 removed

  • tests:+73 added−0 removed
  • other:+10 added−7 removed

7 files+83 added−7 removed

modified:source/core/retry-timing.ts+3 added-3 removed
modified:source/types/options.ts+1 added-1 removed
185 unmodified lines
186 Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.187188 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.189190 When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as current-era Unix timestamps. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.190 When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as Unix timestamps, from 2001-09-09 onwards. A value below that is read as delay seconds, and a timestamp already in the past means the retry happens immediately. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.191192 If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.193194 @example
352 unmodified lines
modified:source/utils/body.ts+5 added-2 removed
166 unmodified lines
167 return response;168};169170export const limitResponseSize = (response: Response, request: Request, maxResponseSize: number): Response => {171 // A body a hook already read cannot be piped through, and would otherwise fail with "The ReadableStream is172 // locked" instead of the native "Body is unusable" error that names the actual mistake.171 if (!response.body || nullBodyStatuses.has(response.status) || maxResponseSize === Number.POSITIVE_INFINITY) {173 if (!response.body || response.bodyUsed || nullBodyStatuses.has(response.status) || maxResponseSize === Number.POSITIVE_INFINITY) {174 return response;175 }176177 let transferredBytes = 0;
14 unmodified lines
192 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());193};194195export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {196 // See `limitResponseSize`: there is nothing left to stream and nothing to report once a hook consumed the body.194 if (!response.body || nullBodyStatuses.has(response.status)) {197 if (!response.body || response.bodyUsed || nullBodyStatuses.has(response.status)) {198 return response;199 }200201 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after
29 unmodified lines
modified:test/response-size.ts+25 added
476 unmodified lines
477 t.is(await response.text(), '');478 t.is(progressCallCount, 0);479 });480}481482// Wrapping a body that a hook already read fails with \"The ReadableStream is locked\", which names neither the real mistake nor the option that caused it. The native \"Body is unusable\" error is far clearer, so the wrappers skip an already consumed body instead of crashing inside `pipeThrough()`.483for (const [label, options] of [484 ['without the limit', {}],485 ['with `maxResponseSize`', {maxResponseSize: 1000}],486 ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],487] as Array<[string, Record<string, unknown>]>) {488 test(`an afterResponse hook that returns a consumed response reports the native error ${label}`, async t => {489 const response = await ky(url, {490 ...options,491 fetch: async () => new Response('x'.repeat(50)),492 hooks: {493 afterResponse: [async ({response}) => {494 await response.text();495 return response;496 }],497 },498 });499500 await t.throwsAsync(response.text(), {501 name: 'TypeError',502 message: 'Body is unusable: Body has already been read',503 });504 });505}
modified:test/retry-timing.ts+17 added
69 unmodified lines
70 const header = getRetryTimingHeader(headers);71 t.deepEqual(header, {value: '1, 2', allowTimestamp: false});72 t.is(calculateRetryTimingDelay(header!), undefined);73});7475// The "current era" cutoff used to be a hardcoded 2024-01-01, so a reset value from just before it fell below the cutoff and was read as delay seconds. A `RateLimit-Reset` of 1700000000 (November 2023) became a 54-year delay.76for (const [description, value, expected] of [77 ['a November 2023 epoch as a reset in the past', '1700000000', 0],78 ['a January 2023 epoch as a reset in the past', '1672531200', 0],79 ['a 2001 epoch as a reset in the past', '1000000000', 0],80 ['a value just below the threshold as a delay', '999999999', 999_999_999_000],81 ['a small reset as a delay', '30', 30_000],82] as Array<[string, string, number]>) {83 test(`RateLimit-Reset reads ${description}`, t => {84 t.is(calculateRetryTimingDelay({value, allowTimestamp: true}), expected);85 });86}8788test('Retry-After numbers are never treated as timestamps', t => {89 t.is(calculateRetryTimingDelay({value: '1700000000', allowTimestamp: false}), 1_700_000_000_000);90});
modified:test/retry.ts+31 added
4924 unmodified lines
4925 message: '`retry.statusCodes` must only contain numbers',4926 });4927 t.is(requestCount, 0);4928});49294930// A `RateLimit-Reset` in the past used to be read as delay seconds when it fell before the hardcoded 2024 cutoff, so a November 2023 reset became a 54-year wait instead of an immediate retry.4931test.serial('a past `RateLimit-Reset` epoch retries immediately', async t => {4932 const now = Date.UTC(2026, 0, 1);4933 let requestCount = 0;49344935 const server = await createHttpTestServer(t);4936 server.get('/', (_request, response) => {4937 requestCount++;4938 if (requestCount === defaultRetryCount + 1) {4939 response.end(fixture);4940 } else {4941 // 2023-11-14T22:13:20Z, well before the old 2024-01-01 cutoff.4942 response.writeHead(429, {'RateLimit-Reset': '1700000000'});4943 response.end('');4944 }4945 });49464947 const dateNow = Date.now;4948 try {4949 Date.now = () => now;4950 await withCapturedTimeouts(async scheduledDelays => {4951 t.is(await ky(server.url).text(), fixture);4952 t.false(scheduledDelays.includes(retryAfterTimestampScheduledDelay));4953 });4954 } finally {4955 Date.now = dateNow;4956 }49574958 t.is(requestCount, 3);4959});
modified:readme.md+1 added-1 removed
278 unmodified lines
279Network errors (e.g., DNS failures, connection refused, offline) are automatically retried for retriable methods. Only errors recognized as network errors are retried; other errors (e.g., programming bugs) are thrown immediately. Use `shouldRetry` to customize this behavior.280281`413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.282283When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as current-era Unix timestamps. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.283When the response status is contained in `afterStatusCodes` and the retry is allowed by `statusCodes` or `shouldRetry`, Ky uses retry timing headers to choose the retry delay. [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) may provide a delay in seconds or an HTTP-date. If `Retry-After` is missing, Ky falls back to rate-limit timing headers (`RateLimit-Reset`, `X-RateLimit-Retry-After`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset`). Numeric `Retry-After` and `X-RateLimit-Retry-After` values are interpreted as delay seconds. Numeric `RateLimit-Reset`, `X-RateLimit-Reset`, and `X-Rate-Limit-Reset` values may also be interpreted as Unix timestamps, from 2001-09-09 onwards. A value below that is read as delay seconds, and a timestamp already in the past means the retry happens immediately. If the status code is not in `afterStatusCodes`, retry timing headers will be ignored.284285If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.286287The `backoffLimit` option is the upper limit of the delay per retry in milliseconds, for the delay calculated by `retry.delay`.
1620 unmodified lines