From 888f06cf8b39d986f543487b9c68a04b6c1b952b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 08:14:23 +0300 Subject: [PATCH 1/2] feat(client)!: retry only idempotent methods by default and make retries safer RetryPolicy now retries only GET, HEAD, OPTIONS, TRACE, PUT and DELETE (RFC 9110 section 9.2.2) unless retryableMethods says otherwise. The new constructor argument is appended last, so existing positional calls keep working. Retry-After is capped at maxDelay, and a request whose body is not seekable is sent once: a retry used to send an empty body because the first attempt had already consumed the stream. --- CHANGELOG.md | 11 + README.md | 11 +- docs/Client-Configuration.md | 4 +- docs/Client-Retry.md | 28 ++- src/Client/Client.php | 22 +- src/Client/Retry/RetryPolicy.php | 47 ++++- .../Unit/Client/Retry/ClientRetryBodyTest.php | 106 ++++++++++ tests/Unit/Client/Retry/ClientRetryTest.php | 197 ++++++++++++++++++ tests/Unit/Client/Retry/RetryPolicyTest.php | 31 +++ 9 files changed, 440 insertions(+), 17 deletions(-) create mode 100644 tests/Unit/Client/Retry/ClientRetryBodyTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b3b8fd..6fcd88b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ All notable changes to **initphp/http** will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed (breaking) + +- **`RetryPolicy` retries only idempotent methods by default** (RFC 9110 §9.2.2: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`). A `POST` or `PATCH` request is now sent once, even when a policy is attached. To restore the old behaviour, or to retry them deliberately, pass the new last constructor argument `retryableMethods`, for example `new RetryPolicy(retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST'])`. New API: `RetryPolicy::DEFAULT_RETRYABLE_METHODS`, `getRetryableMethods()`, `isRetryableMethod()`. + +### Fixed + +- `Retry-After` is now capped at the policy's `maxDelay`. Previously a server could make the client wait for as long as it asked (`Retry-After: 3600` meant an hour). +- A request whose body is not seekable is no longer retried. The retry used to send an empty body, because the first attempt had already consumed the stream; now the first response is returned, or the first exception is thrown. + ## [4.0.0] - 2026-11-22 ### Changed (breaking) diff --git a/README.md b/README.md index 7fd2965..6e3aa04 100644 --- a/README.md +++ b/README.md @@ -177,10 +177,15 @@ Behaviour and backward-compatibility: - A non-retryable `4xx`/`5xx` response is still **returned, never thrown** (PSR-18). - A retryable response that exhausts the attempt cap is returned as-is (the last response); a transport exception that exhausts the cap is re-thrown. +- Only **idempotent methods** (`GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`) + are retried by default; `POST` and `PATCH` are sent once unless you list them in + `retryableMethods`. A request whose body is not seekable is also sent once, + since a retry could not send the body again. - A parseable `Retry-After` header (delay-seconds or HTTP-date) on a retryable - response **overrides** the computed backoff unless you disable it. -- The retryable status set, whether transport exceptions are retried, and - `Retry-After` handling are all configurable on `RetryPolicy`. + response **overrides** the computed backoff, capped at `maxDelay`, unless you + disable it. +- The retryable status set, the retryable methods, whether transport exceptions + are retried, and `Retry-After` handling are all configurable on `RetryPolicy`. ```php // Customise: only retry 429/503, never on transport exceptions, ignore Retry-After. diff --git a/docs/Client-Configuration.md b/docs/Client-Configuration.md index 59028c2..108c0fe 100644 --- a/docs/Client-Configuration.md +++ b/docs/Client-Configuration.md @@ -120,7 +120,9 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy( ``` - Retried by default: transport exceptions (`retryOnException`) and the status codes `408`, `425`, `429`, `500`, `502`, `503` and `504` (`retryableStatusCodes`). -- A parseable `Retry-After` header on a retryable response overrides the computed backoff unless `respectRetryAfter` is `false`. +- Only **idempotent methods** are retried by default: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. A `POST` or `PATCH` is sent once; list it in `retryableMethods` to opt in. +- A request whose body is not seekable is sent once too, because a retry could not send the body again. +- A parseable `Retry-After` header on a retryable response overrides the computed backoff, up to `maxDelay`, unless `respectRetryAfter` is `false`. - A non-retryable `4xx`/`5xx` response is still **returned, never thrown**. A retryable response that exhausts `maxAttempts` is returned as-is; a transport exception that exhausts it is re-thrown. The full reference (every `RetryPolicy` parameter and clamp, the backoff formula, `Retry-After` parsing and the sleeper seam) is on the [Client Retry](Client-Retry.md) page. diff --git a/docs/Client-Retry.md b/docs/Client-Retry.md index 2a28b6f..6164114 100644 --- a/docs/Client-Retry.md +++ b/docs/Client-Retry.md @@ -15,14 +15,22 @@ $response = $client->get('https://api.example.com/reports'); With a policy attached, `sendRequest()` runs this loop (the convenience methods such as `get()` and `post()` go through it too): +0. If the request must not be replayed (see [Which requests are retried](#which-requests-are-retried)), send it once and stop: the first response is returned, or the first exception thrown. 1. Send the request. This is attempt 1. 2. If the transport throws a `Psr\Http\Client\NetworkExceptionInterface` (DNS, TCP, TLS, timeout): retry when the policy has `retryOnException` on and another attempt is allowed. Otherwise the exception is re-thrown. 3. If a response arrives and its status is **not** in the retryable set, return it. This is also true for `4xx` and `5xx` responses: PSR-18 says they are returned, never thrown. 4. If its status is retryable and another attempt is allowed, wait, then go back to step 1. If no attempt is left, the last response is returned as-is. -The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-After` value when the policy honours it (see [`RetryAfter`](#retryafter)). +The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-After` value when the policy honours it (see [`RetryAfter`](#retryafter)). Either way it never exceeds `maxDelay`. -> **The method is not considered.** The policy retries `POST`, `PATCH` and every other method the same way. A request that failed after the server already acted on it can therefore run twice. Attach a policy only where that is safe, for example for idempotent requests, or make the operation idempotent on the server (an idempotency key, for example). Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest. +### Which requests are retried + +A retry sends the request again, so two kinds of request are **sent exactly once**, whatever the status or exception: + +- **A method that is not in `retryableMethods`.** By default only the idempotent methods of RFC 9110 §9.2.2 are retried: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. `POST` and `PATCH` are not, because the server may already have acted on a request that failed on the way back, and a retry would run it twice. To retry them anyway, list them in `retryableMethods` (see below), ideally together with an idempotency key the server honours. +- **A request whose body cannot be rewound.** Each attempt reads the body from the start. A stream that is not seekable (a socket, a pipe, a request body read once) is already used up after the first attempt, so a retry would send an **empty** body. Such a request is not retried; its first response is returned, or its first exception is thrown. Strings, `php://temp` and files are seekable and are retried normally. + +Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest. Errors that are not transport failures are not retried: `RequestException` (a request that cannot be marshalled) and `ClientException` (for example, cURL cannot be initialised) propagate immediately. See [Client Exceptions](Client-Exceptions.md). @@ -40,6 +48,7 @@ new RetryPolicy( bool $retryOnException = true, ?array $retryableStatusCodes = null, // null = RetryPolicy::DEFAULT_RETRYABLE_STATUS bool $respectRetryAfter = true, + ?array $retryableMethods = null, // null = RetryPolicy::DEFAULT_RETRYABLE_METHODS ) ``` @@ -52,9 +61,10 @@ new RetryPolicy( | `jitter` | `0.5` | Ratio in `[0.0, 1.0]`. Out-of-range values are clamped. `0.0` disables jitter. | | `retryOnException` | `true` | Retry when the transport throws a network exception. | | `retryableStatusCodes` | see below | Status codes that trigger a retry. Passing a list replaces the default set; it is not merged with it. | -| `respectRetryAfter` | `true` | Let a parseable `Retry-After` header on a retryable response set the wait. | +| `respectRetryAfter` | `true` | Let a parseable `Retry-After` header on a retryable response set the wait, capped at `maxDelay`. | +| `retryableMethods` | see below | HTTP methods that may be retried, compared case-insensitively. Passing a list replaces the default set; it is not merged with it. An empty list never retries. | -The default retryable set is the constant `RetryPolicy::DEFAULT_RETRYABLE_STATUS`: `408`, `425`, `429`, `500`, `502`, `503` and `504`. +The default retryable set is the constant `RetryPolicy::DEFAULT_RETRYABLE_STATUS`: `408`, `425`, `429`, `500`, `502`, `503` and `504`. The default methods are the constant `RetryPolicy::DEFAULT_RETRYABLE_METHODS`: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. ```php // Retry only on rate limiting and 503, and never on transport errors. @@ -63,6 +73,12 @@ $policy = new RetryPolicy( retryOnException: false, retryableStatusCodes: [429, 503], ); + +// Also retry POST. Only do this when the endpoint is idempotent, for example +// because it honours an Idempotency-Key header. +$policy = new RetryPolicy( + retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST'], +); ``` ### Methods @@ -76,8 +92,10 @@ $policy = new RetryPolicy( | `getJitter()` | `float` | The (clamped) jitter ratio. | | `isRetryOnException()` | `bool` | Whether network exceptions are retried. | | `getRetryableStatusCodes()` | `list` | The retryable status codes. | +| `getRetryableMethods()` | `list` | The retryable methods, upper-cased and without duplicates. | | `isRespectRetryAfter()` | `bool` | Whether `Retry-After` is honoured. | | `isRetryableStatus(int $statusCode)` | `bool` | Whether the status is in the retryable set (strict comparison). | +| `isRetryableMethod(string $method)` | `bool` | Whether the method may be retried (case-insensitive). | | `shouldRetry(int $attempt)` | `bool` | `true` when `$attempt < maxAttempts`. `$attempt` is 1-based: `1` means the first try has just finished. | The policy has no setters. To change a value, build a new `RetryPolicy`. @@ -153,7 +171,7 @@ RetryAfter::parse('Wed, 21 Oct 2015 07:28:00 GMT', 1445412420); // 60.0 RetryAfter::parse(''); // null ``` -In the client, `Retry-After` applies to retryable **responses** only, not to network exceptions, and only when `respectRetryAfter` is `true`. When it applies, its value is used **as is**: it is neither jittered nor capped by `maxDelay`. A server that sends `Retry-After: 3600` makes the client wait an hour before the next attempt. If that is too long for your use case, set `respectRetryAfter: false` so the capped backoff is used, or keep `maxAttempts` low. +In the client, `Retry-After` applies to retryable **responses** only, not to network exceptions, and only when `respectRetryAfter` is `true`. When it applies, its value is not jittered but it **is capped by `maxDelay`**: a server that sends `Retry-After: 3600` with the default `maxDelay` of `30.0` makes the client wait 30 seconds, not an hour. Lower `maxDelay` to bound the wait further, or set `respectRetryAfter: false` to ignore the header and use the backoff delay. ## `SleeperInterface` and `Sleeper` diff --git a/src/Client/Client.php b/src/Client/Client.php index 1428d2d..d42e88a 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -31,6 +31,7 @@ use function is_resource; use function is_string; use function max; +use function min; use function preg_match; use function strlen; use function strpos; @@ -488,8 +489,11 @@ public function head(string $url, $body = null, array $headers = [], string $ver * enabled, transport exceptions) are retried up to the policy's * max-attempts cap, spaced by exponential backoff with jitter. A * `Retry-After` header on a retryable response overrides the computed delay - * when the policy opts in. PSR-18 semantics are preserved: a non-retryable - * 4xx/5xx response is returned, never thrown. + * when the policy opts in, capped at the policy's `maxDelay`. Only the + * policy's retryable methods (idempotent ones by default) are retried, and + * only when the request body can be rewound; any other request is sent + * once. PSR-18 semantics are preserved: a non-retryable 4xx/5xx response is + * returned, never thrown. * * @param RequestInterface $request * @return ResponseInterface @@ -504,6 +508,14 @@ public function sendRequest(RequestInterface $request): ResponseInterface return $this->transport($request); } + // A request that must not be replayed gets a single attempt: a method + // that is not idempotent may already have been acted on by the server, + // and a body that cannot be rewound would be re-sent empty. In both + // cases the first outcome (response or exception) is the answer. + if (!$policy->isRetryableMethod($request->getMethod()) || !$request->getBody()->isSeekable()) { + return $this->transport($request); + } + $backoff = new Backoff($policy, $this->jitterRandomizer); $attempt = 0; @@ -535,8 +547,8 @@ public function sendRequest(RequestInterface $request): ResponseInterface /** * Resolve the delay before the next retry for a retryable *response*: - * honour a parseable `Retry-After` header when the policy opts in, - * otherwise fall back to the jittered exponential backoff for this attempt. + * honour a parseable `Retry-After` header when the policy opts in (capped + * at the policy's `maxDelay`), otherwise fall back to the jittered exponential backoff for this attempt. * * @param RetryPolicy $policy * @param Backoff $backoff @@ -549,7 +561,7 @@ private function retryDelay(RetryPolicy $policy, Backoff $backoff, ResponseInter if ($policy->isRespectRetryAfter()) { $retryAfter = RetryAfter::fromResponse($response); if ($retryAfter !== null) { - return $retryAfter; + return min($retryAfter, $policy->getMaxDelay()); } } diff --git a/src/Client/Retry/RetryPolicy.php b/src/Client/Retry/RetryPolicy.php index 731dc8a..44eb6dc 100644 --- a/src/Client/Retry/RetryPolicy.php +++ b/src/Client/Retry/RetryPolicy.php @@ -15,10 +15,13 @@ namespace InitPHP\HTTP\Client\Retry; +use function array_map; +use function array_unique; use function array_values; use function in_array; use function max; use function min; +use function strtoupper; /** * Immutable configuration for the HTTP client's retry-with-backoff layer. @@ -30,9 +33,10 @@ * space the attempts out. * * The default-constructed policy retries on the conventional transient set — - * connection failures plus HTTP 408, 425, 429, 500, 502, 503 and 504 — which is - * a sensible production default. The client itself stays single-attempt unless - * a policy is explicitly attached, preserving full backward compatibility. + * connection failures plus HTTP 408, 425, 429, 500, 502, 503 and 504 — but only + * for idempotent methods (RFC 9110 §9.2.2), so a request the server may already + * have acted on is never replayed by default. The client itself stays + * single-attempt unless a policy is explicitly attached. */ final class RetryPolicy { @@ -42,6 +46,12 @@ final class RetryPolicy */ public const DEFAULT_RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504]; + /** + * Methods that are safe to repeat by default: the idempotent methods of + * RFC 9110 §9.2.2. POST and PATCH are deliberately absent. + */ + public const DEFAULT_RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS', 'TRACE', 'PUT', 'DELETE']; + /** Total number of attempts (the initial try plus retries). */ private int $maxAttempts; @@ -80,6 +90,13 @@ final class RetryPolicy */ private bool $respectRetryAfter; + /** + * Upper-case HTTP methods that may be retried. + * + * @var list + */ + private array $retryableMethods; + /** * @param int $maxAttempts Total attempts (>= 1). Clamped up to 1. * @param float $baseDelay First backoff interval in seconds (>= 0). @@ -89,6 +106,8 @@ final class RetryPolicy * @param bool $retryOnException Retry on transport exceptions. * @param list|null $retryableStatusCodes Override the default transient status set. * @param bool $respectRetryAfter Honour a `Retry-After` header when present. + * @param list|null $retryableMethods Methods that may be retried (case-insensitive). + * Null = {@see self::DEFAULT_RETRYABLE_METHODS}; add e.g. `'POST'` to opt in. */ public function __construct( int $maxAttempts = 3, @@ -99,6 +118,7 @@ public function __construct( bool $retryOnException = true, ?array $retryableStatusCodes = null, bool $respectRetryAfter = true, + ?array $retryableMethods = null, ) { $this->maxAttempts = max(1, $maxAttempts); $this->baseDelay = max(0.0, $baseDelay); @@ -110,6 +130,10 @@ public function __construct( ? self::DEFAULT_RETRYABLE_STATUS : array_values($retryableStatusCodes); $this->respectRetryAfter = $respectRetryAfter; + $this->retryableMethods = array_values(array_unique(array_map( + static fn($method): string => strtoupper((string) $method), + $retryableMethods ?? self::DEFAULT_RETRYABLE_METHODS, + ))); } public function getMaxAttempts(): int @@ -155,6 +179,23 @@ public function isRespectRetryAfter(): bool return $this->respectRetryAfter; } + /** + * @return list Upper-case HTTP methods that may be retried. + */ + public function getRetryableMethods(): array + { + return $this->retryableMethods; + } + + /** + * Whether a request with the given HTTP method may be retried + * (case-insensitive). + */ + public function isRetryableMethod(string $method): bool + { + return in_array(strtoupper($method), $this->retryableMethods, true); + } + /** * Whether the given response status code is in the retryable set. */ diff --git a/tests/Unit/Client/Retry/ClientRetryBodyTest.php b/tests/Unit/Client/Retry/ClientRetryBodyTest.php new file mode 100644 index 0000000..56ae742 --- /dev/null +++ b/tests/Unit/Client/Retry/ClientRetryBodyTest.php @@ -0,0 +1,106 @@ +setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(2, 0.0, 1.0, 1.0, 0.0, true, [200], true, $methods)); + } + + /** + * @return array{method: string, body: string} + */ + private function echoed(Request $request, Client $client): array + { + $response = $client->sendRequest($request); + + return \json_decode((string) $response->getBody(), true); + } + + public function testRetryResendsTheFullSeekableBody(): void + { + $sleeper = new RecordingSleeper(); + $request = new Request('PUT', self::$baseUrl . '/echo', [], new Stream('payload', null)); + + $data = $this->echoed($request, $this->client($sleeper)); + + self::assertCount(1, $sleeper->sleeps, 'the 200 was retried once'); + self::assertSame('PUT', $data['method']); + self::assertSame('payload', $data['body'], 'the retry must carry the body, not an empty one'); + } + + public function testRequestWithNonSeekableBodyIsSentOnceWithItsBody(): void + { + $sleeper = new RecordingSleeper(); + $request = new Request('PUT', self::$baseUrl . '/echo', [], ClientRetryTest::nonSeekableBody('payload')); + + $data = $this->echoed($request, $this->client($sleeper)); + + self::assertCount(0, $sleeper->sleeps, 'a body that cannot be rewound is never retried'); + self::assertSame('payload', $data['body'], 'the first (and only) attempt carries the body'); + } + + public function testPostIsSentOnceByDefault(): void + { + $sleeper = new RecordingSleeper(); + $request = new Request('POST', self::$baseUrl . '/echo', [], new Stream('payload', null)); + + $data = $this->echoed($request, $this->client($sleeper)); + + self::assertCount(0, $sleeper->sleeps); + self::assertSame('payload', $data['body']); + } + + public function testPostIsRetriedWithItsBodyWhenOptedIn(): void + { + $sleeper = new RecordingSleeper(); + $request = new Request('POST', self::$baseUrl . '/echo', [], new Stream('payload', null)); + + $data = $this->echoed($request, $this->client($sleeper, ['POST'])); + + self::assertCount(1, $sleeper->sleeps); + self::assertSame('payload', $data['body']); + } +} diff --git a/tests/Unit/Client/Retry/ClientRetryTest.php b/tests/Unit/Client/Retry/ClientRetryTest.php index 3a75c78..074185d 100644 --- a/tests/Unit/Client/Retry/ClientRetryTest.php +++ b/tests/Unit/Client/Retry/ClientRetryTest.php @@ -8,6 +8,7 @@ use InitPHP\HTTP\Client\Retry\RetryPolicy; use InitPHP\HTTP\Message\Request; use InitPHP\HTTP\Message\Response; +use InitPHP\HTTP\Message\Stream; use PHPUnit\Framework\TestCase; /** @@ -254,4 +255,200 @@ public function testWithRetryPolicyReturnsCloneAndKeepsOriginalSingleShot(): voi self::assertNull($client->getRetryPolicy()); self::assertInstanceOf(RetryPolicy::class, $clone->getRetryPolicy()); } + + public function testNonIdempotentMethodIsNotRetriedOnRetryableStatus(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest(new Request('POST', 'https://api.example.com/orders')); + + self::assertSame(503, $response->getStatusCode(), 'the first response is returned as is'); + self::assertSame(1, $client->calls); + self::assertCount(0, $sleeper->sleeps); + } + + public function testNonIdempotentMethodIsNotRetriedOnTransportException(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->networkError(), $this->response(200)]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + try { + $client->sendRequest(new Request('PATCH', 'https://api.example.com/orders/1')); + self::fail('The first transport exception must propagate.'); + } catch (NetworkException $e) { + self::assertSame(1, $client->calls); + self::assertCount(0, $sleeper->sleeps); + } + } + + /** + * @return array + */ + public static function idempotentMethodProvider(): array + { + return [ + 'GET' => ['GET'], + 'HEAD' => ['HEAD'], + 'OPTIONS' => ['OPTIONS'], + 'TRACE' => ['TRACE'], + 'PUT' => ['PUT'], + 'DELETE' => ['DELETE'], + 'put (lower case)' => ['put'], + ]; + } + + /** + * @dataProvider idempotentMethodProvider + */ + public function testIdempotentMethodsAreRetriedByDefault(string $method): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest(new Request($method, 'https://api.example.com/resource')); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame(2, $client->calls); + } + + public function testNonIdempotentMethodCanBeOptedIn(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(201)]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0, retryableMethods: ['POST'])); + + $response = $client->sendRequest(new Request('POST', 'https://api.example.com/orders')); + + self::assertSame(201, $response->getStatusCode()); + self::assertSame(2, $client->calls); + } + + public function testMethodOutsideCustomListIsNotRetried(): void + { + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper(new RecordingSleeper()) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0, retryableMethods: ['POST'])); + + $response = $client->sendRequest($this->request()); + + self::assertSame(503, $response->getStatusCode(), 'GET is not in the custom list'); + self::assertSame(1, $client->calls); + } + + public function testRetryAfterIsCappedByMaxDelay(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([ + $this->response(503, ['Retry-After' => '3600']), + $this->response(200), + ]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.05, 2.0, 30.0, 0.0)); + + $client->sendRequest($this->request()); + + self::assertCount(1, $sleeper->sleeps); + self::assertEqualsWithDelta(30.0, $sleeper->sleeps[0], 1e-9); + } + + public function testHttpDateRetryAfterIsCappedByMaxDelay(): void + { + $sleeper = new RecordingSleeper(); + $date = \gmdate('D, d M Y H:i:s', \time() + 7200) . ' GMT'; + $client = new ScriptedClient([ + $this->response(429, ['Retry-After' => $date]), + $this->response(200), + ]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.05, 2.0, 10.0, 0.0)); + + $client->sendRequest($this->request()); + + self::assertEqualsWithDelta(10.0, $sleeper->sleeps[0], 1e-9); + } + + public function testRetryAfterBelowMaxDelayIsUsedAsIs(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([ + $this->response(429, ['Retry-After' => '2']), + $this->response(200), + ]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.05, 2.0, 30.0, 0.0)); + + $client->sendRequest($this->request()); + + self::assertEqualsWithDelta(2.0, $sleeper->sleeps[0], 1e-9); + } + + public function testRequestWithNonSeekableBodyIsNotRetriedOnStatus(): void + { + $sleeper = new RecordingSleeper(); + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper($sleeper) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest( + new Request('PUT', 'https://api.example.com/resource', [], self::nonSeekableBody('payload')), + ); + + self::assertSame(503, $response->getStatusCode(), 'the first response is returned as is'); + self::assertSame(1, $client->calls); + self::assertCount(0, $sleeper->sleeps); + } + + public function testRequestWithNonSeekableBodyIsNotRetriedOnException(): void + { + $client = new ScriptedClient([$this->networkError(), $this->response(200)]); + $client->setSleeper(new RecordingSleeper()) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + try { + $client->sendRequest( + new Request('PUT', 'https://api.example.com/resource', [], self::nonSeekableBody('payload')), + ); + self::fail('The first transport exception must propagate.'); + } catch (NetworkException $e) { + self::assertSame(1, $client->calls); + } + } + + public function testRequestWithSeekableBodyIsStillRetried(): void + { + $client = new ScriptedClient([$this->response(503), $this->response(200)]); + $client->setSleeper(new RecordingSleeper()) + ->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0)); + + $response = $client->sendRequest( + new Request('PUT', 'https://api.example.com/resource', [], new Stream('payload', null)), + ); + + self::assertSame(200, $response->getStatusCode()); + self::assertSame(2, $client->calls); + } + + /** + * A readable stream that cannot be rewound: one end of a socket pair that + * already holds the payload. + */ + public static function nonSeekableBody(string $payload): Stream + { + $pair = \stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + self::assertIsArray($pair); + \fwrite($pair[0], $payload); + \fclose($pair[0]); + $body = new Stream($pair[1]); + self::assertFalse($body->isSeekable()); + + return $body; + } } diff --git a/tests/Unit/Client/Retry/RetryPolicyTest.php b/tests/Unit/Client/Retry/RetryPolicyTest.php index 415d57d..16aa8b6 100644 --- a/tests/Unit/Client/Retry/RetryPolicyTest.php +++ b/tests/Unit/Client/Retry/RetryPolicyTest.php @@ -63,4 +63,35 @@ public function testShouldRetryRespectsAttemptCap(): void self::assertFalse($policy->shouldRetry(3), 'cap reached after the 3rd attempt'); self::assertFalse($policy->shouldRetry(4)); } + + public function testDefaultRetryableMethodsAreTheIdempotentOnes(): void + { + $policy = new RetryPolicy(); + + self::assertSame(['GET', 'HEAD', 'OPTIONS', 'TRACE', 'PUT', 'DELETE'], $policy->getRetryableMethods()); + foreach (['GET', 'HEAD', 'OPTIONS', 'TRACE', 'PUT', 'DELETE'] as $method) { + self::assertTrue($policy->isRetryableMethod($method), $method); + } + self::assertFalse($policy->isRetryableMethod('POST')); + self::assertFalse($policy->isRetryableMethod('PATCH')); + self::assertFalse($policy->isRetryableMethod('CONNECT')); + } + + public function testRetryableMethodsAreCaseInsensitiveAndDeduplicated(): void + { + $policy = new RetryPolicy(retryableMethods: ['post', 'Post', 'get']); + + self::assertSame(['POST', 'GET'], $policy->getRetryableMethods()); + self::assertTrue($policy->isRetryableMethod('POST')); + self::assertTrue($policy->isRetryableMethod('post')); + self::assertFalse($policy->isRetryableMethod('PUT'), 'a custom list replaces the default'); + } + + public function testEmptyRetryableMethodsDisablesRetries(): void + { + $policy = new RetryPolicy(retryableMethods: []); + + self::assertSame([], $policy->getRetryableMethods()); + self::assertFalse($policy->isRetryableMethod('GET')); + } } From 17c163ae3a88adf57daab2e4badb2fc82ff7646a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammet=20=C5=9Eafak?= Date: Tue, 24 Nov 2026 09:38:02 +0300 Subject: [PATCH 2/2] fix(client): keep retry gate failures inside PSR-18 and align retry docs Reading the method or body of a request while deciding whether it may be replayed could leak a raw exception when a policy was attached; such a request is now sent once and fails as a RequestException, as without a policy. Also document that maxDelay caps Retry-After in the RetryPolicy docblocks, correct the CHANGELOG migration recipe and the README comment. --- CHANGELOG.md | 2 +- README.md | 5 +-- docs/Client-Configuration.md | 2 +- src/Client/Client.php | 21 +++++++++++- src/Client/Retry/RetryPolicy.php | 12 ++++--- tests/Unit/Client/Retry/ClientRetryTest.php | 37 +++++++++++++++++++++ 6 files changed, 70 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fcd88b..5fa27bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed (breaking) -- **`RetryPolicy` retries only idempotent methods by default** (RFC 9110 §9.2.2: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`). A `POST` or `PATCH` request is now sent once, even when a policy is attached. To restore the old behaviour, or to retry them deliberately, pass the new last constructor argument `retryableMethods`, for example `new RetryPolicy(retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST'])`. New API: `RetryPolicy::DEFAULT_RETRYABLE_METHODS`, `getRetryableMethods()`, `isRetryableMethod()`. +- **`RetryPolicy` retries only idempotent methods by default** (RFC 9110 §9.2.2: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`). A `POST` or `PATCH` request is now sent once, even when a policy is attached. To retry them deliberately, pass the new last constructor argument `retryableMethods`, for example `new RetryPolicy(retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST', 'PATCH'])`. The list opens only the methods it names: the old behaviour (every method, including custom ones such as `QUERY` or `PROPFIND`) is restored only by naming each of them. New API: `RetryPolicy::DEFAULT_RETRYABLE_METHODS`, `getRetryableMethods()`, `isRetryableMethod()`. ### Fixed diff --git a/README.md b/README.md index 6e3aa04..2254857 100644 --- a/README.md +++ b/README.md @@ -163,11 +163,12 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy( maxAttempts: 4, // 1 initial try + up to 3 retries baseDelay: 0.1, // first backoff interval, seconds multiplier: 2.0, // 0.1s, 0.2s, 0.4s, ... - maxDelay: 30.0, // cap on any single interval + maxDelay: 30.0, // cap on any single wait, Retry-After included jitter: 0.5, // up to 50% random reduction (anti thundering-herd) )); -// Every verb helper inherits the policy transparently. +// Every verb helper inherits the policy, but POST and PATCH are still sent +// once unless you list them in `retryableMethods` (see below). $response = $client->get('https://api.example.com/flaky'); ``` diff --git a/docs/Client-Configuration.md b/docs/Client-Configuration.md index 108c0fe..ace004b 100644 --- a/docs/Client-Configuration.md +++ b/docs/Client-Configuration.md @@ -114,7 +114,7 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy( maxAttempts: 4, // 1 initial try + up to 3 retries baseDelay: 0.1, // first backoff interval, seconds multiplier: 2.0, // 0.1s, 0.2s, 0.4s, ... - maxDelay: 30.0, // cap on any single interval + maxDelay: 30.0, // cap on any single wait, Retry-After included jitter: 0.5, // up to 50% random reduction )); ``` diff --git a/src/Client/Client.php b/src/Client/Client.php index d42e88a..42ccf1c 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -512,7 +512,7 @@ public function sendRequest(RequestInterface $request): ResponseInterface // that is not idempotent may already have been acted on by the server, // and a body that cannot be rewound would be re-sent empty. In both // cases the first outcome (response or exception) is the answer. - if (!$policy->isRetryableMethod($request->getMethod()) || !$request->getBody()->isSeekable()) { + if (!$this->isReplayable($policy, $request)) { return $this->transport($request); } @@ -545,6 +545,25 @@ public function sendRequest(RequestInterface $request): ResponseInterface } } + /** + * Whether $request may be sent more than once under $policy: its method + * is retryable and its body can be rewound. Any failure while reading + * those two accessors counts as "not replayable"; the single attempt that + * follows reports it as a {@see RequestException}, as PSR-18 requires. + * + * @param RetryPolicy $policy + * @param RequestInterface $request + * @return bool + */ + private function isReplayable(RetryPolicy $policy, RequestInterface $request): bool + { + try { + return $policy->isRetryableMethod($request->getMethod()) && $request->getBody()->isSeekable(); + } catch (\Throwable $e) { + return false; + } + } + /** * Resolve the delay before the next retry for a retryable *response*: * honour a parseable `Retry-After` header when the policy opts in (capped diff --git a/src/Client/Retry/RetryPolicy.php b/src/Client/Retry/RetryPolicy.php index 44eb6dc..131c947 100644 --- a/src/Client/Retry/RetryPolicy.php +++ b/src/Client/Retry/RetryPolicy.php @@ -61,7 +61,10 @@ final class RetryPolicy /** Multiplier applied to the delay after each failed attempt. */ private float $multiplier; - /** Hard upper bound, in seconds, on any single backoff interval. */ + /** + * Hard upper bound, in seconds, on any single wait: a backoff interval or a + * delay taken from a `Retry-After` header. + */ private float $maxDelay; /** @@ -86,7 +89,8 @@ final class RetryPolicy /** * Whether a `Retry-After` response header (when present and parseable on a - * retryable response) should override the computed backoff delay. + * retryable response) should override the computed backoff delay. The + * header's delay is still capped at {@see self::$maxDelay}. */ private bool $respectRetryAfter; @@ -101,11 +105,11 @@ final class RetryPolicy * @param int $maxAttempts Total attempts (>= 1). Clamped up to 1. * @param float $baseDelay First backoff interval in seconds (>= 0). * @param float $multiplier Per-attempt growth factor (>= 1.0). - * @param float $maxDelay Cap on any single interval in seconds (>= 0). + * @param float $maxDelay Cap on any single wait in seconds (>= 0), including a `Retry-After` delay. * @param float $jitter Jitter ratio in [0.0, 1.0]. * @param bool $retryOnException Retry on transport exceptions. * @param list|null $retryableStatusCodes Override the default transient status set. - * @param bool $respectRetryAfter Honour a `Retry-After` header when present. + * @param bool $respectRetryAfter Honour a `Retry-After` header when present (capped at $maxDelay). * @param list|null $retryableMethods Methods that may be retried (case-insensitive). * Null = {@see self::DEFAULT_RETRYABLE_METHODS}; add e.g. `'POST'` to opt in. */ diff --git a/tests/Unit/Client/Retry/ClientRetryTest.php b/tests/Unit/Client/Retry/ClientRetryTest.php index 074185d..55fb612 100644 --- a/tests/Unit/Client/Retry/ClientRetryTest.php +++ b/tests/Unit/Client/Retry/ClientRetryTest.php @@ -4,7 +4,9 @@ namespace InitPHP\HTTP\Tests\Unit\Client\Retry; +use InitPHP\HTTP\Client\Client; use InitPHP\HTTP\Client\Exceptions\NetworkException; +use InitPHP\HTTP\Client\Exceptions\RequestException; use InitPHP\HTTP\Client\Retry\RetryPolicy; use InitPHP\HTTP\Message\Request; use InitPHP\HTTP\Message\Response; @@ -436,6 +438,41 @@ public function testRequestWithSeekableBodyIsStillRetried(): void self::assertSame(2, $client->calls); } + public function testBodyAccessorFailureSurfacesAsRequestExceptionWithPolicyAttached(): void + { + // Without a policy the failure is reported as a RequestException (PSR-18); + // attaching a policy must not leak the raw exception instead. + $body = new class ('payload', null) extends Stream { + public function isSeekable(): bool + { + throw new \RuntimeException('cannot inspect the body'); + } + + public function __toString(): string + { + throw new \RuntimeException('cannot read the body'); + } + }; + $client = (new Client())->setRetryPolicy(new RetryPolicy(3, 0.0, 1.0, 1.0, 0.0)); + + $this->expectException(RequestException::class); + $client->sendRequest(new Request('PUT', 'http://127.0.0.1:1/resource', [], $body)); + } + + public function testMethodAccessorFailureSurfacesAsRequestExceptionWithPolicyAttached(): void + { + $request = new class ('GET', 'http://127.0.0.1:1/resource') extends Request { + public function getMethod(): string + { + throw new \RuntimeException('cannot read the method'); + } + }; + $client = (new Client())->setRetryPolicy(new RetryPolicy(3, 0.0, 1.0, 1.0, 0.0)); + + $this->expectException(RequestException::class); + $client->sendRequest($request); + } + /** * A readable stream that cannot be rewound: one end of a socket pair that * already holds the payload.