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