Recognise another copy of Ky: the stop symbol and the retry marker
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 0b1f462 · Browse files · 3 files·+59 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+59 added−3 removed
- tests:+46 added−0 removed
- other:+13 added−3 removed
Provenance
- Commit
01b0839- Tree
405e274- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
0b1f462
3 files changed+59 added−3 removed
modified:source/core/constants.ts+11 added-1 removed
62 unmodified lines63 export const usualFormBoundarySize = 40;64 65 /**66 Symbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.67+68+Registered globally so that a hook written against a second copy of Ky, which happens with a duplicated dependency, still stops the retries. A plain `Symbol` is per module, so the copies would not recognise each other's symbol.69 */68-export const stop = Symbol('stop');70+export const stop = Symbol.for('ky.stop');71 72 /**73 Options for forcing a retry via `ky.retry()`.74 */81 unmodified lines156 /**157 Marker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.158 */159 export class RetryMarker {160+ // Branded so a marker created by a second copy of Ky, which happens with a duplicated dependency, is still recognised. A plain `instanceof` check fails across module instances, and the hook's intent would then vanish silently: no retry and no error.161+ get isRetryMarker(): true {162+ return true;163+ }164+165 options: ForceRetryOptions | undefined;166 167 constructor(options?: ForceRetryOptions) {168 this.options = options;169 }170 }171 172+export const isRetryMarker = (value: unknown): value is RetryMarker =>173+ value instanceof RetryMarker || (value as {isRetryMarker?: unknown} | undefined)?.isRetryMarker === true;174+175 /**176 Force a retry from an `afterResponse` hook.177 178 This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.121 unmodified linesmodified:source/core/Ky.ts+2 added-2 removed
47 unmodified lines48 import {49 maxSafeTimeout,50 responseTypes,51 stop,52- RetryMarker,52+ isRetryMarker,53 supportsAbortController,54 supportsAbortSignal,55 supportsFormData,56 supportsResponseStreams,1177 unmodified lines1234 this.#cancelResponseBody(response);1235 throw error;1236 }1237 1238- if (modifiedResponse instanceof RetryMarker) {1238+ if (isRetryMarker(modifiedResponse)) {1239 // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).1240 // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.1241 if (hookResponse !== response) {1242 this.#cancelResponseBody(hookResponse);285 unmodified linesmodified:test/hooks.ts+46 added
7341 unmodified lines7342 } catch (error) {7343 t.is(error, 'thrown string');7344 }7345 });7346+7347+// `stop` was a plain `Symbol`, so it was per module and a hook written against a second copy of Ky, which happens with a duplicated dependency, never stopped the retries.7348+test('`ky.stop` is recognised across Ky copies', async t => {7349+ let attempts = 0;7350+7351+ const result = await ky('https://example.com', {7352+ retry: {limit: 3, delay: () => 0},7353+ async fetch() {7354+ attempts++;7355+ return new Response('server error', {status: 500});7356+ },7357+ hooks: {7358+ beforeRetry: [() => Symbol.for('ky.stop')],7359+ },7360+ });7361+7362+ t.is(result, undefined);7363+ t.is(attempts, 1);7364+ t.is(ky.stop, Symbol.for('ky.stop'));7365+});7366+7367+// The retry marker was matched with `instanceof`, so a `ky.retry()` returned by a hook written against a second copy of Ky, which happens with a duplicated dependency, was treated as no replacement at all: no retry and no error.7368+test('a `ky.retry()` marker is recognised across Ky copies', async t => {7369+ let attempts = 0;7370+ const seenCodes: Array<string | undefined> = [];7371+7372+ const text = await ky('https://example.com', {7373+ retry: {limit: 3, delay: () => 0},7374+ async fetch() {7375+ attempts++;7376+ return new Response(attempts < 3 ? 'retry me' : 'ok');7377+ },7378+ hooks: {7379+ afterResponse: [async ({response}) => (await response.text()) === 'retry me'7380+ ? {isRetryMarker: true, options: {code: 'FOREIGN_COPY'}}7381+ : undefined],7382+ beforeRetry: [({error}) => {7383+ seenCodes.push(isForceRetryError(error) ? error.code : undefined);7384+ }],7385+ },7386+ }).text();7387+7388+ t.is(text, 'ok');7389+ t.is(attempts, 3);7390+ t.deepEqual(seenCodes, ['FOREIGN_COPY', 'FOREIGN_COPY']);7391+});