Completed
Pull Request — master (#444)
by Yanick
02:55
created

HttpDispatcher::fanOut()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 6
nop 1
dl 0
loc 35
ccs 17
cts 17
cp 1
crap 4
rs 9.36
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the FOSHttpCache package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.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 FOS\HttpCache\ProxyClient;
13
14
use FOS\HttpCache\Exception\ExceptionCollection;
15
use FOS\HttpCache\Exception\InvalidArgumentException;
16
use FOS\HttpCache\Exception\InvalidUrlException;
17
use FOS\HttpCache\Exception\MissingHostException;
18
use FOS\HttpCache\Exception\ProxyResponseException;
19
use FOS\HttpCache\Exception\ProxyUnreachableException;
20
use Http\Client\Common\Plugin\ErrorPlugin;
21
use Http\Client\Common\PluginClient;
22
use Http\Client\Exception\HttpException;
23
use Http\Client\Exception\RequestException;
24
use Http\Client\HttpAsyncClient;
25
use Http\Discovery\HttpAsyncClientDiscovery;
26
use Http\Discovery\UriFactoryDiscovery;
27
use Http\Message\UriFactory;
28
use Http\Promise\Promise;
29
use Psr\Http\Message\RequestInterface;
30
use Psr\Http\Message\UriInterface;
31
32
/**
33
 * Queue and send HTTP requests with a Httplug asynchronous client.
34
 *
35
 * @author David Buchmann <[email protected]>
36
 */
37
class HttpDispatcher implements Dispatcher
38
{
39
    /**
40
     * @var HttpAsyncClient
41
     */
42
    private $httpClient;
43
44
    /**
45
     * @var UriFactory
46
     */
47
    private $uriFactory;
48
49
    /**
50
     * Queued requests.
51
     *
52
     * @var RequestInterface[]
53
     */
54
    private $queue = [];
55
56
    /**
57
     * Caching proxy server host names or IP addresses.
58
     *
59
     * @var UriInterface[]
60
     */
61
    private $servers;
62
63
    /**
64
     * Application host name and optional base URL.
65
     *
66
     * @var UriInterface[]
67
     */
68
    private $baseUris;
69
70
    /**
71
     * If you specify a custom HTTP client, make sure that it converts HTTP
72
     * errors to exceptions.
73
     *
74
     * If your proxy server IPs can not be statically configured, extend this
75
     * class and overwrite getServers. Be sure to have some caching in
76
     * getServers.
77
     *
78
     * @param string[]             $servers    Caching proxy server hostnames or IP
79
     *                                         addresses, including port if not port 80.
80
     *                                         E.g. ['127.0.0.1:6081']
81
     * @param string|string[]      $baseUris   Default application hostnames, optionally
82
     *                                         including base URL, for purge and refresh
83
     *                                         requests (optional). At least one is required if
84
     *                                         you purge and refresh paths instead of
85
     *                                         absolute URLs. A request will be sent for each
86
     *                                         base URL.
87
     * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
88
     *                                         client is supplied, a default one is created
89
     * @param UriFactory|null      $uriFactory Factory for PSR-7 URIs. If not specified, a
90
     *                                         default one is created
91 38
     */
92
    public function __construct(
93
        array $servers,
94
        $baseUris = [],
95
        HttpAsyncClient $httpClient = null,
96
        UriFactory $uriFactory = null
97 38
    ) {
98 26
        if (!$httpClient) {
99 26
            $httpClient = new PluginClient(
100 26
                HttpAsyncClientDiscovery::find(),
101
                [new ErrorPlugin()]
102
            );
103 38
        }
104 38
        $this->httpClient = $httpClient;
105
        $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
106 38
107 35
        $this->setServers($servers);
108 34
109
        // Support both, a string or an array of strings (array_filter to kill empty base URLs)
110
        if (is_string($baseUris)) {
111
            if ('' === $baseUris) {
112
                $baseUris = [];
113
            } else {
114
                $baseUris = [$baseUris];
115
            }
116
        }
117
118 33
        if (!\is_array($baseUris)) {
119
            throw new \InvalidArgumentException(sprintf(
120 33
                'URI parameter must be either a string or an array of strings, %s given',
121 1
                gettype($baseUris)
122
            ));
123
        }
124 32
125
        $this->setBaseUris($baseUris);
126 32
    }
127 1
128
    /**
129
     * {@inheritdoc}
130 32
     */
131 32
    public function invalidate(RequestInterface $invalidationRequest, $validateHost = true)
132
    {
133
        if ($validateHost && 0 === \count($this->baseUris) && !$invalidationRequest->getUri()->getHost()) {
134
            throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
135
        }
136
137
        $signature = $this->getRequestSignature($invalidationRequest);
138
139
        if (isset($this->queue[$signature])) {
140 33
            return;
141
        }
142 33
143 33
        $this->queue[$signature] = $invalidationRequest;
144
    }
145 33
146
    /**
147 33
     * {@inheritdoc}
148
     */
149 33
    public function flush()
150 32
    {
151
        $queue = $this->queue;
152 32
        $this->queue = [];
153 1
        /** @var Promise[] $promises */
154 32
        $promises = [];
155
156
        $exceptions = new ExceptionCollection();
157
158
        foreach ($queue as $request) {
159 33
            foreach ($this->fanOut($request) as $proxyRequest) {
160
                try {
161 32
                    $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
162 4
                } catch (\Exception $e) {
163 2
                    $exceptions->add(new InvalidArgumentException($e));
164 2
                }
165 2
            }
166
        }
167
168
        foreach ($promises as $promise) {
169
            try {
170
                $promise->wait();
171
            } catch (HttpException $exception) {
172
                $exceptions->add(ProxyResponseException::proxyResponse($exception));
173 33
            } catch (RequestException $exception) {
174 5
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
175
            } catch (\Exception $exception) {
176
                // @codeCoverageIgnoreStart
177 31
                $exceptions->add(new InvalidArgumentException($exception));
178
                // @codeCoverageIgnoreEnd
179
            }
180
        }
181
182
        if (count($exceptions)) {
183
            throw $exceptions;
184
        }
185 32
186
        return count($queue);
187 32
    }
188
189
    /**
190
     * Get the list of servers to send invalidation requests to.
191
     *
192
     * @return UriInterface[]
193
     */
194
    protected function getServers()
195
    {
196
        return $this->servers;
197 32
    }
198
199 32
    /**
200
     * Duplicate a request for each caching server.
201 32
     *
202
     * @param RequestInterface $request The request to duplicate for each configured server
203
     *
204
     * @return RequestInterface[]
205 32
     */
206 30
    private function fanOut(RequestInterface $request)
207
    {
208 5
        $serverRequests = [];
209 5
210
        if (0 !== \count($this->baseUris)) {
211
            // If base URIs are configured, try to make partial invalidation
212
            // requests complete and send out a request for every base URI
213 25
            $requests = $this->requestToBaseUris($request);
214 25
        } else {
215
            /** @var RequestInterface[] $requests */
216
            $requests = [$request];
217 25
        }
218 16
219
        // Create all requests to each caching proxy server
220
        foreach ($requests as $request) {
221
222 25
            $uri = $request->getUri();
223 1
224 1
            // Close connections to make sure invalidation (PURGE/BAN) requests
225
            // will not interfere with content (GET) requests.
226
            $requests[] = $request->withUri($uri)->withHeader('Connection', 'Close');
227
228
            foreach ($this->getServers() as $server) {
229
                $serverRequests[] = $request->withUri(
230
                    $uri
231 32
                        ->withScheme($server->getScheme())
232
                        ->withHost($server->getHost())
233
                        ->withPort($server->getPort()),
234 32
                    true    // Preserve application Host header
235 32
                );
236
            }
237 32
        }
238 32
239 32
        return $serverRequests;
240 32
    }
241
242
    /**
243
     * Looks at a given request and returns an array of requests incorporating
244 32
     * every configured base URI.
245
     *
246
     * @param RequestInterface $request The request to modify for every configured base URI
247
     *
248
     * @return RequestInterface[]
249
     */
250
    private function requestToBaseUris(RequestInterface $request)
251
    {
252
        $requests = [];
253
254
        foreach ($this->baseUris as $baseUri) {
255
            $uri = $request->getUri();
256
257 38
            if ($uri->getHost()) {
258
                // Absolute URI: does it already have a scheme?
259 38
                if (!$uri->getScheme() && '' !== $baseUri->getScheme()) {
260 38
                    $uri = $uri->withScheme($baseUri->getScheme());
261 38
                }
262
            } else {
263 35
                // Relative URI
264
                if ('' !== $baseUri->getHost()) {
265
                    $uri = $uri->withHost($baseUri->getHost());
266
                }
267
268
                if ($baseUri->getPort()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $baseUri->getPort() of type null|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
269
                    $uri = $uri->withPort($baseUri->getPort());
270
                }
271
272
                // Base path
273 35
                if ('' !== $baseUri->getPath()) {
274
                    $path = $baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
275 35
                    $uri = $uri->withPath($path);
276 3
                }
277
            }
278 3
279
            $requests[] = $request->withUri($uri);
280
        }
281 32
282 31
        return $requests;
283
    }
284
285
    /**
286
     * Set caching proxy server URI objects, validating them.
287
     *
288
     * @param string[] $servers Caching proxy proxy server hostnames or IP
289
     *                          addresses, including port if not port 80.
290
     *                          E.g. ['127.0.0.1:6081']
291
     *
292
     * @throws InvalidUrlException If server is invalid or contains URL
293
     *                             parts other than scheme, host, port
294
     */
295
    private function setServers(array $servers)
296
    {
297
        $this->servers = [];
298 38
        foreach ($servers as $server) {
299
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
300 38
        }
301 1
    }
302 1
303 1
    /**
304
     * Set application base URI that will be prefixed to relative purge and
305
     * refresh requests, and validate it.
306
     *
307
     * @param array $baseUris Your application’s base URIs
308
     *
309
     * @throws InvalidUrlException If the base URI is not a valid URI
310 38
     */
311 34
    private function setBaseUris(array $baseUris = [])
312
    {
313
        if (0 === \count($baseUris)) {
314
            $this->baseUris = [];
315 38
316 1
            return;
317 1
        }
318
319
        foreach ($baseUris as $baseUri) {
320 37
            $this->baseUris[] = $this->filterUri($baseUri);
321 1
        }
322
    }
323
324 36
    /**
325 36
     * Filter a URL.
326 36
     *
327 36
     * Prefix the URL with "http://" if it has no scheme, then check the URL
328 1
     * for validity. You can specify what parts of the URL are allowed.
329
     *
330
     * @param string   $uriString
331
     * @param string[] $allowedParts Array of allowed URL parts (optional)
332 35
     *
333
     * @return UriInterface Filtered URI (with default scheme if there was no scheme)
334
     *
335
     * @throws InvalidUrlException If URL is invalid, the scheme is not http or
336
     *                             contains parts that are not expected
337
     */
338
    private function filterUri($uriString, array $allowedParts = [])
339
    {
340
        // Creating a PSR-7 URI without scheme (with parse_url) results in the
341
        // original hostname to be seen as path. So first add a scheme if none
342
        // is given.
343
        if (false === strpos($uriString, '://')) {
344
            $uriString = sprintf('%s://%s', 'http', $uriString);
345 32
        }
346
347 32
        try {
348 32
            $uri = $this->uriFactory->createUri($uriString);
349
        } catch (\InvalidArgumentException $e) {
350 32
            throw InvalidUrlException::invalidUrl($uriString);
351
        }
352
353
        if (!$uri->getScheme()) {
354
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
355
        }
356
357
        if (count($allowedParts) > 0) {
358
            $parts = parse_url((string) $uri);
359
            $diff = array_diff(array_keys($parts), $allowedParts);
360
            if (count($diff) > 0) {
361
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
362
            }
363
        }
364
365
        return $uri;
366
    }
367
368
    /**
369
     * Build a request signature based on the request data. Unique for every different request, identical
370
     * for the same requests.
371
     *
372
     * This signature is used to avoid sending the same invalidation request twice.
373
     *
374
     * @param RequestInterface $request An invalidation request
375
     *
376
     * @return string A signature for this request
377
     */
378
    private function getRequestSignature(RequestInterface $request)
379
    {
380
        $headers = $request->getHeaders();
381
        ksort($headers);
382
383
        return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
384
    }
385
}
386