Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * This code is partially based on the Rack-Cache library by Ryan Tomayko,
|
Chris@0
|
9 * which is released under the MIT license.
|
Chris@0
|
10 * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
|
Chris@0
|
11 *
|
Chris@0
|
12 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
13 * file that was distributed with this source code.
|
Chris@0
|
14 */
|
Chris@0
|
15
|
Chris@0
|
16 namespace Symfony\Component\HttpKernel\HttpCache;
|
Chris@0
|
17
|
Chris@17
|
18 use Symfony\Component\HttpFoundation\Request;
|
Chris@17
|
19 use Symfony\Component\HttpFoundation\Response;
|
Chris@0
|
20 use Symfony\Component\HttpKernel\HttpKernelInterface;
|
Chris@0
|
21 use Symfony\Component\HttpKernel\TerminableInterface;
|
Chris@0
|
22
|
Chris@0
|
23 /**
|
Chris@0
|
24 * Cache provides HTTP caching.
|
Chris@0
|
25 *
|
Chris@0
|
26 * @author Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
27 */
|
Chris@0
|
28 class HttpCache implements HttpKernelInterface, TerminableInterface
|
Chris@0
|
29 {
|
Chris@0
|
30 private $kernel;
|
Chris@0
|
31 private $store;
|
Chris@0
|
32 private $request;
|
Chris@0
|
33 private $surrogate;
|
Chris@0
|
34 private $surrogateCacheStrategy;
|
Chris@17
|
35 private $options = [];
|
Chris@17
|
36 private $traces = [];
|
Chris@0
|
37
|
Chris@0
|
38 /**
|
Chris@0
|
39 * Constructor.
|
Chris@0
|
40 *
|
Chris@0
|
41 * The available options are:
|
Chris@0
|
42 *
|
Chris@0
|
43 * * debug: If true, the traces are added as a HTTP header to ease debugging
|
Chris@0
|
44 *
|
Chris@0
|
45 * * default_ttl The number of seconds that a cache entry should be considered
|
Chris@0
|
46 * fresh when no explicit freshness information is provided in
|
Chris@0
|
47 * a response. Explicit Cache-Control or Expires headers
|
Chris@0
|
48 * override this value. (default: 0)
|
Chris@0
|
49 *
|
Chris@0
|
50 * * private_headers Set of request headers that trigger "private" cache-control behavior
|
Chris@0
|
51 * on responses that don't explicitly state whether the response is
|
Chris@0
|
52 * public or private via a Cache-Control directive. (default: Authorization and Cookie)
|
Chris@0
|
53 *
|
Chris@0
|
54 * * allow_reload Specifies whether the client can force a cache reload by including a
|
Chris@0
|
55 * Cache-Control "no-cache" directive in the request. Set it to ``true``
|
Chris@0
|
56 * for compliance with RFC 2616. (default: false)
|
Chris@0
|
57 *
|
Chris@0
|
58 * * allow_revalidate Specifies whether the client can force a cache revalidate by including
|
Chris@0
|
59 * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
|
Chris@0
|
60 * for compliance with RFC 2616. (default: false)
|
Chris@0
|
61 *
|
Chris@0
|
62 * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
|
Chris@0
|
63 * Response TTL precision is a second) during which the cache can immediately return
|
Chris@0
|
64 * a stale response while it revalidates it in the background (default: 2).
|
Chris@0
|
65 * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
|
Chris@0
|
66 * extension (see RFC 5861).
|
Chris@0
|
67 *
|
Chris@0
|
68 * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
|
Chris@0
|
69 * the cache can serve a stale response when an error is encountered (default: 60).
|
Chris@0
|
70 * This setting is overridden by the stale-if-error HTTP Cache-Control extension
|
Chris@0
|
71 * (see RFC 5861).
|
Chris@0
|
72 */
|
Chris@17
|
73 public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
|
Chris@0
|
74 {
|
Chris@0
|
75 $this->store = $store;
|
Chris@0
|
76 $this->kernel = $kernel;
|
Chris@0
|
77 $this->surrogate = $surrogate;
|
Chris@0
|
78
|
Chris@0
|
79 // needed in case there is a fatal error because the backend is too slow to respond
|
Chris@17
|
80 register_shutdown_function([$this->store, 'cleanup']);
|
Chris@0
|
81
|
Chris@17
|
82 $this->options = array_merge([
|
Chris@0
|
83 'debug' => false,
|
Chris@0
|
84 'default_ttl' => 0,
|
Chris@17
|
85 'private_headers' => ['Authorization', 'Cookie'],
|
Chris@0
|
86 'allow_reload' => false,
|
Chris@0
|
87 'allow_revalidate' => false,
|
Chris@0
|
88 'stale_while_revalidate' => 2,
|
Chris@0
|
89 'stale_if_error' => 60,
|
Chris@17
|
90 ], $options);
|
Chris@0
|
91 }
|
Chris@0
|
92
|
Chris@0
|
93 /**
|
Chris@0
|
94 * Gets the current store.
|
Chris@0
|
95 *
|
Chris@17
|
96 * @return StoreInterface A StoreInterface instance
|
Chris@0
|
97 */
|
Chris@0
|
98 public function getStore()
|
Chris@0
|
99 {
|
Chris@0
|
100 return $this->store;
|
Chris@0
|
101 }
|
Chris@0
|
102
|
Chris@0
|
103 /**
|
Chris@0
|
104 * Returns an array of events that took place during processing of the last request.
|
Chris@0
|
105 *
|
Chris@0
|
106 * @return array An array of events
|
Chris@0
|
107 */
|
Chris@0
|
108 public function getTraces()
|
Chris@0
|
109 {
|
Chris@0
|
110 return $this->traces;
|
Chris@0
|
111 }
|
Chris@0
|
112
|
Chris@0
|
113 /**
|
Chris@0
|
114 * Returns a log message for the events of the last request processing.
|
Chris@0
|
115 *
|
Chris@0
|
116 * @return string A log message
|
Chris@0
|
117 */
|
Chris@0
|
118 public function getLog()
|
Chris@0
|
119 {
|
Chris@17
|
120 $log = [];
|
Chris@0
|
121 foreach ($this->traces as $request => $traces) {
|
Chris@0
|
122 $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
|
Chris@0
|
123 }
|
Chris@0
|
124
|
Chris@0
|
125 return implode('; ', $log);
|
Chris@0
|
126 }
|
Chris@0
|
127
|
Chris@0
|
128 /**
|
Chris@0
|
129 * Gets the Request instance associated with the master request.
|
Chris@0
|
130 *
|
Chris@0
|
131 * @return Request A Request instance
|
Chris@0
|
132 */
|
Chris@0
|
133 public function getRequest()
|
Chris@0
|
134 {
|
Chris@0
|
135 return $this->request;
|
Chris@0
|
136 }
|
Chris@0
|
137
|
Chris@0
|
138 /**
|
Chris@0
|
139 * Gets the Kernel instance.
|
Chris@0
|
140 *
|
Chris@0
|
141 * @return HttpKernelInterface An HttpKernelInterface instance
|
Chris@0
|
142 */
|
Chris@0
|
143 public function getKernel()
|
Chris@0
|
144 {
|
Chris@0
|
145 return $this->kernel;
|
Chris@0
|
146 }
|
Chris@0
|
147
|
Chris@0
|
148 /**
|
Chris@0
|
149 * Gets the Surrogate instance.
|
Chris@0
|
150 *
|
Chris@0
|
151 * @return SurrogateInterface A Surrogate instance
|
Chris@0
|
152 *
|
Chris@0
|
153 * @throws \LogicException
|
Chris@0
|
154 */
|
Chris@0
|
155 public function getSurrogate()
|
Chris@0
|
156 {
|
Chris@0
|
157 return $this->surrogate;
|
Chris@0
|
158 }
|
Chris@0
|
159
|
Chris@0
|
160 /**
|
Chris@0
|
161 * {@inheritdoc}
|
Chris@0
|
162 */
|
Chris@0
|
163 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
|
Chris@0
|
164 {
|
Chris@0
|
165 // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
|
Chris@0
|
166 if (HttpKernelInterface::MASTER_REQUEST === $type) {
|
Chris@17
|
167 $this->traces = [];
|
Chris@16
|
168 // Keep a clone of the original request for surrogates so they can access it.
|
Chris@16
|
169 // We must clone here to get a separate instance because the application will modify the request during
|
Chris@16
|
170 // the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
|
Chris@16
|
171 // and adding the X-Forwarded-For header, see HttpCache::forward()).
|
Chris@16
|
172 $this->request = clone $request;
|
Chris@0
|
173 if (null !== $this->surrogate) {
|
Chris@0
|
174 $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
|
Chris@0
|
175 }
|
Chris@0
|
176 }
|
Chris@0
|
177
|
Chris@17
|
178 $this->traces[$this->getTraceKey($request)] = [];
|
Chris@0
|
179
|
Chris@0
|
180 if (!$request->isMethodSafe(false)) {
|
Chris@0
|
181 $response = $this->invalidate($request, $catch);
|
Chris@0
|
182 } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
|
Chris@0
|
183 $response = $this->pass($request, $catch);
|
Chris@14
|
184 } elseif ($this->options['allow_reload'] && $request->isNoCache()) {
|
Chris@14
|
185 /*
|
Chris@14
|
186 If allow_reload is configured and the client requests "Cache-Control: no-cache",
|
Chris@14
|
187 reload the cache by fetching a fresh response and caching it (if possible).
|
Chris@14
|
188 */
|
Chris@14
|
189 $this->record($request, 'reload');
|
Chris@14
|
190 $response = $this->fetch($request, $catch);
|
Chris@0
|
191 } else {
|
Chris@0
|
192 $response = $this->lookup($request, $catch);
|
Chris@0
|
193 }
|
Chris@0
|
194
|
Chris@0
|
195 $this->restoreResponseBody($request, $response);
|
Chris@0
|
196
|
Chris@0
|
197 if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
|
Chris@0
|
198 $response->headers->set('X-Symfony-Cache', $this->getLog());
|
Chris@0
|
199 }
|
Chris@0
|
200
|
Chris@0
|
201 if (null !== $this->surrogate) {
|
Chris@0
|
202 if (HttpKernelInterface::MASTER_REQUEST === $type) {
|
Chris@0
|
203 $this->surrogateCacheStrategy->update($response);
|
Chris@0
|
204 } else {
|
Chris@0
|
205 $this->surrogateCacheStrategy->add($response);
|
Chris@0
|
206 }
|
Chris@0
|
207 }
|
Chris@0
|
208
|
Chris@0
|
209 $response->prepare($request);
|
Chris@0
|
210
|
Chris@0
|
211 $response->isNotModified($request);
|
Chris@0
|
212
|
Chris@0
|
213 return $response;
|
Chris@0
|
214 }
|
Chris@0
|
215
|
Chris@0
|
216 /**
|
Chris@0
|
217 * {@inheritdoc}
|
Chris@0
|
218 */
|
Chris@0
|
219 public function terminate(Request $request, Response $response)
|
Chris@0
|
220 {
|
Chris@0
|
221 if ($this->getKernel() instanceof TerminableInterface) {
|
Chris@0
|
222 $this->getKernel()->terminate($request, $response);
|
Chris@0
|
223 }
|
Chris@0
|
224 }
|
Chris@0
|
225
|
Chris@0
|
226 /**
|
Chris@0
|
227 * Forwards the Request to the backend without storing the Response in the cache.
|
Chris@0
|
228 *
|
Chris@0
|
229 * @param Request $request A Request instance
|
Chris@0
|
230 * @param bool $catch Whether to process exceptions
|
Chris@0
|
231 *
|
Chris@0
|
232 * @return Response A Response instance
|
Chris@0
|
233 */
|
Chris@0
|
234 protected function pass(Request $request, $catch = false)
|
Chris@0
|
235 {
|
Chris@0
|
236 $this->record($request, 'pass');
|
Chris@0
|
237
|
Chris@0
|
238 return $this->forward($request, $catch);
|
Chris@0
|
239 }
|
Chris@0
|
240
|
Chris@0
|
241 /**
|
Chris@0
|
242 * Invalidates non-safe methods (like POST, PUT, and DELETE).
|
Chris@0
|
243 *
|
Chris@0
|
244 * @param Request $request A Request instance
|
Chris@0
|
245 * @param bool $catch Whether to process exceptions
|
Chris@0
|
246 *
|
Chris@0
|
247 * @return Response A Response instance
|
Chris@0
|
248 *
|
Chris@0
|
249 * @throws \Exception
|
Chris@0
|
250 *
|
Chris@0
|
251 * @see RFC2616 13.10
|
Chris@0
|
252 */
|
Chris@0
|
253 protected function invalidate(Request $request, $catch = false)
|
Chris@0
|
254 {
|
Chris@0
|
255 $response = $this->pass($request, $catch);
|
Chris@0
|
256
|
Chris@0
|
257 // invalidate only when the response is successful
|
Chris@0
|
258 if ($response->isSuccessful() || $response->isRedirect()) {
|
Chris@0
|
259 try {
|
Chris@0
|
260 $this->store->invalidate($request);
|
Chris@0
|
261
|
Chris@0
|
262 // As per the RFC, invalidate Location and Content-Location URLs if present
|
Chris@17
|
263 foreach (['Location', 'Content-Location'] as $header) {
|
Chris@0
|
264 if ($uri = $response->headers->get($header)) {
|
Chris@17
|
265 $subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
|
Chris@0
|
266
|
Chris@0
|
267 $this->store->invalidate($subRequest);
|
Chris@0
|
268 }
|
Chris@0
|
269 }
|
Chris@0
|
270
|
Chris@0
|
271 $this->record($request, 'invalidate');
|
Chris@0
|
272 } catch (\Exception $e) {
|
Chris@0
|
273 $this->record($request, 'invalidate-failed');
|
Chris@0
|
274
|
Chris@0
|
275 if ($this->options['debug']) {
|
Chris@0
|
276 throw $e;
|
Chris@0
|
277 }
|
Chris@0
|
278 }
|
Chris@0
|
279 }
|
Chris@0
|
280
|
Chris@0
|
281 return $response;
|
Chris@0
|
282 }
|
Chris@0
|
283
|
Chris@0
|
284 /**
|
Chris@0
|
285 * Lookups a Response from the cache for the given Request.
|
Chris@0
|
286 *
|
Chris@0
|
287 * When a matching cache entry is found and is fresh, it uses it as the
|
Chris@0
|
288 * response without forwarding any request to the backend. When a matching
|
Chris@0
|
289 * cache entry is found but is stale, it attempts to "validate" the entry with
|
Chris@0
|
290 * the backend using conditional GET. When no matching cache entry is found,
|
Chris@0
|
291 * it triggers "miss" processing.
|
Chris@0
|
292 *
|
Chris@0
|
293 * @param Request $request A Request instance
|
Chris@14
|
294 * @param bool $catch Whether to process exceptions
|
Chris@0
|
295 *
|
Chris@0
|
296 * @return Response A Response instance
|
Chris@0
|
297 *
|
Chris@0
|
298 * @throws \Exception
|
Chris@0
|
299 */
|
Chris@0
|
300 protected function lookup(Request $request, $catch = false)
|
Chris@0
|
301 {
|
Chris@0
|
302 try {
|
Chris@0
|
303 $entry = $this->store->lookup($request);
|
Chris@0
|
304 } catch (\Exception $e) {
|
Chris@0
|
305 $this->record($request, 'lookup-failed');
|
Chris@0
|
306
|
Chris@0
|
307 if ($this->options['debug']) {
|
Chris@0
|
308 throw $e;
|
Chris@0
|
309 }
|
Chris@0
|
310
|
Chris@0
|
311 return $this->pass($request, $catch);
|
Chris@0
|
312 }
|
Chris@0
|
313
|
Chris@0
|
314 if (null === $entry) {
|
Chris@0
|
315 $this->record($request, 'miss');
|
Chris@0
|
316
|
Chris@0
|
317 return $this->fetch($request, $catch);
|
Chris@0
|
318 }
|
Chris@0
|
319
|
Chris@0
|
320 if (!$this->isFreshEnough($request, $entry)) {
|
Chris@0
|
321 $this->record($request, 'stale');
|
Chris@0
|
322
|
Chris@0
|
323 return $this->validate($request, $entry, $catch);
|
Chris@0
|
324 }
|
Chris@0
|
325
|
Chris@0
|
326 $this->record($request, 'fresh');
|
Chris@0
|
327
|
Chris@0
|
328 $entry->headers->set('Age', $entry->getAge());
|
Chris@0
|
329
|
Chris@0
|
330 return $entry;
|
Chris@0
|
331 }
|
Chris@0
|
332
|
Chris@0
|
333 /**
|
Chris@0
|
334 * Validates that a cache entry is fresh.
|
Chris@0
|
335 *
|
Chris@0
|
336 * The original request is used as a template for a conditional
|
Chris@0
|
337 * GET request with the backend.
|
Chris@0
|
338 *
|
Chris@0
|
339 * @param Request $request A Request instance
|
Chris@0
|
340 * @param Response $entry A Response instance to validate
|
Chris@0
|
341 * @param bool $catch Whether to process exceptions
|
Chris@0
|
342 *
|
Chris@0
|
343 * @return Response A Response instance
|
Chris@0
|
344 */
|
Chris@0
|
345 protected function validate(Request $request, Response $entry, $catch = false)
|
Chris@0
|
346 {
|
Chris@0
|
347 $subRequest = clone $request;
|
Chris@0
|
348
|
Chris@0
|
349 // send no head requests because we want content
|
Chris@0
|
350 if ('HEAD' === $request->getMethod()) {
|
Chris@0
|
351 $subRequest->setMethod('GET');
|
Chris@0
|
352 }
|
Chris@0
|
353
|
Chris@0
|
354 // add our cached last-modified validator
|
Chris@0
|
355 $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
|
Chris@0
|
356
|
Chris@0
|
357 // Add our cached etag validator to the environment.
|
Chris@0
|
358 // We keep the etags from the client to handle the case when the client
|
Chris@0
|
359 // has a different private valid entry which is not cached here.
|
Chris@17
|
360 $cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
|
Chris@0
|
361 $requestEtags = $request->getETags();
|
Chris@0
|
362 if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
|
Chris@0
|
363 $subRequest->headers->set('if_none_match', implode(', ', $etags));
|
Chris@0
|
364 }
|
Chris@0
|
365
|
Chris@0
|
366 $response = $this->forward($subRequest, $catch, $entry);
|
Chris@0
|
367
|
Chris@0
|
368 if (304 == $response->getStatusCode()) {
|
Chris@0
|
369 $this->record($request, 'valid');
|
Chris@0
|
370
|
Chris@0
|
371 // return the response and not the cache entry if the response is valid but not cached
|
Chris@0
|
372 $etag = $response->getEtag();
|
Chris@17
|
373 if ($etag && \in_array($etag, $requestEtags) && !\in_array($etag, $cachedEtags)) {
|
Chris@0
|
374 return $response;
|
Chris@0
|
375 }
|
Chris@0
|
376
|
Chris@0
|
377 $entry = clone $entry;
|
Chris@0
|
378 $entry->headers->remove('Date');
|
Chris@0
|
379
|
Chris@17
|
380 foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
|
Chris@0
|
381 if ($response->headers->has($name)) {
|
Chris@0
|
382 $entry->headers->set($name, $response->headers->get($name));
|
Chris@0
|
383 }
|
Chris@0
|
384 }
|
Chris@0
|
385
|
Chris@0
|
386 $response = $entry;
|
Chris@0
|
387 } else {
|
Chris@0
|
388 $this->record($request, 'invalid');
|
Chris@0
|
389 }
|
Chris@0
|
390
|
Chris@0
|
391 if ($response->isCacheable()) {
|
Chris@0
|
392 $this->store($request, $response);
|
Chris@0
|
393 }
|
Chris@0
|
394
|
Chris@0
|
395 return $response;
|
Chris@0
|
396 }
|
Chris@0
|
397
|
Chris@0
|
398 /**
|
Chris@14
|
399 * Unconditionally fetches a fresh response from the backend and
|
Chris@14
|
400 * stores it in the cache if is cacheable.
|
Chris@0
|
401 *
|
Chris@0
|
402 * @param Request $request A Request instance
|
Chris@14
|
403 * @param bool $catch Whether to process exceptions
|
Chris@0
|
404 *
|
Chris@0
|
405 * @return Response A Response instance
|
Chris@0
|
406 */
|
Chris@0
|
407 protected function fetch(Request $request, $catch = false)
|
Chris@0
|
408 {
|
Chris@0
|
409 $subRequest = clone $request;
|
Chris@0
|
410
|
Chris@0
|
411 // send no head requests because we want content
|
Chris@0
|
412 if ('HEAD' === $request->getMethod()) {
|
Chris@0
|
413 $subRequest->setMethod('GET');
|
Chris@0
|
414 }
|
Chris@0
|
415
|
Chris@0
|
416 // avoid that the backend sends no content
|
Chris@0
|
417 $subRequest->headers->remove('if_modified_since');
|
Chris@0
|
418 $subRequest->headers->remove('if_none_match');
|
Chris@0
|
419
|
Chris@0
|
420 $response = $this->forward($subRequest, $catch);
|
Chris@0
|
421
|
Chris@0
|
422 if ($response->isCacheable()) {
|
Chris@0
|
423 $this->store($request, $response);
|
Chris@0
|
424 }
|
Chris@0
|
425
|
Chris@0
|
426 return $response;
|
Chris@0
|
427 }
|
Chris@0
|
428
|
Chris@0
|
429 /**
|
Chris@0
|
430 * Forwards the Request to the backend and returns the Response.
|
Chris@0
|
431 *
|
Chris@14
|
432 * All backend requests (cache passes, fetches, cache validations)
|
Chris@14
|
433 * run through this method.
|
Chris@14
|
434 *
|
Chris@0
|
435 * @param Request $request A Request instance
|
Chris@0
|
436 * @param bool $catch Whether to catch exceptions or not
|
Chris@0
|
437 * @param Response $entry A Response instance (the stale entry if present, null otherwise)
|
Chris@0
|
438 *
|
Chris@0
|
439 * @return Response A Response instance
|
Chris@0
|
440 */
|
Chris@0
|
441 protected function forward(Request $request, $catch = false, Response $entry = null)
|
Chris@0
|
442 {
|
Chris@0
|
443 if ($this->surrogate) {
|
Chris@0
|
444 $this->surrogate->addSurrogateCapability($request);
|
Chris@0
|
445 }
|
Chris@0
|
446
|
Chris@0
|
447 // always a "master" request (as the real master request can be in cache)
|
Chris@17
|
448 $response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
|
Chris@0
|
449
|
Chris@0
|
450 // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
|
Chris@17
|
451 if (null !== $entry && \in_array($response->getStatusCode(), [500, 502, 503, 504])) {
|
Chris@0
|
452 if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
|
Chris@0
|
453 $age = $this->options['stale_if_error'];
|
Chris@0
|
454 }
|
Chris@0
|
455
|
Chris@0
|
456 if (abs($entry->getTtl()) < $age) {
|
Chris@0
|
457 $this->record($request, 'stale-if-error');
|
Chris@0
|
458
|
Chris@0
|
459 return $entry;
|
Chris@0
|
460 }
|
Chris@0
|
461 }
|
Chris@0
|
462
|
Chris@14
|
463 /*
|
Chris@14
|
464 RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate
|
Chris@14
|
465 clock MUST NOT send a "Date" header, although it MUST send one in most other cases
|
Chris@14
|
466 except for 1xx or 5xx responses where it MAY do so.
|
Chris@14
|
467
|
Chris@14
|
468 Anyway, a client that received a message without a "Date" header MUST add it.
|
Chris@14
|
469 */
|
Chris@14
|
470 if (!$response->headers->has('Date')) {
|
Chris@14
|
471 $response->setDate(\DateTime::createFromFormat('U', time()));
|
Chris@14
|
472 }
|
Chris@14
|
473
|
Chris@0
|
474 $this->processResponseBody($request, $response);
|
Chris@0
|
475
|
Chris@0
|
476 if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
|
Chris@0
|
477 $response->setPrivate();
|
Chris@0
|
478 } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
|
Chris@0
|
479 $response->setTtl($this->options['default_ttl']);
|
Chris@0
|
480 }
|
Chris@0
|
481
|
Chris@0
|
482 return $response;
|
Chris@0
|
483 }
|
Chris@0
|
484
|
Chris@0
|
485 /**
|
Chris@0
|
486 * Checks whether the cache entry is "fresh enough" to satisfy the Request.
|
Chris@0
|
487 *
|
Chris@0
|
488 * @return bool true if the cache entry if fresh enough, false otherwise
|
Chris@0
|
489 */
|
Chris@0
|
490 protected function isFreshEnough(Request $request, Response $entry)
|
Chris@0
|
491 {
|
Chris@0
|
492 if (!$entry->isFresh()) {
|
Chris@0
|
493 return $this->lock($request, $entry);
|
Chris@0
|
494 }
|
Chris@0
|
495
|
Chris@0
|
496 if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
|
Chris@0
|
497 return $maxAge > 0 && $maxAge >= $entry->getAge();
|
Chris@0
|
498 }
|
Chris@0
|
499
|
Chris@0
|
500 return true;
|
Chris@0
|
501 }
|
Chris@0
|
502
|
Chris@0
|
503 /**
|
Chris@0
|
504 * Locks a Request during the call to the backend.
|
Chris@0
|
505 *
|
Chris@0
|
506 * @return bool true if the cache entry can be returned even if it is staled, false otherwise
|
Chris@0
|
507 */
|
Chris@0
|
508 protected function lock(Request $request, Response $entry)
|
Chris@0
|
509 {
|
Chris@0
|
510 // try to acquire a lock to call the backend
|
Chris@0
|
511 $lock = $this->store->lock($request);
|
Chris@0
|
512
|
Chris@14
|
513 if (true === $lock) {
|
Chris@14
|
514 // we have the lock, call the backend
|
Chris@14
|
515 return false;
|
Chris@14
|
516 }
|
Chris@14
|
517
|
Chris@0
|
518 // there is already another process calling the backend
|
Chris@0
|
519
|
Chris@14
|
520 // May we serve a stale response?
|
Chris@14
|
521 if ($this->mayServeStaleWhileRevalidate($entry)) {
|
Chris@14
|
522 $this->record($request, 'stale-while-revalidate');
|
Chris@0
|
523
|
Chris@0
|
524 return true;
|
Chris@0
|
525 }
|
Chris@0
|
526
|
Chris@14
|
527 // wait for the lock to be released
|
Chris@14
|
528 if ($this->waitForLock($request)) {
|
Chris@14
|
529 // replace the current entry with the fresh one
|
Chris@14
|
530 $new = $this->lookup($request);
|
Chris@14
|
531 $entry->headers = $new->headers;
|
Chris@14
|
532 $entry->setContent($new->getContent());
|
Chris@14
|
533 $entry->setStatusCode($new->getStatusCode());
|
Chris@14
|
534 $entry->setProtocolVersion($new->getProtocolVersion());
|
Chris@14
|
535 foreach ($new->headers->getCookies() as $cookie) {
|
Chris@14
|
536 $entry->headers->setCookie($cookie);
|
Chris@14
|
537 }
|
Chris@14
|
538 } else {
|
Chris@14
|
539 // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
|
Chris@14
|
540 $entry->setStatusCode(503);
|
Chris@14
|
541 $entry->setContent('503 Service Unavailable');
|
Chris@14
|
542 $entry->headers->set('Retry-After', 10);
|
Chris@14
|
543 }
|
Chris@14
|
544
|
Chris@14
|
545 return true;
|
Chris@0
|
546 }
|
Chris@0
|
547
|
Chris@0
|
548 /**
|
Chris@0
|
549 * Writes the Response to the cache.
|
Chris@0
|
550 *
|
Chris@0
|
551 * @throws \Exception
|
Chris@0
|
552 */
|
Chris@0
|
553 protected function store(Request $request, Response $response)
|
Chris@0
|
554 {
|
Chris@0
|
555 try {
|
Chris@0
|
556 $this->store->write($request, $response);
|
Chris@0
|
557
|
Chris@0
|
558 $this->record($request, 'store');
|
Chris@0
|
559
|
Chris@0
|
560 $response->headers->set('Age', $response->getAge());
|
Chris@0
|
561 } catch (\Exception $e) {
|
Chris@0
|
562 $this->record($request, 'store-failed');
|
Chris@0
|
563
|
Chris@0
|
564 if ($this->options['debug']) {
|
Chris@0
|
565 throw $e;
|
Chris@0
|
566 }
|
Chris@0
|
567 }
|
Chris@0
|
568
|
Chris@0
|
569 // now that the response is cached, release the lock
|
Chris@0
|
570 $this->store->unlock($request);
|
Chris@0
|
571 }
|
Chris@0
|
572
|
Chris@0
|
573 /**
|
Chris@0
|
574 * Restores the Response body.
|
Chris@0
|
575 */
|
Chris@0
|
576 private function restoreResponseBody(Request $request, Response $response)
|
Chris@0
|
577 {
|
Chris@0
|
578 if ($response->headers->has('X-Body-Eval')) {
|
Chris@0
|
579 ob_start();
|
Chris@0
|
580
|
Chris@0
|
581 if ($response->headers->has('X-Body-File')) {
|
Chris@0
|
582 include $response->headers->get('X-Body-File');
|
Chris@0
|
583 } else {
|
Chris@0
|
584 eval('; ?>'.$response->getContent().'<?php ;');
|
Chris@0
|
585 }
|
Chris@0
|
586
|
Chris@0
|
587 $response->setContent(ob_get_clean());
|
Chris@0
|
588 $response->headers->remove('X-Body-Eval');
|
Chris@0
|
589 if (!$response->headers->has('Transfer-Encoding')) {
|
Chris@17
|
590 $response->headers->set('Content-Length', \strlen($response->getContent()));
|
Chris@0
|
591 }
|
Chris@0
|
592 } elseif ($response->headers->has('X-Body-File')) {
|
Chris@14
|
593 // Response does not include possibly dynamic content (ESI, SSI), so we need
|
Chris@14
|
594 // not handle the content for HEAD requests
|
Chris@14
|
595 if (!$request->isMethod('HEAD')) {
|
Chris@14
|
596 $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
|
Chris@14
|
597 }
|
Chris@0
|
598 } else {
|
Chris@0
|
599 return;
|
Chris@0
|
600 }
|
Chris@0
|
601
|
Chris@0
|
602 $response->headers->remove('X-Body-File');
|
Chris@0
|
603 }
|
Chris@0
|
604
|
Chris@0
|
605 protected function processResponseBody(Request $request, Response $response)
|
Chris@0
|
606 {
|
Chris@0
|
607 if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
|
Chris@0
|
608 $this->surrogate->process($request, $response);
|
Chris@0
|
609 }
|
Chris@0
|
610 }
|
Chris@0
|
611
|
Chris@0
|
612 /**
|
Chris@0
|
613 * Checks if the Request includes authorization or other sensitive information
|
Chris@0
|
614 * that should cause the Response to be considered private by default.
|
Chris@0
|
615 *
|
Chris@0
|
616 * @return bool true if the Request is private, false otherwise
|
Chris@0
|
617 */
|
Chris@0
|
618 private function isPrivateRequest(Request $request)
|
Chris@0
|
619 {
|
Chris@0
|
620 foreach ($this->options['private_headers'] as $key) {
|
Chris@0
|
621 $key = strtolower(str_replace('HTTP_', '', $key));
|
Chris@0
|
622
|
Chris@0
|
623 if ('cookie' === $key) {
|
Chris@17
|
624 if (\count($request->cookies->all())) {
|
Chris@0
|
625 return true;
|
Chris@0
|
626 }
|
Chris@0
|
627 } elseif ($request->headers->has($key)) {
|
Chris@0
|
628 return true;
|
Chris@0
|
629 }
|
Chris@0
|
630 }
|
Chris@0
|
631
|
Chris@0
|
632 return false;
|
Chris@0
|
633 }
|
Chris@0
|
634
|
Chris@0
|
635 /**
|
Chris@0
|
636 * Records that an event took place.
|
Chris@0
|
637 *
|
Chris@0
|
638 * @param Request $request A Request instance
|
Chris@0
|
639 * @param string $event The event name
|
Chris@0
|
640 */
|
Chris@0
|
641 private function record(Request $request, $event)
|
Chris@0
|
642 {
|
Chris@14
|
643 $this->traces[$this->getTraceKey($request)][] = $event;
|
Chris@14
|
644 }
|
Chris@14
|
645
|
Chris@14
|
646 /**
|
Chris@14
|
647 * Calculates the key we use in the "trace" array for a given request.
|
Chris@14
|
648 *
|
Chris@14
|
649 * @param Request $request
|
Chris@14
|
650 *
|
Chris@14
|
651 * @return string
|
Chris@14
|
652 */
|
Chris@14
|
653 private function getTraceKey(Request $request)
|
Chris@14
|
654 {
|
Chris@0
|
655 $path = $request->getPathInfo();
|
Chris@0
|
656 if ($qs = $request->getQueryString()) {
|
Chris@0
|
657 $path .= '?'.$qs;
|
Chris@0
|
658 }
|
Chris@14
|
659
|
Chris@14
|
660 return $request->getMethod().' '.$path;
|
Chris@14
|
661 }
|
Chris@14
|
662
|
Chris@14
|
663 /**
|
Chris@14
|
664 * Checks whether the given (cached) response may be served as "stale" when a revalidation
|
Chris@14
|
665 * is currently in progress.
|
Chris@14
|
666 *
|
Chris@14
|
667 * @param Response $entry
|
Chris@14
|
668 *
|
Chris@14
|
669 * @return bool true when the stale response may be served, false otherwise
|
Chris@14
|
670 */
|
Chris@14
|
671 private function mayServeStaleWhileRevalidate(Response $entry)
|
Chris@14
|
672 {
|
Chris@14
|
673 $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
|
Chris@14
|
674
|
Chris@14
|
675 if (null === $timeout) {
|
Chris@14
|
676 $timeout = $this->options['stale_while_revalidate'];
|
Chris@14
|
677 }
|
Chris@14
|
678
|
Chris@14
|
679 return abs($entry->getTtl()) < $timeout;
|
Chris@14
|
680 }
|
Chris@14
|
681
|
Chris@14
|
682 /**
|
Chris@14
|
683 * Waits for the store to release a locked entry.
|
Chris@14
|
684 *
|
Chris@14
|
685 * @param Request $request The request to wait for
|
Chris@14
|
686 *
|
Chris@14
|
687 * @return bool true if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded
|
Chris@14
|
688 */
|
Chris@14
|
689 private function waitForLock(Request $request)
|
Chris@14
|
690 {
|
Chris@14
|
691 $wait = 0;
|
Chris@14
|
692 while ($this->store->isLocked($request) && $wait < 100) {
|
Chris@14
|
693 usleep(50000);
|
Chris@14
|
694 ++$wait;
|
Chris@14
|
695 }
|
Chris@14
|
696
|
Chris@14
|
697 return $wait < 100;
|
Chris@0
|
698 }
|
Chris@0
|
699 }
|