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
Provenance
- Commit
23ca564- Tree
88d3b7d- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d89c8c8
7 files changed+83 added−7 removed
modified:source/core/retry-timing.ts+3 added-3 removed
12123456147 unmodified linesExpand all15415515615715815815916016116211 unmodified lines// Older epoch-second values are indistinguishable from ordinary delay seconds, so timestamp compatibility only applies to current-era reset headers.const timestampThreshold = Date.parse('2024-01-01');// A reset value is only read as an epoch from this second onwards (2001-09-09). Older values are ambiguous with an ordinary delay, but a delay of 32 years or more is not a real one, so anything below stays delay seconds. This is a fixed constant rather than a date so it cannot go stale and start misreading a recent-but-past reset.const timestampThresholdSeconds = 1_000_000_000;const delayPattern = /^\d+$/;const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// HTTP-date parsing is limited to IMF-fixdate and the two obsolete HTTP-date formats. Other date-like strings intentionally fall back to the normal retry delay.147 unmodified linesExpand all
// Standard Retry-After numbers are delay seconds. Timestamp compatibility only applies to reset headers. if ( allowTimestamp && delay >= timestampThreshold && Number(value) >= timestampThresholdSeconds ) { delay -= Date.now(); }
11 unmodified linesmodified:source/types/options.ts+1 added-1 removed
185 unmodified lines186 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.187 188 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.189 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 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.191 192 If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.193 194 @example352 unmodified linesmodified:source/utils/body.ts+5 added-2 removed
166 unmodified lines167 return response;168 };169 170 export 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 }176 177 let transferredBytes = 0;14 unmodified lines192 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());193 };194 195 export 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 }200 201 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after29 unmodified linesmodified:test/response-size.ts+25 added
476 unmodified lines477 t.is(await response.text(), '');478 t.is(progressCallCount, 0);479 });480 }481+482+// 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()`.483+for (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+ });499+500+ 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 lines70 const header = getRetryTimingHeader(headers);71 t.deepEqual(header, {value: '1, 2', allowTimestamp: false});72 t.is(calculateRetryTimingDelay(header!), undefined);73 });74+75+// 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.76+for (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+}87+88+test('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 lines4925 message: '`retry.statusCodes` must only contain numbers',4926 });4927 t.is(requestCount, 0);4928 });4929+4930+// 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.4931+test.serial('a past `RateLimit-Reset` epoch retries immediately', async t => {4932+ const now = Date.UTC(2026, 0, 1);4933+ let requestCount = 0;4934+4935+ 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+ });4946+4947+ 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+ }4957+4958+ t.is(requestCount, 3);4959+});modified:readme.md+1 added-1 removed
278 unmodified lines279 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.280 281 `413 Payload Too Large` is only retried when the response includes a retry timing header, unless `shouldRetry` returns `true`.282 283-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.283+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.284 285 If the retry delay from a retry timing header is greater than `maxRetryAfter`, Ky will use `maxRetryAfter`.286 287 The `backoffLimit` option is the upper limit of the delay per retry in milliseconds, for the delay calculated by `retry.delay`.1620 unmodified lines