AmpHttpClient.php 7.0 KB

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