Skip to content
Myr

Recognise a cross-realm `beforeRetry` error and keep the retried error as the cause

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 deb5a33 · Browse files · 4 files+116 added−18 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+116 added−18 removed

  • tests:+104 added−9 removed
  • other:+12 added−9 removed

4 files+116 added−18 removed

modified:source/core/Ky.ts+12 added-9 removed
665 unmodified lines
666 // Ky's internal scheduling and user hook time before the first fetch attempt.667 this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;668 }669670 #calculateDelay(retry: InternalOptions['retry']): number {670 #calculateDelay(retry: InternalOptions['retry'], error: unknown): number {671 const retryDelay = retry.delay(this.#retryCount + 1);672673 // A `retry.delay` that does not return a usable number would turn every delay into `NaN`, which674 // `setTimeout()` clamps to 1ms, silently disabling the configured backoff. The `jitter` function form675 // already guards its own result, so the input is checked here for every jitter form.676 if (typeof retryDelay !== 'number' || Number.isNaN(retryDelay) || retryDelay < 0) {677 // The failure that was being retried is chained as the cause, so `beforeError` can still inspect it678 // instead of losing the response and data to this configuration mistake.677 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`');679 throw new TypeError('`retry.delay` must return a non-negative number or `Infinity`', {cause: error});680 }681682 let jitteredDelay = retryDelay;683 if (retry.jitter === true) {
23 unmodified lines
707 const errorObject = error instanceof Error ? error : new NonError(error);708709 // Handle forced retry from afterResponse hook - skip method check and shouldRetry710 if (isForceRetryError(errorObject)) {709 return errorObject.customDelay ?? this.#calculateDelay(retry);711 return errorObject.customDelay ?? this.#calculateDelay(retry, error);712 }713714 // Check if method is retriable for non-forced retries715 if (!retry.methods.includes(normalizeRetryMethod(this.request.method))) {
22 unmodified lines
738 if (!shouldRetryOverride && !retry.retryOnTimeout) {739 throw error;740 }741740 return this.#calculateDelay(retry);742 return this.#calculateDelay(retry, error);743 }744745 // The `isHTTPError()` brand only checks `name`, so a cross-realm error may not carry a `response`.746 if (isHTTPError(error) && error.response) {
5 unmodified lines
752 if (retryTimingHeader && retry.afterStatusCodes.includes(error.response.status)) {753 const after = calculateRetryTimingDelay(retryTimingHeader);754 if (after === undefined) {755 // Malformed retry timing headers should not disable retries; they only lose their server-provided timing.754 return this.#calculateDelay(retry);756 return this.#calculateDelay(retry, error);757 }758759 // Don't apply jitter when server provides explicit retry timing760 return Math.min(retry.maxRetryAfter, after);
2 unmodified lines
763 if (!shouldRetryOverride && error.response.status === 413) {764 throw error;765 }766765 return this.#calculateDelay(retry);767 return this.#calculateDelay(retry, error);768 }769770 // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.771 if (!shouldRetryOverride && !isNetworkError(error)) {772 throw error;773 }774773 return this.#calculateDelay(retry);775 return this.#calculateDelay(retry, error);776 }777778 #decorateResponse(response: Response): Response {779 if (!this.#options.parseJson || this.#decoratedResponses.has(response)) {
602 unmodified lines
1382 error: error instanceof Error ? error : new NonError(error),1383 retryCount: this.#retryCount + 1,1384 }), this.#userProvidedAbortSignal);1385 } catch (hookError) {1384 // Preserve the original request error path (`throw error`) so beforeError hooks can still run.1385 if (hookError instanceof Error && hookError !== error) {1386 // Preserve the original request error path (`throw error`) so beforeError hooks can still run. `isError`1387 // rather than `instanceof`, so a cross-realm error is recognised the same way `#throwProcessedError` does.1388 if (isError(hookError) && hookError !== error) {1389 this.#beforeRetryHookErrors.add(hookError);1390 }13911392 throw hookError;
193 unmodified lines
modified:test/hooks.ts+29 added
7435 unmodified lines
7436 t.is(text, 'ok');7437 t.is(attempts, 3);7438 t.deepEqual(seenCodes, ['FOREIGN_COPY', 'FOREIGN_COPY']);7439});74407441// `#beforeRetryHookErrors` decided with `instanceof Error` while `#throwProcessedError` decided with the realm-safe `isError`, so a cross-realm error thrown by a `beforeRetry` hook reached the `beforeError` hooks while an identical same-realm error did not, contradicting "Ky will not handle it in any way".7442test('a cross-realm error from a `beforeRetry` hook skips the `beforeError` hooks', async t => {7443 const foreignError = runInNewContext('new Error("from a beforeRetry hook")') as Error;74447445 for (const [label, thrown] of [7446 ['same realm', new Error('from a beforeRetry hook')],7447 ['another realm', foreignError],7448 ] as Array<[string, Error]>) {7449 const seen: string[] = [];74507451 // eslint-disable-next-line no-await-in-loop7452 const error = await t.throwsAsync(ky('https://example.com', {7453 retry: {limit: 1, delay: () => 0},7454 fetch: async () => new Response('server error', {status: 500}),7455 hooks: {7456 beforeRetry: [() => {7457 throw thrown;7458 }],7459 beforeError: [({error: hookError}) => {7460 seen.push(hookError.message);7461 }],7462 },7463 }).text());74647465 t.is(error, thrown, label);7466 t.deepEqual(seen, [], `${label}: the hook error must propagate unchanged`);7467 }7468});
modified:test/main.ts+22 added-6 removed
4267 unmodified lines
4268// on the attempt that produced the response the caller reads.4269test('a body shortcut called after dispatch does not advertise its media type on the retry', async t => {4270 const accepts: string[] = [];4271 let attempts = 0;4272 let markBeforeRetry: () => void;4273 let releaseBeforeRetry: () => void;42744275 // The `beforeRetry` hook gates the retry, so the shortcut is guaranteed to be called while `ky.request` is the clone prepared for that retry rather than racing a timer against it.4276 const beforeRetryStarted = new Promise<void>(resolve => {4277 markBeforeRetry = resolve;4278 });4279 const beforeRetryGate = new Promise<void>(resolve => {4280 releaseBeforeRetry = resolve;4281 });42824283 const promise = ky('https://example.com', {4274 retry: {limit: 1, delay: () => 20},4284 retry: {limit: 1, delay: () => 0},4285 async fetch(request) {4286 attempts++;4287 accepts.push(request.headers.get('accept') ?? 'none');4288 return attempts === 1 ? new Response('{"ok":true}', {status: 500}) : new Response('{"ok":true}');4289 },4290 hooks: {4291 beforeRetry: [async () => {4292 markBeforeRetry!();4293 await beforeRetryGate;4294 }],4295 },4296 });42974282 // Dispatch the first attempt, then ask for JSON while the retry delay is still running.4283 await new Promise(resolve => {4284 setTimeout(resolve, 5);4285 });4286 t.is(JSON.stringify(await promise.json()), '{"ok":true}');4298 await beforeRetryStarted;4299 // `.json()` sets the Accept header synchronously, before it awaits the request.4300 const jsonPromise = promise.json();4301 releaseBeforeRetry!();4302 t.is(JSON.stringify(await jsonPromise), '{"ok":true}');43034304 t.is(attempts, 2);4305 t.deepEqual(accepts, ['none', 'none']);4306});
modified:test/retry.ts+53 added-3 removed
5142 unmodified lines
51435144 const error = await t.throwsAsync(ky.post('https://example.com', {5145 body: 'payload',5146 retry: {limit: 2, delay: () => 5000, methods: ['post']},5147 totalTimeout: 300,5147 totalTimeout: 2000,5148 async fetch(request) {5149 attempts++;5150 sentRequest = request;5151 return new Response('server error', {status: 500});
9 unmodified lines
5161 const sentRequests: Request[] = [];5162 let attempts = 0;51635164 const error = await t.throwsAsync(ky.get('https://example.com', {5165 // A budget that comfortably fits several attempts, so the check is about which request is named rather than about how many retries fit in the window.5165 retry: {limit: 20, delay: () => 30},5166 totalTimeout: 300,5166 retry: {limit: 100, delay: () => 20},5167 totalTimeout: 800,5168 async fetch(request) {5169 attempts++;5170 sentRequests.push(request);5171 return new Response('server error', {status: 500});
2 unmodified lines
51745175 t.true(attempts > 1, `the request should have been retried before the budget ran out, got ${attempts}`);5176 t.is((error as {request: Request}).request, sentRequests.at(-1));5177});51785179// A `retry.delay` that does not return a usable number is a configuration mistake, but it happens on the retry-decision path, so the `HTTPError` that was being retried would otherwise be lost. It is chained as the cause so `beforeError` can still reach it.5180test('a bad `retry.delay` result keeps the original error as the cause', async t => {5181 const seen: Array<{name: string; causeName: string; causeStatus: number}> = [];51825183 const error = await t.throwsAsync(ky('https://example.com', {5184 fetch: async () => new Response('server error', {status: 500}),5185 retry: {limit: 1, delay: () => Number.NaN},5186 hooks: {5187 beforeError: [({error}) => {5188 const {cause} = error as {cause?: {name?: string; response?: {status?: number}}};5189 seen.push({5190 name: error.name,5191 causeName: String(cause?.name),5192 causeStatus: cause?.response?.status ?? 0,5193 });5194 }],5195 },5196 }).text(), {5197 name: 'TypeError',5198 message: '`retry.delay` must return a non-negative number or `Infinity`',5199 });52005201 t.deepEqual(seen, [{name: 'TypeError', causeName: 'HTTPError', causeStatus: 500}]);5202 t.is((error as {cause?: {name?: string}}).cause?.name, 'HTTPError');5203});52045205// A `jitter` function that returns a bad value falls back to the unjittered delay, which is the safe reading: the caller still gets a backoff rather than a 1ms retry.5206test.serial('a `retry.jitter` function that returns a bad value falls back to the computed delay', async t => {5207 for (const value of [Number.NaN, -1, Number.NEGATIVE_INFINITY]) {5208 let requestCount = 0;52095210 // eslint-disable-next-line no-await-in-loop5211 await withCapturedTimeouts(async scheduledDelays => {5212 await t.throwsAsync(ky('https://example.com', {5213 retry: {limit: 1, delay: () => 10, jitter: () => value as number},5214 async fetch() {5215 requestCount++;5216 return new Response(null, {status: 500});5217 },5218 }).text());52195220 t.true(scheduledDelays.includes(10), `jitter returning ${value} should keep the 10ms delay`);5221 t.false(scheduledDelays.includes(Number.NaN), `jitter returning ${value} must not schedule a 1ms delay`);5222 });52235224 t.is(requestCount, 2);5225 }5226});