Completed
Pull Request — master (#361)
by David
10:30
created

HttpDispatcher::getRequestSignature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
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
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 $baseUri;
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               $baseUri    Default application hostname, optionally
82
     *                                         including base URL, for purge and refresh
83
     *                                         requests (optional). This is required if
84
     *                                         you purge and refresh paths instead of
85
     *                                         absolute URLs
86
     * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
87
     *                                         client is supplied, a default one is created
88
     * @param UriFactory|null      $uriFactory Factory for PSR-7 URIs. If not specified, a
89
     *                                         default one is created
90
     */
91 38
    public function __construct(
92
        array $servers,
93
        $baseUri = '',
94
        HttpAsyncClient $httpClient = null,
95
        UriFactory $uriFactory = null
96
    ) {
97 38
        if (!$httpClient) {
98 26
            $httpClient = new PluginClient(
99 26
                HttpAsyncClientDiscovery::find(),
100 26
                [new ErrorPlugin()]
101 26
            );
102 26
        }
103 38
        $this->httpClient = $httpClient;
104 38
        $this->uriFactory = $uriFactory ?: UriFactoryDiscovery::find();
105
106 38
        $this->setServers($servers);
107 35
        $this->setBaseUri($baseUri);
108 34
    }
109
110
    /**
111
     * Queue invalidation request.
112
     *
113
     * @param RequestInterface $invalidationRequest
114
     * @param bool             $validateHost If false, do not validate that we either have a base
115 33
     *                                       uri or the invalidation request has a host set.
116
     */
117 33
    public function invalidate(RequestInterface $invalidationRequest, $validateHost = true)
118 1
    {
119
        if ($validateHost && !$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
120
            throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
121 32
        }
122
123 32
        $signature = $this->getRequestSignature($invalidationRequest);
124 1
125
        if (isset($this->queue[$signature])) {
126
            return;
127 32
        }
128 32
129
        $this->queue[$signature] = $invalidationRequest;
130
    }
131
132
    /**
133
     * Send all pending invalidation requests and make sure the requests have terminated and gather exceptions.
134
     *
135
     * @return int The number of cache invalidations performed per caching server
136
     *
137 33
     * @throws ExceptionCollection If any errors occurred during flush
138
     */
139 33
    public function flush()
140 33
    {
141
        $queue = $this->queue;
142 33
        $this->queue = [];
143
        /** @var Promise[] $promises */
144 33
        $promises = [];
145
146 33
        $exceptions = new ExceptionCollection();
147 32
148
        foreach ($queue as $request) {
149 32
            foreach ($this->fanOut($request) as $proxyRequest) {
150 32
                try {
151 1
                    $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
152
                } catch (\Exception $e) {
153 32
                    $exceptions->add(new InvalidArgumentException($e));
154 33
                }
155
            }
156 33
        }
157
158 32
        foreach ($promises as $promise) {
159 32
            try {
160 2
                $promise->wait();
161 4
            } catch (HttpException $exception) {
162 2
                $exceptions->add(ProxyResponseException::proxyResponse($exception));
163 2
            } catch (RequestException $exception) {
164
                $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
165
            } catch (\Exception $exception) {
166
                // @codeCoverageIgnoreStart
167
                $exceptions->add(new InvalidArgumentException($exception));
168 33
                // @codeCoverageIgnoreEnd
169
            }
170 33
        }
171 5
172
        if (count($exceptions)) {
173
            throw $exceptions;
174 31
        }
175
176
        return count($queue);
177
    }
178
179
    /**
180
     * Get the list of servers to send invalidation requests to.
181
     *
182 32
     * @return UriInterface[]
183
     */
184 32
    protected function getServers()
185
    {
186
        return $this->servers;
187
    }
188
189
    /**
190
     * Duplicate a request for each caching server.
191
     *
192
     * @param RequestInterface $request The request to duplicate for each configured server
193
     *
194 32
     * @return RequestInterface[]
195
     */
196 32
    private function fanOut(RequestInterface $request)
197
    {
198 32
        $requests = [];
199
200
        $uri = $request->getUri();
201
202 32
        // If a base URI is configured, try to make partial invalidation
203 30
        // requests complete.
204
        if ($this->baseUri) {
205 5
            if ($uri->getHost()) {
206 1
                // Absolute URI: does it already have a scheme?
207 1
                if (!$uri->getScheme() && $this->baseUri->getScheme() !== '') {
208 5
                    $uri = $uri->withScheme($this->baseUri->getScheme());
209
                }
210 25
            } else {
211 25
                // Relative URI
212 25
                if ($this->baseUri->getHost() !== '') {
213
                    $uri = $uri->withHost($this->baseUri->getHost());
214 25
                }
215 16
216 16
                if ($this->baseUri->getPort()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->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...
217
                    $uri = $uri->withPort($this->baseUri->getPort());
218
                }
219 25
220 1
                // Base path
221 1
                if ($this->baseUri->getPath() !== '') {
222 1
                    $path = $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
223
                    $uri = $uri->withPath($path);
224 30
                }
225
            }
226
        }
227
228 32
        // Close connections to make sure invalidation (PURGE/BAN) requests
229
        // will not interfere with content (GET) requests.
230
        $request = $request->withUri($uri)->withHeader('Connection', 'Close');
231 32
232 32
        // Create a request to each caching proxy server
233
        foreach ($this->getServers() as $server) {
234 32
            $requests[] = $request->withUri(
235 32
                $uri
236 32
                    ->withScheme($server->getScheme())
237
                    ->withHost($server->getHost())
238 32
                    ->withPort($server->getPort()),
239 32
                true    // Preserve application Host header
240
            );
241 32
        }
242
243
        return $requests;
244
    }
245
246
    /**
247
     * Set caching proxy server URI objects, validating them.
248
     *
249
     * @param string[] $servers Caching proxy proxy server hostnames or IP
250
     *                          addresses, including port if not port 80.
251
     *                          E.g. ['127.0.0.1:6081']
252
     *
253
     * @throws InvalidUrlException If server is invalid or contains URL
254 38
     *                             parts other than scheme, host, port
255
     */
256 38
    private function setServers(array $servers)
257 38
    {
258 38
        $this->servers = [];
259 35
        foreach ($servers as $server) {
260 35
            $this->servers[] = $this->filterUri($server, ['scheme', 'host', 'port']);
261
        }
262
    }
263
264
    /**
265
     * Set application base URI that will be prefixed to relative purge and
266
     * refresh requests, and validate it.
267
     *
268
     * @param string $uriString Your application’s base URI
269
     *
270 35
     * @throws InvalidUrlException If the base URI is not a valid URI
271
     */
272 35
    private function setBaseUri($uriString = null)
273 3
    {
274
        if (!$uriString) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uriString of type string|null is loosely compared to false; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
275 3
            $this->baseUri = null;
276
277
            return;
278 32
        }
279 31
280
        $this->baseUri = $this->filterUri($uriString);
281
    }
