AmpHttpClient.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. public const OPTIONS_DEFAULTS = HttpClientInterface::OPTIONS_DEFAULTS + [
  44. 'crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
  45. ];
  46. /**
  47. * @var mixed[]
  48. */
  49. private $defaultOptions = self::OPTIONS_DEFAULTS;
  50. /**
  51. * @var mixed[]
  52. */
  53. private static $emptyDefaults = self::OPTIONS_DEFAULTS;
  54. /**
  55. * @var \Symfony\Component\HttpClient\Internal\AmpClientState
  56. */
  57. private $multi;
  58. /**
  59. * @param array $defaultOptions Default requests' options
  60. * @param callable|null $clientConfigurator A callable that builds a {@see DelegateHttpClient} from a {@see PooledHttpClient};
  61. * passing null builds an {@see InterceptedHttpClient} with 2 retries on failures
  62. * @param int $maxHostConnections The maximum number of connections to a single host
  63. * @param int $maxPendingPushes The maximum number of pushed responses to accept in the queue
  64. *
  65. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  66. */
  67. public function __construct($defaultOptions = [], $clientConfigurator = null, $maxHostConnections = 6, $maxPendingPushes = 50)
  68. {
  69. $this->defaultOptions['buffer'] = $this->defaultOptions['buffer'] ?? \Closure::fromCallable([self::class, 'shouldBuffer']);
  70. if ($defaultOptions) {
  71. [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
  72. }
  73. $this->multi = new AmpClientState($clientConfigurator, $maxHostConnections, $maxPendingPushes, $this->logger);
  74. }
  75. /**
  76. * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
  77. * @param string $method
  78. * @param string $url
  79. * @param mixed[] $options
  80. */
  81. public function request($method, $url, $options = [])
  82. {
  83. [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
  84. $options['proxy'] = self::getProxy($options['proxy'], $url, $options['no_proxy']);
  85. if (null !== $options['proxy'] && !class_exists(Http1TunnelConnector::class)) {
  86. 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".');
  87. }
  88. if ($options['bindto']) {
  89. if (strncmp($options['bindto'], 'if!', strlen('if!')) === 0) {
  90. throw new TransportException(__CLASS__.' cannot bind to network interfaces, use e.g. CurlHttpClient instead.');
  91. }
  92. if (strncmp($options['bindto'], 'host!', strlen('host!')) === 0) {
  93. $options['bindto'] = substr($options['bindto'], 5);
  94. }
  95. }
  96. if (('' !== $options['body'] || 'POST' === $method || isset($options['normalized_headers']['content-length'])) && !isset($options['normalized_headers']['content-type'])) {
  97. $options['headers'][] = 'Content-Type: application/x-www-form-urlencoded';
  98. }
  99. if (!isset($options['normalized_headers']['user-agent'])) {
  100. $options['headers'][] = 'User-Agent: Symfony HttpClient (Amp)';
  101. }
  102. if (0 < $options['max_duration']) {
  103. $options['timeout'] = min($options['max_duration'], $options['timeout']);
  104. }
  105. if ($options['resolve']) {
  106. $this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
  107. }
  108. if ($options['peer_fingerprint'] && !isset($options['peer_fingerprint']['pin-sha256'])) {
  109. throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.');
  110. }
  111. $request = new Request(implode('', $url), $method);
  112. if ($options['http_version']) {
  113. switch ((float) $options['http_version']) {
  114. case 1.0:
  115. $request->setProtocolVersions(['1.0']);
  116. break;
  117. case 1.1:
  118. $request->setProtocolVersions($request->setProtocolVersions(['1.1', '1.0']));
  119. break;
  120. default:
  121. $request->setProtocolVersions(['2', '1.1', '1.0']);
  122. break;
  123. }
  124. }
  125. foreach ($options['headers'] as $v) {
  126. $h = explode(': ', $v, 2);
  127. $request->addHeader($h[0], $h[1]);
  128. }
  129. $request->setTcpConnectTimeout(1000 * $options['timeout']);
  130. $request->setTlsHandshakeTimeout(1000 * $options['timeout']);
  131. $request->setTransferTimeout(1000 * $options['max_duration']);
  132. if (method_exists($request, 'setInactivityTimeout')) {
  133. $request->setInactivityTimeout(0);
  134. }
  135. if ('' !== $request->getUri()->getUserInfo() && !$request->hasHeader('authorization')) {
  136. $auth = explode(':', $request->getUri()->getUserInfo(), 2);
  137. $auth = array_map('rawurldecode', $auth) + [1 => ''];
  138. $request->setHeader('Authorization', 'Basic '.base64_encode(implode(':', $auth)));
  139. }
  140. return new AmpResponse($this->multi, $request, $options, $this->logger);
  141. }
  142. /**
  143. * @param \Symfony\Contracts\HttpClient\ResponseInterface|mixed[] $responses
  144. * @param float|null $timeout
  145. */
  146. public function stream($responses, $timeout = null)
  147. {
  148. if ($responses instanceof AmpResponse) {
  149. $responses = [$responses];
  150. }
  151. return new ResponseStream(AmpResponse::stream($responses, $timeout));
  152. }
  153. public function reset()
  154. {
  155. $this->multi->dnsCache = [];
  156. foreach ($this->multi->pushedResponses as $authority => $pushedResponses) {
  157. foreach ($pushedResponses as [$pushedUrl, $pushDeferred]) {
  158. $pushDeferred->fail(new CancelledException());
  159. ($logger = $this->logger) ? $logger->debug(sprintf('Unused pushed response: "%s"', $pushedUrl)) : null;
  160. }
  161. }
  162. $this->multi->pushedResponses = [];
  163. }
  164. }