diff --git a/.changeset/add-retry-backoff.md b/.changeset/add-retry-backoff.md new file mode 100644 index 0000000..caeb52f --- /dev/null +++ b/.changeset/add-retry-backoff.md @@ -0,0 +1,5 @@ +--- +"@kamsteegsoftware/fetchify": minor +--- + +`createFetchify` now accepts an optional `retry` (`FetchifyRetryOptions`), applied as the default retry configuration for every request made by the client, and each `FetchifyMethod` call accepts a per-request `retry` override — either a replacement `FetchifyRetryOptions` object or `false` to disable retry for that call. A failed request is retried with capped exponential backoff and full jitter (or the response's `Retry-After` header, for a `429`/`503`), re-running `beforeRequest` and getting a fresh `timeout` window per attempt. With no `retryOn` supplied, only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) are retried, and only for network failures, `FetchifyTimeoutError`s, and `FetchifyError`s with status `408`, `429`, `500`, `502`, `503`, or `504` — `POST`/`PATCH` are never retried by default, and a caller-triggered `AbortSignal` is never retried under any configuration. Retry never applies to a cache-served `GET`. With no `retry` configured, requests behave exactly as they did before this option existed. diff --git a/DOCS.md b/DOCS.md index 47b03b2..63c19e8 100644 --- a/DOCS.md +++ b/DOCS.md @@ -109,6 +109,21 @@ try { await client.get("/slow", { timeout: 500 }); ``` +`options.retry` accepts a [`FetchifyRetryOptions`](#fetchifyretryoptions) object, applied as the default retry configuration for every request made by the client; omitting it makes every request exactly one network attempt, unchanged from before this option existed. A single call can override it via `retry` on that [`FetchifyMethod`](#fetchifymethod) call — either a different `FetchifyRetryOptions` object (replacing the client default outright, not merging with it) or `false` to disable retry for that call. With no `retryOn` supplied, only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) are retried, and only for network failures, a [`FetchifyTimeoutError`](#fetchifytimeouterror), or a [`FetchifyError`](#fetchifyerrort) with status `408`, `429`, `500`, `502`, `503`, or `504` — `POST`/`PATCH` are never retried by default. Each retry waits using capped exponential backoff with full jitter (or the response's `Retry-After` header, for a `429`/`503`), re-runs `beforeRequest`, and gets its own fresh `timeout` window. A caller-triggered `AbortSignal` is never retried. Retry never applies to a cache-served `GET`, since no `fetch` call is made for a cache hit. + +```ts +const client = createFetchify({ + baseUrl: "https://api.example.com", + retry: { retries: 3 }, // exponential backoff with jitter, 200ms base delay +}); + +await client.get("/flaky"); // retried on network errors, timeouts, and 408/429/5xx + +// Override the client default for a single call +await client.get("/flaky", { retry: { retries: 1, retryOn: () => true } }); +await client.post("/orders", { body, retry: false }); // never retried +``` + ## `defineOptions` ```ts @@ -299,10 +314,46 @@ interface FetchifyOptions { headers?: Record; hooks?: FetchifyHooks; timeout?: number; + retry?: FetchifyRetryOptions; +} +``` + +Configuration accepted by `createFetchify` and `defineOptions`. `headers` (see [`defineHeaders`](#defineheaders)) are the default headers sent with every request made by the client. `hooks` (see [`FetchifyHooks`](#fetchifyhooks)) configures lifecycle hooks, currently just `beforeRequest`. `timeout` is the default number of milliseconds a request may take before it's aborted with a [`FetchifyTimeoutError`](#fetchifytimeouterror); see [`createFetchify`](#createfetchify) for the full behavior. `retry` is the default [`FetchifyRetryOptions`](#fetchifyretryoptions) applied to every request; see [`createFetchify`](#createfetchify) for the full behavior. + +### `FetchifyRetryOptions` + +```ts +interface FetchifyRetryOptions { + retries?: number; + delay?: number; + backoffFactor?: number; + maxDelay?: number; + jitter?: boolean; + retryOn?: (context: FetchifyRetryContext) => boolean; +} +``` + +Retry configuration accepted by [`FetchifyOptions.retry`](#fetchifyoptions) (client-level default) and [`FetchifyMethodOptions.retry`](#fetchifymethodoptions) (per-call override). Every field is optional; supplying `{}` enables retry with every default applied. + +- `retries` — maximum number of retry attempts after the initial one. Default `3`. +- `delay` — base delay, in milliseconds, before the first retry. Default `200`. +- `backoffFactor` — multiplier applied to the delay on each subsequent retry. Default `2`. +- `maxDelay` — upper bound, in milliseconds, on any computed delay (including a `Retry-After`-derived one). Default `30000`. +- `jitter` — when `true`, the actual wait is a random value between `0` and the computed delay ("full jitter"), instead of the computed delay exactly. Default `true`. +- `retryOn` — overrides the default eligibility predicate entirely, for every method including `POST`/`PATCH`. Called with a [`FetchifyRetryContext`](#fetchifyretrycontext); returning `true` retries, `false` stops and propagates the failure. Never consulted for a caller-triggered `AbortSignal`, which is never retried. + +### `FetchifyRetryContext` + +```ts +interface FetchifyRetryContext { + method: string; + url: string; + attempt: number; + error: FetchifyError | FetchifyTimeoutError | Error; } ``` -Configuration accepted by `createFetchify` and `defineOptions`. `headers` (see [`defineHeaders`](#defineheaders)) are the default headers sent with every request made by the client. `hooks` (see [`FetchifyHooks`](#fetchifyhooks)) configures lifecycle hooks, currently just `beforeRequest`. `timeout` is the default number of milliseconds a request may take before it's aborted with a [`FetchifyTimeoutError`](#fetchifytimeouterror); see [`createFetchify`](#createfetchify) for the full behavior. +Passed to a custom [`FetchifyRetryOptions.retryOn`](#fetchifyretryoptions) after each failed attempt: the uppercase HTTP verb, the fully resolved request URL, the 1-based count of attempts made so far (including the one that just failed), and the error that triggered the eligibility check. ### `FetchifyHooks` @@ -420,6 +471,7 @@ interface FetchifyMethodOptions { body?: RequestInit['body'] | JsonSerializable; init?: RequestInit; timeout?: number; + retry?: FetchifyRetryOptions | false; } ``` @@ -430,6 +482,7 @@ Per-request options accepted by every [`FetchifyMethod`](#fetchifymethod) call: - `body` — the request body. Accepts either a standard `BodyInit` value (`string`, `Blob`, `ArrayBuffer`/typed array, `FormData`, `URLSearchParams`, `ReadableStream`) or any JSON-serializable value (plain object, array, number, boolean, `null`). When the resolved `Content-Type` header (see `headers` above) is `application/json`, a non-`BodyInit` body is automatically run through `JSON.stringify` before being sent; otherwise it's forwarded to `fetch` exactly as given, with no auto-serialization and no auto-setting of `Content-Type`. Standard `BodyInit` values are never re-serialized, even when `Content-Type` is `application/json`, so an already-`JSON.stringify`'d string is never double-encoded. Takes precedence over `init.body` when both are set — `init.body` is never serialized, regardless of `Content-Type`. - `init` — the underlying `RequestInit`, for request settings not covered by `headers`/`params`/`body` (e.g. `signal`, `credentials`). Its `headers` and `body` fields, if set, are superseded by the computed `headers` and `body` above rather than merged with them. - `timeout` — overrides the client's default `timeout` (see [`createFetchify`](#createfetchify)) for this request only; `0` explicitly disables an inherited client-level timeout. +- `retry` — overrides the client's default `retry` (see [`createFetchify`](#createfetchify)) for this request only, replacing it outright rather than merging; `false` explicitly disables an inherited client-level retry. ```ts await client.get("/users", { diff --git a/GETTING-STARTED.md b/GETTING-STARTED.md index 8e74e06..5708bcf 100644 --- a/GETTING-STARTED.md +++ b/GETTING-STARTED.md @@ -127,6 +127,37 @@ await client.get("/slow", { timeout: 0 }); // no timeout for this call With no `timeout` configured, requests wait on the network indefinitely, same as before this option existed. See [DOCS.md](./DOCS.md#createfetchify) for how it composes with a caller-supplied `AbortSignal`. +## Retrying failed requests + +Pass `retry` to automatically retry a request on a transient failure — a network error, a timeout, or a `408`/`429`/`5xx` response — using exponential backoff with jitter: + +```ts +const client = createFetchify({ + baseUrl: "https://api.example.com", + retry: { retries: 3 }, +}); + +await client.get("/flaky"); // retried up to 3 times before rejecting +``` + +By default only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) are retried, so a `POST`/`PATCH` never gets retried automatically — pass your own `retryOn` if you know a specific write is safe to retry (e.g. it's protected by an idempotency key): + +```ts +await client.post("/orders", { + body: { id: "already-generated-client-side" }, + retry: { retries: 2, retryOn: () => true }, +}); +``` + +Override the client's default for a single call, including disabling it outright: + +```ts +await client.get("/flaky", { retry: { retries: 1 } }); // replaces the client default +await client.get("/flaky", { retry: false }); // never retried for this call +``` + +With no `retry` configured, requests behave exactly as before this option existed — one attempt, no retry. See [DOCS.md](./DOCS.md#createfetchify) for the full default eligibility rules, backoff/jitter formula, and `Retry-After` handling. + ## Using cache adapters Pass a `CacheAdapter` as the `cache` option to `createFetchify` to cache `GET` responses. Caching only applies to `GET` requests — other verbs always hit the network. On a `GET`, fetchify checks the cache first; on a cache miss, it makes the request and, if the response is `ok`, stores it for next time. diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/.openspec.yaml b/openspec/changes/archive/2026-08-07-add-retry-backoff/.openspec.yaml new file mode 100644 index 0000000..878dc31 --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-08-07 diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/design.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/design.md new file mode 100644 index 0000000..53f5bcf --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/design.md @@ -0,0 +1,48 @@ +## Context + +`createFetchify`'s request path (`src/lib/create-fetchify.ts`) currently makes exactly one network attempt per call: `performRequest` runs the `beforeRequest` hook, applies the resolved timeout, calls `fetch`, and either resolves a `FetchifyResponse` or throws (`FetchifyTimeoutError` on abort, `FetchifyError` on a non-ok response, or the raw `fetch` rejection on a network failure). There is no shared retry/backoff mechanism; consumers must wrap call sites themselves. + +This change adds an opt-in retry loop around that single network attempt, reusing the existing timeout and `beforeRequest` machinery per attempt rather than replacing them. + +## Goals / Non-Goals + +**Goals:** +- Retry a request automatically on transient failures (network errors, timeouts, and `408`/`429`/`5xx` responses), with exponential backoff and jitter. +- Make retry opt-in at the client level (`FetchifyOptions.retry`) and overridable per call (`FetchifyMethodOptions.retry`), mirroring the existing `timeout` option pattern. +- Default to only retrying idempotent methods, so enabling retry does not silently introduce duplicate-side-effect risk on `POST`/`PATCH`. +- Honor a `Retry-After` response header when present, since it is server-authoritative information about how long to wait. +- Leave cache-hit `GET`s, the `beforeRequest` hook contract, and the timeout contract behaviorally unchanged except for being re-run per attempt. + +**Non-Goals:** +- No per-attempt observability hook (e.g. an `onRetry` callback) or exposing an attempt count on `FetchifyResponse`/`FetchifyError` — the existing `logger` continues to receive exactly one entry per top-level call, keyed on the final outcome, unchanged from today's contract. +- No retry budget shared across concurrent requests (e.g. a circuit breaker) — each call's retry loop is independent. +- No change to `response-error-handling` or `logger-adapter` requirements; this change touches only `http-client` and `fetchify-options`, plus the new `request-retry` capability. + +## Decisions + +**Retry loop location**: the loop wraps the existing "one network attempt" logic inside `performRequest` (hook invocation through building the resolved value or throwing), not the outer `request` function that owns logging/timing. This keeps `logger.log` firing exactly once per call, after the loop settles, unchanged from today. +- Alternative considered: loop in `request`, re-invoking `performRequest` wholesale. Rejected — `performRequest` already reads `cache` first; looping at that level would re-check the cache on every retry, which is wrong (a cache miss on attempt 1 will always miss on attempt 2). + +**Config shape — object with named fields, not a boolean or bare number**: `FetchifyRetryOptions { retries?, delay?, backoffFactor?, maxDelay?, jitter?, retryOn? }`, all optional with defaults (`retries: 3`, `delay: 200`, `backoffFactor: 2`, `maxDelay: 30000`, `jitter: true`). Presence of `retry` (even `{}`) enables retry with defaults, matching how `cache`/`logger` are enabled by presence. +- Alternative considered: a single `retries: number` field (mirroring `timeout: number`). Rejected — unlike timeout, retry needs several independently-meaningful knobs (count, base delay, cap, predicate); collapsing them into one primitive would force a second option anyway. + +**Per-call override replaces, not merges**: `FetchifyMethodOptions.retry` fully replaces the client-level `retry` config for that call (`retry: false` disables it outright). No deep-merge of individual fields. +- Alternative considered: shallow-merge per-call fields over the client default (like `headers`). Rejected for simplicity and predictability — `timeout` (the closest precedent) is also a full override, not a merge, and a retry config is small enough to restate in full when a call needs different behavior. + +**Default retry eligibility — idempotency-gated, not just status-gated**: the default `retryOn` predicate is `isIdempotent(method) && isTransient(error)`, where `isIdempotent` allows `GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`, and `isTransient` is true for a raw network failure (fetch rejection not caused by the caller's own signal), a `FetchifyTimeoutError`, or a `FetchifyError` with status `408`, `429`, `500`, `502`, `503`, `504`. +- Alternative considered: retry any method on a transient error, since a slow response doesn't always mean the write landed. Rejected — retrying a `POST` by default risks duplicate side effects on the origin server; consumers who know their `POST` is safe (e.g. idempotency-key protected) can supply a custom `retryOn` to opt in explicitly. + +**Caller-triggered aborts are never retried**: the loop distinguishes a timeout-driven abort (already tracked via the existing `timeoutSignal.aborted` check used to construct `FetchifyTimeoutError`) from the caller's own `init.signal` firing, and only the former is eligible for the default predicate. A caller abort always propagates immediately, matching current behavior with no retry attempted, regardless of `retryOn`. + +**Backoff formula — capped exponential with full jitter**: for the Nth retry (1-indexed), `computed = min(maxDelay, delay * backoffFactor ** (N - 1))`, and when `jitter` is true (default) the actual wait is `random(0, computed)` ("full jitter", the AWS-recommended strategy for avoiding thundering-herd retries). When `jitter` is false, the wait is `computed` exactly. + +**`Retry-After` overrides computed delay, still capped**: when the triggering error is a `FetchifyError` with status `429` or `503` and a parseable `Retry-After` header (integer delta-seconds or an HTTP-date), that value (converted to ms) is used as the wait instead of the backoff formula's output, but still clamped to `maxDelay` — a misbehaving upstream should not be able to stall a caller indefinitely. + +**Per-attempt hook and timeout**: each retry re-runs `beforeRequest` (so a hook can refresh a stale auth token or tracing header before the next attempt) and gets a fresh timeout window sized from the same resolved `timeout` value used on attempt 1. This falls out naturally from the loop wrapping the same code path attempt 1 uses; no new requirement text is needed in `request-timeout` since "the underlying network fetch call" already means one fetch call per the existing spec, and a retry's fetch is a new one. + +## Risks / Trade-offs + +- **Retrying can multiply latency and load** on an already-struggling upstream. → Mitigated by capped exponential backoff with jitter, a `maxDelay` ceiling, and a default `retries` of 3 (not unbounded). +- **Retrying a non-idempotent method could duplicate a write** if a consumer overrides `retryOn` carelessly. → Default predicate excludes `POST`/`PATCH`; documentation on `retryOn` calls out the risk explicitly. +- **`Retry-After` parsing adds a small surface for malformed input** (non-numeric, invalid date). → Falls back to the computed backoff delay whenever the header is absent or unparseable, never throws. + diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/proposal.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/proposal.md new file mode 100644 index 0000000..bc46c90 --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/proposal.md @@ -0,0 +1,28 @@ +## Why + +Every request made through `createFetchify` fails permanently on the first transient error — a dropped connection, a `FetchifyTimeoutError`, or a `5xx`/`429` response from an upstream that is momentarily overloaded. Consumers must currently hand-roll their own retry loop around every call site, with no client-wide default and no shared backoff/jitter logic. A short-lived blip in an otherwise healthy upstream should not have to surface as a hard failure to the caller. + +## What Changes + +- Add an optional `retry` (`FetchifyRetryOptions`) to `FetchifyOptions`, configuring the default retry behavior for every request made by the resulting client. Omitting it preserves today's no-retry behavior. +- Add an optional `retry` to `FetchifyMethodOptions`, overriding the client-level retry config for that single call — `retry: false` explicitly disables retry for that call even when the client has a default configured. +- `FetchifyRetryOptions` covers: `retries` (max retry attempts, default `3`), `delay` (base backoff delay in ms, default `200`), `backoffFactor` (multiplier applied per attempt, default `2`), `maxDelay` (cap on any computed delay, default `30000`), `jitter` (apply full jitter to each computed delay, default `true`), and `retryOn` (a predicate overriding which failures are retried). +- Default retry eligibility (when `retryOn` is not supplied): only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) are retried, and only for network failures, `FetchifyTimeoutError`s, and `FetchifyError`s with status `408`, `429`, `500`, `502`, `503`, or `504`. `POST`/`PATCH` are never retried by default. A caller-triggered `AbortSignal` is never retried, regardless of method. +- A `Retry-After` response header (seconds or HTTP-date) on a `429`/`503` overrides the computed backoff delay for that wait, still bounded by `maxDelay`. +- Each retry attempt re-invokes the configured `beforeRequest` hook and gets its own fresh timeout window (per the existing `request-timeout` capability); retries never apply to a cache-served `GET`. + +## Capabilities + +### New Capabilities +- `request-retry`: Defines the `retry` option (client-level and per-request), the default retry-eligibility predicate and idempotency restriction, the exponential-backoff-with-jitter delay calculation, `Retry-After` header handling, and how retry composes with timeouts, the `beforeRequest` hook, and caching. + +### Modified Capabilities +- `http-client`: `FetchifyMethodOptions` gains a `retry` field, and request handling now retries a failed network attempt before resolving or throwing, per the `request-retry` capability. +- `fetchify-options`: `FetchifyOptions` (and `defineOptions`) gains a `retry` field. + +## Impact + +- `src/lib/create-fetchify.ts`: the network-attempt portion of request handling gains a retry loop (eligibility check, delay computation, re-running the hook and a fresh timeout per attempt). +- `src/lib/define-options.ts`, `src/types/fetchify-method.ts`: option shapes gain `retry`. +- New `src/types/retry.ts` (or similar) exporting `FetchifyRetryOptions` and `FetchifyRetryContext`. +- No breaking changes — `retry` is opt-in and existing no-retry behavior is unchanged. diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/fetchify-options/spec.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/fetchify-options/spec.md new file mode 100644 index 0000000..209668e --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/fetchify-options/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: FetchifyOptions accepts an optional client-level retry configuration +`FetchifyOptions` (and therefore `defineOptions`) SHALL accept an optional `retry?: FetchifyRetryOptions` field: the default retry configuration applied to every request made by a client created from these options, per the `request-retry` capability. + +#### Scenario: retry as a plain object +- **WHEN** a consumer calls `defineOptions({ retry: { retries: 3 } })` +- **THEN** the call type-checks and returns the object unchanged + +#### Scenario: retry with a custom retryOn predicate +- **WHEN** a consumer calls `defineOptions({ retry: { retries: 2, retryOn: (ctx) => ctx.error instanceof FetchifyTimeoutError } })` +- **THEN** the call type-checks and returns the object unchanged + +#### Scenario: Defined retry is usable with createFetchify +- **WHEN** a consumer passes the object returned by `defineOptions({ retry: { retries: 3 } })` directly to `createFetchify` +- **THEN** the resulting client applies that retry configuration to every request, identical to passing `{ retry: { retries: 3 } }` directly to `createFetchify` diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/http-client/spec.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/http-client/spec.md new file mode 100644 index 0000000..2aaca78 --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/http-client/spec.md @@ -0,0 +1,16 @@ +## MODIFIED Requirements + +### Requirement: FetchifyMethodOptions accepts a per-request timeout override +Each HTTP method wrapper's `options: FetchifyMethodOptions` SHALL accept an optional `timeout?: number` field, used per the `request-timeout` capability to override the client's default timeout for that single call, and an optional `retry?: FetchifyRetryOptions | false` field, used per the `request-retry` capability to override the client's default retry configuration for that single call. + +#### Scenario: Per-request timeout option type-checks and is honored +- **WHEN** a client calls `client.get("/users", { timeout: 200 })` +- **THEN** the call type-checks, and the resolved timeout for that request is 200ms regardless of any client-level `timeout` default; see the `request-timeout` capability for the full abort behavior + +#### Scenario: Per-request retry option type-checks and is honored +- **WHEN** a client calls `client.get("/users", { retry: { retries: 1 } })` +- **THEN** the call type-checks, and the resolved retry configuration for that request is `{ retries: 1 }` (with remaining fields defaulted) regardless of any client-level `retry` default; see the `request-retry` capability for the full retry behavior + +#### Scenario: Per-request retry: false type-checks and disables retry +- **WHEN** a client created with a client-level `retry` default calls `client.get("/users", { retry: false })` +- **THEN** the call type-checks, and no retry is performed for that request; see the `request-retry` capability diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/request-retry/spec.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/request-retry/spec.md new file mode 100644 index 0000000..d036c05 --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/specs/request-retry/spec.md @@ -0,0 +1,124 @@ +## ADDED Requirements + +### Requirement: Configurable retry with backoff on transient failures +`createFetchify` SHALL accept an optional `retry` (`FetchifyRetryOptions`) on `FetchifyOptions`, applied as the default retry configuration for every request made by the resulting client, and each HTTP method wrapper SHALL accept an optional `retry` on its `FetchifyMethodOptions` — either a `FetchifyRetryOptions` object or `false` — overriding the client's default for that single call. A per-call `retry: false` SHALL disable retry for that call even when the client has a default `retry` configured. When no `retry` is resolved (neither a client default nor a per-call value is configured), the request behaves exactly as it did before this capability existed, making exactly one network attempt. + +`FetchifyRetryOptions` SHALL have the shape `{ retries?: number; delay?: number; backoffFactor?: number; maxDelay?: number; jitter?: boolean; retryOn?: (context: FetchifyRetryContext) => boolean }`, all fields optional, defaulting respectively to `retries: 3`, `delay: 200`, `backoffFactor: 2`, `maxDelay: 30000`, `jitter: true`, and the default retry-eligibility predicate described below. Supplying `retry: {}` SHALL enable retry with every default applied. + +A per-call `retry` object SHALL fully replace the client-level `retry` configuration for that call rather than being merged field-by-field with it. + +#### Scenario: Client-level retry retries a failing idempotent request +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2 } })` calls `client.get("/flaky")` and the first two responses are `503` while the third is `200` +- **THEN** the call resolves with the `200` response's data, having made three network attempts in total + +#### Scenario: Retries exhausted still throws +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2 } })` calls `client.get("/down")` and every response is `503` +- **THEN** the call rejects with a `FetchifyError` whose `status` is `503`, after having made three network attempts in total (the initial attempt plus 2 retries) + +#### Scenario: No retry configured preserves current behavior +- **WHEN** a client created without a `retry` option (and without a per-call `retry`) calls any HTTP method and the response is `503` +- **THEN** the call rejects immediately with a `FetchifyError` after exactly one network attempt, unchanged from behavior before this capability existed + +#### Scenario: Per-call retry overrides the client default +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 5 } })` calls `client.get("/flaky", { retry: { retries: 1 } })` and every response is `503` +- **THEN** the call makes at most 2 network attempts in total (the initial attempt plus 1 retry), not 6 + +#### Scenario: Per-call retry: false disables a configured client default +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 5 } })` calls `client.get("/flaky", { retry: false })` and the response is `503` +- **THEN** the call rejects after exactly one network attempt, with no retry performed + +#### Scenario: Empty retry object enables all defaults +- **WHEN** a client created with `createFetchify({ baseUrl, retry: {} })` calls `client.get("/flaky")` and the first response is `503` while the second is `200` +- **THEN** the call resolves after a second network attempt, using the default `retries`, `delay`, `backoffFactor`, `maxDelay`, and `jitter` values + +### Requirement: Default retry eligibility is idempotency-gated and status/failure-gated +When `retryOn` is not supplied, a failed attempt SHALL be eligible for retry only when both of the following hold: the request's HTTP method is one of `GET`, `HEAD`, `OPTIONS`, `PUT`, or `DELETE` (an idempotent method), and the failure is one of: a network failure (the underlying `fetch` call rejected for a reason other than the caller's own `AbortSignal` firing), a `FetchifyTimeoutError`, or a `FetchifyError` whose `status` is `408`, `429`, `500`, `502`, `503`, or `504`. `POST` and `PATCH` requests SHALL NOT be retried under the default predicate, regardless of the failure's nature. + +A request aborted by the caller's own `AbortSignal` (passed via `options.init.signal`) SHALL NOT be retried under any circumstances — including when a custom `retryOn` is supplied — and SHALL propagate the same error it would produce without retry configured. + +#### Scenario: Default predicate retries a 429 GET +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 } })` calls `client.get("/rate-limited")` and the first response is `429` while the second is `200` +- **THEN** the call resolves after retrying once + +#### Scenario: Default predicate does not retry a POST +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.post("/orders", { body: { id: 1 } })` and the response is `503` +- **THEN** the call rejects with a `FetchifyError` after exactly one network attempt, since `POST` is not idempotent and the default predicate excludes it + +#### Scenario: Default predicate does not retry a non-transient status +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.get("/missing")` and the response is `404` +- **THEN** the call rejects with a `FetchifyError` after exactly one network attempt, since `404` is not in the default transient-status set + +#### Scenario: Caller abort is never retried +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.get("/slow", { init: { signal: controller.signal } })` and `controller.abort()` is called before the response arrives +- **THEN** the call rejects with the same abort error it would produce without retry configured, after exactly one network attempt + +### Requirement: Custom retryOn predicate overrides default eligibility +`FetchifyRetryOptions.retryOn`, when supplied, SHALL fully replace the default eligibility predicate. It SHALL be called with a `FetchifyRetryContext` — `{ method: string; url: string; attempt: number; error: FetchifyError | FetchifyTimeoutError | Error }`, where `attempt` is the 1-based count of attempts made so far (including the one that just failed) — and its boolean return value SHALL determine whether another attempt is made, for every method including `POST` and `PATCH`. This override does not apply when the failure is a caller-triggered abort, which is never retried. + +#### Scenario: Custom retryOn enables retrying a POST +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2, retryOn: () => true } })` calls `client.post("/orders", { body: { id: 1 } })` and the first response is `503` while the second is `201` +- **THEN** the call resolves after one retry, since the custom `retryOn` overrides the default method restriction + +#### Scenario: Custom retryOn can narrow eligibility further +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3, retryOn: (ctx) => ctx.attempt < 2 } })` calls `client.get("/flaky")` and every response is `503` +- **THEN** the call makes exactly 2 network attempts in total, since `retryOn` returns `false` once `attempt` reaches `2` + +#### Scenario: retryOn receives the failed attempt's context +- **WHEN** a `retryOn` function is supplied and a request's first attempt fails with a `FetchifyError` of status `502` +- **THEN** `retryOn` is called with a context whose `method` and `url` reflect the request, `attempt` is `1`, and `error` is that `FetchifyError` + +### Requirement: Backoff delay uses capped exponential growth with optional full jitter +Before each retry, the wait duration SHALL be computed as `min(maxDelay, delay * backoffFactor ** (attempt - 1))`, where `attempt` is the 1-based number of the retry about to be made (the first retry uses `attempt = 1`, producing `delay` as the base case). When `jitter` is `true` (the default), the actual wait SHALL be a uniformly random duration between `0` and the computed value inclusive (full jitter); when `jitter` is `false`, the actual wait SHALL be exactly the computed value. + +#### Scenario: Second retry waits longer than the first under default backoff +- **WHEN** a client is configured with `retry: { delay: 100, backoffFactor: 2, jitter: false, retries: 2 }` and a request fails twice before succeeding +- **THEN** the wait before the first retry is `100`ms and the wait before the second retry is `200`ms + +#### Scenario: Computed delay is capped at maxDelay +- **WHEN** a client is configured with `retry: { delay: 1000, backoffFactor: 10, maxDelay: 2000, jitter: false, retries: 3 }` and a request fails on every attempt +- **THEN** no computed wait between attempts exceeds `2000`ms, even though the uncapped formula would produce `10000`ms and `100000`ms for later retries + +#### Scenario: Jitter produces a wait no greater than the computed delay +- **WHEN** a client is configured with `retry: { delay: 100, backoffFactor: 2, jitter: true, retries: 1 }` and a request fails once before succeeding +- **THEN** the actual wait before the retry is between `0`ms and `100`ms inclusive + +### Requirement: A Retry-After header overrides the computed backoff delay +When the triggering failure is a `FetchifyError` with `status` `429` or `503` and its `response` includes a `Retry-After` header parseable either as a non-negative integer number of seconds or as an HTTP-date, the wait before the next attempt SHALL be that value converted to milliseconds instead of the computed backoff delay, still clamped to `maxDelay`. When the header is absent, unparseable, or the status is not `429`/`503`, the computed backoff delay (per the previous requirement) SHALL be used unchanged. + +#### Scenario: Retry-After in seconds overrides computed delay +- **WHEN** a client is configured with `retry: { delay: 100, retries: 1 }` and a request's first attempt fails with a `429` response carrying header `Retry-After: 1` +- **THEN** the wait before the retry is approximately `1000`ms, not the `100`ms the backoff formula would compute + +#### Scenario: Retry-After as an HTTP-date overrides computed delay +- **WHEN** a request's first attempt fails with a `503` response carrying a `Retry-After` header set to an HTTP-date approximately `2` seconds in the future +- **THEN** the wait before the retry is approximately `2000`ms + +#### Scenario: Retry-After is still clamped to maxDelay +- **WHEN** a client is configured with `retry: { maxDelay: 500, retries: 1 }` and a request's first attempt fails with a `429` response carrying header `Retry-After: 30` +- **THEN** the wait before the retry does not exceed `500`ms + +#### Scenario: Unparseable Retry-After falls back to computed backoff +- **WHEN** a request's first attempt fails with a `429` response carrying header `Retry-After: not-a-value` +- **THEN** the wait before the retry uses the computed backoff delay, not the invalid header value + +#### Scenario: Retry-After on a non-408/429/5xx-adjacent status is ignored +- **WHEN** a request's first attempt fails with a `500` response that happens to carry a `Retry-After` header +- **THEN** the wait before the retry uses the computed backoff delay, since `Retry-After` handling only applies to `429` and `503` + +### Requirement: Retry composes with the beforeRequest hook and per-attempt timeout +Each retry attempt SHALL re-invoke the configured `hooks.beforeRequest` exactly as a first attempt would, per the `request-hooks` capability, allowing a hook to refresh headers or other request state before the next attempt. Each retry attempt SHALL apply the resolved `timeout` (client default or per-call override) as its own independent timeout window, per the `request-timeout` capability, rather than sharing a single deadline across all attempts. + +#### Scenario: beforeRequest hook runs again on retry +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 }, hooks: { beforeRequest } })` calls a method whose first attempt fails with a `503` and second attempt succeeds +- **THEN** `beforeRequest` is invoked twice, once for each network attempt + +#### Scenario: Each retry gets its own timeout window +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 }, timeout: 100 })` calls a method whose first attempt exceeds the 100ms timeout and second attempt completes within 100ms +- **THEN** the first attempt is aborted with a `FetchifyTimeoutError` (treated as a retryable failure), and the second attempt is given its own fresh 100ms window rather than inheriting any elapsed time from the first + +### Requirement: Retry does not apply to cache-served responses +A configured `retry` SHALL have no effect on a `GET` request served from a configured cache adapter, since no `fetch` call is made — and therefore no failure can occur — for a cache hit. + +#### Scenario: Cache hit resolves without engaging retry +- **WHEN** a client created with `createFetchify({ baseUrl, cache, retry: { retries: 3 } })` calls `client.get("/users")` and the cache adapter already has a matching entry +- **THEN** the call resolves immediately from the cache, `cached: true`, with no network attempts made and no retry logic engaged diff --git a/openspec/changes/archive/2026-08-07-add-retry-backoff/tasks.md b/openspec/changes/archive/2026-08-07-add-retry-backoff/tasks.md new file mode 100644 index 0000000..af89099 --- /dev/null +++ b/openspec/changes/archive/2026-08-07-add-retry-backoff/tasks.md @@ -0,0 +1,48 @@ +## 1. Retry types + +- [x] 1.1 Add `src/types/retry.ts` exporting `FetchifyRetryOptions` (`{ retries?: number; delay?: number; backoffFactor?: number; maxDelay?: number; jitter?: boolean; retryOn?: (context: FetchifyRetryContext) => boolean }`) and `FetchifyRetryContext` (`{ method: string; url: string; attempt: number; error: FetchifyError | FetchifyTimeoutError | Error }`) +- [x] 1.2 Define the default constants (`DEFAULT_RETRIES = 3`, `DEFAULT_DELAY = 200`, `DEFAULT_BACKOFF_FACTOR = 2`, `DEFAULT_MAX_DELAY = 30000`, `DEFAULT_JITTER = true`) alongside the type, or in `create-fetchify.ts` where they're consumed + +## 2. Option shapes + +- [x] 2.1 Add optional `retry?: FetchifyRetryOptions` to `FetchifyOptions` in `src/lib/define-options.ts` +- [x] 2.2 Add optional `retry?: FetchifyRetryOptions | false` to `FetchifyMethodOptions` in `src/types/fetchify-method.ts` + +## 3. Backoff and eligibility helpers + +- [x] 3.1 Add `src/utils/compute-retry-delay.ts`: given `{ attempt, delay, backoffFactor, maxDelay, jitter }`, return `min(maxDelay, delay * backoffFactor ** (attempt - 1))`, then apply full jitter (`random(0, computed)`) when `jitter` is true +- [x] 3.2 Add `src/utils/compute-retry-delay.test.ts` covering: base case (attempt 1 = `delay`), exponential growth across attempts, `maxDelay` capping, jitter bounds (with `jitter: false` for deterministic assertions plus a bounds check for `jitter: true`) +- [x] 3.3 Add `src/utils/parse-retry-after.ts`: given a `Response`'s `Retry-After` header value, return milliseconds for a valid non-negative integer (seconds) or valid HTTP-date, otherwise `undefined` +- [x] 3.4 Add `src/utils/parse-retry-after.test.ts` covering: numeric seconds, HTTP-date, missing header, malformed value +- [x] 3.5 Add `src/utils/is-retryable.ts` implementing the default predicate: idempotent method (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) AND (network failure not caused by caller abort, OR `FetchifyTimeoutError`, OR `FetchifyError` with status in `[408, 429, 500, 502, 503, 504]`) +- [x] 3.6 Add `src/utils/is-retryable.test.ts` covering each branch of the predicate, including that `POST`/`PATCH` are always excluded + +## 4. Request pipeline + +- [x] 4.1 In `src/lib/create-fetchify.ts`, resolve the effective retry config per request: per-call `requestOptions?.retry` if defined (including `false` meaning "disabled"), otherwise the client-level `options.retry`; when neither is set, behavior is unchanged (single attempt, no loop overhead) +- [x] 4.2 Wrap the network-attempt portion of `performRequest` (the `beforeRequest` hook call, timeout/signal setup, `fetch` call, and response/error handling — everything after the cache-read branch) in a retry loop keyed on the resolved retry config +- [x] 4.3 On a caught failure (network error, `FetchifyTimeoutError`, or `FetchifyError`), determine retry eligibility: skip retry entirely for a caller-triggered abort; otherwise call the resolved `retryOn` (custom or default via `is-retryable.ts`) with a `FetchifyRetryContext` built from the current attempt number and the failure +- [x] 4.4 When eligible and attempts remain (`attempt <= retries`), compute the wait via `Retry-After` (for `FetchifyError` with status `429`/`503`, using `parse-retry-after.ts`, clamped to `maxDelay`) or else `compute-retry-delay.ts`, `await` it, increment the attempt counter, and loop (re-running the hook and building a fresh timeout signal) +- [x] 4.5 When not eligible or attempts are exhausted, rethrow/resolve exactly as the non-retry path does today +- [x] 4.6 Confirm the retry loop sits after the cache-read branch so a cache hit never enters it, and confirm a successful attempt after retries still writes to the cache exactly as attempt 1 would + +## 5. Tests + +- [x] 5.1 Add/extend tests in `src/lib/create-fetchify.test.ts`: client-level `retry` retries a failing idempotent request and resolves once a later attempt succeeds +- [x] 5.2 Retries exhausted still rejects with the final `FetchifyError`/`FetchifyTimeoutError`/network error, after making `retries + 1` attempts total +- [x] 5.3 No `retry` configured makes exactly one attempt (unchanged pre-change behavior) +- [x] 5.4 Per-call `retry` overrides (not merges with) the client-level default +- [x] 5.5 Per-call `retry: false` disables a configured client-level default +- [x] 5.6 Default predicate excludes `POST`/`PATCH` and non-transient statuses (e.g. `404`) +- [x] 5.7 Custom `retryOn` can both broaden eligibility (retry a `POST`) and narrow it (stop early via `context.attempt`) +- [x] 5.8 Caller-triggered `AbortSignal` is never retried, even with a permissive custom `retryOn` +- [x] 5.9 `beforeRequest` hook is invoked once per attempt +- [x] 5.10 Each attempt gets its own timeout window (a timed-out first attempt doesn't shorten the second attempt's budget) +- [x] 5.11 `Retry-After` (seconds and HTTP-date forms) overrides the computed backoff delay, still clamped to `maxDelay`; unparseable header falls back to computed backoff +- [x] 5.12 Cache-served `GET` responses resolve without engaging retry logic at all + +## 6. Documentation & release + +- [x] 6.1 Document `retry` (client-level and per-request), the default eligibility rules, backoff/jitter behavior, and `Retry-After` handling in `DOCS.md` +- [x] 6.2 Add a usage example to `GETTING-STARTED.md` +- [x] 6.3 Run `bun run changeset` to record this as a minor, user-facing change diff --git a/openspec/specs/fetchify-options/spec.md b/openspec/specs/fetchify-options/spec.md index 1cd1923..eb9607c 100644 --- a/openspec/specs/fetchify-options/spec.md +++ b/openspec/specs/fetchify-options/spec.md @@ -66,3 +66,18 @@ The package SHALL export a `defineOptions` function that accepts a `FetchifyOpti #### Scenario: Defined timeout is usable with createFetchify - **WHEN** a consumer passes the object returned by `defineOptions({ timeout: 5000 })` directly to `createFetchify` - **THEN** the resulting client applies a 5000ms default timeout to every request, identical to passing `{ timeout: 5000 }` directly to `createFetchify` + +### Requirement: FetchifyOptions accepts an optional client-level retry configuration +`FetchifyOptions` (and therefore `defineOptions`) SHALL accept an optional `retry?: FetchifyRetryOptions` field: the default retry configuration applied to every request made by a client created from these options, per the `request-retry` capability. + +#### Scenario: retry as a plain object +- **WHEN** a consumer calls `defineOptions({ retry: { retries: 3 } })` +- **THEN** the call type-checks and returns the object unchanged + +#### Scenario: retry with a custom retryOn predicate +- **WHEN** a consumer calls `defineOptions({ retry: { retries: 2, retryOn: (ctx) => ctx.error instanceof FetchifyTimeoutError } })` +- **THEN** the call type-checks and returns the object unchanged + +#### Scenario: Defined retry is usable with createFetchify +- **WHEN** a consumer passes the object returned by `defineOptions({ retry: { retries: 3 } })` directly to `createFetchify` +- **THEN** the resulting client applies that retry configuration to every request, identical to passing `{ retry: { retries: 3 } }` directly to `createFetchify` diff --git a/openspec/specs/http-client/spec.md b/openspec/specs/http-client/spec.md index 0be61f6..06bc5bd 100644 --- a/openspec/specs/http-client/spec.md +++ b/openspec/specs/http-client/spec.md @@ -211,12 +211,20 @@ The request `body` SHALL be `options.body` when `options.body` is not `undefined - **THEN** the resolved value's `cached` field is `false` ### Requirement: FetchifyMethodOptions accepts a per-request timeout override -Each HTTP method wrapper's `options: FetchifyMethodOptions` SHALL accept an optional `timeout?: number` field, used per the `request-timeout` capability to override the client's default timeout for that single call. +Each HTTP method wrapper's `options: FetchifyMethodOptions` SHALL accept an optional `timeout?: number` field, used per the `request-timeout` capability to override the client's default timeout for that single call, and an optional `retry?: FetchifyRetryOptions | false` field, used per the `request-retry` capability to override the client's default retry configuration for that single call. #### Scenario: Per-request timeout option type-checks and is honored - **WHEN** a client calls `client.get("/users", { timeout: 200 })` - **THEN** the call type-checks, and the resolved timeout for that request is 200ms regardless of any client-level `timeout` default; see the `request-timeout` capability for the full abort behavior +#### Scenario: Per-request retry option type-checks and is honored +- **WHEN** a client calls `client.get("/users", { retry: { retries: 1 } })` +- **THEN** the call type-checks, and the resolved retry configuration for that request is `{ retries: 1 }` (with remaining fields defaulted) regardless of any client-level `retry` default; see the `request-retry` capability for the full retry behavior + +#### Scenario: Per-request retry: false type-checks and disables retry +- **WHEN** a client created with a client-level `retry` default calls `client.get("/users", { retry: false })` +- **THEN** the call type-checks, and no retry is performed for that request; see the `request-retry` capability + ### Requirement: Optional request logging via a configured logger When `createFetchify` is called with a `logger` option conforming to `LoggerAdapter`, each HTTP method wrapper SHALL call `logger.log(entry)` exactly once per invocation, after the request settles (resolves or throws), with a `FetchifyLogEntry` describing that request. When no `logger` option is configured, the client SHALL NOT perform any logging. diff --git a/openspec/specs/request-retry/spec.md b/openspec/specs/request-retry/spec.md new file mode 100644 index 0000000..94002e9 --- /dev/null +++ b/openspec/specs/request-retry/spec.md @@ -0,0 +1,130 @@ +# request-retry Specification + +## Purpose + +Defines fetchify's optional request-retry capability: retrying a failed request with capped exponential backoff and optional jitter, at both the client level and per-request level, the default idempotency- and status-gated eligibility rule, support for a custom `retryOn` predicate, `Retry-After` header handling, and how retry composes with the `request-hooks` and `request-timeout` capabilities. + +## Requirements + +### Requirement: Configurable retry with backoff on transient failures +`createFetchify` SHALL accept an optional `retry` (`FetchifyRetryOptions`) on `FetchifyOptions`, applied as the default retry configuration for every request made by the resulting client, and each HTTP method wrapper SHALL accept an optional `retry` on its `FetchifyMethodOptions` — either a `FetchifyRetryOptions` object or `false` — overriding the client's default for that single call. A per-call `retry: false` SHALL disable retry for that call even when the client has a default `retry` configured. When no `retry` is resolved (neither a client default nor a per-call value is configured), the request behaves exactly as it did before this capability existed, making exactly one network attempt. + +`FetchifyRetryOptions` SHALL have the shape `{ retries?: number; delay?: number; backoffFactor?: number; maxDelay?: number; jitter?: boolean; retryOn?: (context: FetchifyRetryContext) => boolean }`, all fields optional, defaulting respectively to `retries: 3`, `delay: 200`, `backoffFactor: 2`, `maxDelay: 30000`, `jitter: true`, and the default retry-eligibility predicate described below. Supplying `retry: {}` SHALL enable retry with every default applied. + +A per-call `retry` object SHALL fully replace the client-level `retry` configuration for that call rather than being merged field-by-field with it. + +#### Scenario: Client-level retry retries a failing idempotent request +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2 } })` calls `client.get("/flaky")` and the first two responses are `503` while the third is `200` +- **THEN** the call resolves with the `200` response's data, having made three network attempts in total + +#### Scenario: Retries exhausted still throws +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2 } })` calls `client.get("/down")` and every response is `503` +- **THEN** the call rejects with a `FetchifyError` whose `status` is `503`, after having made three network attempts in total (the initial attempt plus 2 retries) + +#### Scenario: No retry configured preserves current behavior +- **WHEN** a client created without a `retry` option (and without a per-call `retry`) calls any HTTP method and the response is `503` +- **THEN** the call rejects immediately with a `FetchifyError` after exactly one network attempt, unchanged from behavior before this capability existed + +#### Scenario: Per-call retry overrides the client default +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 5 } })` calls `client.get("/flaky", { retry: { retries: 1 } })` and every response is `503` +- **THEN** the call makes at most 2 network attempts in total (the initial attempt plus 1 retry), not 6 + +#### Scenario: Per-call retry: false disables a configured client default +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 5 } })` calls `client.get("/flaky", { retry: false })` and the response is `503` +- **THEN** the call rejects after exactly one network attempt, with no retry performed + +#### Scenario: Empty retry object enables all defaults +- **WHEN** a client created with `createFetchify({ baseUrl, retry: {} })` calls `client.get("/flaky")` and the first response is `503` while the second is `200` +- **THEN** the call resolves after a second network attempt, using the default `retries`, `delay`, `backoffFactor`, `maxDelay`, and `jitter` values + +### Requirement: Default retry eligibility is idempotency-gated and status/failure-gated +When `retryOn` is not supplied, a failed attempt SHALL be eligible for retry only when both of the following hold: the request's HTTP method is one of `GET`, `HEAD`, `OPTIONS`, `PUT`, or `DELETE` (an idempotent method), and the failure is one of: a network failure (the underlying `fetch` call rejected for a reason other than the caller's own `AbortSignal` firing), a `FetchifyTimeoutError`, or a `FetchifyError` whose `status` is `408`, `429`, `500`, `502`, `503`, or `504`. `POST` and `PATCH` requests SHALL NOT be retried under the default predicate, regardless of the failure's nature. + +A request aborted by the caller's own `AbortSignal` (passed via `options.init.signal`) SHALL NOT be retried under any circumstances — including when a custom `retryOn` is supplied — and SHALL propagate the same error it would produce without retry configured. + +#### Scenario: Default predicate retries a 429 GET +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 } })` calls `client.get("/rate-limited")` and the first response is `429` while the second is `200` +- **THEN** the call resolves after retrying once + +#### Scenario: Default predicate does not retry a POST +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.post("/orders", { body: { id: 1 } })` and the response is `503` +- **THEN** the call rejects with a `FetchifyError` after exactly one network attempt, since `POST` is not idempotent and the default predicate excludes it + +#### Scenario: Default predicate does not retry a non-transient status +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.get("/missing")` and the response is `404` +- **THEN** the call rejects with a `FetchifyError` after exactly one network attempt, since `404` is not in the default transient-status set + +#### Scenario: Caller abort is never retried +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3 } })` calls `client.get("/slow", { init: { signal: controller.signal } })` and `controller.abort()` is called before the response arrives +- **THEN** the call rejects with the same abort error it would produce without retry configured, after exactly one network attempt + +### Requirement: Custom retryOn predicate overrides default eligibility +`FetchifyRetryOptions.retryOn`, when supplied, SHALL fully replace the default eligibility predicate. It SHALL be called with a `FetchifyRetryContext` — `{ method: string; url: string; attempt: number; error: FetchifyError | FetchifyTimeoutError | Error }`, where `attempt` is the 1-based count of attempts made so far (including the one that just failed) — and its boolean return value SHALL determine whether another attempt is made, for every method including `POST` and `PATCH`. This override does not apply when the failure is a caller-triggered abort, which is never retried. + +#### Scenario: Custom retryOn enables retrying a POST +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 2, retryOn: () => true } })` calls `client.post("/orders", { body: { id: 1 } })` and the first response is `503` while the second is `201` +- **THEN** the call resolves after one retry, since the custom `retryOn` overrides the default method restriction + +#### Scenario: Custom retryOn can narrow eligibility further +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 3, retryOn: (ctx) => ctx.attempt < 2 } })` calls `client.get("/flaky")` and every response is `503` +- **THEN** the call makes exactly 2 network attempts in total, since `retryOn` returns `false` once `attempt` reaches `2` + +#### Scenario: retryOn receives the failed attempt's context +- **WHEN** a `retryOn` function is supplied and a request's first attempt fails with a `FetchifyError` of status `502` +- **THEN** `retryOn` is called with a context whose `method` and `url` reflect the request, `attempt` is `1`, and `error` is that `FetchifyError` + +### Requirement: Backoff delay uses capped exponential growth with optional full jitter +Before each retry, the wait duration SHALL be computed as `min(maxDelay, delay * backoffFactor ** (attempt - 1))`, where `attempt` is the 1-based number of the retry about to be made (the first retry uses `attempt = 1`, producing `delay` as the base case). When `jitter` is `true` (the default), the actual wait SHALL be a uniformly random duration between `0` and the computed value inclusive (full jitter); when `jitter` is `false`, the actual wait SHALL be exactly the computed value. + +#### Scenario: Second retry waits longer than the first under default backoff +- **WHEN** a client is configured with `retry: { delay: 100, backoffFactor: 2, jitter: false, retries: 2 }` and a request fails twice before succeeding +- **THEN** the wait before the first retry is `100`ms and the wait before the second retry is `200`ms + +#### Scenario: Computed delay is capped at maxDelay +- **WHEN** a client is configured with `retry: { delay: 1000, backoffFactor: 10, maxDelay: 2000, jitter: false, retries: 3 }` and a request fails on every attempt +- **THEN** no computed wait between attempts exceeds `2000`ms, even though the uncapped formula would produce `10000`ms and `100000`ms for later retries + +#### Scenario: Jitter produces a wait no greater than the computed delay +- **WHEN** a client is configured with `retry: { delay: 100, backoffFactor: 2, jitter: true, retries: 1 }` and a request fails once before succeeding +- **THEN** the actual wait before the retry is between `0`ms and `100`ms inclusive + +### Requirement: A Retry-After header overrides the computed backoff delay +When the triggering failure is a `FetchifyError` with `status` `429` or `503` and its `response` includes a `Retry-After` header parseable either as a non-negative integer number of seconds or as an HTTP-date, the wait before the next attempt SHALL be that value converted to milliseconds instead of the computed backoff delay, still clamped to `maxDelay`. When the header is absent, unparseable, or the status is not `429`/`503`, the computed backoff delay (per the previous requirement) SHALL be used unchanged. + +#### Scenario: Retry-After in seconds overrides computed delay +- **WHEN** a client is configured with `retry: { delay: 100, retries: 1 }` and a request's first attempt fails with a `429` response carrying header `Retry-After: 1` +- **THEN** the wait before the retry is approximately `1000`ms, not the `100`ms the backoff formula would compute + +#### Scenario: Retry-After as an HTTP-date overrides computed delay +- **WHEN** a request's first attempt fails with a `503` response carrying a `Retry-After` header set to an HTTP-date approximately `2` seconds in the future +- **THEN** the wait before the retry is approximately `2000`ms + +#### Scenario: Retry-After is still clamped to maxDelay +- **WHEN** a client is configured with `retry: { maxDelay: 500, retries: 1 }` and a request's first attempt fails with a `429` response carrying header `Retry-After: 30` +- **THEN** the wait before the retry does not exceed `500`ms + +#### Scenario: Unparseable Retry-After falls back to computed backoff +- **WHEN** a request's first attempt fails with a `429` response carrying header `Retry-After: not-a-value` +- **THEN** the wait before the retry uses the computed backoff delay, not the invalid header value + +#### Scenario: Retry-After on a non-408/429/5xx-adjacent status is ignored +- **WHEN** a request's first attempt fails with a `500` response that happens to carry a `Retry-After` header +- **THEN** the wait before the retry uses the computed backoff delay, since `Retry-After` handling only applies to `429` and `503` + +### Requirement: Retry composes with the beforeRequest hook and per-attempt timeout +Each retry attempt SHALL re-invoke the configured `hooks.beforeRequest` exactly as a first attempt would, per the `request-hooks` capability, allowing a hook to refresh headers or other request state before the next attempt. Each retry attempt SHALL apply the resolved `timeout` (client default or per-call override) as its own independent timeout window, per the `request-timeout` capability, rather than sharing a single deadline across all attempts. + +#### Scenario: beforeRequest hook runs again on retry +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 }, hooks: { beforeRequest } })` calls a method whose first attempt fails with a `503` and second attempt succeeds +- **THEN** `beforeRequest` is invoked twice, once for each network attempt + +#### Scenario: Each retry gets its own timeout window +- **WHEN** a client created with `createFetchify({ baseUrl, retry: { retries: 1 }, timeout: 100 })` calls a method whose first attempt exceeds the 100ms timeout and second attempt completes within 100ms +- **THEN** the first attempt is aborted with a `FetchifyTimeoutError` (treated as a retryable failure), and the second attempt is given its own fresh 100ms window rather than inheriting any elapsed time from the first + +### Requirement: Retry does not apply to cache-served responses +A configured `retry` SHALL have no effect on a `GET` request served from a configured cache adapter, since no `fetch` call is made — and therefore no failure can occur — for a cache hit. + +#### Scenario: Cache hit resolves without engaging retry +- **WHEN** a client created with `createFetchify({ baseUrl, cache, retry: { retries: 3 } })` calls `client.get("/users")` and the cache adapter already has a matching entry +- **THEN** the call resolves immediately from the cache, `cached: true`, with no network attempts made and no retry logic engaged diff --git a/src/index.ts b/src/index.ts index 0b9ef17..189c58b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,3 +21,4 @@ export type { BeforeRequestHook, FetchifyHooks, } from './types/before-request-hook'; +export type { FetchifyRetryOptions, FetchifyRetryContext } from './types/retry'; diff --git a/src/lib/create-fetchify.test.ts b/src/lib/create-fetchify.test.ts index aeabc64..c85aaec 100644 --- a/src/lib/create-fetchify.test.ts +++ b/src/lib/create-fetchify.test.ts @@ -1206,6 +1206,304 @@ test( "the timeout firing before the caller's abort signal reports FetchifyTimeo expect( controller.signal.aborted ).toBe( false ); } ); +function createSequencedFetchMock( responses: Array ) { + let call = 0; + return mock( () => { + const next = responses[Math.min( call, responses.length - 1 )] as Response | Error; + call += 1; + return next instanceof Error ? Promise.reject( next ) : Promise.resolve( next ); + } ); +} + +test( 'a client-level retry retries a failing idempotent request until it succeeds', async () => { + fetchMock = createSequencedFetchMock( [ + new Response( 'unavailable', { status: 503 } ), + new Response( 'unavailable', { status: 503 } ), + new Response( 'ok', { status: 200 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 2, delay: 1, jitter: false }, + } ); + + const result = await client.get( '/flaky' ); + + expect( result.response.status ).toBe( 200 ); + expect( fetchMock ).toHaveBeenCalledTimes( 3 ); +} ); + +test( 'retries exhausted still rejects with the final error after retries + 1 attempts', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 2, delay: 1, jitter: false }, + } ); + + const error = await client.get( '/down' ).catch( ( e ) => e as FetchifyError ); + + expect( error ).toBeInstanceOf( FetchifyError ); + expect( error.status ).toBe( 503 ); + expect( fetchMock ).toHaveBeenCalledTimes( 3 ); +} ); + +test( 'no retry configured makes exactly one attempt', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { baseUrl: 'https://api.example.com' } ); + + await expect( client.get( '/down' ) ).rejects.toBeInstanceOf( FetchifyError ); + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + +test( 'a per-call retry overrides, not merges with, the client-level default', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 5, delay: 1, jitter: false }, + } ); + + await expect( + client.get( '/flaky', { retry: { retries: 1, delay: 1, jitter: false } } ), + ).rejects.toBeInstanceOf( FetchifyError ); + + expect( fetchMock ).toHaveBeenCalledTimes( 2 ); +} ); + +test( 'a per-call retry: false disables a configured client-level default', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 5, delay: 1, jitter: false }, + } ); + + await expect( client.get( '/flaky', { retry: false } ) ).rejects.toBeInstanceOf( FetchifyError ); + + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + +test( 'the default predicate does not retry a POST', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 3, delay: 1, jitter: false }, + } ); + + await expect( + client.post( '/orders', { body: { id: 1 } } ), + ).rejects.toBeInstanceOf( FetchifyError ); + + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + +test( 'the default predicate does not retry a non-transient status', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'not found', { status: 404 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 3, delay: 1, jitter: false }, + } ); + + await expect( client.get( '/missing' ) ).rejects.toBeInstanceOf( FetchifyError ); + + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + +test( 'a custom retryOn can enable retrying a POST', async () => { + fetchMock = createSequencedFetchMock( [ + new Response( 'unavailable', { status: 503 } ), + new Response( 'created', { status: 201 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 2, delay: 1, jitter: false, retryOn: () => true }, + } ); + + const result = await client.post( '/orders', { body: { id: 1 } } ); + + expect( result.response.status ).toBe( 201 ); + expect( fetchMock ).toHaveBeenCalledTimes( 2 ); +} ); + +test( 'a custom retryOn can narrow eligibility using context.attempt', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'unavailable', { status: 503 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 3, delay: 1, jitter: false, retryOn: ( context ) => context.attempt < 2 }, + } ); + + await expect( client.get( '/flaky' ) ).rejects.toBeInstanceOf( FetchifyError ); + + expect( fetchMock ).toHaveBeenCalledTimes( 2 ); +} ); + +test( 'retryOn receives the resolved method, url, attempt, and error', async () => { + fetchMock = mock( () => Promise.resolve( new Response( 'bad gateway', { status: 502 } ) ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const retryOn = mock( () => false ); + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 2, delay: 1, jitter: false, retryOn }, + } ); + + await expect( client.get( '/flaky' ) ).rejects.toBeInstanceOf( FetchifyError ); + + expect( retryOn ).toHaveBeenCalledTimes( 1 ); + const [ context ] = retryOn.mock.calls[0] as [ + { method: string; url: string; attempt: number; error: FetchifyError }, + ]; + expect( context.method ).toBe( 'GET' ); + expect( context.url ).toBe( 'https://api.example.com/flaky' ); + expect( context.attempt ).toBe( 1 ); + expect( context.error ).toBeInstanceOf( FetchifyError ); +} ); + +test( 'a caller-triggered abort is never retried, even with a permissive retryOn', async () => { + fetchMock = createAbortAwareFetchMock( 200, () => new Response( null, { status: 204 } ) ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 3, delay: 1, jitter: false, retryOn: () => true }, + } ); + const controller = new AbortController(); + setTimeout( () => controller.abort( new Error( 'caller cancelled' ) ), 10 ); + + const error = await client + .get( '/slow', { init: { signal: controller.signal } } ) + .catch( ( e ) => e as Error ); + + expect( error.message ).toBe( 'caller cancelled' ); + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + +test( 'beforeRequest is invoked once per attempt', async () => { + const hook = mock( async () => undefined ); + fetchMock = createSequencedFetchMock( [ + new Response( 'unavailable', { status: 503 } ), + new Response( 'ok', { status: 200 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 1, delay: 1, jitter: false }, + hooks: { beforeRequest: hook }, + } ); + + await client.get( '/flaky' ); + + expect( hook ).toHaveBeenCalledTimes( 2 ); +} ); + +test( 'each retry attempt gets its own timeout window', async () => { + let call = 0; + fetchMock = mock( ( _url: unknown, init?: RequestInit ) => { + call += 1; + const delayMs = call === 1 ? 100 : 10; + return new Promise( ( resolve, reject ) => { + const timer = setTimeout( () => resolve( new Response( 'ok', { status: 200 } ) ), delayMs ); + const signal = init?.signal; + if ( signal === undefined || signal === null ) { + return; + } + signal.addEventListener( 'abort', () => { + clearTimeout( timer ); + reject( signal.reason ); + } ); + } ); + } ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + timeout: 50, + retry: { retries: 1, delay: 1, jitter: false }, + } ); + + const result = await client.get( '/slow' ); + + expect( result.response.status ).toBe( 200 ); + expect( fetchMock ).toHaveBeenCalledTimes( 2 ); +} ); + +test( 'a Retry-After header in seconds overrides the computed backoff delay', async () => { + fetchMock = createSequencedFetchMock( [ + new Response( 'too many requests', { status: 429, headers: { 'Retry-After': '0' } } ), + new Response( 'ok', { status: 200 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 1, delay: 10000, jitter: false }, + } ); + + const start = performance.now(); + const result = await client.get( '/rate-limited' ); + + expect( result.response.status ).toBe( 200 ); + expect( performance.now() - start ).toBeLessThan( 5000 ); +} ); + +test( 'an unparseable Retry-After header falls back to the computed backoff delay', async () => { + fetchMock = createSequencedFetchMock( [ + new Response( 'too many requests', { status: 429, headers: { 'Retry-After': 'not-a-value' } } ), + new Response( 'ok', { status: 200 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 1, delay: 1, jitter: false }, + } ); + + const result = await client.get( '/rate-limited' ); + + expect( result.response.status ).toBe( 200 ); +} ); + +test( 'a Retry-After header is still clamped to maxDelay', async () => { + fetchMock = createSequencedFetchMock( [ + new Response( 'too many requests', { status: 429, headers: { 'Retry-After': '30' } } ), + new Response( 'ok', { status: 200 } ), + ] ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + retry: { retries: 1, maxDelay: 5, jitter: false }, + } ); + + const start = performance.now(); + const result = await client.get( '/rate-limited' ); + + expect( result.response.status ).toBe( 200 ); + expect( performance.now() - start ).toBeLessThan( 1000 ); +} ); + +test( 'a cache-served GET response resolves without engaging retry logic', async () => { + const cache = createStoreCache(); + fetchMock = mock( () => + Promise.resolve( new Response( JSON.stringify( { id: 1 } ), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + } ) ), + ); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const client = createFetchify( { + baseUrl: 'https://api.example.com', + cache, + retry: { retries: 3, delay: 1, jitter: false }, + } ); + + await client.get( '/users' ); + const second = await client.get( '/users' ); + + expect( second.cached ).toBe( true ); + expect( fetchMock ).toHaveBeenCalledTimes( 1 ); +} ); + test( 'a cache hit resolves normally even with a very small configured timeout', async () => { const cache = createStoreCache(); fetchMock = mock( () => diff --git a/src/lib/create-fetchify.ts b/src/lib/create-fetchify.ts index 9bde049..c537245 100644 --- a/src/lib/create-fetchify.ts +++ b/src/lib/create-fetchify.ts @@ -1,16 +1,20 @@ import type { FetchifyOptions } from './define-options'; import type { FetchifyMethod, FetchifyMethodOptions } from '../types/fetchify-method'; import type { FetchifyResponse } from '../types/fetchify-response'; -import type { FetchifyLogEntry, LoggerAdapter } from '../types/logger-adapter'; import type { BeforeRequestContext } from '../types/before-request-hook'; +import type { FetchifyRetryContext } from '../types/retry'; import { FetchifyError } from './fetchify-error'; import { FetchifyTimeoutError } from './fetchify-timeout-error'; import { isJsonContentType } from '../utils/is-json-content-type'; import { mergeHeaders } from '../utils/merge-headers'; import { mergeParams } from '../utils/merge-params'; import { parseBody } from '../utils/parse-body'; +import { resolveRetryDelayMs } from '../utils/resolve-retry-delay'; +import { resolveRetryOptions } from '../utils/resolve-retry-options'; +import { safeLog } from '../utils/safe-log'; import { serializeBody } from '../utils/serialize-body'; import { toResponseBody } from '../utils/to-response-body'; +import { wait } from '../utils/wait'; export interface Fetchify { get: FetchifyMethod; @@ -39,21 +43,6 @@ interface CachedResponse { headers: [string, string][]; } -function safeLog( logger: LoggerAdapter | undefined, entry: FetchifyLogEntry ): void { - if ( logger === undefined ) { - return; - } - try { - const result = logger.log( entry ); - if ( result instanceof Promise ) { - result.catch( () => { - } ); - } - } catch { - // A misbehaving logger should not affect the request's result. - } -} - export function createFetchify( options: FetchifyOptions = {} ): Fetchify { const baseUrl = options.baseUrl === undefined ? undefined : new URL( options.baseUrl ); @@ -62,6 +51,7 @@ export function createFetchify( options: FetchifyOptions = {} ): Fetchify { const defaultHeaders = options.headers; const beforeRequest = options.hooks?.beforeRequest; const timeout = options.timeout; + const retry = options.retry; const performRequest = async ( verb: ( typeof HTTP_METHODS )[number]['verb'], @@ -91,124 +81,162 @@ export function createFetchify( options: FetchifyOptions = {} ): Fetchify { } } - let headers = mergeHeaders( defaultHeaders, requestOptions?.headers ); - const contentType = new Headers( headers ).get( 'content-type' ); - let body = - requestOptions?.body !== undefined ? - ( serializeBody( requestOptions.body, contentType ) as RequestInit['body'] ) : - requestOptions?.init?.body; - let resolvedUrl: URL | string = url; - let init = requestOptions?.init; - - if ( beforeRequest !== undefined ) { - const context: BeforeRequestContext = { - method: verb, - url: resolvedUrl, - headers, - body, - init, - }; - const overrides = await beforeRequest( context ); - - if ( overrides !== undefined ) { - if ( overrides.headers !== undefined ) { - headers = mergeHeaders( headers, overrides.headers ); - } - if ( overrides.body !== undefined ) { - const overriddenContentType = new Headers( headers ).get( 'content-type' ); - body = serializeBody( overrides.body, overriddenContentType ) as RequestInit['body']; - } - if ( overrides.url !== undefined ) { - resolvedUrl = overrides.url instanceof URL ? overrides.url : new URL( overrides.url ); - } - if ( overrides.init !== undefined ) { - init = { ...init, ...overrides.init }; + let callerAborted = false; + + const attemptRequest = async (): Promise> => { + callerAborted = false; + + let headers = mergeHeaders( defaultHeaders, requestOptions?.headers ); + const contentType = new Headers( headers ).get( 'content-type' ); + let body = + requestOptions?.body !== undefined ? + ( serializeBody( requestOptions.body, contentType ) as RequestInit['body'] ) : + requestOptions?.init?.body; + let resolvedUrl: URL | string = url; + let init = requestOptions?.init; + + if ( beforeRequest !== undefined ) { + const context: BeforeRequestContext = { + method: verb, + url: resolvedUrl, + headers, + body, + init, + }; + const overrides = await beforeRequest( context ); + + if ( overrides !== undefined ) { + if ( overrides.headers !== undefined ) { + headers = mergeHeaders( headers, overrides.headers ); + } + if ( overrides.body !== undefined ) { + const overriddenContentType = new Headers( headers ).get( 'content-type' ); + body = serializeBody( overrides.body, overriddenContentType ) as RequestInit['body']; + } + if ( overrides.url !== undefined ) { + resolvedUrl = overrides.url instanceof URL ? overrides.url : new URL( overrides.url ); + } + if ( overrides.init !== undefined ) { + init = { ...init, ...overrides.init }; + } } } - } - const requestedTimeout = - requestOptions?.timeout !== undefined ? requestOptions.timeout : timeout; - let timeoutSignal: AbortSignal | undefined; - if ( requestedTimeout !== undefined && requestedTimeout > 0 ) { - timeoutSignal = AbortSignal.timeout( requestedTimeout ); - } - const callerSignal = init?.signal ?? undefined; - const fetchSignal = - timeoutSignal === undefined ? callerSignal : - callerSignal === undefined ? timeoutSignal : - AbortSignal.any( [ timeoutSignal, callerSignal ] ); + const requestedTimeout = + requestOptions?.timeout !== undefined ? requestOptions.timeout : timeout; + let timeoutSignal: AbortSignal | undefined; + if ( requestedTimeout !== undefined && requestedTimeout > 0 ) { + timeoutSignal = AbortSignal.timeout( requestedTimeout ); + } + const callerSignal = init?.signal ?? undefined; + const fetchSignal = + timeoutSignal === undefined ? callerSignal : + callerSignal === undefined ? timeoutSignal : + AbortSignal.any( [ timeoutSignal, callerSignal ] ); - let raw: Response; - try { - raw = await fetch( resolvedUrl, { - ...init, - method: verb, - headers, - body, - signal: fetchSignal, - } ); - } catch ( error ) { - if ( timeoutSignal !== undefined && timeoutSignal.aborted ) { - throw new FetchifyTimeoutError( requestedTimeout as number, { + let raw: Response; + try { + raw = await fetch( resolvedUrl, { + ...init, method: verb, - url: resolvedUrl.toString(), + headers, + body, + signal: fetchSignal, } ); + } catch ( error ) { + if ( timeoutSignal !== undefined && timeoutSignal.aborted ) { + throw new FetchifyTimeoutError( requestedTimeout as number, { + method: verb, + url: resolvedUrl.toString(), + } ); + } + if ( callerSignal !== undefined && callerSignal.aborted ) { + callerAborted = true; + } + throw error; + } + // bun-types' ambient `Response.clone()` resolves to undici's Response + // type (missing Bun's Headers extras) when the "dom" lib isn't loaded, + // even though the value at runtime is a normal Bun Response. + const response = raw.clone() as Response; + + if ( !raw.ok ) { + let errorData: T | null = null; + try { + if ( isJsonContentType( raw.headers.get( 'content-type' ) ) ) { + errorData = await raw.json() as T; + } else { + errorData = ( await raw.text() ) as unknown as T; + } + } catch { + errorData = null; + } + throw new FetchifyError( + raw.status, + raw.statusText, + response, + errorData, + { method: verb, url: resolvedUrl.toString() }, + ); } - throw error; - } - // bun-types' ambient `Response.clone()` resolves to undici's Response - // type (missing Bun's Headers extras) when the "dom" lib isn't loaded, - // even though the value at runtime is a normal Bun Response. - const response = raw.clone() as Response; - if ( !raw.ok ) { - let errorData: T | null = null; + let data: T | null = null; try { - if ( isJsonContentType( raw.headers.get( 'content-type' ) ) ) { - errorData = await raw.json() as T; + if ( verb === 'GET' && cache !== undefined ) { + const text = await raw.text(); + data = parseBody( text, raw.headers.get( 'content-type' ) ); + + try { + const entry: CachedResponse = { + body: text, + status: raw.status, + statusText: raw.statusText, + headers: [ ...raw.headers.entries() ], + }; + await cache.set( cacheKey, JSON.stringify( entry ) ); + } catch { + // A broken cache write should not affect the resolved response. + } + } else if ( isJsonContentType( raw.headers.get( 'content-type' ) ) ) { + data = await raw.json() as T; } else { - errorData = ( await raw.text() ) as unknown as T; + data = ( await raw.text() ) as unknown as T; } } catch { - errorData = null; + data = null; } - throw new FetchifyError( - raw.status, - raw.statusText, - response, - errorData, - { method: verb, url: resolvedUrl.toString() }, - ); + + return { data, response, cached: false }; + }; + + const requestedRetry = requestOptions?.retry !== undefined ? requestOptions.retry : retry; + if ( requestedRetry === undefined || requestedRetry === false ) { + return attemptRequest(); } - let data: T | null = null; - try { - if ( verb === 'GET' && cache !== undefined ) { - const text = await raw.text(); - data = parseBody( text, raw.headers.get( 'content-type' ) ); + const resolvedRetry = resolveRetryOptions( requestedRetry ); + let attempt = 1; - try { - const entry: CachedResponse = { - body: text, - status: raw.status, - statusText: raw.statusText, - headers: [ ...raw.headers.entries() ], - }; - await cache.set( cacheKey, JSON.stringify( entry ) ); - } catch { - // A broken cache write should not affect the resolved response. + while ( true ) { + try { + return await attemptRequest(); + } catch ( error ) { + if ( callerAborted || !( error instanceof Error ) || attempt > resolvedRetry.retries ) { + throw error; } - } else if ( isJsonContentType( raw.headers.get( 'content-type' ) ) ) { - data = await raw.json() as T; - } else { - data = ( await raw.text() ) as unknown as T; + const retryContext: FetchifyRetryContext = { + method: verb, + url: url.toString(), + attempt, + error, + }; + if ( !resolvedRetry.retryOn( retryContext ) ) { + throw error; + } + await wait( resolveRetryDelayMs( error, attempt, resolvedRetry ) ); + attempt += 1; } - } catch { - data = null; } - - return { data, response, cached: false }; }; const request = async ( diff --git a/src/lib/define-options.ts b/src/lib/define-options.ts index 23f8cc5..0cca2c3 100644 --- a/src/lib/define-options.ts +++ b/src/lib/define-options.ts @@ -1,6 +1,7 @@ import type { CacheAdapter } from '../types/cache-adapter'; import type { LoggerAdapter } from '../types/logger-adapter'; import type { FetchifyHooks } from '../types/before-request-hook'; +import type { FetchifyRetryOptions } from '../types/retry'; export interface FetchifyOptions { baseUrl?: string | URL; @@ -9,6 +10,7 @@ export interface FetchifyOptions { headers?: Record; hooks?: FetchifyHooks; timeout?: number; + retry?: FetchifyRetryOptions; } export function defineOptions( diff --git a/src/types/fetchify-method.ts b/src/types/fetchify-method.ts index 33c37e2..7052252 100644 --- a/src/types/fetchify-method.ts +++ b/src/types/fetchify-method.ts @@ -1,4 +1,5 @@ import type { FetchifyResponse } from './fetchify-response'; +import type { FetchifyRetryOptions } from './retry'; export type JsonSerializable = Record | @@ -14,6 +15,7 @@ export interface FetchifyMethodOptions { body?: RequestInit['body'] | JsonSerializable; init?: RequestInit; timeout?: number; + retry?: FetchifyRetryOptions | false; } export type FetchifyMethod = ( diff --git a/src/types/retry.ts b/src/types/retry.ts new file mode 100644 index 0000000..1b39c5c --- /dev/null +++ b/src/types/retry.ts @@ -0,0 +1,18 @@ +import type { FetchifyError } from '../lib/fetchify-error'; +import type { FetchifyTimeoutError } from '../lib/fetchify-timeout-error'; + +export interface FetchifyRetryContext { + method: string; + url: string; + attempt: number; + error: FetchifyError | FetchifyTimeoutError | Error; +} + +export interface FetchifyRetryOptions { + retries?: number; + delay?: number; + backoffFactor?: number; + maxDelay?: number; + jitter?: boolean; + retryOn?: ( context: FetchifyRetryContext ) => boolean; +} diff --git a/src/utils/compute-retry-delay.test.ts b/src/utils/compute-retry-delay.test.ts new file mode 100644 index 0000000..e18ff1a --- /dev/null +++ b/src/utils/compute-retry-delay.test.ts @@ -0,0 +1,49 @@ +import { expect, test } from 'bun:test'; +import { computeRetryDelay } from './compute-retry-delay'; + +test( 'the first attempt uses the base delay unmodified', () => { + const result = computeRetryDelay( { + attempt: 1, + delay: 100, + backoffFactor: 2, + maxDelay: 10000, + jitter: false, + } ); + + expect( result ).toBe( 100 ); +} ); + +test( 'delay grows exponentially with the backoff factor', () => { + const options = { delay: 100, backoffFactor: 2, maxDelay: 10000, jitter: false }; + + expect( computeRetryDelay( { ...options, attempt: 1 } ) ).toBe( 100 ); + expect( computeRetryDelay( { ...options, attempt: 2 } ) ).toBe( 200 ); + expect( computeRetryDelay( { ...options, attempt: 3 } ) ).toBe( 400 ); +} ); + +test( 'the computed delay is capped at maxDelay', () => { + const result = computeRetryDelay( { + attempt: 5, + delay: 1000, + backoffFactor: 10, + maxDelay: 2000, + jitter: false, + } ); + + expect( result ).toBe( 2000 ); +} ); + +test( 'jitter produces a value between 0 and the computed delay, inclusive', () => { + for ( let i = 0; i < 20; i++ ) { + const result = computeRetryDelay( { + attempt: 2, + delay: 100, + backoffFactor: 2, + maxDelay: 10000, + jitter: true, + } ); + + expect( result ).toBeGreaterThanOrEqual( 0 ); + expect( result ).toBeLessThanOrEqual( 200 ); + } +} ); diff --git a/src/utils/compute-retry-delay.ts b/src/utils/compute-retry-delay.ts new file mode 100644 index 0000000..af3e9b1 --- /dev/null +++ b/src/utils/compute-retry-delay.ts @@ -0,0 +1,13 @@ +export interface ComputeRetryDelayOptions { + attempt: number; + delay: number; + backoffFactor: number; + maxDelay: number; + jitter: boolean; +} + +export function computeRetryDelay( options: ComputeRetryDelayOptions ): number { + const { attempt, delay, backoffFactor, maxDelay, jitter } = options; + const computed = Math.min( maxDelay, delay * backoffFactor ** ( attempt - 1 ) ); + return jitter ? Math.random() * computed : computed; +} diff --git a/src/utils/is-retryable.test.ts b/src/utils/is-retryable.test.ts new file mode 100644 index 0000000..604ab66 --- /dev/null +++ b/src/utils/is-retryable.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from 'bun:test'; +import { FetchifyError } from '../lib/fetchify-error'; +import { FetchifyTimeoutError } from '../lib/fetchify-timeout-error'; +import { isRetryable } from './is-retryable'; + +const request = { method: 'GET', url: 'https://api.example.com/users' }; + +test( 'a FetchifyTimeoutError is retryable on an idempotent method', () => { + const error = new FetchifyTimeoutError( 100, request ); + + expect( isRetryable( 'GET', error ) ).toBe( true ); +} ); + +test( 'a FetchifyError with a transient status is retryable on an idempotent method', () => { + const error = new FetchifyError( 503, 'Service Unavailable', new Response(), null, request ); + + expect( isRetryable( 'GET', error ) ).toBe( true ); +} ); + +test( 'a FetchifyError with a non-transient status is not retryable', () => { + const error = new FetchifyError( 404, 'Not Found', new Response(), null, request ); + + expect( isRetryable( 'GET', error ) ).toBe( false ); +} ); + +test( 'a generic network error is retryable on an idempotent method', () => { + expect( isRetryable( 'GET', new Error( 'network down' ) ) ).toBe( true ); +} ); + +test.each( [ 'POST', 'PATCH' ] )( '%s is never retryable, regardless of the failure', ( method ) => { + const timeoutError = new FetchifyTimeoutError( 100, request ); + const statusError = new FetchifyError( 503, 'Service Unavailable', new Response(), null, request ); + const networkError = new Error( 'network down' ); + + expect( isRetryable( method, timeoutError ) ).toBe( false ); + expect( isRetryable( method, statusError ) ).toBe( false ); + expect( isRetryable( method, networkError ) ).toBe( false ); +} ); + +test.each( [ 'HEAD', 'OPTIONS', 'PUT', 'DELETE' ] )( '%s is idempotent and eligible for retry on a transient failure', ( method ) => { + const error = new FetchifyTimeoutError( 100, request ); + + expect( isRetryable( method, error ) ).toBe( true ); +} ); diff --git a/src/utils/is-retryable.ts b/src/utils/is-retryable.ts new file mode 100644 index 0000000..3663cc9 --- /dev/null +++ b/src/utils/is-retryable.ts @@ -0,0 +1,22 @@ +import { FetchifyError } from '../lib/fetchify-error'; +import { FetchifyTimeoutError } from '../lib/fetchify-timeout-error'; + +const IDEMPOTENT_METHODS = new Set( [ 'GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE' ] ); + +const TRANSIENT_STATUSES = new Set( [ 408, 429, 500, 502, 503, 504 ] ); + +export function isRetryable( method: string, error: Error ): boolean { + if ( !IDEMPOTENT_METHODS.has( method ) ) { + return false; + } + + if ( error instanceof FetchifyTimeoutError ) { + return true; + } + + if ( error instanceof FetchifyError ) { + return TRANSIENT_STATUSES.has( error.status ); + } + + return true; +} diff --git a/src/utils/parse-retry-after.test.ts b/src/utils/parse-retry-after.test.ts new file mode 100644 index 0000000..b7afc02 --- /dev/null +++ b/src/utils/parse-retry-after.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from 'bun:test'; +import { parseRetryAfter } from './parse-retry-after'; + +test( 'parses a delta-seconds value into milliseconds', () => { + expect( parseRetryAfter( '5' ) ).toBe( 5000 ); +} ); + +test( 'parses an HTTP-date value relative to now', () => { + const now = Date.parse( '2026-01-01T00:00:00.000Z' ); + const future = new Date( now + 2000 ).toUTCString(); + + expect( parseRetryAfter( future, now ) ).toBe( 2000 ); +} ); + +test( 'clamps a past HTTP-date to 0', () => { + const now = Date.parse( '2026-01-01T00:00:00.000Z' ); + const past = new Date( now - 5000 ).toUTCString(); + + expect( parseRetryAfter( past, now ) ).toBe( 0 ); +} ); + +test( 'returns undefined for a missing header', () => { + expect( parseRetryAfter( null ) ).toBeUndefined(); +} ); + +test( 'returns undefined for a malformed value', () => { + expect( parseRetryAfter( 'not-a-value' ) ).toBeUndefined(); +} ); diff --git a/src/utils/parse-retry-after.ts b/src/utils/parse-retry-after.ts new file mode 100644 index 0000000..f94aecf --- /dev/null +++ b/src/utils/parse-retry-after.ts @@ -0,0 +1,18 @@ +export function parseRetryAfter( value: string | null, now: number = Date.now() ): number | undefined { + if ( value === null ) { + return undefined; + } + + const trimmed = value.trim(); + + if ( /^\d+$/.test( trimmed ) ) { + return Number( trimmed ) * 1000; + } + + const dateMs = Date.parse( trimmed ); + if ( Number.isNaN( dateMs ) ) { + return undefined; + } + + return Math.max( 0, dateMs - now ); +} diff --git a/src/utils/resolve-retry-delay.test.ts b/src/utils/resolve-retry-delay.test.ts new file mode 100644 index 0000000..d7fcd5f --- /dev/null +++ b/src/utils/resolve-retry-delay.test.ts @@ -0,0 +1,77 @@ +import { expect, test } from 'bun:test'; +import { FetchifyError } from '../lib/fetchify-error'; +import { resolveRetryDelayMs } from './resolve-retry-delay'; +import { resolveRetryOptions } from './resolve-retry-options'; + +const request = { method: 'GET', url: 'https://api.example.com/users' }; + +test( 'falls back to the computed backoff delay for a generic error', () => { + const resolved = resolveRetryOptions( { delay: 100, backoffFactor: 2, jitter: false } ); + + expect( resolveRetryDelayMs( new Error( 'network down' ), 1, resolved ) ).toBe( 100 ); +} ); + +test( 'a Retry-After header on a 429 overrides the computed delay', () => { + const resolved = resolveRetryOptions( { delay: 100, jitter: false } ); + const error = new FetchifyError( + 429, + 'Too Many Requests', + new Response( null, { headers: { 'Retry-After': '2' } } ), + null, + request, + ); + + expect( resolveRetryDelayMs( error, 1, resolved ) ).toBe( 2000 ); +} ); + +test( 'a Retry-After header on a 503 overrides the computed delay', () => { + const resolved = resolveRetryOptions( { delay: 100, jitter: false } ); + const error = new FetchifyError( + 503, + 'Service Unavailable', + new Response( null, { headers: { 'Retry-After': '1' } } ), + null, + request, + ); + + expect( resolveRetryDelayMs( error, 1, resolved ) ).toBe( 1000 ); +} ); + +test( 'a Retry-After header is clamped to maxDelay', () => { + const resolved = resolveRetryOptions( { maxDelay: 500, jitter: false } ); + const error = new FetchifyError( + 429, + 'Too Many Requests', + new Response( null, { headers: { 'Retry-After': '30' } } ), + null, + request, + ); + + expect( resolveRetryDelayMs( error, 1, resolved ) ).toBe( 500 ); +} ); + +test( 'an unparseable Retry-After header falls back to the computed delay', () => { + const resolved = resolveRetryOptions( { delay: 100, jitter: false } ); + const error = new FetchifyError( + 429, + 'Too Many Requests', + new Response( null, { headers: { 'Retry-After': 'not-a-value' } } ), + null, + request, + ); + + expect( resolveRetryDelayMs( error, 1, resolved ) ).toBe( 100 ); +} ); + +test( 'a Retry-After header on a status other than 429/503 is ignored', () => { + const resolved = resolveRetryOptions( { delay: 100, jitter: false } ); + const error = new FetchifyError( + 500, + 'Internal Server Error', + new Response( null, { headers: { 'Retry-After': '5' } } ), + null, + request, + ); + + expect( resolveRetryDelayMs( error, 1, resolved ) ).toBe( 100 ); +} ); diff --git a/src/utils/resolve-retry-delay.ts b/src/utils/resolve-retry-delay.ts new file mode 100644 index 0000000..ab214e3 --- /dev/null +++ b/src/utils/resolve-retry-delay.ts @@ -0,0 +1,20 @@ +import type { ResolvedRetryOptions } from './resolve-retry-options'; +import { FetchifyError } from '../lib/fetchify-error'; +import { computeRetryDelay } from './compute-retry-delay'; +import { parseRetryAfter } from './parse-retry-after'; + +export function resolveRetryDelayMs( error: Error, attempt: number, resolved: ResolvedRetryOptions ): number { + if ( error instanceof FetchifyError && ( error.status === 429 || error.status === 503 ) ) { + const retryAfterMs = parseRetryAfter( error.response.headers.get( 'retry-after' ) ); + if ( retryAfterMs !== undefined ) { + return Math.min( resolved.maxDelay, retryAfterMs ); + } + } + return computeRetryDelay( { + attempt, + delay: resolved.delay, + backoffFactor: resolved.backoffFactor, + maxDelay: resolved.maxDelay, + jitter: resolved.jitter, + } ); +} diff --git a/src/utils/resolve-retry-options.test.ts b/src/utils/resolve-retry-options.test.ts new file mode 100644 index 0000000..a2137b4 --- /dev/null +++ b/src/utils/resolve-retry-options.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from 'bun:test'; +import { FetchifyError } from '../lib/fetchify-error'; +import { resolveRetryOptions } from './resolve-retry-options'; + +test( 'an empty object resolves to every default', () => { + const resolved = resolveRetryOptions( {} ); + + expect( resolved.retries ).toBe( 3 ); + expect( resolved.delay ).toBe( 200 ); + expect( resolved.backoffFactor ).toBe( 2 ); + expect( resolved.maxDelay ).toBe( 30000 ); + expect( resolved.jitter ).toBe( true ); +} ); + +test( 'explicit fields override their defaults', () => { + const resolved = resolveRetryOptions( { + retries: 5, + delay: 100, + backoffFactor: 3, + maxDelay: 1000, + jitter: false, + } ); + + expect( resolved.retries ).toBe( 5 ); + expect( resolved.delay ).toBe( 100 ); + expect( resolved.backoffFactor ).toBe( 3 ); + expect( resolved.maxDelay ).toBe( 1000 ); + expect( resolved.jitter ).toBe( false ); +} ); + +test( 'a custom retryOn is used as-is', () => { + const retryOn = () => true; + + const resolved = resolveRetryOptions( { retryOn } ); + + expect( resolved.retryOn ).toBe( retryOn ); +} ); + +test( 'the default retryOn delegates to the idempotency/transient-status predicate', () => { + const resolved = resolveRetryOptions( {} ); + const request = { method: 'POST', url: 'https://api.example.com/orders' }; + const error = new FetchifyError( 503, 'Service Unavailable', new Response(), null, request ); + + expect( resolved.retryOn( { method: 'POST', url: request.url, attempt: 1, error } ) ).toBe( false ); + expect( resolved.retryOn( { method: 'GET', url: request.url, attempt: 1, error } ) ).toBe( true ); +} ); diff --git a/src/utils/resolve-retry-options.ts b/src/utils/resolve-retry-options.ts new file mode 100644 index 0000000..e1e485b --- /dev/null +++ b/src/utils/resolve-retry-options.ts @@ -0,0 +1,28 @@ +import type { FetchifyRetryContext, FetchifyRetryOptions } from '../types/retry'; +import { isRetryable } from './is-retryable'; + +const DEFAULT_RETRIES = 3; +const DEFAULT_DELAY = 200; +const DEFAULT_BACKOFF_FACTOR = 2; +const DEFAULT_MAX_DELAY = 30000; +const DEFAULT_JITTER = true; + +export interface ResolvedRetryOptions { + retries: number; + delay: number; + backoffFactor: number; + maxDelay: number; + jitter: boolean; + retryOn: ( context: FetchifyRetryContext ) => boolean; +} + +export function resolveRetryOptions( retry: FetchifyRetryOptions ): ResolvedRetryOptions { + return { + retries: retry.retries ?? DEFAULT_RETRIES, + delay: retry.delay ?? DEFAULT_DELAY, + backoffFactor: retry.backoffFactor ?? DEFAULT_BACKOFF_FACTOR, + maxDelay: retry.maxDelay ?? DEFAULT_MAX_DELAY, + jitter: retry.jitter ?? DEFAULT_JITTER, + retryOn: retry.retryOn ?? ( ( context ) => isRetryable( context.method, context.error ) ), + }; +} diff --git a/src/utils/safe-log.test.ts b/src/utils/safe-log.test.ts new file mode 100644 index 0000000..d04c84f --- /dev/null +++ b/src/utils/safe-log.test.ts @@ -0,0 +1,63 @@ +import { expect, mock, test } from 'bun:test'; +import type { FetchifyLogEntry, LoggerAdapter } from '../types/logger-adapter'; +import { safeLog } from './safe-log'; + +const entry: FetchifyLogEntry = { + method: 'GET', + url: 'https://api.example.com/users', + status: 200, + durationMs: 5, + cached: false, +}; + +test( 'does nothing when no logger is given', () => { + expect( () => safeLog( undefined, entry ) ).not.toThrow(); +} ); + +test( 'calls log with the given entry', () => { + const log = mock( () => { + } ); + const logger: LoggerAdapter = { log }; + + safeLog( logger, entry ); + + expect( log ).toHaveBeenCalledTimes( 1 ); + expect( log ).toHaveBeenCalledWith( entry ); +} ); + +test( 'a synchronously throwing logger does not propagate', () => { + const logger: LoggerAdapter = { + log: () => { + throw new Error( 'boom' ); + }, + }; + + expect( () => safeLog( logger, entry ) ).not.toThrow(); +} ); + +test( 'a rejected logger promise does not produce an unhandled rejection', async () => { + const logger: LoggerAdapter = { + log: () => Promise.reject( new Error( 'boom' ) ), + }; + + expect( () => safeLog( logger, entry ) ).not.toThrow(); + + await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); +} ); + +test( 'does not await a slow async logger', () => { + let resolved = false; + const logger: LoggerAdapter = { + log: () => + new Promise( ( resolve ) => { + setTimeout( () => { + resolved = true; + resolve(); + }, 50 ); + } ), + }; + + safeLog( logger, entry ); + + expect( resolved ).toBe( false ); +} ); diff --git a/src/utils/safe-log.ts b/src/utils/safe-log.ts new file mode 100644 index 0000000..fedb5c6 --- /dev/null +++ b/src/utils/safe-log.ts @@ -0,0 +1,16 @@ +import type { FetchifyLogEntry, LoggerAdapter } from '../types/logger-adapter'; + +export function safeLog( logger: LoggerAdapter | undefined, entry: FetchifyLogEntry ): void { + if ( logger === undefined ) { + return; + } + try { + const result = logger.log( entry ); + if ( result instanceof Promise ) { + result.catch( () => { + } ); + } + } catch { + // A misbehaving logger should not affect the request's result. + } +} diff --git a/src/utils/wait.test.ts b/src/utils/wait.test.ts new file mode 100644 index 0000000..a744bf3 --- /dev/null +++ b/src/utils/wait.test.ts @@ -0,0 +1,14 @@ +import { expect, test } from 'bun:test'; +import { wait } from './wait'; + +test( 'resolves after approximately the given duration', async () => { + const start = performance.now(); + + await wait( 20 ); + + expect( performance.now() - start ).toBeGreaterThanOrEqual( 15 ); +} ); + +test( 'resolves with no value', async () => { + await expect( wait( 0 ) ).resolves.toBeUndefined(); +} ); diff --git a/src/utils/wait.ts b/src/utils/wait.ts new file mode 100644 index 0000000..2646da0 --- /dev/null +++ b/src/utils/wait.ts @@ -0,0 +1,3 @@ +export function wait( ms: number ): Promise { + return new Promise( ( resolve ) => setTimeout( resolve, ms ) ); +}