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 = null;
  191. do {
  192. try {
  193. $response = $this->lookup($request, $catch);
  194. } catch (CacheWasLockedException) {
  195. }
  196. } while (null === $response);
  197. }
  198. $this->restoreResponseBody($request, $response);
  199. if (HttpKernelInterface::MAIN_REQUEST === $type) {
  200. $this->addTraces($response);
  201. }
  202. if (null !== $this->surrogate) {
  203. if (HttpKernelInterface::MAIN_REQUEST === $type) {
  204. $this->surrogateCacheStrategy->update($response);
  205. } else {
  206. $this->surrogateCacheStrategy->add($response);
  207. }
  208. }
  209. $response->prepare($request);
  210. if (HttpKernelInterface::MAIN_REQUEST === $type) {
  211. $response->isNotModified($request);
  212. }
  213. return $response;
  214. }
  215. public function terminate(Request $request, Response $response): void
  216. {
  217. // Do not call any listeners in case of a cache hit.
  218. // This ensures identical behavior as if you had a separate
  219. // reverse caching proxy such as Varnish and the like.
  220. if (\in_array('fresh', $this->traces[$this->getTraceKey($request)] ?? [], true)) {
  221. return;
  222. }
  223. if ($this->getKernel() instanceof TerminableInterface) {
  224. $this->getKernel()->terminate($request, $response);
  225. }
  226. }
  227. /**
  228. * Forwards the Request to the backend without storing the Response in the cache.
  229. *
  230. * @param bool $catch Whether to process exceptions
  231. */
  232. protected function pass(Request $request, bool $catch = false): Response
  233. {
  234. $this->record($request, 'pass');
  235. return $this->forward($request, $catch);
  236. }
  237. /**
  238. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  239. *
  240. * @param bool $catch Whether to process exceptions
  241. *
  242. * @throws \Exception
  243. *
  244. * @see RFC2616 13.10
  245. */
  246. protected function invalidate(Request $request, bool $catch = false): Response
  247. {
  248. $response = $this->pass($request, $catch);
  249. // invalidate only when the response is successful
  250. if ($response->isSuccessful() || $response->isRedirect()) {
  251. try {
  252. $this->store->invalidate($request);
  253. // As per the RFC, invalidate Location and Content-Location URLs if present
  254. foreach (['Location', 'Content-Location'] as $header) {
  255. if ($uri = $response->headers->get($header)) {
  256. $subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
  257. $this->store->invalidate($subRequest);
  258. }
  259. }
  260. $this->record($request, 'invalidate');
  261. } catch (\Exception $e) {
  262. $this->record($request, 'invalidate-failed');
  263. if ($this->options['debug']) {
  264. throw $e;
  265. }
  266. }
  267. }
  268. return $response;
  269. }
  270. /**
  271. * Lookups a Response from the cache for the given Request.
  272. *
  273. * When a matching cache entry is found and is fresh, it uses it as the
  274. * response without forwarding any request to the backend. When a matching
  275. * cache entry is found but is stale, it attempts to "validate" the entry with
  276. * the backend using conditional GET. When no matching cache entry is found,
  277. * it triggers "miss" processing.
  278. *
  279. * @param bool $catch Whether to process exceptions
  280. *
  281. * @throws \Exception
  282. */
  283. protected function lookup(Request $request, bool $catch = false): Response
  284. {
  285. try {
  286. $entry = $this->store->lookup($request);
  287. } catch (\Exception $e) {
  288. $this->record($request, 'lookup-failed');
  289. if ($this->options['debug']) {
  290. throw $e;
  291. }
  292. return $this->pass($request, $catch);
  293. }
  294. if (null === $entry) {
  295. $this->record($request, 'miss');
  296. return $this->fetch($request, $catch);
  297. }
  298. if (!$this->isFreshEnough($request, $entry)) {
  299. $this->record($request, 'stale');
  300. return $this->validate($request, $entry, $catch);
  301. }
  302. if ($entry->headers->hasCacheControlDirective('no-cache')) {
  303. return $this->validate($request, $entry, $catch);
  304. }
  305. $this->record($request, 'fresh');
  306. $entry->headers->set('Age', $entry->getAge());
  307. return $entry;
  308. }
  309. /**
  310. * Validates that a cache entry is fresh.
  311. *
  312. * The original request is used as a template for a conditional
  313. * GET request with the backend.
  314. *
  315. * @param bool $catch Whether to process exceptions
  316. */
  317. protected function validate(Request $request, Response $entry, bool $catch = false): Response
  318. {
  319. $subRequest = clone $request;
  320. // send no head requests because we want content
  321. if ('HEAD' === $request->getMethod()) {
  322. $subRequest->setMethod('GET');
  323. }
  324. // add our cached last-modified validator
  325. if ($entry->headers->has('Last-Modified')) {
  326. $subRequest->headers->set('If-Modified-Since', $entry->headers->get('Last-Modified'));
  327. }
  328. // Add our cached etag validator to the environment.
  329. // We keep the etags from the client to handle the case when the client
  330. // has a different private valid entry which is not cached here.
  331. $cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
  332. $requestEtags = $request->getETags();
  333. if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
  334. $subRequest->headers->set('If-None-Match', implode(', ', $etags));
  335. }
  336. $response = $this->forward($subRequest, $catch, $entry);
  337. if (304 == $response->getStatusCode()) {
  338. $this->record($request, 'valid');
  339. // return the response and not the cache entry if the response is valid but not cached
  340. $etag = $response->getEtag();
  341. if ($etag && \in_array($etag, $requestEtags, true) && !\in_array($etag, $cachedEtags, true)) {
  342. return $response;
  343. }
  344. $entry = clone $entry;
  345. $entry->headers->remove('Date');
  346. foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
  347. if ($response->headers->has($name)) {
  348. $entry->headers->set($name, $response->headers->get($name));
  349. }
  350. }
  351. $response = $entry;
  352. } else {
  353. $this->record($request, 'invalid');
  354. }
  355. if ($response->isCacheable()) {
  356. $this->store($request, $response);
  357. }
  358. return $response;
  359. }
  360. /**
  361. * Unconditionally fetches a fresh response from the backend and
  362. * stores it in the cache if is cacheable.
  363. *
  364. * @param bool $catch Whether to process exceptions
  365. */
  366. protected function fetch(Request $request, bool $catch = false): Response
  367. {
  368. $subRequest = clone $request;
  369. // send no head requests because we want content
  370. if ('HEAD' === $request->getMethod()) {
  371. $subRequest->setMethod('GET');
  372. }
  373. // avoid that the backend sends no content
  374. $subRequest->headers->remove('If-Modified-Since');
  375. $subRequest->headers->remove('If-None-Match');
  376. $response = $this->forward($subRequest, $catch);
  377. if ($response->isCacheable()) {
  378. $this->store($request, $response);
  379. }
  380. return $response;
  381. }
  382. /**
  383. * Forwards the Request to the backend and returns the Response.
  384. *
  385. * All backend requests (cache passes, fetches, cache validations)
  386. * run through this method.
  387. *
  388. * @param bool $catch Whether to catch exceptions or not
  389. * @param Response|null $entry A Response instance (the stale entry if present, null otherwise)
  390. */
  391. protected function forward(Request $request, bool $catch = false, ?Response $entry = null): Response
  392. {
  393. $this->surrogate?->addSurrogateCapability($request);
  394. // always a "master" request (as the real master request can be in cache)
  395. $response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST, $catch);
  396. /*
  397. * Support stale-if-error given on Responses or as a config option.
  398. * RFC 7234 summarizes in Section 4.2.4 (but also mentions with the individual
  399. * Cache-Control directives) that
  400. *
  401. * A cache MUST NOT generate a stale response if it is prohibited by an
  402. * explicit in-protocol directive (e.g., by a "no-store" or "no-cache"
  403. * cache directive, a "must-revalidate" cache-response-directive, or an
  404. * applicable "s-maxage" or "proxy-revalidate" cache-response-directive;
  405. * see Section 5.2.2).
  406. *
  407. * https://tools.ietf.org/html/rfc7234#section-4.2.4
  408. *
  409. * We deviate from this in one detail, namely that we *do* serve entries in the
  410. * stale-if-error case even if they have a `s-maxage` Cache-Control directive.
  411. */
  412. if (null !== $entry
  413. && \in_array($response->getStatusCode(), [500, 502, 503, 504], true)
  414. && !$entry->headers->hasCacheControlDirective('no-cache')
  415. && !$entry->mustRevalidate()
  416. ) {
  417. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  418. $age = $this->options['stale_if_error'];
  419. }
  420. /*
  421. * stale-if-error gives the (extra) time that the Response may be used *after* it has become stale.
  422. * So we compare the time the $entry has been sitting in the cache already with the
  423. * time it was fresh plus the allowed grace period.
  424. */
  425. if ($entry->getAge() <= $entry->getMaxAge() + $age) {
  426. $this->record($request, 'stale-if-error');
  427. return $entry;
  428. }
  429. }
  430. /*
  431. RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate
  432. clock MUST NOT send a "Date" header, although it MUST send one in most other cases
  433. except for 1xx or 5xx responses where it MAY do so.
  434. Anyway, a client that received a message without a "Date" header MUST add it.
  435. */
  436. if (!$response->headers->has('Date')) {
  437. $response->setDate(\DateTimeImmutable::createFromFormat('U', time()));
  438. }
  439. $this->processResponseBody($request, $response);
  440. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  441. $response->setPrivate();
  442. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  443. $response->setTtl($this->options['default_ttl']);
  444. }
  445. return $response;
  446. }
  447. /**
  448. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  449. */
  450. protected function isFreshEnough(Request $request, Response $entry): bool
  451. {
  452. if (!$entry->isFresh()) {
  453. return $this->lock($request, $entry);
  454. }
  455. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  456. return $maxAge > 0 && $maxAge >= $entry->getAge();
  457. }
  458. return true;
  459. }
  460. /**
  461. * Locks a Request during the call to the backend.
  462. *
  463. * @return bool true if the cache entry can be returned even if it is staled, false otherwise
  464. */
  465. protected function lock(Request $request, Response $entry): bool
  466. {
  467. // try to acquire a lock to call the backend
  468. $lock = $this->store->lock($request);
  469. if (true === $lock) {
  470. // we have the lock, call the backend
  471. return false;
  472. }
  473. // there is already another process calling the backend
  474. // May we serve a stale response?
  475. if ($this->mayServeStaleWhileRevalidate($entry)) {
  476. $this->record($request, 'stale-while-revalidate');
  477. return true;
  478. }
  479. $this->record($request, 'waiting');
  480. // wait for the lock to be released
  481. if ($this->waitForLock($request)) {
  482. throw new CacheWasLockedException(); // unwind back to handle(), try again
  483. } else {
  484. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  485. $entry->setStatusCode(503);
  486. $entry->setContent('503 Service Unavailable');
  487. $entry->headers->set('Retry-After', 10);
  488. }
  489. return true;
  490. }
  491. /**
  492. * Writes the Response to the cache.
  493. *
  494. * @throws \Exception
  495. */
  496. protected function store(Request $request, Response $response): void
  497. {
  498. try {
  499. $restoreHeaders = [];
  500. foreach ($this->options['skip_response_headers'] as $header) {
  501. if (!$response->headers->has($header)) {
  502. continue;
  503. }
  504. $restoreHeaders[$header] = $response->headers->all($header);
  505. $response->headers->remove($header);
  506. }
  507. $this->store->write($request, $response);
  508. $this->record($request, 'store');
  509. $response->headers->set('Age', $response->getAge());
  510. } catch (\Exception $e) {
  511. $this->record($request, 'store-failed');
  512. if ($this->options['debug']) {
  513. throw $e;
  514. }
  515. } finally {
  516. foreach ($restoreHeaders as $header => $values) {
  517. $response->headers->set($header, $values);
  518. }
  519. }
  520. // now that the response is cached, release the lock
  521. $this->store->unlock($request);
  522. }
  523. /**
  524. * Restores the Response body.
  525. */
  526. private function restoreResponseBody(Request $request, Response $response): void
  527. {
  528. if ($response->headers->has('X-Body-Eval')) {
  529. \assert(self::BODY_EVAL_BOUNDARY_LENGTH === 24);
  530. ob_start();
  531. $content = $response->getContent();
  532. $boundary = substr($content, 0, 24);
  533. $j = strpos($content, $boundary, 24);
  534. echo substr($content, 24, $j - 24);
  535. $i = $j + 24;
  536. while (false !== $j = strpos($content, $boundary, $i)) {
  537. [$uri, $alt, $ignoreErrors, $part] = explode("\n", substr($content, $i, $j - $i), 4);
  538. $i = $j + 24;
  539. echo $this->surrogate->handle($this, $uri, $alt, $ignoreErrors);
  540. echo $part;
  541. }
  542. $response->setContent(ob_get_clean());
  543. $response->headers->remove('X-Body-Eval');
  544. if (!$response->headers->has('Transfer-Encoding')) {
  545. $response->headers->set('Content-Length', \strlen($response->getContent()));
  546. }
  547. } elseif ($response->headers->has('X-Body-File')) {
  548. // Response does not include possibly dynamic content (ESI, SSI), so we need
  549. // not handle the content for HEAD requests
  550. if (!$request->isMethod('HEAD')) {
  551. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  552. }
  553. } else {
  554. return;
  555. }
  556. $response->headers->remove('X-Body-File');
  557. }
  558. protected function processResponseBody(Request $request, Response $response): void
  559. {
  560. if ($this->surrogate?->needsParsing($response)) {
  561. $this->surrogate->process($request, $response);
  562. }
  563. }
  564. /**
  565. * Checks if the Request includes authorization or other sensitive information
  566. * that should cause the Response to be considered private by default.
  567. */
  568. private function isPrivateRequest(Request $request): bool
  569. {
  570. foreach ($this->options['private_headers'] as $key) {
  571. $key = strtolower(str_replace('HTTP_', '', $key));
  572. if ('cookie' === $key) {
  573. if (\count($request->cookies->all())) {
  574. return true;
  575. }
  576. } elseif ($request->headers->has($key)) {
  577. return true;
  578. }
  579. }
  580. return false;
  581. }
  582. /**
  583. * Records that an event took place.
  584. */
  585. private function record(Request $request, string $event): void
  586. {
  587. $this->traces[$this->getTraceKey($request)][] = $event;
  588. }
  589. /**
  590. * Calculates the key we use in the "trace" array for a given request.
  591. */
  592. private function getTraceKey(Request $request): string
  593. {
  594. $path = $request->getPathInfo();
  595. if ($qs = $request->getQueryString()) {
  596. $path .= '?'.$qs;
  597. }
  598. try {
  599. return $request->getMethod().' '.$path;
  600. } catch (SuspiciousOperationException) {
  601. return '_BAD_METHOD_ '.$path;
  602. }
  603. }
  604. /**
  605. * Checks whether the given (cached) response may be served as "stale" when a revalidation
  606. * is currently in progress.
  607. */
  608. private function mayServeStaleWhileRevalidate(Response $entry): bool
  609. {
  610. $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
  611. $timeout ??= $this->options['stale_while_revalidate'];
  612. $age = $entry->getAge();
  613. $maxAge = $entry->getMaxAge() ?? 0;
  614. $ttl = $maxAge - $age;
  615. return abs($ttl) < $timeout;
  616. }
  617. /**
  618. * Waits for the store to release a locked entry.
  619. */
  620. private function waitForLock(Request $request): bool
  621. {
  622. $wait = 0;
  623. while ($this->store->isLocked($request) && $wait < 100) {
  624. usleep(50000);
  625. ++$wait;
  626. }
  627. return $wait < 100;
  628. }
  629. }