AbstractAdapterTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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\Cache\Traits;
  11. use Psr\Cache\CacheItemInterface;
  12. use Psr\Log\LoggerAwareTrait;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  15. /**
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. *
  18. * @internal
  19. */
  20. trait AbstractAdapterTrait
  21. {
  22. use LoggerAwareTrait;
  23. /**
  24. * needs to be set by class, signature is function(string <key>, mixed <value>, bool <isHit>).
  25. */
  26. private static \Closure $createCacheItem;
  27. /**
  28. * needs to be set by class, signature is function(array <deferred>, string <namespace>, array <&expiredIds>).
  29. */
  30. private static \Closure $mergeByLifetime;
  31. private string $namespace = '';
  32. private int $defaultLifetime;
  33. private string $namespaceVersion = '';
  34. private bool $versioningIsEnabled = false;
  35. private array $deferred = [];
  36. private array $ids = [];
  37. /**
  38. * @var int|null The maximum length to enforce for identifiers or null when no limit applies
  39. */
  40. protected $maxIdLength;
  41. /**
  42. * Fetches several cache items.
  43. *
  44. * @param array $ids The cache identifiers to fetch
  45. *
  46. * @return array|\Traversable
  47. */
  48. abstract protected function doFetch(array $ids): iterable;
  49. /**
  50. * Confirms if the cache contains specified cache item.
  51. *
  52. * @param string $id The identifier for which to check existence
  53. */
  54. abstract protected function doHave(string $id): bool;
  55. /**
  56. * Deletes all items in the pool.
  57. *
  58. * @param string $namespace The prefix used for all identifiers managed by this pool
  59. */
  60. abstract protected function doClear(string $namespace): bool;
  61. /**
  62. * Removes multiple items from the pool.
  63. *
  64. * @param array $ids An array of identifiers that should be removed from the pool
  65. */
  66. abstract protected function doDelete(array $ids): bool;
  67. /**
  68. * Persists several cache items immediately.
  69. *
  70. * @param array $values The values to cache, indexed by their cache identifier
  71. * @param int $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
  72. *
  73. * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
  74. */
  75. abstract protected function doSave(array $values, int $lifetime): array|bool;
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function hasItem(mixed $key): bool
  80. {
  81. $id = $this->getId($key);
  82. if (isset($this->deferred[$key])) {
  83. $this->commit();
  84. }
  85. try {
  86. return $this->doHave($id);
  87. } catch (\Exception $e) {
  88. CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  89. return false;
  90. }
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function clear(string $prefix = ''): bool
  96. {
  97. $this->deferred = [];
  98. if ($cleared = $this->versioningIsEnabled) {
  99. if ('' === $namespaceVersionToClear = $this->namespaceVersion) {
  100. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  101. $namespaceVersionToClear = $v;
  102. }
  103. }
  104. $namespaceToClear = $this->namespace.$namespaceVersionToClear;
  105. $namespaceVersion = self::formatNamespaceVersion(mt_rand());
  106. try {
  107. $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  108. } catch (\Exception $e) {
  109. }
  110. if (true !== $e && [] !== $e) {
  111. $cleared = false;
  112. $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  113. CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
  114. } else {
  115. $this->namespaceVersion = $namespaceVersion;
  116. $this->ids = [];
  117. }
  118. } else {
  119. $namespaceToClear = $this->namespace.$prefix;
  120. }
  121. try {
  122. return $this->doClear($namespaceToClear) || $cleared;
  123. } catch (\Exception $e) {
  124. CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  125. return false;
  126. }
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. public function deleteItem(mixed $key): bool
  132. {
  133. return $this->deleteItems([$key]);
  134. }
  135. /**
  136. * {@inheritdoc}
  137. */
  138. public function deleteItems(array $keys): bool
  139. {
  140. $ids = [];
  141. foreach ($keys as $key) {
  142. $ids[$key] = $this->getId($key);
  143. unset($this->deferred[$key]);
  144. }
  145. try {
  146. if ($this->doDelete($ids)) {
  147. return true;
  148. }
  149. } catch (\Exception $e) {
  150. }
  151. $ok = true;
  152. // When bulk-delete failed, retry each item individually
  153. foreach ($ids as $key => $id) {
  154. try {
  155. $e = null;
  156. if ($this->doDelete([$id])) {
  157. continue;
  158. }
  159. } catch (\Exception $e) {
  160. }
  161. $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  162. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  163. $ok = false;
  164. }
  165. return $ok;
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function getItem(mixed $key): CacheItem
  171. {
  172. $id = $this->getId($key);
  173. if (isset($this->deferred[$key])) {
  174. $this->commit();
  175. }
  176. $isHit = false;
  177. $value = null;
  178. try {
  179. foreach ($this->doFetch([$id]) as $value) {
  180. $isHit = true;
  181. }
  182. return (self::$createCacheItem)($key, $value, $isHit);
  183. } catch (\Exception $e) {
  184. CacheItem::log($this->logger, 'Failed to fetch key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  185. }
  186. return (self::$createCacheItem)($key, null, false);
  187. }
  188. /**
  189. * {@inheritdoc}
  190. */
  191. public function getItems(array $keys = []): iterable
  192. {
  193. $ids = [];
  194. $commit = false;
  195. foreach ($keys as $key) {
  196. $ids[] = $this->getId($key);
  197. $commit = $commit || isset($this->deferred[$key]);
  198. }
  199. if ($commit) {
  200. $this->commit();
  201. }
  202. try {
  203. $items = $this->doFetch($ids);
  204. } catch (\Exception $e) {
  205. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => $keys, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  206. $items = [];
  207. }
  208. $ids = array_combine($ids, $keys);
  209. return $this->generateItems($items, $ids);
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function save(CacheItemInterface $item): bool
  215. {
  216. if (!$item instanceof CacheItem) {
  217. return false;
  218. }
  219. $this->deferred[$item->getKey()] = $item;
  220. return $this->commit();
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function saveDeferred(CacheItemInterface $item): bool
  226. {
  227. if (!$item instanceof CacheItem) {
  228. return false;
  229. }
  230. $this->deferred[$item->getKey()] = $item;
  231. return true;
  232. }
  233. /**
  234. * Enables/disables versioning of items.
  235. *
  236. * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  237. * but old keys may need garbage collection and extra round-trips to the back-end are required.
  238. *
  239. * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
  240. *
  241. * @return bool the previous state of versioning
  242. */
  243. public function enableVersioning(bool $enable = true): bool
  244. {
  245. $wasEnabled = $this->versioningIsEnabled;
  246. $this->versioningIsEnabled = $enable;
  247. $this->namespaceVersion = '';
  248. $this->ids = [];
  249. return $wasEnabled;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function reset()
  255. {
  256. if ($this->deferred) {
  257. $this->commit();
  258. }
  259. $this->namespaceVersion = '';
  260. $this->ids = [];
  261. }
  262. public function __sleep(): array
  263. {
  264. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  265. }
  266. public function __wakeup()
  267. {
  268. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  269. }
  270. public function __destruct()
  271. {
  272. if ($this->deferred) {
  273. $this->commit();
  274. }
  275. }
  276. private function generateItems(iterable $items, array &$keys): \Generator
  277. {
  278. $f = self::$createCacheItem;
  279. try {
  280. foreach ($items as $id => $value) {
  281. if (!isset($keys[$id])) {
  282. throw new InvalidArgumentException(sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys)));
  283. }
  284. $key = $keys[$id];
  285. unset($keys[$id]);
  286. yield $key => $f($key, $value, true);
  287. }
  288. } catch (\Exception $e) {
  289. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => array_values($keys), 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  290. }
  291. foreach ($keys as $key) {
  292. yield $key => $f($key, null, false);
  293. }
  294. }
  295. private function getId(mixed $key)
  296. {
  297. if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  298. $this->ids = [];
  299. $this->namespaceVersion = '1'.static::NS_SEPARATOR;
  300. try {
  301. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  302. $this->namespaceVersion = $v;
  303. }
  304. $e = true;
  305. if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  306. $this->namespaceVersion = self::formatNamespaceVersion(time());
  307. $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  308. }
  309. } catch (\Exception $e) {
  310. }
  311. if (true !== $e && [] !== $e) {
  312. $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  313. CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null, 'cache-adapter' => get_debug_type($this)]);
  314. }
  315. }
  316. if (\is_string($key) && isset($this->ids[$key])) {
  317. return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  318. }
  319. \assert('' !== CacheItem::validateKey($key));
  320. $this->ids[$key] = $key;
  321. if (\count($this->ids) > 1000) {
  322. $this->ids = \array_slice($this->ids, 500, null, true); // stop memory leak if there are many keys
  323. }
  324. if (null === $this->maxIdLength) {
  325. return $this->namespace.$this->namespaceVersion.$key;
  326. }
  327. if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  328. // Use MD5 to favor speed over security, which is not an issue here
  329. $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  330. $id = $this->namespace.$this->namespaceVersion.$id;
  331. }
  332. return $id;
  333. }
  334. /**
  335. * @internal
  336. */
  337. public static function handleUnserializeCallback(string $class)
  338. {
  339. throw new \DomainException('Class not found: '.$class);
  340. }
  341. private static function formatNamespaceVersion(int $value): string
  342. {
  343. return strtr(substr_replace(base64_encode(pack('V', $value)), static::NS_SEPARATOR, 5), '/', '_');
  344. }
  345. }