vendor/friendsofsymfony/http-cache/src/ProxyClient/HttpDispatcher.php line 99

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the FOSHttpCache package.
  4. *
  5. * (c) FriendsOfSymfony <http://friendsofsymfony.github.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 FOS\HttpCache\ProxyClient;
  11. use FOS\HttpCache\Exception\ExceptionCollection;
  12. use FOS\HttpCache\Exception\InvalidArgumentException;
  13. use FOS\HttpCache\Exception\InvalidUrlException;
  14. use FOS\HttpCache\Exception\MissingHostException;
  15. use FOS\HttpCache\Exception\ProxyResponseException;
  16. use FOS\HttpCache\Exception\ProxyUnreachableException;
  17. use Http\Client\Common\Plugin\ErrorPlugin;
  18. use Http\Client\Common\PluginClient;
  19. use Http\Client\Exception\HttpException;
  20. use Http\Client\Exception\NetworkException;
  21. use Http\Client\HttpAsyncClient;
  22. use Http\Discovery\HttpAsyncClientDiscovery;
  23. use Http\Discovery\UriFactoryDiscovery;
  24. use Http\Message\UriFactory;
  25. use Http\Promise\Promise;
  26. use Psr\Http\Message\RequestInterface;
  27. use Psr\Http\Message\UriInterface;
  28. /**
  29. * Queue and send HTTP requests with a Httplug asynchronous client.
  30. *
  31. * @author David Buchmann <mail@davidbu.ch>
  32. */
  33. class HttpDispatcher implements Dispatcher
  34. {
  35. /**
  36. * @var HttpAsyncClient
  37. */
  38. private $httpClient;
  39. /**
  40. * @var UriFactory
  41. */
  42. private $uriFactory;
  43. /**
  44. * Queued requests.
  45. *
  46. * @var RequestInterface[]
  47. */
  48. private $queue = [];
  49. /**
  50. * Caching proxy server host names or IP addresses.
  51. *
  52. * @var UriInterface[]
  53. */
  54. private $servers;
  55. /**
  56. * Application host name and optional base URL.
  57. *
  58. * @var UriInterface
  59. */
  60. private $baseUri;
  61. /**
  62. * If you specify a custom HTTP client, make sure that it converts HTTP
  63. * errors to exceptions.
  64. *
  65. * If your proxy server IPs can not be statically configured, extend this
  66. * class and overwrite getServers. Be sure to have some caching in
  67. * getServers.
  68. *
  69. * @param string[] $servers Caching proxy server hostnames or IP
  70. * addresses, including port if not port 80.
  71. * E.g. ['127.0.0.1:6081']
  72. * @param string $baseUri Default application hostname, optionally
  73. * including base URL, for purge and refresh
  74. * requests (optional). This is required if
  75. * you purge and refresh paths instead of
  76. * absolute URLs
  77. * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
  78. * client is supplied, a default one is created
  79. * @param UriFactory|null $uriFactory Factory for PSR-7 URIs. If not specified, a
  80. * default one is created
  81. */
  82. public function __construct(
  83. array $servers,
  84. $baseUri = '',
  85. ?HttpAsyncClient $httpClient = null,
  86. ?UriFactory $uriFactory = null
  87. ) {
  88. if (!$httpClient) {
  89. $httpClient = new PluginClient(
  90. HttpAsyncClientDiscovery::find(),
  91. [new ErrorPlugin()]
  92. );
  93. }
  94. $this->httpClient = $httpClient;
  95. $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
  96. $this->setServers($servers);
  97. $this->setBaseUri($baseUri);
  98. }
  99. public function invalidate(RequestInterface $invalidationRequest, $validateHost = true)
  100. {
  101. if ($validateHost && !$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
  102. throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
  103. }
  104. $signature = $this->getRequestSignature($invalidationRequest);
  105. if (isset($this->queue[$signature])) {
  106. return;
  107. }
  108. $this->queue[$signature] = $invalidationRequest;
  109. }
  110. public function flush()
  111. {
  112. $queue = $this->queue;
  113. $this->queue = [];
  114. /** @var Promise[] $promises */
  115. $promises = [];
  116. $exceptions = new ExceptionCollection();
  117. foreach ($queue as $request) {
  118. foreach ($this->fanOut($request) as $proxyRequest) {
  119. try {
  120. $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
  121. } catch (\Exception $e) {
  122. $exceptions->add(new InvalidArgumentException($e->getMessage(), $e->getCode(), $e));
  123. }
  124. }
  125. }
  126. foreach ($promises as $promise) {
  127. try {
  128. $promise->wait();
  129. } catch (HttpException $exception) {
  130. $exceptions->add(ProxyResponseException::proxyResponse($exception));
  131. } catch (NetworkException $exception) {
  132. $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
  133. } catch (\Exception $exception) {
  134. // @codeCoverageIgnoreStart
  135. $exceptions->add(new InvalidArgumentException($exception->getMessage(), $exception->getCode(), $exception));
  136. // @codeCoverageIgnoreEnd
  137. }
  138. }
  139. if (count($exceptions)) {
  140. throw $exceptions;
  141. }
  142. return count($queue);
  143. }
  144. /**
  145. * Get the list of servers to send invalidation requests to.
  146. *
  147. * @return UriInterface[]
  148. */
  149. protected function getServers()
  150. {
  151. return $this->servers;
  152. }
  153. /**
  154. * Duplicate a request for each caching server.
  155. *
  156. * @param RequestInterface $request The request to duplicate for each configured server
  157. *
  158. * @return RequestInterface[]
  159. */
  160. private function fanOut(RequestInterface $request)
  161. {
  162. $requests = [];
  163. $uri = $request->getUri();
  164. // If a base URI is configured, try to make partial invalidation
  165. // requests complete.
  166. if ($this->baseUri) {
  167. if ($uri->getHost()) {
  168. // Absolute URI: does it already have a scheme?
  169. if (!$uri->getScheme() && '' !== $this->baseUri->getScheme()) {
  170. $uri = $uri->withScheme($this->baseUri->getScheme());
  171. }
  172. } else {
  173. // Relative URI
  174. if ('' !== $this->baseUri->getHost()) {
  175. $uri = $uri->withHost($this->baseUri->getHost());
  176. }
  177. if ($this->baseUri->getPort()) {
  178. $uri = $uri->withPort($this->baseUri->getPort());
  179. }
  180. // Base path
  181. if ('' !== $this->baseUri->getPath()) {
  182. $path = $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
  183. $uri = $uri->withPath($path);
  184. }
  185. }
  186. }
  187. // Close connections to make sure invalidation (PURGE/BAN) requests
  188. // will not interfere with content (GET) requests.
  189. $request = $request->withUri($uri)->withHeader('Connection', 'Close');
  190. // Create a request to each caching proxy server
  191. foreach ($this->getServers() as $server) {
  192. $serverUri = $uri
  193. ->withScheme($server->getScheme())
  194. ->withHost($server->getHost())
  195. ->withPort($server->getPort());
  196. if ($userInfo = $server->getUserInfo()) {
  197. $userInfoParts = explode(':', $userInfo, 2);
  198. $serverUri = $serverUri
  199. ->withUserInfo($userInfoParts[0], $userInfoParts[1] ?? null);
  200. }
  201. $requests[] = $request->withUri($serverUri, true); // Preserve application Host header
  202. }
  203. return $requests;
  204. }
  205. /**
  206. * Set caching proxy server URI objects, validating them.
  207. *
  208. * @param string[] $servers Caching proxy proxy server hostnames or IP
  209. * addresses, including port if not port 80.
  210. * E.g. ['127.0.0.1:6081']
  211. *
  212. * @throws InvalidUrlException If server is invalid or contains URL
  213. * parts other than scheme, host, port
  214. */
  215. private function setServers(array $servers)
  216. {
  217. $this->servers = [];
  218. foreach ($servers as $server) {
  219. $this->servers[] = $this->filterUri($server, ['scheme', 'user', 'pass', 'host', 'port']);
  220. }
  221. }
  222. /**
  223. * Set application base URI that will be prefixed to relative purge and
  224. * refresh requests, and validate it.
  225. *
  226. * @param string $uriString Your application’s base URI
  227. *
  228. * @throws InvalidUrlException If the base URI is not a valid URI
  229. */
  230. private function setBaseUri($uriString = null)
  231. {
  232. if (!$uriString) {
  233. $this->baseUri = null;
  234. return;
  235. }
  236. $this->baseUri = $this->filterUri($uriString);
  237. }
  238. /**
  239. * Filter a URL.
  240. *
  241. * Prefix the URL with "http://" if it has no scheme, then check the URL
  242. * for validity. You can specify what parts of the URL are allowed.
  243. *
  244. * @param string $uriString
  245. * @param string[] $allowedParts Array of allowed URL parts (optional)
  246. *
  247. * @return UriInterface Filtered URI (with default scheme if there was no scheme)
  248. *
  249. * @throws InvalidUrlException If URL is invalid, the scheme is not http or
  250. * contains parts that are not expected
  251. */
  252. private function filterUri($uriString, array $allowedParts = [])
  253. {
  254. if (!is_string($uriString)) {
  255. throw new \InvalidArgumentException(sprintf(
  256. 'URI parameter must be a string, %s given',
  257. gettype($uriString)
  258. ));
  259. }
  260. // Creating a PSR-7 URI without scheme (with parse_url) results in the
  261. // original hostname to be seen as path. So first add a scheme if none
  262. // is given.
  263. if (false === strpos($uriString, '://')) {
  264. $uriString = sprintf('%s://%s', 'http', $uriString);
  265. }
  266. try {
  267. $uri = $this->uriFactory->createUri($uriString);
  268. } catch (\InvalidArgumentException $e) {
  269. throw InvalidUrlException::invalidUrl($uriString);
  270. }
  271. if (!$uri->getScheme()) {
  272. throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
  273. }
  274. if (count($allowedParts) > 0) {
  275. $parts = parse_url((string) $uri);
  276. $diff = array_diff(array_keys($parts), $allowedParts);
  277. if (count($diff) > 0) {
  278. throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
  279. }
  280. }
  281. return $uri;
  282. }
  283. /**
  284. * Build a request signature based on the request data. Unique for every different request, identical
  285. * for the same requests.
  286. *
  287. * This signature is used to avoid sending the same invalidation request twice.
  288. *
  289. * @param RequestInterface $request An invalidation request
  290. *
  291. * @return string A signature for this request
  292. */
  293. private function getRequestSignature(RequestInterface $request)
  294. {
  295. $headers = $request->getHeaders();
  296. ksort($headers);
  297. return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
  298. }
  299. }