HttpCache.php 26 KB

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