]> git.mxchange.org Git - friendica.git/blob - src/Core/Cache/Type/RedisCache.php
Restructure Cache to follow new paradigm
[friendica.git] / src / Core / Cache / Type / RedisCache.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core\Cache\Type;
23
24 use Exception;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Cache\IMemoryCache;
27 use Friendica\Core\Cache\Enum\Type;
28 use Friendica\Core\Config\IConfig;
29 use Redis;
30
31 /**
32  * Redis Cache. This driver is based on Memcache driver
33  */
34 class RedisCache extends BaseCache implements IMemoryCache
35 {
36         /**
37          * @var Redis
38          */
39         private $redis;
40
41         /**
42          * @throws Exception
43          */
44         public function __construct(string $hostname, IConfig $config)
45         {
46                 if (!class_exists('Redis', false)) {
47                         throw new Exception('Redis class isn\'t available');
48                 }
49
50                 parent::__construct($hostname);
51
52                 $this->redis = new Redis();
53
54                 $redis_host = $config->get('system', 'redis_host');
55                 $redis_port = $config->get('system', 'redis_port');
56                 $redis_pw   = $config->get('system', 'redis_password');
57                 $redis_db   = $config->get('system', 'redis_db', 0);
58
59                 if (isset($redis_port) && !@$this->redis->connect($redis_host, $redis_port)) {
60                         throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
61                 } elseif (!@$this->redis->connect($redis_host)) {
62                         throw new Exception('Expected Redis server at ' . $redis_host . ' isn\'t available');
63                 }
64
65                 if (isset($redis_pw) && !$this->redis->auth($redis_pw)) {
66                         throw new Exception('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port);
67                 }
68
69                 if ($redis_db !== 0 && !$this->redis->select($redis_db)) {
70                         throw new Exception('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port);
71                 }
72         }
73
74         /**
75          * (@inheritdoc)
76          */
77         public function getAllKeys($prefix = null)
78         {
79                 if (empty($prefix)) {
80                         $search = '*';
81                 } else {
82                         $search = $prefix . '*';
83                 }
84
85                 $list = $this->redis->keys($this->getCacheKey($search));
86
87                 return $this->getOriginalKeys($list);
88         }
89
90         /**
91          * (@inheritdoc)
92          */
93         public function get($key)
94         {
95                 $return = null;
96                 $cachekey = $this->getCacheKey($key);
97
98                 $cached = $this->redis->get($cachekey);
99                 if ($cached === false && !$this->redis->exists($cachekey)) {
100                         return null;
101                 }
102
103                 $value = unserialize($cached);
104
105                 // Only return a value if the serialized value is valid.
106                 // We also check if the db entry is a serialized
107                 // boolean 'false' value (which we want to return).
108                 if ($cached === serialize(false) || $value !== false) {
109                         $return = $value;
110                 }
111
112                 return $return;
113         }
114
115         /**
116          * (@inheritdoc)
117          */
118         public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
119         {
120                 $cachekey = $this->getCacheKey($key);
121
122                 $cached = serialize($value);
123
124                 if ($ttl > 0) {
125                         return $this->redis->setex(
126                                 $cachekey,
127                                 $ttl,
128                                 $cached
129                         );
130                 } else {
131                         return $this->redis->set(
132                                 $cachekey,
133                                 $cached
134                         );
135                 }
136         }
137
138         /**
139          * (@inheritdoc)
140          */
141         public function delete($key)
142         {
143                 $cachekey = $this->getCacheKey($key);
144                 $this->redis->del($cachekey);
145                 // Redis doesn't have an error state for del()
146                 return true;
147         }
148
149         /**
150          * (@inheritdoc)
151          */
152         public function clear($outdated = true)
153         {
154                 if ($outdated) {
155                         return true;
156                 } else {
157                         return $this->redis->flushAll();
158                 }
159         }
160
161         /**
162          * (@inheritdoc)
163          */
164         public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
165         {
166                 $cachekey = $this->getCacheKey($key);
167                 $cached = serialize($value);
168
169                 return $this->redis->setnx($cachekey, $cached);
170         }
171
172         /**
173          * (@inheritdoc)
174          */
175         public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES)
176         {
177                 $cachekey = $this->getCacheKey($key);
178
179                 $newCached = serialize($newValue);
180
181                 $this->redis->watch($cachekey);
182                 // If the old value isn't what we expected, somebody else changed the key meanwhile
183                 if ($this->get($key) === $oldValue) {
184                         if ($ttl > 0) {
185                                 $result = $this->redis->multi()
186                                         ->setex($cachekey, $ttl, $newCached)
187                                         ->exec();
188                         } else {
189                                 $result = $this->redis->multi()
190                                         ->set($cachekey, $newCached)
191                                         ->exec();
192                         }
193                         return $result !== false;
194                 }
195                 $this->redis->unwatch();
196                 return false;
197         }
198
199         /**
200          * (@inheritdoc)
201          */
202         public function compareDelete($key, $value)
203         {
204                 $cachekey = $this->getCacheKey($key);
205
206                 $this->redis->watch($cachekey);
207                 // If the old value isn't what we expected, somebody else changed the key meanwhile
208                 if ($this->get($key) === $value) {
209                         $result = $this->redis->multi()
210                                 ->del($cachekey)
211                                 ->exec();
212                         return $result !== false;
213                 }
214                 $this->redis->unwatch();
215                 return false;
216         }
217
218         /**
219          * {@inheritDoc}
220          */
221         public function getName()
222         {
223                 return Type::REDIS;
224         }
225 }