Redis.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Robin McCorkell <robin@mccorkell.me.uk>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Stefan Weil <sw@weilnetz.de>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Memcache;
  31. use OCP\IMemcacheTTL;
  32. class Redis extends Cache implements IMemcacheTTL {
  33. /** name => [script, sha1] */
  34. public const LUA_SCRIPTS = [
  35. 'dec' => [
  36. 'if redis.call("exists", KEYS[1]) == 1 then return redis.call("decrby", KEYS[1], ARGV[1]) else return "NEX" end',
  37. '720b40cb66cef1579f2ef16ec69b3da8c85510e9',
  38. ],
  39. 'cas' => [
  40. 'if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("set", KEYS[1], ARGV[2]) return 1 else return 0 end',
  41. '94eac401502554c02b811e3199baddde62d976d4',
  42. ],
  43. 'cad' => [
  44. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
  45. 'cf0e94b2e9ffc7e04395cf88f7583fc309985910',
  46. ],
  47. ];
  48. /**
  49. * @var \Redis|\RedisCluster $cache
  50. */
  51. private static $cache = null;
  52. public function __construct($prefix = '', string $logFile = '') {
  53. parent::__construct($prefix);
  54. }
  55. /**
  56. * @return \Redis|\RedisCluster|null
  57. * @throws \Exception
  58. */
  59. public function getCache() {
  60. if (is_null(self::$cache)) {
  61. self::$cache = \OC::$server->getGetRedisFactory()->getInstance();
  62. }
  63. return self::$cache;
  64. }
  65. public function get($key) {
  66. $result = $this->getCache()->get($this->getPrefix() . $key);
  67. if ($result === false) {
  68. return null;
  69. }
  70. return self::decodeValue($result);
  71. }
  72. public function set($key, $value, $ttl = 0) {
  73. $value = self::encodeValue($value);
  74. if ($ttl > 0) {
  75. return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
  76. } else {
  77. return $this->getCache()->set($this->getPrefix() . $key, $value);
  78. }
  79. }
  80. public function hasKey($key) {
  81. return (bool)$this->getCache()->exists($this->getPrefix() . $key);
  82. }
  83. public function remove($key) {
  84. if ($this->getCache()->unlink($this->getPrefix() . $key)) {
  85. return true;
  86. } else {
  87. return false;
  88. }
  89. }
  90. public function clear($prefix = '') {
  91. // TODO: this is slow and would fail with Redis cluster
  92. $prefix = $this->getPrefix() . $prefix . '*';
  93. $keys = $this->getCache()->keys($prefix);
  94. $deleted = $this->getCache()->del($keys);
  95. return (is_array($keys) && (count($keys) === $deleted));
  96. }
  97. /**
  98. * Set a value in the cache if it's not already stored
  99. *
  100. * @param string $key
  101. * @param mixed $value
  102. * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
  103. * @return bool
  104. */
  105. public function add($key, $value, $ttl = 0) {
  106. $value = self::encodeValue($value);
  107. $args = ['nx'];
  108. if ($ttl !== 0 && is_int($ttl)) {
  109. $args['ex'] = $ttl;
  110. }
  111. return $this->getCache()->set($this->getPrefix() . $key, $value, $args);
  112. }
  113. /**
  114. * Increase a stored number
  115. *
  116. * @param string $key
  117. * @param int $step
  118. * @return int | bool
  119. */
  120. public function inc($key, $step = 1) {
  121. return $this->getCache()->incrBy($this->getPrefix() . $key, $step);
  122. }
  123. /**
  124. * Decrease a stored number
  125. *
  126. * @param string $key
  127. * @param int $step
  128. * @return int | bool
  129. */
  130. public function dec($key, $step = 1) {
  131. $res = $this->evalLua('dec', [$key], [$step]);
  132. return ($res === 'NEX') ? false : $res;
  133. }
  134. /**
  135. * Compare and set
  136. *
  137. * @param string $key
  138. * @param mixed $old
  139. * @param mixed $new
  140. * @return bool
  141. */
  142. public function cas($key, $old, $new) {
  143. $old = self::encodeValue($old);
  144. $new = self::encodeValue($new);
  145. return $this->evalLua('cas', [$key], [$old, $new]) > 0;
  146. }
  147. /**
  148. * Compare and delete
  149. *
  150. * @param string $key
  151. * @param mixed $old
  152. * @return bool
  153. */
  154. public function cad($key, $old) {
  155. $old = self::encodeValue($old);
  156. return $this->evalLua('cad', [$key], [$old]) > 0;
  157. }
  158. public function setTTL($key, $ttl) {
  159. $this->getCache()->expire($this->getPrefix() . $key, $ttl);
  160. }
  161. public static function isAvailable(): bool {
  162. return \OC::$server->getGetRedisFactory()->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 (false === $result) {
  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. }