Enforce total timeout after fetch and body processing
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 d636438 · Browse files · 4 files·+259 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+259 added−9 removed
- tests:+235 added−1 removed
- other:+24 added−8 removed
Provenance
- Commit
82fa84c- Tree
ac579f4- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d636438
4 files changed+259 added−9 removed
modified:source/core/Ky.ts+24 added-8 removed
244 unmodified lines245 const httpError: HTTPError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());246 const errorToThrow: Error = httpError;247 // eslint-disable-next-line no-await-in-loop248 httpError.data = await ky.#getResponseData(currentResponse);249+ ky.#throwIfTotalTimeoutExhausted();250 251 if (responseFromHook) {252 throw errorToThrow;253 }527 unmodified lines781 result = timeoutPromise === undefined782 ? await bodyPromise783 : await Promise.race([bodyPromise, timeoutPromise]);784 } catch (error: unknown) {785+ this.#throwIfAbortedByUser();786+ if (this.#getRemainingTotalTimeout() !== 0) {784- // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.785- // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.786- if (isRawNetworkError(error)) {787- this.#throwIfAbortedByUser();788- await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));787+ // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.788+ // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.789+ if (isRawNetworkError(error)) {790+ await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));791+ }792+793+ throw error;794 }795 791- throw error;796+ result = timedOutResponseData;797 }798 794- if (result === timedOutResponseData) {799+ if (result === timedOutResponseData || this.#getRemainingTotalTimeout() === 0) {800 // The stream is locked by the native body method's own reader by this point, so801 // `response.body.cancel()` would reject as "already locked". Aborting the request's802 // signal is what actually interrupts the underlying network read.803 this.#abortController?.abort();404 unmodified lines1208 timeout: effectiveTimeout,1209 fetch,1210 });1211 1212+ if (this.#getRemainingTotalTimeout() === 0) {1213+ this.#abortController?.abort();1214+ this.#cancelResponseBody(response);1215+ throw new TimeoutError(request);1216+ }1217+1218 return this.#setResponseRequest(response, request);1219 } catch (error) {1220+ this.#throwIfAbortedByUser();1221+ if (this.#getRemainingTotalTimeout() === 0) {1222+ this.#abortController?.abort();1223+ throw new TimeoutError(request);1224+ }1225+1226 if (isRawNetworkError(error)) {1210- this.#throwIfAbortedByUser();1227 throw new NetworkError(this.request, {cause: error as Error});1228 }1229 1230 throw error;78 unmodified linesmodified:test/http-error.ts+53 added-1 removed
1 import test from 'ava';2 import {expectTypeOf} from 'expect-type';3-import ky, {HTTPError, isHTTPError} from '../source/index.js';3+import ky, {HTTPError, isHTTPError, TimeoutError} from '../source/index.js';4 import {type Mutable} from '../source/utils/types.js';5 import {createHttpTestServer} from './helpers/create-http-test-server.js';6 7 function createFakeResponse({status, statusText}: {status?: number; statusText?: string}): Response {214 unmodified lines222 t.is(error?.data, undefined);223 t.true(Date.now() - start < 5000);224 });225 226+test.serial('totalTimeout is enforced after synchronous error JSON parsing', async t => {227+ const originalPerformanceNow = globalThis.performance.now;228+ let currentTime = 0;229+ let didParse = false;230+ globalThis.performance.now = () => currentTime;231+ t.teardown(() => {232+ globalThis.performance.now = originalPerformanceNow;233+ });234+235+ await t.throwsAsync(ky('https://example.com', {236+ retry: 0,237+ totalTimeout: 500,238+ async fetch() {239+ return Response.json({error: 'failure'}, {status: 500});240+ },241+ parseJson(text) {242+ didParse = true;243+ currentTime = 501;244+ return JSON.parse(text);245+ },246+ }), {instanceOf: TimeoutError});247+248+ t.true(didParse);249+});250+251+test.serial('totalTimeout is enforced after reading a plain-text error body', async t => {252+ const originalPerformanceNow = globalThis.performance.now;253+ let currentTime = 0;254+ let didRead = false;255+ globalThis.performance.now = () => currentTime;256+ t.teardown(() => {257+ globalThis.performance.now = originalPerformanceNow;258+ });259+260+ await t.throwsAsync(ky('https://example.com', {261+ retry: 0,262+ totalTimeout: 500,263+ async fetch() {264+ return new Response(new ReadableStream({265+ pull(controller) {266+ didRead = true;267+ currentTime = 501;268+ controller.enqueue(new TextEncoder().encode('failure'));269+ controller.close();270+ },271+ }, {highWaterMark: 0}), {status: 500});272+ },273+ }), {instanceOf: TimeoutError});274+275+ t.true(didRead);276+});277+278 test('HTTPError#data does not call parseJson for non-JSON responses', async t => {279 const server = await createHttpTestServer(t);280 server.get('/', (_request, response) => {281 response.status(400).type('text/plain').send('plain text');370 unmodified linesmodified:test/main.ts+82 added
1079 unmodified lines1080 t.true(didStartBodyRead);1081 t.true(Date.now() - start < 2000);1082 });1083 1084+for (const timeout of [false, 10_000] as const) {1085+ test.serial(`totalTimeout rejects a completed fetch past the deadline with timeout ${timeout}`, async t => {1086+ const originalPerformanceNow = globalThis.performance.now;1087+ let currentTime = 0;1088+ let fetchCount = 0;1089+ let hookCallCount = 0;1090+ let requestSignal: AbortSignal | undefined;1091+ let canceledBody = false;1092+ globalThis.performance.now = () => currentTime;1093+ t.teardown(() => {1094+ globalThis.performance.now = originalPerformanceNow;1095+ });1096+1097+ await t.throwsAsync(ky('https://example.com', {1098+ timeout,1099+ totalTimeout: 500,1100+ async fetch(request) {1101+ fetchCount++;1102+ requestSignal = request.signal;1103+ currentTime = 501;1104+ return new Response(new ReadableStream({1105+ cancel() {1106+ canceledBody = true;1107+ },1108+ }));1109+ },1110+ hooks: {1111+ beforeError: [({error}) => {1112+ hookCallCount++;1113+ t.true(error instanceof TimeoutError);1114+ return error;1115+ }],1116+ },1117+ }), {instanceOf: TimeoutError});1118+ t.is(fetchCount, 1);1119+ t.is(hookCallCount, 1);1120+ t.true(requestSignal?.aborted);1121+ t.true(canceledBody);1122+ });1123+}1124+1125+for (const method of ['text', 'arrayBuffer', 'json'] as const) {1126+ test.serial(`totalTimeout rejects a completed ${method} body read past the deadline`, async t => {1127+ const originalPerformanceNow = globalThis.performance.now;1128+ let currentTime = 0;1129+ let didRead = false;1130+ let requestSignal: AbortSignal | undefined;1131+ let hookCallCount = 0;1132+ globalThis.performance.now = () => currentTime;1133+ t.teardown(() => {1134+ globalThis.performance.now = originalPerformanceNow;1135+ });1136+1137+ const response = ky('https://example.com', {1138+ totalTimeout: 500,1139+ async fetch(request) {1140+ requestSignal = request.signal;1141+ return new Response(new ReadableStream({1142+ pull(controller) {1143+ didRead = true;1144+ currentTime = 501;1145+ controller.enqueue(new TextEncoder().encode('{"ok":true}'));1146+ controller.close();1147+ },1148+ }, {highWaterMark: 0}));1149+ },1150+ hooks: {1151+ beforeError: [({error}) => {1152+ hookCallCount++;1153+ t.true(error instanceof TimeoutError);1154+ return error;1155+ }],1156+ },1157+ });1158+1159+ await t.throwsAsync(response[method](), {instanceOf: TimeoutError});1160+ t.true(didRead);1161+ t.true(requestSignal?.aborted);1162+ t.is(hookCallCount, 1);1163+ });1164+}1165+1166 test('beforeError hook receives totalTimeout exhausted before a shortcut body read starts', async t => {1167 let didReadBody = false;1168 let hookError: Error | undefined;1169 2637 unmodified linesmodified:test/retry.ts+100 added
13 unmodified lines14 import {parseRawBody} from './helpers/parse-body.js';15 import {withPerformance} from './helpers/with-performance.js';16 17 const fixture = 'fixture';18+19+for (const {title, elapsed, totalTimeout, errorType} of [20+ {21+ title: 'expired', elapsed: 100, totalTimeout: 50, errorType: TimeoutError,22+ },23+ {24+ title: 'unexpired', elapsed: 25, totalTimeout: 50, errorType: NetworkError,25+ },26+ {27+ title: 'disabled', elapsed: 100, totalTimeout: false, errorType: NetworkError,28+ },29+] as const) {30+ test.serial(`body read failure respects ${title} totalTimeout`, async t => {31+ const originalPerformanceNow = globalThis.performance.now;32+ let currentTime = 0;33+ globalThis.performance.now = () => currentTime;34+ t.teardown(() => {35+ globalThis.performance.now = originalPerformanceNow;36+ });37+38+ let requestCount = 0;39+ const hookErrors: Error[] = [];40+ const error = await t.throwsAsync(ky('https://example.com', {41+ timeout: false,42+ totalTimeout,43+ async fetch() {44+ requestCount++;45+ return new Response(new ReadableStream({46+ pull(controller) {47+ currentTime = elapsed;48+ controller.error(new TypeError('terminated'));49+ },50+ }, {highWaterMark: 0}));51+ },52+ hooks: {53+ beforeError: [({error}) => {54+ hookErrors.push(error);55+ return error;56+ }],57+ },58+ }).text(), {instanceOf: errorType});59+60+ t.is(error.request.url, 'https://example.com/');61+ t.deepEqual(hookErrors, [error]);62+ t.is(requestCount, 1);63+ });64+}65+66+test.serial('totalTimeout takes precedence when fetch rejects after the deadline', async t => {67+ const originalPerformanceNow = globalThis.performance.now;68+ let currentTime = 0;69+ globalThis.performance.now = () => currentTime;70+ t.teardown(() => {71+ globalThis.performance.now = originalPerformanceNow;72+ });73+74+ let requestCount = 0;75+ let errorHookCount = 0;76+ await t.throwsAsync(ky('https://example.com', {77+ timeout: false,78+ totalTimeout: 50,79+ retry: 0,80+ async fetch() {81+ requestCount++;82+ currentTime = 100;83+ throw new TypeError('fetch failed');84+ },85+ hooks: {86+ beforeError: [({error}) => {87+ errorHookCount++;88+ t.true(error instanceof TimeoutError);89+ return error;90+ }],91+ },92+ }), {instanceOf: TimeoutError});93+ t.is(requestCount, 1);94+ t.is(errorHookCount, 1);95+96+ currentTime = 0;97+ await t.throwsAsync(ky('https://example.com', {98+ timeout: false,99+ totalTimeout: 50,100+ retry: 0,101+ async fetch() {102+ currentTime = 25;103+ throw new TypeError('fetch failed');104+ },105+ }), {instanceOf: NetworkError});106+107+ await t.throwsAsync(ky('https://example.com', {108+ timeout: false,109+ totalTimeout: false,110+ retry: 0,111+ async fetch() {112+ currentTime = 100;113+ throw new TypeError('fetch failed');114+ },115+ }), {instanceOf: NetworkError});116+});117+118 const defaultRetryCount = 2;119 const retryAfterOn500 = 2;120 const retryAfterOn413 = 2;121 const retryAfterTimestampText = '1704067200';3951 unmodified lines