Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]

### Fixed

- `RetryAfter` now follows RFC 9110 §10.2.3. Delay-seconds is only a run of ASCII digits, so `-5` no longer becomes a date (it was read as an offset of 18000 seconds), and `1.5` or relative words such as `tomorrow` and `now` are ignored (`null`, so the client falls back to its backoff). All three HTTP-date formats (IMF-fixdate, RFC 850 and asctime) are read as GMT; asctime used to be read in PHP's default time zone, which shifted the delay by the zone's offset. A date whose day name does not match its date (`Mon, 21 Oct 2015 ...`) is rejected, and the two-digit year of the RFC 850 form follows the RFC's 50-year rule instead of PHP's fixed 1970 pivot.
- A request is no longer retried while the client's cURL options set `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or `CURLOPT_READDATA`. The first attempt consumes that read source, so the retry sent an empty body; now the first response is returned, or the first exception is thrown.

### Documentation

- [Client Retry](docs/Client-Retry.md), Client Configuration, the README and the `RetryPolicy` docblock describe the stricter `Retry-After` parsing and the cURL read-source rule.

## [5.0.0] - 2026-11-25

### Changed (breaking)
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,9 @@ Behaviour and backward-compatibility:
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.
`retryableMethods`. A request whose body is not seekable, or whose client sets a cURL read source
(`CURLOPT_INFILE`, `CURLOPT_READFUNCTION`, `CURLOPT_READDATA`), 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, capped at `maxDelay`, unless you
disable it.
Expand Down
2 changes: 1 addition & 1 deletion docs/Client-Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ $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`).
- 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 request whose body is not seekable is sent once too, because a retry could not send the body again. The same holds while the client's cURL options set `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or `CURLOPT_READDATA`: that read source is used up by the first attempt.
- 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.

Expand Down
10 changes: 6 additions & 4 deletions docs/Client-Retry.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-Afte

### 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 retry sends the request again, so three 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.
- **A request on a client whose cURL options set a read source.** `CURLOPT_INFILE`, `CURLOPT_READFUNCTION` and `CURLOPT_READDATA` (the same option as `CURLOPT_INFILE` in ext-curl) make cURL read the body from a resource or a callback. The first attempt consumes it and it cannot be rewound, so a retry would send an empty body. While any of them is set through `setCurlOptions()`, the client sends each request once: the first response is returned, or the first exception is thrown. Clear the option (or use a client without it) to get retries back.

Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest.

Expand Down Expand Up @@ -148,7 +149,7 @@ $backoff->delayFor(3); // 2.0, the lower edge of the jitter range

## `RetryAfter`

`final class RetryAfter` reads the `Retry-After` response header (RFC 7231 §7.1.3). Both methods are static and return a delay in seconds as a `?float`; `null` means "no usable value", and the client then falls back to the backoff delay.
`final class RetryAfter` reads the `Retry-After` response header (RFC 9110 §10.2.3). Both methods are static and return a delay in seconds as a `?float`; `null` means "no usable value", and the client then falls back to the backoff delay.

| Method | Description |
| --- | --- |
Expand All @@ -160,8 +161,9 @@ $backoff->delayFor(3); // 2.0, the lower edge of the jitter range
`parse()` follows these rules, in order:

1. The value is trimmed. An empty string gives `null`.
2. A value made only of digits is a number of seconds: `'120'` gives `120.0`.
3. Anything else goes to `strtotime()`. If that fails, the result is `null`. Otherwise the result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`.
2. A value made only of ASCII digits (`^\d+$`) is a number of seconds: `'120'` gives `120.0`. A sign (`-5`, `+5`), a fraction (`1.5`) or an exponent (`1e3`) is not delay-seconds, and the value is not tried as a date either.
3. A value in one of the three HTTP-date formats of RFC 9110 §5.6.7 is a date: IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`), the obsolete RFC 850 form (`Sunday, 06-Nov-94 08:49:37 GMT`) and asctime (`Sun Nov 6 08:49:37 1994`). Every form is read as **GMT**; the PHP default time zone is never used, so the result does not depend on `date_default_timezone_set()` or `TZ`. In the RFC 850 form a two-digit year that would be more than 50 years ahead stands for the most recent past year with those digits. The result is the difference to `$now`, never below `0`, so a date in the past gives `0.0`. A date that does not exist (`31 Feb`) is `null`, and so is a date whose day name does not match it (`Mon, 21 Oct 2015 07:28:00 GMT` is a Wednesday). The day name must also use the form of its format: three letters in IMF-fixdate and asctime, the full name in RFC 850.
4. Anything else is `null`, including relative phrases such as `tomorrow`, `now` or `+1 hour`, and ISO 8601 or zoned dates. The client then uses the backoff delay.