282
283
    /**
284
     * Filter a URL.
285
     *
286
     * Prefix the URL with "http://" if it has no scheme, then check the URL
287
     * for validity. You can specify what parts of the URL are allowed.
288
     *
289
     * @param string   $uriString
290
     * @param string[] $allowedParts Array of allowed URL parts (optional)
291
     *
292
     * @return UriInterface Filtered URI (with default scheme if there was no scheme)
293
     *
294
     * @throws InvalidUrlException If URL is invalid, the scheme is not http or
295 38
     *                             contains parts that are not expected
296
     */
297 38
    private function filterUri($uriString, array $allowedParts = [])
298 1
    {
299 1
        if (!is_string($uriString)) {
300 1
            throw new \InvalidArgumentException(sprintf(
301 1
                'URI parameter must be a string, %s given',
302
                gettype($uriString)
303
            ));
304
        }
305
306
        // Creating a PSR-7 URI without scheme (with parse_url) results in the
307 38
        // original hostname to be seen as path. So first add a scheme if none
308 34
        // is given.
309 34
        if (false === strpos($uriString, '://')) {
310
            $uriString = sprintf('%s://%s', 'http', $uriString);
311
        }
312 38
313 38
        try {
314 1
            $uri = $this->uriFactory->createUri($uriString);
315
        } catch (\InvalidArgumentException $e) {
316
            throw InvalidUrlException::invalidUrl($uriString);
317 37
        }
318 1
319
        if (!$uri->getScheme()) {
320
            throw InvalidUrlException::invalidUrl($uriString, 'empty scheme');
321 36
        }
322 36
323 36
        if (count($allowedParts) > 0) {
324 36
            $parts = parse_url((string) $uri);
325 1
            $diff = array_diff(array_keys($parts), $allowedParts);
326
            if (count($diff) > 0) {
327 35
                throw InvalidUrlException::invalidUrlParts($uriString, $allowedParts);
328
            }
329 35
        }
330
331
        return $uri;
332
    }
333
334
    /**
335
     * Build a request signature based on the request data. Unique for every different request, identical
336
     * for the same requests.
337
     *
338
     * This signature is used to avoid sending the same invalidation request twice.
339
     *
340
     * @param RequestInterface $request An invalidation request
341
     *
342 32
     * @return string A signature for this request
343
     */
344 32
    private function getRequestSignature(RequestInterface $request)
345 32
    {
346
        $headers = $request->getHeaders();
347 32
        ksort($headers);
348
349
        return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headers, true));
350
    }
351
}
352