Middleware
Middleware is a step that every request of the client and its response pass through. It is the place for computed headers, token refresh and metrics.
The interface
use Flytachi\Winter\Cast\Message\CastRequest;
use Flytachi\Winter\Cast\Message\CastResponse;
use Flytachi\Winter\Cast\Middleware\CastMiddleware;
final class TimingMiddleware implements CastMiddleware
{
public function __construct(private Metrics $metrics) {}
public function process(CastRequest $request, callable $next): CastResponse
{
$start = hrtime(true);
$response = $next($request);
$this->metrics->observe($request->getUri()->getHost(), (hrtime(true) - $start) / 1e6);
return $response;
}
}
$client = $client->withMiddleware(new TimingMiddleware($metrics));$next($request) passes the request down the chain and returns the response. Middleware can
change the request before the call, the response after it, or not call $next at all and
return a response of its own.
A closure works instead of a class:
$client = $client->withMiddleware(
fn(CastRequest $request, callable $next) => $next($request->withHeader('X-Request-ID', $requestId)),
);Middleware always receives a CastRequest — even when the client was given a foreign PSR-7
request.
Order
$client->withMiddleware($a)->withMiddleware($b, $c);The one added first runs first: $a → $b → $c → network → $c → $b → $a.
withoutMiddleware(TimingMiddleware::class) removes middleware by class — handy in tests.
Middleware runs once per request. Retries and redirects happen inside the chain, closer to the network. The client’s default headers are already in the request when it reaches middleware.
Built-in
AuthMiddleware
use Flytachi\Winter\Cast\Middleware\AuthMiddleware;
AuthMiddleware::bearer($token); // Authorization: Bearer …
AuthMiddleware::bearer(fn() => $tokens->current()); // the token is fetched on every request
AuthMiddleware::basic($user, $password); // Authorization: Basic …
AuthMiddleware::header('X-Api-Key', $key); // a key in a header of its ownIf the request already has that header, the middleware leaves it alone. A header from
header() is marked as secret: it is hidden in dumps and not sent to another host on a
redirect.
A constant key is simpler to set on the client: withBearerToken() or withHeader().
AuthMiddleware is for a value that changes while the client lives.
HeadersMiddleware
Headers computed for every request:
use Flytachi\Winter\Cast\Middleware\HeadersMiddleware;
new HeadersMiddleware(fn(CastRequest $request) => [
'X-Request-ID' => bin2hex(random_bytes(8)),
'X-Signature' => $signer->sign($request),
]);
new HeadersMiddleware([$signer, 'headersFor']); // an object's methodThe headers are set on top of the request: same-name headers are replaced.
RefreshTokenMiddleware
On a 401 it gets a new token and sends the request again:
use Flytachi\Winter\Cast\Middleware\RefreshTokenMiddleware;
$client = $client
->withMiddleware(new RefreshTokenMiddleware(fn() => $tokens->refresh()))
->withMiddleware(AuthMiddleware::bearer(fn() => $tokens->current()));- the function gets the 401 response and returns a new token, or
nullwhen there is none — then the 401 is returned; - the request is sent again with all its headers and its body; a body that cannot be rewound is not sent twice;
maxRetries(1 by default) — how many times to try refreshing the token;- keeping the token for later requests is the job of your token store, as in the example.
Your own log format
The client’s logger writes one line per request (see Winter integration). If you need a format of your own, it is a few lines of middleware:
$client = $client->withMiddleware(function (CastRequest $request, callable $next) use ($logger) {
$response = $next($request);
$logger->info(sprintf(
'%s %s → %d in %.3f s (%d attempts)',
$request->getMethod(),
$request->getUri()->getHost(),
$response->getStatusCode(),
$response->info()->totalTime,
$response->info()->attempts,
));
return $response;
});