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
4 changes: 4 additions & 0 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ Implements: `Psr\Http\Client\ClientInterface`.
| `getCurlOptions()` | `array` |
| `setRetryPolicy(?RetryPolicy) / withRetryPolicy(?RetryPolicy)` | `self` |
| `getRetryPolicy()` | `?RetryPolicy` |
| `setSleeper(SleeperInterface) / withSleeper(SleeperInterface)` | `self` |
| `setJitterRandomizer(?callable) / withJitterRandomizer(?callable)` | `self` |

The retry classes (`RetryPolicy`, `Backoff`, `RetryAfter`, `SleeperInterface`, `Sleeper`) are documented, with their signatures, on [Client Retry](Client-Retry.md).

## `Emitter\Emitter` — [page](Emitter.md)

Expand Down
2 changes: 2 additions & 0 deletions docs/Client-Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy(
- A parseable `Retry-After` header on a retryable response overrides the computed backoff 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.

Need a different policy (idempotency keys, circuit breakers, ...)? Wrap the client in your own loop instead:

```php
Expand Down
203 changes: 203 additions & 0 deletions docs/Client-Retry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
# Client Retry

The PSR-18 [`Client`](PSR-18-Client.md) is **single-attempt by default**. To retry *transient* failures automatically, attach a `RetryPolicy`. This page is the reference for the classes in `InitPHP\HTTP\Client\Retry`. The short version, with a usage example, is in [Client Configuration → Retries](Client-Configuration.md#retries).

```php
use InitPHP\HTTP\Client\Client;
use InitPHP\HTTP\Client\Retry\RetryPolicy;

$client = (new Client())->withRetryPolicy(new RetryPolicy(maxAttempts: 4));

$response = $client->get('https://api.example.com/reports');
```

## How a retry works

With a policy attached, `sendRequest()` runs this loop (the convenience methods such as `get()` and `post()` go through it too):

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 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.

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).

## `RetryPolicy`

`final class RetryPolicy` is an immutable description of *whether* and *how* to retry. Every argument has a default, so `new RetryPolicy()` is a working production policy.

```php
new RetryPolicy(
int $maxAttempts = 3,
float $baseDelay = 0.1,
float $multiplier = 2.0,
float $maxDelay = 30.0,
float $jitter = 0.5,
bool $retryOnException = true,
?array $retryableStatusCodes = null, // null = RetryPolicy::DEFAULT_RETRYABLE_STATUS
bool $respectRetryAfter = true,
)
```

| Parameter | Default | Meaning |
| --- | --- | --- |
| `maxAttempts` | `3` | **Total** attempts: the first try plus retries. `3` means at most 2 retries. Values below `1` are raised to `1`, which never retries. |
| `baseDelay` | `0.1` | Seconds to wait before the first retry. Negative values become `0`. |
| `multiplier` | `2.0` | Growth factor applied to the delay for each further retry. Values below `1.0` become `1.0`. |
| `maxDelay` | `30.0` | Cap, in seconds, on one backoff interval. Negative values become `0`. |
| `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. |

The default retryable set is the constant `RetryPolicy::DEFAULT_RETRYABLE_STATUS`: `408`, `425`, `429`, `500`, `502`, `503` and `504`.

```php
// Retry only on rate limiting and 503, and never on transport errors.
$policy = new RetryPolicy(
maxAttempts: 5,
retryOnException: false,
retryableStatusCodes: [429, 503],
);
```

### Methods

| Method | Returns | Description |
| --- | --- | --- |
| `getMaxAttempts()` | `int` | The (clamped) total number of attempts. |
| `getBaseDelay()` | `float` | The (clamped) base delay in seconds. |
| `getMultiplier()` | `float` | The (clamped) multiplier. |
| `getMaxDelay()` | `float` | The (clamped) maximum delay in seconds. |
| `getJitter()` | `float` | The (clamped) jitter ratio. |
| `isRetryOnException()` | `bool` | Whether network exceptions are retried. |
| `getRetryableStatusCodes()` | `list<int>` | The retryable status codes. |
| `isRespectRetryAfter()` | `bool` | Whether `Retry-After` is honoured. |
| `isRetryableStatus(int $statusCode)` | `bool` | Whether the status is in the retryable set (strict comparison). |
| `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`.

## `Backoff`

`final class Backoff` computes the wait between attempts. The client builds one per `sendRequest()` call; you only need it to inspect or test a policy.

```php
new Backoff(RetryPolicy $policy, ?callable $randomizer = null)
```

`$randomizer` is a `callable(): float` that returns a value in `[0, 1)`. By default it is a `mt_rand()`-based uniform source. Values outside `[0, 1]` are clamped.

| Method | Returns | Description |
| --- | --- | --- |
| `baseDelayFor(int $attempt)` | `float` | The capped delay in seconds **without** jitter. |
| `delayFor(int $attempt)` | `float` | The delay in seconds **with** jitter, the one the client waits. |

`$attempt` is 1-based: `1` is the wait before the second try. Values below `1` are treated as `1`.

The base delay grows geometrically and is capped:

```text
baseDelayFor(n) = min(maxDelay, baseDelay * multiplier ** (n - 1))
```

Jitter then lowers it by a random amount of up to `jitter` of its value, so `delayFor(n)` always lies in `[base * (1 - jitter), base]`. With `jitter` at `0.0`, or a base delay of `0`, `delayFor()` returns the base delay unchanged. Spreading retries this way keeps a fleet of clients that failed at the same moment from retrying in lockstep.

For `baseDelay: 1.0, multiplier: 2.0, maxDelay: 5.0, jitter: 0.5`:

| Attempt | `baseDelayFor()` | `delayFor()` range |
| --- | --- | --- |
| 1 | `1.0` | `0.5` to `1.0` |
| 2 | `2.0` | `1.0` to `2.0` |
| 3 | `4.0` | `2.0` to `4.0` |
| 4 | `5.0` (capped) | `2.5` to `5.0` |

Pin the random source to get repeatable numbers:

```php
use InitPHP\HTTP\Client\Retry\{Backoff, RetryPolicy};

$policy = new RetryPolicy(baseDelay: 1.0, multiplier: 2.0, maxDelay: 5.0, jitter: 0.5);
$backoff = new Backoff($policy, static fn (): float => 0.0);

$backoff->baseDelayFor(3); // 4.0
$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.

| Method | Description |
| --- | --- |
| `RetryAfter::fromResponse(ResponseInterface $response, ?int $now = null)` | Returns `null` when the header is absent; otherwise parses its value. |
| `RetryAfter::parse(string $value, ?int $now = null)` | Parses a raw header value. |

`$now` is the Unix timestamp used as "current time" for HTTP-dates and defaults to `time()`. It exists to make tests deterministic.

`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`.

```php
use InitPHP\HTTP\Client\Retry\RetryAfter;

RetryAfter::parse('120'); // 120.0
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.

## `SleeperInterface` and `Sleeper`

The client waits through a `SleeperInterface`, so tests do not have to wait for real time.

```php
interface SleeperInterface
{
public function sleep(float $seconds): void;
}
```

Implementations must treat zero and negative values as a no-op. The default, `final class Sleeper`, does exactly that and otherwise calls `usleep()`, converting seconds to microseconds.

Replace it with `setSleeper()` (in place) or `withSleeper()` (a clone), for instance to record the requested waits in a test:

```php
use InitPHP\HTTP\Client\Client;
use InitPHP\HTTP\Client\Retry\{RetryPolicy, SleeperInterface};

final class RecordingSleeper implements SleeperInterface
{
/** @var list<float> */
public array $waits = [];

public function sleep(float $seconds): void
{
$this->waits[] = $seconds;
}
}

$sleeper = new RecordingSleeper();

$client = (new Client())
->withRetryPolicy(new RetryPolicy(maxAttempts: 3))
->withSleeper($sleeper)
->withJitterRandomizer(static fn (): float => 0.0); // repeatable jitter
```

`setJitterRandomizer(?callable)` and `withJitterRandomizer(?callable)` forward the random source to the `Backoff` the client creates; `null` restores the default. These two seams, together with `setSleeper()`/`withSleeper()`, exist mainly for tests.

## See also

- [Client Configuration → Retries](Client-Configuration.md#retries): the short guide, plus a hand-written retry loop for policies this one cannot express.
- [PSR-18 Client](PSR-18-Client.md): `sendRequest()` and the convenience methods.
- [Client Exceptions](Client-Exceptions.md): which failures are network exceptions.
- [API Reference](API-Reference.md): the `Client` methods for the retry policy, sleeper and jitter source.
1 change: 1 addition & 0 deletions docs/PSR-18-Client.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ POST/PUT/PATCH/DELETE requests always set `CURLOPT_POSTFIELDS`, even when the bo
## See also

- [Configuration](Client-Configuration.md) — timeouts, user agent, raw `CURLOPT_*` overrides.
- [Client Retry](Client-Retry.md) — opt-in retries with exponential backoff and `Retry-After`.
- [Client Exceptions](Client-Exceptions.md) — the PSR-18 error contract.
- [Helpers](Helpers.md) — the `send_request()` global helper that auto-encodes arrays/objects.
- [Recipe — Proxying Requests](Recipe-Proxying-Requests.md) — incoming `ServerRequest` → outgoing `Request`.
77 changes: 70 additions & 7 deletions docs/Recipe-File-Upload.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,85 @@

## Server side: receiving uploads

Treat everything the client sends about a file as untrusted input: its name, its media type and its extension. The helper below stores an upload under a name the **server** generates, with an extension taken from an allow-list that is keyed by the type detected from the file's **content**.

```php
use Psr\Http\Message\UploadedFileInterface;

/**
* Stores one upload and returns the server-generated file name.
*
* @param array<string, string> $allowed Detected media type => extension to store it with.
*/
function storeUpload(UploadedFileInterface $file, string $directory, array $allowed, int $maxBytes): string
{
if ($file->getError() !== UPLOAD_ERR_OK) {
throw new \DomainException('Upload failed: error #' . $file->getError());
}
if ($file->getSize() === null) {
throw new \DomainException('The upload size is unknown.');
}
if ($file->getSize() > $maxBytes) {
throw new \DomainException('The upload is too large.');
}

// Detect the type from the bytes. getClientMediaType() is just a header the client chose.
// An upload built from a stream may have been read already, and a stream that cannot be
// rewound cannot be checked and then stored intact, so it is rejected rather than skipped.
$stream = $file->getStream();
if (!$stream->isSeekable()) {
throw new \DomainException('This upload cannot be inspected.');
}
$stream->rewind();
$head = $stream->read(8192);
$stream->rewind(); // moveTo() copies from the start; leave the stream there
$type = (new \finfo(FILEINFO_MIME_TYPE))->buffer($head);
if ($type === false || !isset($allowed[$type])) {
throw new \DomainException('This file type is not allowed.');
}

// Random name, extension from the allow-list. Nothing here comes from the client.
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$type];
$file->moveTo(rtrim($directory, '/') . '/' . $name);

return $name;
}
```

Use it on the request:

```php
use InitPHP\HTTP\Message\ServerRequest;

$request = ServerRequest::createFromGlobals();

$allowed = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'application/pdf' => 'pdf',
];

foreach ($request->getUploadedFiles() as $field => $file) {
if ($file instanceof \Psr\Http\Message\UploadedFileInterface) {
if ($file->getError() !== UPLOAD_ERR_OK) {
throw new \DomainException('Upload failed: error #' . $file->getError());
}
$file->moveTo('/var/www/uploads/' . bin2hex(random_bytes(8)) . '.bin');
$storedName = storeUpload($file, '/var/uploads', $allowed, 5 * 1024 * 1024);
// Save $storedName (and, if you need it, the original name as plain data) in your database.
}
}
```

See [UploadedFile](Uploaded-File.md) for the full `UPLOAD_ERR_*` error map.

### Why it is written this way

- **Never build the path from `getClientFilename()`.** The name is whatever the client sent. A value such as `shell.php` lets the client pick an extension your web server may execute, or overwrite an existing file with the same name; a path such as `../../public/index.php` can choose where the file lands. (PHP's own `$_FILES` handling strips directories from `name`, but a request built from another source may not, and the extension and overwrite risks remain.) A random name removes all of them.
- **Never trust `getClientMediaType()`.** It is the `Content-Type` the client declared for that part, so it can say `image/png` about anything. The helper reads the first bytes of the file and asks `finfo` instead. Detection by content is a safeguard, not a guarantee that a file is harmless: still store uploads in a directory your web server does not execute code from, ideally outside the document root, and serve them through your own handler.
- **The extension comes from the allow-list, not from the client.** A type that is not in `$allowed` is rejected, and an accepted type is always stored with the extension you mapped to it.
- **The original name is data, not a path.** If you want to show it to users later, keep it in your database and escape it on output.
- **The stream is rewound before and after the check.** An upload built from a stream may already have been read, and `moveTo()` copies from the start. Checking and storing the same bytes matters, so a stream that cannot be rewound is rejected instead of being checked partially. Uploads from `ServerRequest::createFromGlobals()` are backed by a file path and open a fresh stream on every `getStream()` call.
- **Size is checked too.** `$maxBytes` is your application limit. PHP's own `upload_max_filesize` and `post_max_size` still apply and surface as `UPLOAD_ERR_*` errors.

`finfo` needs the `fileinfo` extension, which is bundled with PHP and enabled by default.

## Nested file inputs

PHP represents inputs like `name="docs[parent][child]"` as parallel arrays of `tmp_name`, `size`, `error`, `name`, `type`. `ServerRequest::normalizeFiles()` walks the tree recursively and produces a matching tree of `UploadedFile` values:
Expand All @@ -40,7 +102,7 @@ $tree['docs']['exhibits']['a'] instanceof UploadedFileInterface; // true
$tree['docs']['exhibits']['b'] instanceof UploadedFileInterface; // true
```

Walk the tree with a small recursive helper:
Walk the tree with a small recursive helper, and store each file with the `storeUpload()` function from above:

```php
function walk(array $files, callable $sink): void {
Expand All @@ -53,9 +115,10 @@ function walk(array $files, callable $sink): void {
}
}

walk($tree, static function (\Psr\Http\Message\UploadedFileInterface $file) {
walk($tree, static function (\Psr\Http\Message\UploadedFileInterface $file) use ($allowed) {
if ($file->getError() === UPLOAD_ERR_OK) {
$file->moveTo('/uploads/' . $file->getClientFilename());
$storedName = storeUpload($file, '/var/uploads', $allowed, 5 * 1024 * 1024);
// Save $storedName in your database, otherwise nothing links the stored file to its owner.
}
});
```
Expand Down
1 change: 1 addition & 0 deletions docs/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
**PSR-18 Client**
- [Client](PSR-18-Client.md)
- [Configuration](Client-Configuration.md)
- [Retry & Backoff](Client-Retry.md)
- [Exceptions](Client-Exceptions.md)

**Emitter (SAPI)**
Expand Down
Loading