Redis.php 6.5 KB

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