AbstractAdapterTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 = strtr(substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5), '/', '_');
  106. try {
  107. $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  108. } catch (\Exception $e) {
  109. $cleared = false;
  110. }
  111. if ($cleared = true === $cleared || [] === $cleared) {
  112. $this->namespaceVersion = $namespaceVersion;
  113. $this->ids = [];
  114. }
  115. } else {
  116. $namespaceToClear = $this->namespace.$prefix;
  117. }
  118. try {
  119. return $this->doClear($namespaceToClear) || $cleared;
  120. } catch (\Exception $e) {
  121. CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  122. return false;
  123. }
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function deleteItem(mixed $key): bool
  129. {
  130. return $this->deleteItems([$key]);
  131. }
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function deleteItems(array $keys): bool
  136. {
  137. $ids = [];
  138. foreach ($keys as $key) {
  139. $ids[$key] = $this->getId($key);
  140. unset($this->deferred[$key]);
  141. }
  142. try {
  143. if ($this->doDelete($ids)) {
  144. return true;
  145. }
  146. } catch (\Exception $e) {
  147. }
  148. $ok = true;
  149. // When bulk-delete failed, retry each item individually
  150. foreach ($ids as $key => $id) {
  151. try {
  152. $e = null;
  153. if ($this->doDelete([$id])) {
  154. continue;
  155. }
  156. } catch (\Exception $e) {
  157. }
  158. $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  159. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  160. $ok = false;
  161. }
  162. return $ok;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. public function getItem(mixed $key): CacheItem
  168. {
  169. $id = $this->getId($key);
  170. if (isset($this->deferred[$key])) {
  171. $this->commit();
  172. }
  173. $isHit = false;
  174. $value = null;
  175. try {
  176. foreach ($this->doFetch([$id]) as $value) {
  177. $isHit = true;
  178. }
  179. return (self::$createCacheItem)($key, $value, $isHit);
  180. } catch (\Exception $e) {
  181. CacheItem::log($this->logger, 'Failed to fetch key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  182. }
  183. return (self::$createCacheItem)($key, null, false);
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function getItems(array $keys = []): iterable
  189. {
  190. $ids = [];
  191. $commit = false;
  192. foreach ($keys as $key) {
  193. $ids[] = $this->getId($key);
  194. $commit = $commit || isset($this->deferred[$key]);
  195. }
  196. if ($commit) {
  197. $this->commit();
  198. }
  199. try {
  200. $items = $this->doFetch($ids);
  201. } catch (\Exception $e) {
  202. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => $keys, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  203. $items = [];
  204. }
  205. $ids = array_combine($ids, $keys);
  206. return $this->generateItems($items, $ids);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function save(CacheItemInterface $item): bool
  212. {
  213. if (!$item instanceof CacheItem) {
  214. return false;
  215. }
  216. $this->deferred[$item->getKey()] = $item;
  217. return $this->commit();
  218. }
  219. /**
  220. * {@inheritdoc}
  221. */
  222. public function saveDeferred(CacheItemInterface $item): bool
  223. {
  224. if (!$item instanceof CacheItem) {
  225. return false;
  226. }
  227. $this->deferred[$item->getKey()] = $item;
  228. return true;
  229. }
  230. /**
  231. * Enables/disables versioning of items.
  232. *
  233. * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  234. * but old keys may need garbage collection and extra round-trips to the back-end are required.
  235. *
  236. * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
  237. *
  238. * @return bool the previous state of versioning
  239. */
  240. public function enableVersioning(bool $enable = true): bool
  241. {
  242. $wasEnabled = $this->versioningIsEnabled;
  243. $this->versioningIsEnabled = $enable;
  244. $this->namespaceVersion = '';
  245. $this->ids = [];
  246. return $wasEnabled;
  247. }
  248. /**
  249. * {@inheritdoc}
  250. */
  251. public function reset()
  252. {
  253. if ($this->deferred) {
  254. $this->commit();
  255. }
  256. $this->namespaceVersion = '';
  257. $this->ids = [];
  258. }
  259. public function __sleep(): array
  260. {
  261. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  262. }
  263. public function __wakeup()
  264. {
  265. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  266. }
  267. public function __destruct()
  268. {
  269. if ($this->deferred) {
  270. $this->commit();
  271. }
  272. }
  273. private function generateItems(iterable $items, array &$keys): \Generator
  274. {
  275. $f = self::$createCacheItem;
  276. try {
  277. foreach ($items as $id => $value) {
  278. if (!isset($keys[$id])) {
  279. throw new InvalidArgumentException(sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys)));
  280. }
  281. $key = $keys[$id];
  282. unset($keys[$id]);
  283. yield $key => $f($key, $value, true);
  284. }
  285. } catch (\Exception $e) {
  286. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => array_values($keys), 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  287. }
  288. foreach ($keys as $key) {
  289. yield $key => $f($key, null, false);
  290. }
  291. }
  292. private function getId(mixed $key)
  293. {
  294. if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  295. $this->ids = [];
  296. $this->namespaceVersion = '1'.static::NS_SEPARATOR;
  297. try {
  298. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  299. $this->namespaceVersion = $v;
  300. }
  301. if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  302. $this->namespaceVersion = strtr(substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5), '/', '_');
  303. $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  304. }
  305. } catch (\Exception $e) {
  306. }
  307. }
  308. if (\is_string($key) && isset($this->ids[$key])) {
  309. return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  310. }
  311. \assert('' !== CacheItem::validateKey($key));
  312. $this->ids[$key] = $key;
  313. if (\count($this->ids) > 1000) {
  314. array_splice($this->ids, 0, 500); // stop memory leak if there are many keys
  315. }
  316. if (null === $this->maxIdLength) {
  317. return $this->namespace.$this->namespaceVersion.$key;
  318. }
  319. if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  320. // Use MD5 to favor speed over security, which is not an issue here
  321. $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  322. $id = $this->namespace.$this->namespaceVersion.$id;
  323. }
  324. return $id;
  325. }
  326. /**
  327. * @internal
  328. */
  329. public static function handleUnserializeCallback(string $class)
  330. {
  331. throw new \DomainException('Class not found: '.$class);
  332. }
  333. }