Redis.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Memcache;
  8. use OCP\IMemcacheTTL;
  9. class Redis extends Cache implements IMemcacheTTL {
  10. /** name => [script, sha1] */
  11. public const LUA_SCRIPTS = [
  12. 'dec' => [
  13. 'if redis.call("exists", KEYS[1]) == 1 then return redis.call("decrby", KEYS[1], ARGV[1]) else return "NEX" end',
  14. '720b40cb66cef1579f2ef16ec69b3da8c85510e9',
  15. ],
  16. 'cas' => [
  17. 'if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("set", KEYS[1], ARGV[2]) return 1 else return 0 end',
  18. '94eac401502554c02b811e3199baddde62d976d4',
  19. ],
  20. 'cad' => [
  21. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
  22. 'cf0e94b2e9ffc7e04395cf88f7583fc309985910',
  23. ],
  24. 'caSetTtl' => [
  25. 'if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("expire", KEYS[1], ARGV[2]) return 1 else return 0 end',
  26. 'fa4acbc946d23ef41d7d3910880b60e6e4972d72',
  27. ],
  28. ];
  29. private const MAX_TTL = 30 * 24 * 60 * 60; // 1 month
  30. /**
  31. * @var \Redis|\RedisCluster $cache
  32. */
  33. private static $cache = null;
  34. public function __construct($prefix = '', string $logFile = '') {
  35. parent::__construct($prefix);
  36. }
  37. /**
  38. * @return \Redis|\RedisCluster|null
  39. * @throws \Exception
  40. */
  41. public function getCache() {
  42. if (is_null(self::$cache)) {
  43. self::$cache = \OC::$server->get('RedisFactory')->getInstance();
  44. }
  45. return self::$cache;
  46. }
  47. public function get($key) {
  48. $result = $this->getCache()->get($this->getPrefix() . $key);
  49. if ($result === false) {
  50. return null;
  51. }
  52. return self::decodeValue($result);
  53. }
  54. public function set($key, $value, $ttl = 0) {
  55. $value = self::encodeValue($value);
  56. if ($ttl === 0) {
  57. // having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
  58. $ttl = self::DEFAULT_TTL;
  59. }
  60. $ttl = min($ttl, self::MAX_TTL);
  61. return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
  62. }
  63. public function hasKey($key) {
  64. return (bool)$this->getCache()->exists($this->getPrefix() . $key);
  65. }
  66. public function remove($key) {
  67. if ($this->getCache()->unlink($this->getPrefix() . $key)) {
  68. return true;
  69. } else {
  70. return false;
  71. }
  72. }
  73. public function clear($prefix = '') {
  74. // TODO: this is slow and would fail with Redis cluster
  75. $prefix = $this->getPrefix() . $prefix . '*';
  76. $keys = $this->getCache()->keys($prefix);
  77. $deleted = $this->getCache()->del($keys);
  78. return (is_array($keys) && (count($keys) === $deleted));
  79. }
  80. /**
  81. * Set a value in the cache if it's not already stored
  82. *
  83. * @param string $key
  84. * @param mixed $value
  85. * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
  86. * @return bool
  87. */
  88. public function add($key, $value, $ttl = 0) {
  89. $value = self::encodeValue($value);
  90. if ($ttl === 0) {
  91. // having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
  92. $ttl = self::DEFAULT_TTL;
  93. }
  94. $ttl = min($ttl, self::MAX_TTL);
  95. $args = ['nx'];
  96. $args['ex'] = $ttl;
  97. return $this->getCache()->set($this->getPrefix() . $key, $value, $args);
  98. }
  99. /**
  100. * Increase a stored number
  101. *
  102. * @param string $key
  103. * @param int $step
  104. * @return int | bool
  105. */
  106. public function inc($key, $step = 1) {
  107. return $this->getCache()->incrBy($this->getPrefix() . $key, $step);
  108. }
  109. /**
  110. * Decrease a stored number
  111. *
  112. * @param string $key
  113. * @param int $step
  114. * @return int | bool
  115. */
  116. public function dec($key, $step = 1) {
  117. $res = $this->evalLua('dec', [$key], [$step]);
  118. return ($res === 'NEX') ? false : $res;
  119. }
  120. /**
  121. * Compare and set
  122. *
  123. * @param string $key
  124. * @param mixed $old
  125. * @param mixed $new
  126. * @return bool
  127. */
  128. public function cas($key, $old, $new) {
  129. $old = self::encodeValue($old);
  130. $new = self::encodeValue($new);
  131. return $this->evalLua('cas', [$key], [$old, $new]) > 0;
  132. }
  133. /**
  134. * Compare and delete
  135. *
  136. * @param string $key
  137. * @param mixed $old
  138. * @return bool
  139. */
  140. public function cad($key, $old) {
  141. $old = self::encodeValue($old);
  142. return $this->evalLua('cad', [$key], [$old]) > 0;
  143. }
  144. public function setTTL($key, $ttl) {
  145. if ($ttl === 0) {
  146. // having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
  147. $ttl = self::DEFAULT_TTL;
  148. }
  149. $ttl = min($ttl, self::MAX_TTL);
  150. $this->getCache()->expire($this->getPrefix() . $key, $ttl);
  151. }
  152. public function getTTL(string $key): int|false {
  153. $ttl = $this->getCache()->ttl($this->getPrefix() . $key);
  154. return $ttl > 0 ? (int)$ttl : false;
  155. }
  156. public function compareSetTTL(string $key, mixed $value, int $ttl): bool {
  157. $value = self::encodeValue($value);
  158. return $this->evalLua('caSetTtl', [$key], [$value, $ttl]) > 0;
  159. }
  160. public static function isAvailable(): bool {
  161. return \OC::$server->get('RedisFactory')->isAvailable();
  162. }
  163. protected function evalLua(string $scriptName, array $keys, array $args) {
  164. $keys = array_map(fn ($key) => $this->getPrefix() . $key, $keys);
  165. $args = array_merge($keys, $args);
  166. $script = self::LUA_SCRIPTS[$scriptName];
  167. $result = $this->getCache()->evalSha($script[1], $args, count($keys));
  168. if ($result === false) {
  169. $result = $this->getCache()->eval($script[0], $args, count($keys));
  170. }
  171. return $result;
  172. }
  173. protected static function encodeValue(mixed $value): string {
  174. return is_int($value) ? (string) $value : json_encode($value);
  175. }
  176. protected static function decodeValue(string $value): mixed {
  177. return is_numeric($value) ? (int) $value : json_decode($value, true);
  178. }
  179. }