8000 [HttpClient] fix monitoring responses issued before reset() by nicolas-grekas · Pull Request #44625 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpClient] fix monitoring responses issued before reset() #44625

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 14, 2021
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: 2 additions & 2 deletions src/Symfony/Component/HttpClient/CurlHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,9 @@ public function stream($responses, float $timeout = null): ResponseStreamInterfa
throw new \TypeError(sprintf('"%s()" expects parameter 1 to be an iterable of CurlResponse objects, "%s" given.', __METHOD__, \is_object($responses) ? \get_class($responses) : \gettype($responses)));
}

if (\is_resource($this->multi->handle) || $this->multi->handle instanceof \CurlMultiHandle) {
if (\is_resource($mh = $this->multi->handles[0] ?? null) || $mh instanceof \CurlMultiHandle) {
$active = 0;
while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)) {
while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $active)) {
}
}

Expand Down
57 changes: 26 additions & 31 deletions src/Symfony/Component/HttpClient/Internal/CurlClientState.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
*/
final class CurlClientState extends ClientState
{
/** @var \CurlMultiHandle|resource */
public $handle;
/** @var array<\CurlMultiHandle|resource> */
public $handles = [];
/** @var PushedResponse[] */
public $pushedResponses = [];
/** @var DnsCache */
Expand All @@ -41,20 +41,20 @@ public function __construct(int $maxHostConnections, int $maxPendingPushes)
{
self::$curlVersion = self::$curlVersion ?? curl_version();

$this->handle = curl_multi_init();
array_unshift($this->handles, $mh = curl_multi_init());
$this->dnsCache = new DnsCache();
$this->maxHostConnections = $maxHostConnections;
$this->maxPendingPushes = $maxPendingPushes;

// Don't enable HTTP/1.1 pipelining: it forces responses to be sent in order
if (\defined('CURLPIPE_MULTIPLEX')) {
curl_multi_setopt($this->handle, \CURLMOPT_PIPELINING, \CURLPIPE_MULTIPLEX);
curl_multi_setopt($mh, \CURLMOPT_PIPELINING, \CURLPIPE_MULTIPLEX);
}
if (\defined('CURLMOPT_MAX_HOST_CONNECTIONS')) {
$maxHostConnections = curl_multi_setopt($this->handle, \CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX) ? 0 : $maxHostConnections;
$maxHostConnections = curl_multi_setopt($mh, \CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX) ? 0 : $maxHostConnections;
}
if (\defined('CURLMOPT_MAXCONNECTS') && 0 < $maxHostConnections) {
curl_multi_setopt($this->handle, \CURLMOPT_MAXCONNECTS, $maxHostConnections);
curl_multi_setopt($mh, \CURLMOPT_MAXCONNECTS, $maxHostConnections);
}

// Skip configuring HTTP/2 push when it's unsupported or buggy, see https://bugs.php.net/77535
Expand All @@ -67,45 +67,40 @@ public function __construct(int $maxHostConnections, int $maxPendingPushes)
return;
}

curl_multi_setopt($this->handle, \CURLMOPT_PUSHFUNCTION, function ($parent, $pushed, array $requestHeaders) use ($maxPendingPushes) {
return $this->handlePush($parent, $pushed, $requestHeaders, $maxPendingPushes);
// Clone to prevent a circular reference
$multi = clone $this;
$multi->handles = [$mh];
$multi->pushedResponses = &$this->pushedResponses;
$multi->logger = &$this->logger;
$multi->handlesActivity = &$this->handlesActivity;
$multi->openHandles = &$this->openHandles;
$multi->lastTimeout = &$this->lastTimeout;

curl_multi_setopt($mh, \CURLMOPT_PUSHFUNCTION, static function ($parent, $pushed, array $requestHeaders) use ($multi, $maxPendingPushes) {
return $multi->handlePush($parent, $pushed, $requestHeaders, $maxPendingPushes);
});
}

public function reset()
{
if ($this->logger) {
foreach ($this->pushedResponses as $url => $response) {
$this->logger->debug(sprintf('Unused pushed response: "%s"', $url));
foreach ($this->pushedResponses as $url => $response) {
$this->logger && $this->logger->debug(sprintf('Unused pushed response: "%s"', $url));

foreach ($this->handles as $mh) {
curl_multi_remove_handle($mh, $response->handle);
}
curl_close($response->handle);
}

$this->pushedResponses = [];
$this->dnsCache->evictions = $this->dnsCache->evictions ?: $this->dnsCache->removals;
$this->dnsCache->removals = $this->dnsCache->hostnames = [];

if (\is_resource($this->handle) || $this->handle instanceof \CurlMultiHandle) {
if (\defined('CURLMOPT_PUSHFUNCTION')) {
curl_multi_setopt($this->handle, \CURLMOPT_PUSHFUNCTION, null);
}

curl_multi_close($this->handle);
$this->__construct($this->maxHostConnections, $this->maxPendingPushes);
if (\defined('CURLMOPT_PUSHFUNCTION')) {
curl_multi_setopt($this->handles[0], \CURLMOPT_PUSHFUNCTION, null);
}
}

public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}

public function __destruct()
{
foreach ($this->openHandles as [$ch]) {
if (\is_resource($ch) || $ch instanceof \CurlHandle) {
curl_setopt($ch, \CURLOPT_VERBOSE, false);
}
}
$this->__construct($this->maxHostConnections, $this->maxPendingPushes);
}

private function handlePush($parent, $pushed, array $requestHeaders, int $maxPendingPushes): int
Expand Down
66 changes: 38 additions & 28 deletions src/Symfony/Component/HttpClient/Response/CurlResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public function __construct(CurlClientState $multi, $ch, array $options = null,
// Schedule the request in a non-blocking way
$multi->lastTimeout = null;
$multi->openHandles[$id] = [$ch, $options];
curl_multi_add_handle($multi->handle, $ch);
curl_multi_add_handle($multi->handles[0], $ch);

$this->canary = new Canary(static function () use ($ch, $multi, $id) {
unset($multi->openHandles[$id], $multi->handlesActivity[$id]);
Expand All @@ -160,7 +160,9 @@ public function __construct(CurlClientState $multi, $ch, array $options = null,
return;
}

curl_multi_remove_handle($multi->handle, $ch);
foreach ($multi->handles as $mh) {
curl_multi_remove_handle($mh, $ch);
}
curl_setopt_array($ch, [
\CURLOPT_NOPROGRESS => true,
\CURLOPT_PROGRESSFUNCTION => null,
Expand Down Expand Up @@ -242,7 +244,7 @@ public function __destruct()
*/
private static function schedule(self $response, array &$runningResponses): void
{
if (isset($runningResponses[$i = (int) $response->multi->handle])) {
if (isset($runningResponses[$i = (int) $response->multi->handles[0]])) {
$runningResponses[$i][1][$response->id] = $response;
} else {
$runningResponses[$i] = [$response->multi, [$response->id => $response]];
Expand Down Expand Up @@ -274,39 +276,47 @@ private static function perform(ClientState $multi, array &$responses = null): v

try {
self::$performing = true;
$active = 0;
while (\CURLM_CALL_MULTI_PERFORM === ($err = curl_multi_exec($multi->handle, $active))) {
}

if (\CURLM_OK !== $err) {
throw new TransportException(curl_multi_strerror($err));
}

while ($info = curl_multi_info_read($multi->handle)) {
if (\CURLMSG_DONE !== 8000 $info['msg']) {
continue;
foreach ($multi->handles as $i => $mh) {
$active = 0;
while (\CURLM_CALL_MULTI_PERFORM === ($err = curl_multi_exec($mh, $active))) {
}
$result = $info['result'];
$id = (int) $ch = $info['handle'];
$waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';

if (\in_array($result, [\CURLE_SEND_ERROR, \CURLE_RECV_ERROR, /*CURLE_HTTP2*/ 16, /*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
curl_multi_remove_handle($multi->handle, $ch);
$waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
curl_setopt($ch, \CURLOPT_FORBID_REUSE, true);
if (\CURLM_OK !== $err) {
throw new TransportException(curl_multi_strerror($err));
}

if (0 === curl_multi_add_handle($multi->handle, $ch)) {
while ($info = curl_multi_info_read($mh)) {
if (\CURLMSG_DONE !== $info['msg']) {
continue;
}
}
$result = $info['result'];
$id = (int) $ch = $info['handle'];
$waitFor = @curl_getinfo($ch, \CURLINFO_PRIVATE) ?: '_0';

if (\in_array($result, [\CURLE_SEND_ERROR, \CURLE_RECV_ERROR, /*CURLE_HTTP2*/ 16, /*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
curl_multi_remove_handle($mh, $ch);
$waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
curl_setopt($ch, \CURLOPT_PRIVATE, $waitFor);
curl_setopt($ch, \CURLOPT_FORBID_REUSE, true);

if (0 === curl_multi_add_handle($mh, $ch)) {
continue;
}
}

if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
$multi->handlesActivity[$id][] = new FirstChunk();
}

if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
$multi->handlesActivity[$id][] = new FirstChunk();
$multi->handlesActivity[$id][] = null;
$multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($result), curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
}

$multi->handlesActivity[$id][] = null;
$multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK, \CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch, \CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch, \CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(sprintf('%s for "%s".', curl_strerror($result), curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL)));
if (!$active && 0 < $i) {
curl_multi_close($mh);
unset($multi->handles[$i]);
}
}
} finally {
self::$performing = false;
Expand All @@ -325,7 +335,7 @@ private static function select(ClientState $multi, float $timeout): int
$timeout = min($timeout, 0.01);
}

return curl_multi_select($multi->handle, $timeout);
return curl_multi_select($multi->handles[array_key_last($multi->handles)], $timeout);
}

/**
Expand Down
15 changes: 13 additions & 2 deletions src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,20 @@ public function testHandleI 756B sReinitOnReset()
$r = new \ReflectionProperty($httpClient, 'multi');
$r->setAccessible(true);
$clientState = $r->getValue($httpClient);
$initialHandleId = (int) $clientState->handle;
$initialHandleId = (int) $clientState->handles[0];
$httpClient->reset();
self::assertNotSame($initialHandleId, (int) $clientState->handle);
self::assertNotSame($initialHandleId, (int) $clientState->handles[0]);
}

public function testProcessAfterReset()
{
$client = $this->getHttpClient(__FUNCTION__);

$response = $client->request('GET', 'http://127.0.0.1:8057/json');

$client->reset();

$this->assertSame(['application/json'], $response->getHeaders()['content-type']);
}

private function getVulcainClient(): CurlHttpClient
Expand Down
0