Redis.php 6.0 KB

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