ResponseCacheStrategy.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. namespace Symfony\Component\HttpKernel\HttpCache;
  11. use Symfony\Component\HttpFoundation\Response;
  12. /**
  13. * ResponseCacheStrategy knows how to compute the Response cache HTTP header
  14. * based on the different response cache headers.
  15. *
  16. * This implementation changes the main response TTL to the smallest TTL received
  17. * or force validation if one of the surrogates has validation cache strategy.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class ResponseCacheStrategy implements ResponseCacheStrategyInterface
  22. {
  23. /**
  24. * Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
  25. */
  26. private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
  27. /**
  28. * Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
  29. */
  30. private const INHERIT_DIRECTIVES = ['public', 'immutable'];
  31. private int $embeddedResponses = 0;
  32. private bool $isNotCacheableResponseEmbedded = false;
  33. private int $age = 0;
  34. private \DateTimeInterface|false|null $lastModified = null;
  35. private array $flagDirectives = [
  36. 'no-cache' => null,
  37. 'no-store' => null,
  38. 'no-transform' => null,
  39. 'must-revalidate' => null,
  40. 'proxy-revalidate' => null,
  41. 'public' => null,
  42. 'private' => null,
  43. 'immutable' => null,
  44. ];
  45. private array $ageDirectives = [
  46. 'max-age' => null,
  47. 's-maxage' => null,
  48. 'expires' => false,
  49. ];
  50. /**
  51. * @return void
  52. */
  53. public function add(Response $response)
  54. {
  55. ++$this->embeddedResponses;
  56. foreach (self::OVERRIDE_DIRECTIVES as $directive) {
  57. if ($response->headers->hasCacheControlDirective($directive)) {
  58. $this->flagDirectives[$directive] = true;
  59. }
  60. }
  61. foreach (self::INHERIT_DIRECTIVES as $directive) {
  62. if (false !== $this->flagDirectives[$directive]) {
  63. $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
  64. }
  65. }
  66. $age = $response->getAge();
  67. $this->age = max($this->age, $age);
  68. if ($this->willMakeFinalResponseUncacheable($response)) {
  69. $this->isNotCacheableResponseEmbedded = true;
  70. return;
  71. }
  72. $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
  73. $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
  74. $expires = $response->getExpires();
  75. $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
  76. // See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
  77. // If a response is "public" but does not have maximum lifetime, heuristics might be applied.
  78. // Do not store NULL values so the final response can have more limiting value from other responses.
  79. $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public')
  80. && null === $maxAge
  81. && null === $sharedMaxAge
  82. && null === $expires;
  83. if (!$isHeuristicallyCacheable || null !== $maxAge || null !== $expires) {
  84. $this->storeRelativeAgeDirective('max-age', $maxAge, $expires, $age);
  85. }
  86. if (!$isHeuristicallyCacheable || null !== $sharedMaxAge || null !== $expires) {
  87. $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $expires, $age);
  88. }
  89. if (null !== $expires) {
  90. $this->ageDirectives['expires'] = true;
  91. }
  92. if (false !== $this->lastModified) {
  93. $lastModified = $response->getLastModified();
  94. $this->lastModified = $lastModified ? max($this->lastModified, $lastModified) : false;
  95. }
  96. }
  97. /**
  98. * @return void
  99. */
  100. public function update(Response $response)
  101. {
  102. // if we have no embedded Response, do nothing
  103. if (0 === $this->embeddedResponses) {
  104. return;
  105. }
  106. // Remove Etag since it cannot be merged from embedded responses.
  107. $response->setEtag(null);
  108. $this->add($response);
  109. $response->headers->set('Age', $this->age);
  110. if ($this->isNotCacheableResponseEmbedded) {
  111. $response->setLastModified(null);
  112. if ($this->flagDirectives['no-store']) {
  113. $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
  114. } else {
  115. $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
  116. }
  117. return;
  118. }
  119. $response->setLastModified($this->lastModified ?: null);
  120. $flags = array_filter($this->flagDirectives);
  121. if (isset($flags['must-revalidate'])) {
  122. $flags['no-cache'] = true;
  123. }
  124. $response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
  125. $maxAge = null;
  126. if (is_numeric($this->ageDirectives['max-age'])) {
  127. $maxAge = $this->ageDirectives['max-age'] + $this->age;
  128. $response->headers->addCacheControlDirective('max-age', $maxAge);
  129. }
  130. if (is_numeric($this->ageDirectives['s-maxage'])) {
  131. $sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
  132. if ($maxAge !== $sMaxage) {
  133. $response->headers->addCacheControlDirective('s-maxage', $sMaxage);
  134. }
  135. }
  136. if ($this->ageDirectives['expires'] && null !== $maxAge) {
  137. $date = clone $response->getDate();
  138. $date = $date->modify('+'.$maxAge.' seconds');
  139. $response->setExpires($date);
  140. }
  141. }
  142. /**
  143. * RFC2616, Section 13.4.
  144. *
  145. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
  146. */
  147. private function willMakeFinalResponseUncacheable(Response $response): bool
  148. {
  149. // RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
  150. // MAY be stored by a cache […] unless a cache-control directive prohibits caching.
  151. if ($response->headers->hasCacheControlDirective('no-cache')
  152. || $response->headers->hasCacheControlDirective('no-store')
  153. ) {
  154. return true;
  155. }
  156. // Etag headers cannot be merged, they render the response uncacheable
  157. // by default (except if the response also has max-age etc.).
  158. if (null === $response->getEtag() && \in_array($response->getStatusCode(), [200, 203, 300, 301, 410])) {
  159. return false;
  160. }
  161. // RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
  162. // MUST NOT be returned in a reply to a subsequent request unless there are
  163. // cache-control directives or another header(s) that explicitly allow it.
  164. $cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
  165. foreach ($cacheControl as $key) {
  166. if ($response->headers->hasCacheControlDirective($key)) {
  167. return false;
  168. }
  169. }
  170. if ($response->headers->has('Expires')) {
  171. return false;
  172. }
  173. return true;
  174. }
  175. /**
  176. * Store lowest max-age/s-maxage/expires for the final response.
  177. *
  178. * The response might have been stored in cache a while ago. To keep things comparable,
  179. * we have to subtract the age so that the value is normalized for an age of 0.
  180. *
  181. * If the value is lower than the currently stored value, we update the value, to keep a rolling
  182. * minimal value of each instruction. If the value is NULL, the directive will not be set on the final response.
  183. */
  184. private function storeRelativeAgeDirective(string $directive, ?int $value, ?int $expires, int $age): void
  185. {
  186. if (null === $value && null === $expires) {
  187. $this->ageDirectives[$directive] = false;
  188. }
  189. if (false !== $this->ageDirectives[$directive]) {
  190. $value = min($value ?? \PHP_INT_MAX, $expires ?? \PHP_INT_MAX);
  191. $value -= $age;
  192. $this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
  193. }
  194. }
  195. }