This commit is contained in:
Javier Casares 2026-11-03 16:45:29 +00:00
commit 600aac43b6

View file

@ -105,10 +105,6 @@ final class StreamHandler
*/
private const DEFAULT_IDLE_TIMEOUT_MS = 60000;
private array $lastHeaders = [];
private ?float $lastDeadline = null;
private ?\Throwable $onStatsException = null;
private string $transportSharingMode;
@ -180,7 +176,7 @@ final class StreamHandler
// Sleep if there is a delay specified.
if (isset($options['delay'])) {
\usleep((int) ($options['delay'] * 1000));
Clock::sleep((int) ($options['delay'] * 1000));
}
$multiplex = $options['multiplex'] ?? null;
@ -234,11 +230,17 @@ final class StreamHandler
$request = $request->withHeader('Content-Length', (string) \strlen($body));
}
$deadline = null;
$stream = $this->createStream($request, $options, $body, $deadline);
$headers = \stream_get_meta_data($stream)['wrapper_data'];
return $this->createResponse(
$request,
$options,
$this->createStream($request, $options, $body),
$startTime
$stream,
\is_array($headers) ? $headers : [],
$startTime,
$deadline
);
} catch (\InvalidArgumentException $e) {
throw $e;
@ -392,13 +394,11 @@ final class StreamHandler
#[\SensitiveParameter]
array $options,
$stream,
?float $startTime
#[\SensitiveParameter]
array $hdrs,
?float $startTime,
?float $deadline
): PromiseInterface {
$hdrs = $this->lastHeaders;
$this->lastHeaders = [];
$deadline = $this->lastDeadline;
$this->lastDeadline = null;
try {
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
} catch (\Throwable $e) {
@ -408,8 +408,10 @@ final class StreamHandler
$canHaveBody = HeaderProcessor::responseCanHaveBody($request->getMethod(), $status);
$framingFailure = null;
$declaredLength = null;
$chunked = false;
try {
$declaredLength = HeaderProcessor::validateResponseFraming($request->getMethod(), $status, $headers);
$chunked = $canHaveBody && HeaderProcessor::parseTransferEncoding($headers);
if (empty($options['stream'])) {
HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength);
}
@ -417,26 +419,35 @@ final class StreamHandler
$framingFailure = $e;
}
if ($framingFailure === null) {
try {
$headers = $this->decodeChunkedResponse($headers, $stream, $canHaveBody);
} catch (\RuntimeException $e) {
$framingFailure = $e;
}
if ($chunked) {
HeaderProcessor::removeHeader('Transfer-Encoding', $headers);
} elseif (!$canHaveBody) {
$headers = self::removeChunkedTransferCoding($headers);
}
$streamFactory = self::requireStreamFactory($options[RequestOptions::STREAM_FACTORY] ?? new Psr7\HttpFactory());
$responseFactory = self::requireResponseFactory($options[RequestOptions::RESPONSE_FACTORY] ?? new Psr7\HttpFactory());
// Wrap the transport resource with the configured stream factory, and
// decorate buffered transfers with the deadline source before optional
// content decoding layers an InflateStream on top, so every read that
// pulls from the transport observes the deadline.
// decorate buffered transfers with the deadline source before framing
// and optional content decoding layer on top, so every read that pulls
// from the transport observes the deadline.
$resource = $stream;
$stream = $streamFactory->createStreamFromResource($stream);
if ($framingFailure === null && $deadline !== null && empty($options['stream'])) {
$stream = self::createDeadlineSource($stream, $resource, $deadline, $options);
}
if ($chunked || !empty($options['stream'])) {
$stream = new TransportStream($stream);
}
if ($chunked) {
$stream = new ChunkedBodyStream($stream);
} elseif (!empty($options['stream'])) {
$length = HeaderProcessor::contentLengthToInt($declaredLength);
if ($length !== null) {
$stream = new DeclaredLengthStream($stream, $length);
}
}
$encodedBody = null;
if ($framingFailure === null) {
@ -633,21 +644,15 @@ final class StreamHandler
}
/**
* Applies the HTTP wrapper's normal chunked-response handling.
* Removes Transfer-Encoding values that start with chunked from a response
* that cannot have a body, as PHP's HTTP wrapper did.
*
* @param array<string, string[]> $headers
* @param resource $stream
* @param bool $decodeBody Whether to attach the dechunk filter
*
* @return array<string, string[]>
*
* @throws \RuntimeException when the dechunk filter cannot be attached
*/
private function decodeChunkedResponse(array $headers, $stream, bool $decodeBody): array
private static function removeChunkedTransferCoding(array $headers): array
{
$decodedHeaders = $headers;
$decode = false;
foreach ($headers as $name => $values) {
if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) {
continue;
@ -655,33 +660,19 @@ final class StreamHandler
$remaining = [];
foreach ($values as $value) {
// Match PHP's legacy auto_decode prefix check so moving the
// filter does not change which responses are dechunked.
if (Psr7\Utils::caselessEquals(\substr($value, 0, 7), 'chunked')) {
$decode = true;
} else {
if (!Psr7\Utils::caselessEquals(\substr($value, 0, 7), 'chunked')) {
$remaining[] = $value;
}
}
if ($remaining === []) {
unset($decodedHeaders[$name]);
unset($headers[$name]);
} else {
$decodedHeaders[$name] = $remaining;
$headers[$name] = $remaining;
}
}
if (!$decode) {
return $headers;
}
if ($decodeBody) {
$this->createResource(static function () use ($stream) {
return \stream_filter_append($stream, 'dechunk', \STREAM_FILTER_READ);
});
}
return $decodedHeaders;
return $headers;
}
/**
@ -707,7 +698,7 @@ final class StreamHandler
$stream = $encodedBody;
}
$stream = new Psr7\InflateStream($stream);
$stream = new InflateBodyStream($stream, $encoding[0] === 'deflate');
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
// Remove content-encoding header
@ -745,7 +736,6 @@ final class StreamHandler
try {
// Buffered paths reject unrepresentable lengths before draining.
$declaredLength = HeaderProcessor::contentLengthToInt($declaredResponseBodyLength);
$declaredLength = $declaredLength !== null && $declaredLength > 0 ? $declaredLength : null;
$copyLimit = $encodedBody === null ? $declaredLength ?? -1 : -1;
try {
@ -857,12 +847,11 @@ final class StreamHandler
/**
* Decorates the transport stream so each buffered-body read observes the
* remaining wall-clock budget of the "timeout" request option, bounded
* by the "read_timeout" idle timeout when that is shorter. The transport
* is switched to non-blocking mode because filtered reads (chunked and
* compressed responses) otherwise block until a full buffer arrives,
* which would keep the deadline from being enforced between small pieces
* of data.
* remaining wall-clock budget of the "timeout" request option, bounded by
* the "read_timeout" idle timeout when that is shorter. The transport is
* switched to non-blocking mode because a blocking read waits for data up
* to the transport's own timeout, which would keep the deadline from being
* enforced while the server stalls.
*
* @param resource $resource
*/
@ -943,7 +932,8 @@ final class StreamHandler
RequestInterface $request,
#[\SensitiveParameter]
array $options,
string $body
string $body,
?float &$deadline
) {
// Report a stream-open failure against the request passed here, not the
// Connection: close clone built for the wire.
@ -1029,8 +1019,8 @@ final class StreamHandler
);
try {
$resource = $this->createResource(function () use ($uri, $contextResource, $idleTimeout, $timeout) {
$this->lastDeadline = $timeout > 0 ? Clock::now() + $timeout / 1000 : null;
$resource = $this->createResource(function () use ($uri, $contextResource, $idleTimeout, $timeout, &$deadline) {
$deadline = $timeout > 0 ? Clock::now() + $timeout / 1000 : null;
// Blank the from ini setting for the transfer so ambient
// configuration cannot leak into a From header; the wrapper
@ -1044,13 +1034,6 @@ final class StreamHandler
}
}
// PHP 8.5 deprecates the local $http_response_header variable.
if (function_exists('http_get_last_response_headers')) {
$http_response_header = \http_get_last_response_headers();
}
$this->lastHeaders = $http_response_header ?? [];
if (false === $resource) {
return false;
}