```php
use InitPHP\HTTP\Client\Retry\RetryAfter;
Expand Down
32 changes: 27 additions & 5 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,17 @@
*/
class Client implements \Psr\Http\Client\ClientInterface
{
/**
* cURL options that make cURL read the request body from a resource or a
* callback instead of the PSR-7 stream. Such a source is consumed by the
* first attempt and cannot be rewound, so a request with any of them set
* is never retried. CURLOPT_READDATA is the same option number as
* CURLOPT_INFILE in ext-curl, so listing CURLOPT_INFILE covers both.
*
* @var list<int>
*/
private const NON_REPLAYABLE_CURL_OPTIONS = [\CURLOPT_INFILE, \CURLOPT_READFUNCTION];

protected string $userAgent = 'InitPHP HTTP PSR-18 Client cURL';

/**
Expand Down Expand Up @@ -510,8 +521,10 @@ public function sendRequest(RequestInterface $request): ResponseInterface

// 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.
// and a body that cannot be rewound (a PSR-7 stream that is not
// seekable, or a cURL read source set through CURLOPT_INFILE or
// CURLOPT_READFUNCTION) would be re-sent empty. In every case the
// first outcome (response or exception) is the answer.
if (!$this->isReplayable($policy, $request)) {
return $this->transport($request);
}
Expand Down Expand Up @@ -547,16 +560,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.
* is retryable, its body can be rewound and no cURL read source is
* configured (CURLOPT_INFILE, CURLOPT_READFUNCTION and CURLOPT_READDATA
* feed the body from a resource or callback that the first attempt has
* already consumed). Any failure while reading the request 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
{
foreach (self::NON_REPLAYABLE_CURL_OPTIONS as $option) {
if (\array_key_exists($option, $this->curlOptions)) {
return false;
}
}

try {
return $policy->isRetryableMethod($request->getMethod()) && $request->getBody()->isSeekable();
} catch (\Throwable $e) {
Expand Down
116 changes: 106 additions & 10 deletions src/Client/Retry/RetryAfter.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,33 @@

namespace InitPHP\HTTP\Client\Retry;

use DateTimeImmutable;
use DateTimeZone;
use Psr\Http\Message\ResponseInterface;

use function ctype_digit;
use function is_array;
use function max;
use function strtotime;
use function preg_match;
use function time;
use function trim;

/**
* Parses the `Retry-After` response header (RFC 7231 §7.1.3) into a delay in
* Parses the `Retry-After` response header (RFC 9110 §10.2.3) into a delay in
* seconds.
*
* The header takes one of two forms:
* - a non-negative integer number of seconds (`Retry-After: 120`), or
* - delay-seconds: one or more ASCII digits and nothing else
* (`Retry-After: 120`), or
* - an HTTP-date (`Retry-After: Wed, 21 Oct 2015 07:28:00 GMT`), from which
* the delay is the difference between that instant and "now".
* the delay is the difference between that instant and "now". All three
* HTTP-date formats of RFC 9110 §5.6.7 are accepted (IMF-fixdate, the
* obsolete RFC 850 form and asctime) and are always read as GMT; PHP's
* default time zone plays no part.
*
* Unparseable or absent headers yield `null`, leaving the caller free to fall
* back to its computed backoff. A past HTTP-date clamps to 0.
* Anything else (a negative or fractional number, a relative phrase such as
* `tomorrow`, an unparseable date) and an absent header yield `null`, leaving
* the caller free to fall back to its computed backoff. A past HTTP-date
* clamps to 0.
*/
final class RetryAfter
{
Expand Down Expand Up @@ -71,17 +79,105 @@ public static function parse(string $value, ?int $now = null): ?float
return null;
}

if (ctype_digit($value)) {
if (preg_match('/^\d+$/D', $value) === 1) {
return (float) $value;
}

$timestamp = strtotime($value);
if ($timestamp === false) {
$timestamp = self::parseHttpDate($value, $now);
if ($timestamp === null) {
return null;
}

$reference = $now ?? time();

return (float) max(0, $timestamp - $reference);
}

/**
* Parse an HTTP-date (RFC 9110 §5.6.7) into a Unix timestamp, reading it as
* GMT. Returns null when the value matches none of the three formats,
* names a date that does not exist (such as 31 February) or carries a day
* name that does not belong to its date (`Mon, 21 Oct 2015 ...` is a
* Wednesday).
*
* The day name is checked here instead of being left to
* DateTimeImmutable::createFromFormat(): its `D` and `l` tokens do not
* validate the name, they shift the date to the next such weekday.
*
* @param string $value
* @param int|null $now Reference "now" for the RFC 850 two-digit year rule.
* @return int|null
*/
private static function parseHttpDate(string $value, ?int $now): ?int
{
$utc = new DateTimeZone('UTC');

// IMF-fixdate: Sun, 06 Nov 1994 08:49:37 GMT
if (preg_match('/^([A-Z][a-z]{2}), (\d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2}) GMT$/D', $value, $m) === 1) {
$date = self::fromFormat('d M Y H:i:s', $m[2], $utc);

return self::hasWeekday($date, 'D', $m[1]) ? $date?->getTimestamp() : null;
}

// RFC 850 (obsolete): Sunday, 06-Nov-94 08:49:37 GMT
if (preg_match('/^([A-Z][a-z]{5,8}), (\d{2})-([A-Z][a-z]{2})-(\d{2}) (\d{2}:\d{2}:\d{2}) GMT$/D', $value, $m) === 1) {
// RFC 9110 §5.6.7: a two-digit year that would land more than 50
// years in the future stands for the most recent past year with
// the same last two digits. PHP's own `y` token uses a fixed 1970
// pivot instead, so the century is chosen here.
$limit = (new DateTimeImmutable('@' . ($now ?? time())))->modify('+50 years')->getTimestamp();
foreach (['20', '19'] as $century) {
$date = self::fromFormat('d-M-Y H:i:s', $m[2] . '-' . $m[3] . '-' . $century . $m[4] . ' ' . $m[5], $utc);
if ($date !== null && $date->getTimestamp() <= $limit) {
break;
}
}

return self::hasWeekday($date, 'l', $m[1]) ? $date?->getTimestamp() : null;
}

// asctime: Sun Nov 6 08:49:37 1994 (the day is space-padded)
if (preg_match('/^([A-Z][a-z]{2}) ([A-Z][a-z]{2}) ([ \d]\d) (\d{2}:\d{2}:\d{2}) (\d{4})$/D', $value, $m) === 1) {
$date = self::fromFormat('j M Y H:i:s', trim($m[3]) . ' ' . $m[2] . ' ' . $m[5] . ' ' . $m[4], $utc);

return self::hasWeekday($date, 'D', $m[1]) ? $date?->getTimestamp() : null;
}

return null;
}

/**
* Whether $date falls on the weekday named by $name. $token is the
* DateTimeInterface::format() token for the name's form: `D` for the
* three-letter abbreviation, `l` for the full name.
*
* @param DateTimeImmutable|null $date
* @param string $token
* @param string $name
* @return bool
*/
private static function hasWeekday(?DateTimeImmutable $date, string $token, string $name): bool
{
return $date !== null && $date->format($token) === $name;
}

/**
* Build a date from $value with $format in $zone, rejecting values that
* PHP would silently roll over (31 February, 25:00:00, ...).
*
* @param string $format
* @param string $value
* @param DateTimeZone $zone
* @return DateTimeImmutable|null
*/
private static function fromFormat(string $format, string $value, DateTimeZone $zone): ?DateTimeImmutable
{
$date = DateTimeImmutable::createFromFormat('!' . $format, $value, $zone);
$errors = DateTimeImmutable::getLastErrors();
if ($date === false || (is_array($errors) && ($errors['warning_count'] > 0 || $errors['error_count'] > 0))) {
return null;
}

return $date;
}
}
6 changes: 6 additions & 0 deletions src/Client/Retry/RetryPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
* 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.
*
* A request whose body cannot be sent twice is never retried, whatever the
* policy says: its first response is returned, or its first exception is
* thrown. That covers a body stream that is not seekable and a client whose
* cURL options set a read source (`CURLOPT_INFILE`, `CURLOPT_READFUNCTION` or
* `CURLOPT_READDATA`), because the first attempt consumes it.
*/
final class RetryPolicy
{
Expand Down
60 changes: 60 additions & 0 deletions tests/Unit/Client/Retry/ClientRetryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,66 @@ public function testRequestWithNonSeekableBodyIsNotRetriedOnException(): void
}
}

/**
* @return array<string, array{int, callable(): mixed}>
*/
public static function curlReadSources(): array
{
return [
'CURLOPT_INFILE' => [\CURLOPT_INFILE, static fn() => \fopen('php://memory', 'r+')],
'CURLOPT_READDATA' => [\CURLOPT_READDATA, static fn() => \fopen('php://memory', 'r+')],
'CURLOPT_READFUNCTION' => [\CURLOPT_READFUNCTION, static fn() => static fn($ch, $fd, $length) => ''],
];
}

/**
* @dataProvider curlReadSources
*/
public function testRequestWithCurlReadSourceIsSentOnceOnRetryableStatus(int $option, callable $value): void
{
$sleeper = new RecordingSleeper();
$client = new ScriptedClient([$this->response(503), $this->response(200)]);
$client->setSleeper($sleeper)
->setCurlOptions([$option => $value()])
->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0));

$response = $client->sendRequest(new Request('PUT', 'https://api.example.com/resource'));

self::assertSame(503, $response->getStatusCode(), 'the first response is returned');
self::assertSame(1, $client->calls);
self::assertCount(0, $sleeper->sleeps);
}

public function testRequestWithCurlReadSourceIsSentOnceOnTransportException(): void
{
$client = new ScriptedClient([$this->networkError(), $this->response(200)]);
$client->setSleeper(new RecordingSleeper())
->setCurlOptions([\CURLOPT_INFILE => \fopen('php://memory', 'r+')])
->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0));

try {
$client->sendRequest(new Request('PUT', 'https://api.example.com/resource'));
self::fail('The first transport exception must propagate.');
} catch (NetworkException $e) {
self::assertSame(1, $client->calls);
}
}

public function testClearingTheCurlReadSourceRestoresRetries(): void
{
$sleeper = new RecordingSleeper();
$client = new ScriptedClient([$this->response(503), $this->response(200)]);
$client->setSleeper($sleeper)
->setCurlOptions([\CURLOPT_INFILE => \fopen('php://memory', 'r+')])
->setCurlOptions([\CURLOPT_TIMEOUT => 5])
->setRetryPolicy(new RetryPolicy(3, 0.1, 2.0, 30.0, 0.0));

$response = $client->sendRequest(new Request('PUT', 'https://api.example.com/resource'));

self::assertSame(200, $response->getStatusCode());
self::assertSame(2, $client->calls);
}

public function testRequestWithSeekableBodyIsStillRetried(): void
{
$client = new ScriptedClient([$this->response(503), $this->response(200)]);
Expand Down
Loading
Loading