1
0

Redis.php 5.5 KB

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