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