CouchbaseBucketCache.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Common\Cache;
  4. use Couchbase\Bucket;
  5. use Couchbase\Document;
  6. use Couchbase\Exception;
  7. use RuntimeException;
  8. use function phpversion;
  9. use function serialize;
  10. use function sprintf;
  11. use function substr;
  12. use function time;
  13. use function unserialize;
  14. use function version_compare;
  15. /**
  16. * Couchbase ^2.3.0 cache provider.
  17. */
  18. final class CouchbaseBucketCache extends CacheProvider
  19. {
  20. private const MINIMUM_VERSION = '2.3.0';
  21. private const KEY_NOT_FOUND = 13;
  22. private const MAX_KEY_LENGTH = 250;
  23. private const THIRTY_DAYS_IN_SECONDS = 2592000;
  24. /** @var Bucket */
  25. private $bucket;
  26. public function __construct(Bucket $bucket)
  27. {
  28. if (version_compare(phpversion('couchbase'), self::MINIMUM_VERSION) < 0) {
  29. // Manager is required to flush cache and pull stats.
  30. throw new RuntimeException(sprintf('ext-couchbase:^%s is required.', self::MINIMUM_VERSION));
  31. }
  32. $this->bucket = $bucket;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected function doFetch($id)
  38. {
  39. $id = $this->normalizeKey($id);
  40. try {
  41. $document = $this->bucket->get($id);
  42. } catch (Exception $e) {
  43. return false;
  44. }
  45. if ($document instanceof Document && $document->value !== false) {
  46. return unserialize($document->value);
  47. }
  48. return false;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. protected function doContains($id)
  54. {
  55. $id = $this->normalizeKey($id);
  56. try {
  57. $document = $this->bucket->get($id);
  58. } catch (Exception $e) {
  59. return false;
  60. }
  61. if ($document instanceof Document) {
  62. return ! $document->error;
  63. }
  64. return false;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. protected function doSave($id, $data, $lifeTime = 0)
  70. {
  71. $id = $this->normalizeKey($id);
  72. $lifeTime = $this->normalizeExpiry($lifeTime);
  73. try {
  74. $encoded = serialize($data);
  75. $document = $this->bucket->upsert($id, $encoded, [
  76. 'expiry' => (int) $lifeTime,
  77. ]);
  78. } catch (Exception $e) {
  79. return false;
  80. }
  81. if ($document instanceof Document) {
  82. return ! $document->error;
  83. }
  84. return false;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. protected function doDelete($id)
  90. {
  91. $id = $this->normalizeKey($id);
  92. try {
  93. $document = $this->bucket->remove($id);
  94. } catch (Exception $e) {
  95. return $e->getCode() === self::KEY_NOT_FOUND;
  96. }
  97. if ($document instanceof Document) {
  98. return ! $document->error;
  99. }
  100. return false;
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. protected function doFlush()
  106. {
  107. $manager = $this->bucket->manager();
  108. // Flush does not return with success or failure, and must be enabled per bucket on the server.
  109. // Store a marker item so that we will know if it was successful.
  110. $this->doSave(__METHOD__, true, 60);
  111. $manager->flush();
  112. if ($this->doContains(__METHOD__)) {
  113. $this->doDelete(__METHOD__);
  114. return false;
  115. }
  116. return true;
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. protected function doGetStats()
  122. {
  123. $manager = $this->bucket->manager();
  124. $stats = $manager->info();
  125. $nodes = $stats['nodes'];
  126. $node = $nodes[0];
  127. $interestingStats = $node['interestingStats'];
  128. return [
  129. Cache::STATS_HITS => $interestingStats['get_hits'],
  130. Cache::STATS_MISSES => $interestingStats['cmd_get'] - $interestingStats['get_hits'],
  131. Cache::STATS_UPTIME => $node['uptime'],
  132. Cache::STATS_MEMORY_USAGE => $interestingStats['mem_used'],
  133. Cache::STATS_MEMORY_AVAILABLE => $node['memoryFree'],
  134. ];
  135. }
  136. private function normalizeKey(string $id) : string
  137. {
  138. $normalized = substr($id, 0, self::MAX_KEY_LENGTH);
  139. if ($normalized === false) {
  140. return $id;
  141. }
  142. return $normalized;
  143. }
  144. /**
  145. * Expiry treated as a unix timestamp instead of an offset if expiry is greater than 30 days.
  146. *
  147. * @src https://developer.couchbase.com/documentation/server/4.1/developer-guide/expiry.html
  148. */
  149. private function normalizeExpiry(int $expiry) : int
  150. {
  151. if ($expiry > self::THIRTY_DAYS_IN_SECONDS) {
  152. return time() + $expiry;
  153. }
  154. return $expiry;
  155. }
  156. }