AmpHttpClient.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient;
  11. use Amp\CancelledException;
  12. use Amp\Http\Client\DelegateHttpClient;
  13. use Amp\Http\Client\InterceptedHttpClient;
  14. use Amp\Http\Client\PooledHttpClient;
  15. use Amp\Http\Client\Request;
  16. use Amp\Http\Tunnel\Http1TunnelConnector;
  17. use Amp\Promise;
  18. use Psr\Log\LoggerAwareInterface;
  19. use Psr\Log\LoggerAwareTrait;
  20. use Symfony\Component\HttpClient\Exception\TransportException;
  21. use Symfony\Component\HttpClient\Internal\AmpClientState;
  22. use Symfony\Component\HttpClient\Response\AmpResponse;
  23. use Symfony\Component\HttpClient\Response\ResponseStream;
  24. use Symfony\Contracts\HttpClient\HttpClientInterface;
  25. use Symfony\Contracts\HttpClient\ResponseInterface;
  26. use Symfony\Contracts\HttpClient\ResponseStreamInterface;
  27. use Symfony\Contracts\Service\ResetInterface;
  28. if (!interface_exists(DelegateHttpClient::class)) {
  29. throw new \LogicException('You cannot use "Symfony\Component\HttpClient\AmpHttpClient" as the "amphp/http-client" package is not installed. Try running "composer require amphp/http-client:^4.2.1".');
  30. }
  31. if (!interface_exists(Promise::class)) {
  32. throw new \LogicException('You cannot use "Symfony\Component\HttpClient\AmpHttpClient" as the installed "amphp/http-client" is not compatible with this version of "symfony/http-client". Try downgrading "amphp/http-client" to "^4.2.1".');
  33. }
  34. /**
  35. * A portable implementation of the HttpClientInterface contracts based on Amp's HTTP client.
  36. *
  37. * @author Nicolas Grekas <p@tchwork.com>
  38. */
  39. final class AmpHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
  40. {
  41. use HttpClientTrait;
  42. use LoggerAwareTrait;
  43. private array $defaultOptions = self::OPTIONS_DEFAULTS;
  44. private static array $emptyDefaults = self::OPTIONS_DEFAULTS;
  45. private $multi;
  46. /**
  47. * @param array $defaultOptions Default requests' options
  48. * @param callable $clientConfigurator A callable that builds a {@see DelegateHttpClient} from a {@see PooledHttpClient};
  49. * passing null builds an {@see InterceptedHttpClient} with 2 retries on failures
  50. * @param int $maxHostConnections The maximum number of connections to a single host
  51. * @param int $maxPendingPushes The maximum number of pushed responses to accept in the queue
  52. *
  53. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  54. */
  55. public function __construct(array $defaultOptions = [], callable $clientConfigurator = null, int $maxHostConnections = 6, int $maxPendingPushes = 50)
  56. {
  57. $this->defaultOptions['buffer'] = $this->defaultOptions['buffer'] ?? \Closure::fromCallable([__CLASS__, 'shouldBuffer']);
  58. if ($defaultOptions) {
  59. [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
  60. }
  61. $this->multi = new AmpClientState($clientConfigurator, $maxHostConnections, $maxPendingPushes, $this->logger);
  62. }
  63. /**
  64. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  65. *
  66. * {@inheritdoc}
  67. */
  68. public function request(string $method, string $url, array $options = []): ResponseInterface
  69. {
  70. [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
  71. $options['proxy'] = self::getProxy($options['proxy'], $url, $options['no_proxy']);
  72. if (null !== $options['proxy'] && !class_exists(Http1TunnelConnector::class)) {
  73. throw new \LogicException('You cannot use the "proxy" option as the "amphp/http-tunnel" package is not installed. Try running "composer require amphp/http-tunnel".');
  74. }
  75. if ($options['bindto']) {
  76. if (0 === strpos($options['bindto'], 'if!')) {
  77. throw new TransportException(__CLASS__.' cannot bind to network interfaces, use e.g. CurlHttpClient instead.');
  78. }
  79. if (0 === strpos($options['bindto'], 'host!')) {
  80. $options['bindto'] = substr($options['bindto'], 5);
  81. }
  82. }
  83. if (('' !== $options['body'] || 'POST' === $method || isset($options['normalized_headers']['content-length'])) && !isset($options['normalized_headers']['content-type'])) {
  84. $options['headers'][] = 'Content-Type: application/x-www-form-urlencoded';
  85. }
  86. if (!isset($options['normalized_headers']['user-agent'])) {
  87. $options['headers'][] = 'User-Agent: Symfony HttpClient/Amp';
  88. }
  89. if (0 < $options['max_duration']) {
  90. $options['timeout'] = min($options['max_duration'], $options['timeout']);
  91. }
  92. if ($options['resolve']) {
  93. $this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
  94. }
  95. if ($options['peer_fingerprint'] && !isset($options['peer_fingerprint']['pin-sha256'])) {
  96. throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.');
  97. }
  98. $request = new Request(implode('', $url), $method);
  99. if ($options['http_version']) {
  100. switch ((float) $options['http_version']) {
  101. case 1.0: $request->setProtocolVersions(['1.0']); break;
  102. case 1.1: $request->setProtocolVersions(['1.1', '1.0']); break;
  103. default: $request->setProtocolVersions(['2', '1.1', '1.0']); break;
  104. }
  105. }
  106. foreach ($options['headers'] as $v) {
  107. $h = explode(': ', $v, 2);
  108. $request->addHeader($h[0], $h[1]);
  109. }
  110. $request->setTcpConnectTimeout(1000 * $options['timeout']);
  111. $request->setTlsHandshakeTimeout(1000 * $options['timeout']);
  112. $request->setTransferTimeout(1000 * $options['max_duration']);
  113. if (method_exists($request, 'setInactivityTimeout')) {
  114. $request->setInactivityTimeout(0);
  115. }
  116. if ('' !== $request->getUri()->getUserInfo() && !$request->hasHeader('authorization')) {
  117. $auth = explode(':', $request->getUri()->getUserInfo(), 2);
  118. $auth = array_map('rawurldecode', $auth) + [1 => ''];
  119. $request->setHeader('Authorization', 'Basic '.base64_encode(implode(':', $auth)));
  120. }
  121. return new AmpResponse($this->multi, $request, $options, $this->logger);
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
  127. {
  128. if ($responses instanceof AmpResponse) {
  129. $responses = [$responses];
  130. }
  131. return new ResponseStream(AmpResponse::stream($responses, $timeout));
  132. }
  133. public function reset()
  134. {
  135. $this->multi->dnsCache = [];
  136. foreach ($this->multi->pushedResponses as $authority => $pushedResponses) {
  137. foreach ($pushedResponses as [$pushedUrl, $pushDeferred]) {
  138. $pushDeferred->fail(new CancelledException());
  139. if ($this->logger) {
  140. $this->logger->debug(sprintf('Unused pushed response: "%s"', $pushedUrl));
  141. }
  142. }
  143. }
  144. $this->multi->pushedResponses = [];
  145. }
  146. }