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@0
|
18 use Symfony\Component\HttpKernel\HttpKernelInterface;
|
Chris@0
|
19 use Symfony\Component\HttpKernel\TerminableInterface;
|
Chris@0
|
20 use Symfony\Component\HttpFoundation\Request;
|
Chris@0
|
21 use Symfony\Component\HttpFoundation\Response;
|
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@0
|
35 private $options = array();
|
Chris@0
|
36 private $traces = array();
|
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@0
|
73 public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
|
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@0
|
80 register_shutdown_function(array($this->store, 'cleanup'));
|
Chris@0
|
81
|
Chris@0
|
82 $this->options = array_merge(array(
|
Chris@0
|
83 'debug' => false,
|
Chris@0
|
84 'default_ttl' => 0,
|
Chris@0
|
85 'private_headers' => array('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@0
|
90 ), $options);
|
Chris@0
|
91 }
|
Chris@0
|
92
|
Chris@0
|
93 /**
|
Chris@0
|
94 * Gets the current store.
|
Chris@0
|
95 *
|
Chris@0
|
96 * @return StoreInterface $store 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@0
|
120 $log = array();
|
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@0
|
167 $this->traces = array();
|
Chris@0
|
168 $this->request = $request;
|
Chris@0
|
169 if (null !== $this->surrogate) {
|
Chris@0
|
170 $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
|
Chris@0
|
171 }
|
Chris@0
|
172 }
|
Chris@0
|
173
|
Chris@14
|
174 $this->traces[$this->getTraceKey($request)] = array();
|
Chris@0
|
175
|
Chris@0
|
176 if (!$request->isMethodSafe(false)) {
|
Chris@0
|
177 $response = $this->invalidate($request, $catch);
|
Chris@0
|
178 } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
|
Chris@0
|
179 $response = $this->pass($request, $catch);
|
Chris@14
|
180 } elseif ($this->options['allow_reload'] && $request->isNoCache()) {
|
Chris@14
|
181 /*
|
Chris@14
|
182 If allow_reload is configured and the client requests "Cache-Control: no-cache",
|
Chris@14
|
183 reload the cache by fetching a fresh response and caching it (if possible).
|
Chris@14
|
184 */
|
Chris@14
|
185 $this->record($request, 'reload');
|
Chris@14
|
186 $response = $this->fetch($request, $catch);
|
Chris@0
|
187 } else {
|
Chris@0
|
188 $response = $this->lookup($request, $catch);
|
Chris@0
|
189 }
|
Chris@0
|
190
|
Chris@0
|
191 $this->restoreResponseBody($request, $response);
|
Chris@0
|
192
|
Chris@0
|
193 if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
|
Chris@0
|
194 $response->headers->set('X-Symfony-Cache', $this->getLog());
|
Chris@0
|
195 }
|
Chris@0
|
196
|
Chris@0
|
197 if (null !== $this->surrogate) {
|
Chris@0
|
198 if (HttpKernelInterface::MASTER_REQUEST === $type) {
|
Chris@0
|
199 $this->surrogateCacheStrategy->update($response);
|
Chris@0
|
200 } else {
|
Chris@0
|
201 $this->surrogateCacheStrategy->add($response);
|
Chris@0
|
202 }
|
Chris@0
|
203 }
|
Chris@0
|
204
|
Chris@0
|
205 $response->prepare($request);
|
Chris@0
|
206
|
Chris@0
|
207 $response->isNotModified($request);
|
Chris@0
|
208
|
Chris@0
|
209 return $response;
|
Chris@0
|
210 }
|
Chris@0
|
211
|
Chris@0
|
212 /**
|
Chris@0
|
213 * {@inheritdoc}
|
Chris@0
|
214 */
|
Chris@0
|
215 public function terminate(Request $request, Response $response)
|
Chris@0
|
216 {
|
Chris@0
|
217 if ($this->getKernel() instanceof TerminableInterface) {
|
Chris@0
|
218 $this->getKernel()->terminate($request, $response);
|
Chris@0
|
219 }
|
Chris@0
|
220 }
|
Chris@0
|
221
|
Chris@0
|
222 /**
|
Chris@0
|
223 * Forwards the Request to the backend without storing the Response in the cache.
|
Chris@0
|
224 *
|
Chris@0
|
225 * @param Request $request A Request instance
|
Chris@0
|
226 * @param bool $catch Whether to process exceptions
|
Chris@0
|
227 *
|
Chris@0
|
228 * @return Response A Response instance
|
Chris@0
|
229 */
|
Chris@0
|
230 protected function pass(Request $request, $catch = false)
|
Chris@0
|
231 {
|
Chris@0
|
232 $this->record($request, 'pass');
|
Chris@0
|
233
|
Chris@0
|
234 return $this->forward($request, $catch);
|
Chris@0
|
235 }
|
Chris@0
|
236
|
Chris@0
|
237 /**
|
Chris@0
|
238 * Invalidates non-safe methods (like POST, PUT, and DELETE).
|
Chris@0
|
239 *
|
Chris@0
|
240 * @param Request $request A Request instance
|
Chris@0
|
241 * @param bool $catch Whether to process exceptions
|
Chris@0
|
242 *
|
Chris@0
|
243 * @return Response A Response instance
|
Chris@0
|
244 *
|
Chris@0
|
245 * @throws \Exception
|
Chris@0
|
246 *
|
Chris@0
|
247 * @see RFC2616 13.10
|
Chris@0
|
248 */
|
Chris@0
|
249 protected function invalidate(Request $request, $catch = false)
|
Chris@0
|
250 {
|
Chris@0
|
251 $response = $this->pass($request, $catch);
|
Chris@0
|
252
|
Chris@0
|
253 // invalidate only when the response is successful
|
Chris@0
|
254 if ($response->isSuccessful() || $response->isRedirect()) {
|
Chris@0
|
255 try {
|
Chris@0
|
256 $this->store->invalidate($request);
|
Chris@0
|
257
|
Chris@0
|
258 // As per the RFC, invalidate Location and Content-Location URLs if present
|
Chris@0
|
259 foreach (array('Location', 'Content-Location') as $header) {
|
Chris@0
|
260 if ($uri = $response->headers->get($header)) {
|
Chris@0
|
261 $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
|
Chris@0
|
262
|
Chris@0
|
263 $this->store->invalidate($subRequest);
|
Chris@0
|
264 }
|
Chris@0
|
265 }
|
Chris@0
|
266
|
Chris@0
|
267 $this->record($request, 'invalidate');
|
Chris@0
|
268 } catch (\Exception $e) {
|
Chris@0
|
269 $this->record($request, 'invalidate-failed');
|
Chris@0
|
270
|
Chris@0
|
271 if ($this->options['debug']) {
|
Chris@0
|
272 throw $e;
|
Chris@0
|
273 }
|
Chris@0
|
274 }
|
Chris@0
|
275 }
|
Chris@0
|
276
|
Chris@0
|
277 return $response;
|
Chris@0
|
278 }
|
Chris@0
|
279
|
Chris@0
|
280 /**
|
Chris@0
|
281 * Lookups a Response from the cache for the given Request.
|
Chris@0
|
282 *
|
Chris@0
|
283 * When a matching cache entry is found and is fresh, it uses it as the
|
Chris@0
|
284 * response without forwarding any request to the backend. When a matching
|
Chris@0
|
285 * cache entry is found but is stale, it attempts to "validate" the entry with
|
Chris@0
|
286 * the backend using conditional GET. When no matching cache entry is found,
|
Chris@0
|
287 * it triggers "miss" processing.
|
Chris@0
|
288 *
|
Chris@0
|
289 * @param Request $request A Request instance
|
Chris@14
|
290 * @param bool $catch Whether to process exceptions
|
Chris@0
|
291 *
|
Chris@0
|
292 * @return Response A Response instance
|
Chris@0
|
293 *
|
Chris@0
|
294 * @throws \Exception
|
Chris@0
|
295 */
|
Chris@0
|
296 protected function lookup(Request $request, $catch = false)
|
Chris@0
|
297 {
|
Chris@0
|
298 try {
|
Chris@0
|
299 $entry = $this->store->lookup($request);
|
Chris@0
|
300 } catch (\Exception $e) {
|
Chris@0
|
301 $this->record($request, 'lookup-failed');
|
Chris@0
|
302
|
Chris@0
|
303 if ($this->options['debug']) {
|
Chris@0
|
304 throw $e;
|
Chris@0
|
305 }
|
Chris@0
|
306
|
Chris@0
|
307 return $this->pass($request, $catch);
|
Chris@0
|
308 }
|
Chris@0
|
309
|
Chris@0
|
310 if (null === $entry) {
|
Chris@0
|
311 $this->record($request, 'miss');
|
Chris@0
|
312
|
Chris@0
|
313 return $this->fetch($request, $catch);
|
Chris@0
|
314 }
|
Chris@0
|
315
|
Chris@0
|
316 if (!$this->isFreshEnough($request, $entry)) {
|
Chris@0
|
317 $this->record($request, 'stale');
|
Chris@0
|
318
|
Chris@0
|
319 return $this->validate($request, $entry, $catch);
|
Chris@0
|
320 }
|
Chris@0
|
321
|
Chris@0
|
322 $this->record($request, 'fresh');
|
Chris@0
|
323
|
Chris@0
|
324 $entry->headers->set('Age', $entry->getAge());
|
Chris@0
|
325
|
Chris@0
|
326 return $entry;
|
Chris@0
|
327 }
|
Chris@0
|
328
|
Chris@0
|
329 /**
|
Chris@0
|
330 * Validates that a cache entry is fresh.
|
Chris@0
|
331 *
|
Chris@0
|
332 * The original request is used as a template for a conditional
|
Chris@0
|
333 * GET request with the backend.
|
Chris@0
|
334 *
|
Chris@0
|
335 * @param Request $request A Request instance
|
Chris@0
|
336 * @param Response $entry A Response instance to validate
|
Chris@0
|
337 * @param bool $catch Whether to process exceptions
|
Chris@0
|
338 *
|
Chris@0
|
339 * @return Response A Response instance
|
Chris@0
|
340 */
|
Chris@0
|
341 protected function validate(Request $request, Response $entry, $catch = false)
|
Chris@0
|
342 {
|
Chris@0
|
343 $subRequest = clone $request;
|
Chris@0
|
344
|
Chris@0
|
345 // send no head requests because we want content
|
Chris@0
|
346 if ('HEAD' === $request->getMethod()) {
|
Chris@0
|
347 $subRequest->setMethod('GET');
|
Chris@0
|
348 }
|
Chris@0
|
349
|
Chris@0
|
350 // add our cached last-modified validator
|
Chris@0
|
351 $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
|
Chris@0
|
352
|
Chris@0
|
353 // Add our cached etag validator to the environment.
|
Chris@0
|
354 // We keep the etags from the client to handle the case when the client
|
Chris@0
|
355 // has a different private valid entry which is not cached here.
|
Chris@0
|
356 $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
|
Chris@0
|
357 $requestEtags = $request->getETags();
|
Chris@0
|
358 if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
|
Chris@0
|
359 $subRequest->headers->set('if_none_match', implode(', ', $etags));
|
Chris@0
|
360 }
|
Chris@0
|
361
|
Chris@0
|
362 $response = $this->forward($subRequest, $catch, $entry);
|
Chris@0
|
363
|
Chris@0
|
364 if (304 == $response->getStatusCode()) {
|
Chris@0
|
365 $this->record($request, 'valid');
|
Chris@0
|
366
|
Chris@0
|
367 // return the response and not the cache entry if the response is valid but not cached
|
Chris@0
|
368 $etag = $response->getEtag();
|
Chris@0
|
369 if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
|
Chris@0
|
370 return $response;
|
Chris@0
|
371 }
|
Chris@0
|
372
|
Chris@0
|
373 $entry = clone $entry;
|
Chris@0
|
374 $entry->headers->remove('Date');
|
Chris@0
|
375
|
Chris@0
|
376 foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
|
Chris@0
|
377 if ($response->headers->has($name)) {
|
Chris@0
|
378 $entry->headers->set($name, $response->headers->get($name));
|
Chris@0
|
379 }
|
Chris@0
|
380 }
|
Chris@0
|
381
|
Chris@0
|
382 $response = $entry;
|
Chris@0
|
383 } else {
|
Chris@0
|
384 $this->record($request, 'invalid');
|
Chris@0
|
385 }
|
Chris@0
|
386
|
Chris@0
|
387 if ($response->isCacheable()) {
|
Chris@0
|
388 $this->store($request, $response);
|
Chris@0
|
389 }
|
Chris@0
|
390
|
Chris@0
|
391 return $response;
|
Chris@0
|
392 }
|
Chris@0
|
393
|
Chris@0
|
394 /**
|
Chris@14
|
395 * Unconditionally fetches a fresh response from the backend and
|
Chris@14
|
396 * stores it in the cache if is cacheable.
|
Chris@0
|
397 *
|
Chris@0
|
398 * @param Request $request A Request instance
|
Chris@14
|
399 * @param bool $catch Whether to process exceptions
|
Chris@0
|
400 *
|
Chris@0
|
401 * @return Response A Response instance
|
Chris@0
|
402 */
|
Chris@0
|
403 protected function fetch(Request $request, $catch = false)
|
Chris@0
|
404 {
|
Chris@0
|
405 $subRequest = clone $request;
|
Chris@0
|
406
|
Chris@0
|
407 // send no head requests because we want content
|
Chris@0
|
408 if ('HEAD' === $request->getMethod()) {
|
Chris@0
|
409 $subRequest->setMethod('GET');
|
Chris@0
|
410 }
|
Chris@0
|
411
|
Chris@0
|
412 // avoid that the backend sends no content
|
Chris@0
|
413 $subRequest->headers->remove('if_modified_since');
|
Chris@0
|
414 $subRequest->headers->remove('if_none_match');
|
Chris@0
|
415
|
Chris@0
|
416 $response = $this->forward($subRequest, $catch);
|
Chris@0
|
417
|
Chris@0
|
418 if ($response->isCacheable()) {
|
Chris@0
|
419 $this->store($request, $response);
|
Chris@0
|
420 }
|
Chris@0
|
421
|
Chris@0
|
422 return $response;
|
Chris@0
|
423 }
|
Chris@0
|
424
|
Chris@0
|
425 /**
|
Chris@0
|
426 * Forwards the Request to the backend and returns the Response.
|
Chris@0
|
427 *
|
Chris@14
|
428 * All backend requests (cache passes, fetches, cache validations)
|
Chris@14
|
429 * run through this method.
|
Chris@14
|
430 *
|
Chris@0
|
431 * @param Request $request A Request instance
|
Chris@0
|
432 * @param bool $catch Whether to catch exceptions or not
|
Chris@0
|
433 * @param Response $entry A Response instance (the stale entry if present, null otherwise)
|
Chris@0
|
434 *
|
Chris@0
|
435 * @return Response A Response instance
|
Chris@0
|
436 */
|
Chris@0
|
437 protected function forward(Request $request, $catch = false, Response $entry = null)
|
Chris@0
|
438 {
|
Chris@0
|
439 if ($this->surrogate) {
|
Chris@0
|
440 $this->surrogate->addSurrogateCapability($request);
|
Chris@0
|
441 }
|
Chris@0
|
442
|
Chris@0
|
443 // modify the X-Forwarded-For header if needed
|
Chris@0
|
444 $forwardedFor = $request->headers->get('X-Forwarded-For');
|
Chris@0
|
445 if ($forwardedFor) {
|
Chris@0
|
446 $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
|
Chris@0
|
447 } else {
|
Chris@0
|
448 $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
|
Chris@0
|
449 }
|
Chris@0
|
450
|
Chris@0
|
451 // fix the client IP address by setting it to 127.0.0.1 as HttpCache
|
Chris@0
|
452 // is always called from the same process as the backend.
|
Chris@0
|
453 $request->server->set('REMOTE_ADDR', '127.0.0.1');
|
Chris@0
|
454
|
Chris@0
|
455 // make sure HttpCache is a trusted proxy
|
Chris@0
|
456 if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
|
Chris@0
|
457 $trustedProxies[] = '127.0.0.1';
|
Chris@14
|
458 Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL);
|
Chris@0
|
459 }
|
Chris@0
|
460
|
Chris@0
|
461 // always a "master" request (as the real master request can be in cache)
|
Chris@0
|
462 $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
|
Chris@0
|
463 // FIXME: we probably need to also catch exceptions if raw === true
|
Chris@0
|
464
|
Chris@0
|
465 // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
|
Chris@0
|
466 if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
|
Chris@0
|
467 if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
|
Chris@0
|
468 $age = $this->options['stale_if_error'];
|
Chris@0
|
469 }
|
Chris@0
|
470
|
Chris@0
|
471 if (abs($entry->getTtl()) < $age) {
|
Chris@0
|
472 $this->record($request, 'stale-if-error');
|
Chris@0
|
473
|
Chris@0
|
474 return $entry;
|
Chris@0
|
475 }
|
Chris@0
|
476 }
|
Chris@0
|
477
|
Chris@14
|
478 /*
|
Chris@14
|
479 RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate
|
Chris@14
|
480 clock MUST NOT send a "Date" header, although it MUST send one in most other cases
|
Chris@14
|
481 except for 1xx or 5xx responses where it MAY do so.
|
Chris@14
|
482
|
Chris@14
|
483 Anyway, a client that received a message without a "Date" header MUST add it.
|
Chris@14
|
484 */
|
Chris@14
|
485 if (!$response->headers->has('Date')) {
|
Chris@14
|
486 $response->setDate(\DateTime::createFromFormat('U', time()));
|
Chris@14
|
487 }
|
Chris@14
|
488
|
Chris@0
|
489 $this->processResponseBody($request, $response);
|
Chris@0
|
490
|
Chris@0
|
491 if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
|
Chris@0
|
492 $response->setPrivate();
|
Chris@0
|
493 } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
|
Chris@0
|
494 $response->setTtl($this->options['default_ttl']);
|
Chris@0
|
495 }
|
Chris@0
|
496
|
Chris@0
|
497 return $response;
|
Chris@0
|
498 }
|
Chris@0
|
499
|
Chris@0
|
500 /**
|
Chris@0
|
501 * Checks whether the cache entry is "fresh enough" to satisfy the Request.
|
Chris@0
|
502 *
|
Chris@0
|
503 * @return bool true if the cache entry if fresh enough, false otherwise
|
Chris@0
|
504 */
|
Chris@0
|
505 protected function isFreshEnough(Request $request, Response $entry)
|
Chris@0
|
506 {
|
Chris@0
|
507 if (!$entry->isFresh()) {
|
Chris@0
|
508 return $this->lock($request, $entry);
|
Chris@0
|
509 }
|
Chris@0
|
510
|
Chris@0
|
511 if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
|
Chris@0
|
512 return $maxAge > 0 && $maxAge >= $entry->getAge();
|
Chris@0
|
513 }
|
Chris@0
|
514
|
Chris@0
|
515 return true;
|
Chris@0
|
516 }
|
Chris@0
|
517
|
Chris@0
|
518 /**
|
Chris@0
|
519 * Locks a Request during the call to the backend.
|
Chris@0
|
520 *
|
Chris@0
|
521 * @return bool true if the cache entry can be returned even if it is staled, false otherwise
|
Chris@0
|
522 */
|
Chris@0
|
523 protected function lock(Request $request, Response $entry)
|
Chris@0
|
524 {
|
Chris@0
|
525 // try to acquire a lock to call the backend
|
Chris@0
|
526 $lock = $this->store->lock($request);
|
Chris@0
|
527
|
Chris@14
|
528 if (true === $lock) {
|
Chris@14
|
529 // we have the lock, call the backend
|
Chris@14
|
530 return false;
|
Chris@14
|
531 }
|
Chris@14
|
532
|
Chris@0
|
533 // there is already another process calling the backend
|
Chris@0
|
534
|
Chris@14
|
535 // May we serve a stale response?
|
Chris@14
|
536 if ($this->mayServeStaleWhileRevalidate($entry)) {
|
Chris@14
|
537 $this->record($request, 'stale-while-revalidate');
|
Chris@0
|
538
|
Chris@0
|
539 return true;
|
Chris@0
|
540 }
|
Chris@0
|
541
|
Chris@14
|
542 // wait for the lock to be released
|
Chris@14
|
543 if ($this->waitForLock($request)) {
|
Chris@14
|
544 // replace the current entry with the fresh one
|
Chris@14
|
545 $new = $this->lookup($request);
|
Chris@14
|
546 $entry->headers = $new->headers;
|
Chris@14
|
547 $entry->setContent($new->getContent());
|
Chris@14
|
548 $entry->setStatusCode($new->getStatusCode());
|
Chris@14
|
549 $entry->setProtocolVersion($new->getProtocolVersion());
|
Chris@14
|
550 foreach ($new->headers->getCookies() as $cookie) {
|
Chris@14
|
551 $entry->headers->setCookie($cookie);
|
Chris@14
|
552 }
|
Chris@14
|
553 } else {
|
Chris@14
|
554 // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
|
Chris@14
|
555 $entry->setStatusCode(503);
|
Chris@14
|
556 $entry->setContent('503 Service Unavailable');
|
Chris@14
|
557 $entry->headers->set('Retry-After', 10);
|
Chris@14
|
558 }
|
Chris@14
|
559
|
Chris@14
|
560 return true;
|
Chris@0
|
561 }
|
Chris@0
|
562
|
Chris@0
|
563 /**
|
Chris@0
|
564 * Writes the Response to the cache.
|
Chris@0
|
565 *
|
Chris@0
|
566 * @throws \Exception
|
Chris@0
|
567 */
|
Chris@0
|
568 protected function store(Request $request, Response $response)
|
Chris@0
|
569 {
|
Chris@0
|
570 try {
|
Chris@0
|
571 $this->store->write($request, $response);
|
Chris@0
|
572
|
Chris@0
|
573 $this->record($request, 'store');
|
Chris@0
|
574
|
Chris@0
|
575 $response->headers->set('Age', $response->getAge());
|
Chris@0
|
576 } catch (\Exception $e) {
|
Chris@0
|
577 $this->record($request, 'store-failed');
|
Chris@0
|
578
|
Chris@0
|
579 if ($this->options['debug']) {
|
Chris@0
|
580 throw $e;
|
Chris@0
|
581 }
|
Chris@0
|
582 }
|
Chris@0
|
583
|
Chris@0
|
584 // now that the response is cached, release the lock
|
Chris@0
|
585 $this->store->unlock($request);
|
Chris@0
|
586 }
|
Chris@0
|
587
|
Chris@0
|
588 /**
|
Chris@0
|
589 * Restores the Response body.
|
Chris@0
|
590 */
|
Chris@0
|
591 private function restoreResponseBody(Request $request, Response $response)
|
Chris@0
|
592 {
|
Chris@0
|
593 if ($response->headers->has('X-Body-Eval')) {
|
Chris@0
|
594 ob_start();
|
Chris@0
|
595
|
Chris@0
|
596 if ($response->headers->has('X-Body-File')) {
|
Chris@0
|
597 include $response->headers->get('X-Body-File');
|
Chris@0
|
598 } else {
|
Chris@0
|
599 eval('; ?>'.$response->getContent().'<?php ;');
|
Chris@0
|
600 }
|
Chris@0
|
601
|
Chris@0
|
602 $response->setContent(ob_get_clean());
|
Chris@0
|
603 $response->headers->remove('X-Body-Eval');
|
Chris@0
|
604 if (!$response->headers->has('Transfer-Encoding')) {
|
Chris@0
|
605 $response->headers->set('Content-Length', strlen($response->getContent()));
|
Chris@0
|
606 }
|
Chris@0
|
607 } elseif ($response->headers->has('X-Body-File')) {
|
Chris@14
|
608 // Response does not include possibly dynamic content (ESI, SSI), so we need
|
Chris@14
|
609 // not handle the content for HEAD requests
|
Chris@14
|
610 if (!$request->isMethod('HEAD')) {
|
Chris@14
|
611 $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
|
Chris@14
|
612 }
|
Chris@0
|
613 } else {
|
Chris@0
|
614 return;
|
Chris@0
|
615 }
|
Chris@0
|
616
|
Chris@0
|
617 $response->headers->remove('X-Body-File');
|
Chris@0
|
618 }
|
Chris@0
|
619
|
Chris@0
|
620 protected function processResponseBody(Request $request, Response $response)
|
Chris@0
|
621 {
|
Chris@0
|
622 if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
|
Chris@0
|
623 $this->surrogate->process($request, $response);
|
Chris@0
|
624 }
|
Chris@0
|
625 }
|
Chris@0
|
626
|
Chris@0
|
627 /**
|
Chris@0
|
628 * Checks if the Request includes authorization or other sensitive information
|
Chris@0
|
629 * that should cause the Response to be considered private by default.
|
Chris@0
|
630 *
|
Chris@0
|
631 * @return bool true if the Request is private, false otherwise
|
Chris@0
|
632 */
|
Chris@0
|
633 private function isPrivateRequest(Request $request)
|
Chris@0
|
634 {
|
Chris@0
|
635 foreach ($this->options['private_headers'] as $key) {
|
Chris@0
|
636 $key = strtolower(str_replace('HTTP_', '', $key));
|
Chris@0
|
637
|
Chris@0
|
638 if ('cookie' === $key) {
|
Chris@0
|
639 if (count($request->cookies->all())) {
|
Chris@0
|
640 return true;
|
Chris@0
|
641 }
|
Chris@0
|
642 } elseif ($request->headers->has($key)) {
|
Chris@0
|
643 return true;
|
Chris@0
|
644 }
|
Chris@0
|
645 }
|
Chris@0
|
646
|
Chris@0
|
647 return false;
|
Chris@0
|
648 }
|
Chris@0
|
649
|
Chris@0
|
650 /**
|
Chris@0
|
651 * Records that an event took place.
|
Chris@0
|
652 *
|
Chris@0
|
653 * @param Request $request A Request instance
|
Chris@0
|
654 * @param string $event The event name
|
Chris@0
|
655 */
|
Chris@0
|
656 private function record(Request $request, $event)
|
Chris@0
|
657 {
|
Chris@14
|
658 $this->traces[$this->getTraceKey($request)][] = $event;
|
Chris@14
|
659 }
|
Chris@14
|
660
|
Chris@14
|
661 /**
|
Chris@14
|
662 * Calculates the key we use in the "trace" array for a given request.
|
Chris@14
|
663 *
|
Chris@14
|
664 * @param Request $request
|
Chris@14
|
665 *
|
Chris@14
|
666 * @return string
|
Chris@14
|
667 */
|
Chris@14
|
668 private function getTraceKey(Request $request)
|
Chris@14
|
669 {
|
Chris@0
|
670 $path = $request->getPathInfo();
|
Chris@0
|
671 if ($qs = $request->getQueryString()) {
|
Chris@0
|
672 $path .= '?'.$qs;
|
Chris@0
|
673 }
|
Chris@14
|
674
|
Chris@14
|
675 return $request->getMethod().' '.$path;
|
Chris@14
|
676 }
|
Chris@14
|
677
|
Chris@14
|
678 /**
|
Chris@14
|
679 * Checks whether the given (cached) response may be served as "stale" when a revalidation
|
Chris@14
|
680 * is currently in progress.
|
Chris@14
|
681 *
|
Chris@14
|
682 * @param Response $entry
|
Chris@14
|
683 *
|
Chris@14
|
684 * @return bool true when the stale response may be served, false otherwise
|
Chris@14
|
685 */
|
Chris@14
|
686 private function mayServeStaleWhileRevalidate(Response $entry)
|
Chris@14
|
687 {
|
Chris@14
|
688 $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
|
Chris@14
|
689
|
Chris@14
|
690 if (null === $timeout) {
|
Chris@14
|
691 $timeout = $this->options['stale_while_revalidate'];
|
Chris@14
|
692 }
|
Chris@14
|
693
|
Chris@14
|
694 return abs($entry->getTtl()) < $timeout;
|
Chris@14
|
695 }
|
Chris@14
|
696
|
Chris@14
|
697 /**
|
Chris@14
|
698 * Waits for the store to release a locked entry.
|
Chris@14
|
699 *
|
Chris@14
|
700 * @param Request $request The request to wait for
|
Chris@14
|
701 *
|
Chris@14
|
702 * @return bool true if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded
|
Chris@14
|
703 */
|
Chris@14
|
704 private function waitForLock(Request $request)
|
Chris@14
|
705 {
|
Chris@14
|
706 $wait = 0;
|
Chris@14
|
707 while ($this->store->isLocked($request) && $wait < 100) {
|
Chris@14
|
708 usleep(50000);
|
Chris@14
|
709 ++$wait;
|
Chris@14
|
710 }
|
Chris@14
|
711
|
Chris@14
|
712 return $wait < 100;
|
Chris@0
|
713 }
|
Chris@0
|
714 }
|