1
0

Redis.php 5.8 KB

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