]> git.mxchange.org Git - friendica.git/blob - src/Core/Cache/Type/RedisCache.php
Move Cache to strategies
[friendica.git] / src / Core / Cache / Type / RedisCache.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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 Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Cache\Capability\ICanCacheInMemory;
26 use Friendica\Core\Cache\Exception\CachePersistenceException;
27 use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
28 use Friendica\Core\Config\Capability\IManageConfigValues;
29 use Redis;
30
31 /**
32  * Redis Cache. This driver is based on Memcache driver
33  */
34 class RedisCache extends AbstractCache implements ICanCacheInMemory
35 {
36         public static $NAME = 'redis';
37
38         /**
39          * @var Redis
40          */
41         private $redis;
42
43         /**
44          * @throws InvalidCacheDriverException
45          * @throws CachePersistenceException
46          */
47         public function __construct(string $hostname, IManageConfigValues $config)
48         {
49                 if (!class_exists('Redis', false)) {
50                         throw new InvalidCacheDriverException('Redis class isn\'t available');
51                 }
52
53                 parent::__construct($hostname);
54
55                 $this->redis = new Redis();
56
57                 $redis_host = $config->get('system', 'redis_host');
58                 $redis_port = $config->get('system', 'redis_port');
59                 $redis_pw   = $config->get('system', 'redis_password');
60                 $redis_db   = $config->get('system', 'redis_db', 0);
61
62                 try {
63
64                         if (!empty($redis_port) && !@$this->redis->connect($redis_host, $redis_port)) {
65                                 throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
66                         } else if (!@$this->redis->connect($redis_host)) {
67                                 throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ' isn\'t available');
68                         }
69
70                         if (!empty($redis_pw) && !$this->redis->auth($redis_pw)) {
71                                 throw new CachePersistenceException('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port);
72                         }
73
74                         if ($redis_db !== 0 && !$this->redis->select($redis_db)) {
75                                 throw new CachePersistenceException('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port);
76                         }
77                 } catch (\RedisException $exception) {
78                         throw new CachePersistenceException('Redis connection fails unexpectedly', $exception);
79                 }
80         }
81
82         /**
83          * (@inheritdoc)
84          */
85         public function getAllKeys(?string $prefix = null): array
86         {
87                 if (empty($prefix)) {
88                         $search = '*';
89                 } else {
90                         $search = $prefix . '*';
91                 }
92
93                 $list = $this->redis->keys($this->getCacheKey($search));
94
95                 return $this->getOriginalKeys($list);
96         }
97
98         /**
99          * (@inheritdoc)
100          */
101         public function get(string $key)
102         {
103                 $return   = null;
104                 $cacheKey = $this->getCacheKey($key);
105
106                 $cached = $this->redis->get($cacheKey);
107                 if ($cached === false && !$this->redis->exists($cacheKey)) {
108                         return null;
109                 }
110
111                 $value = unserialize($cached);
112
113                 // Only return a value if the serialized value is valid.
114                 // We also check if the db entry is a serialized
115                 // boolean 'false' value (which we want to return).
116                 if ($cached === serialize(false) || $value !== false) {
117                         $return = $value;
118                 }
119
120                 return $return;
121         }
122
123         /**
124          * (@inheritdoc)
125          */
126         public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
127         {
128                 $cacheKey = $this->getCacheKey($key);
129
130                 $cached = serialize($value);
131
132                 if ($ttl > 0) {
133                         return $this->redis->setex(
134                                 $cacheKey,
135                                 $ttl,
136                                 $cached
137                         );
138                 } else {
139                         return $this->redis->set(
140                                 $cacheKey,
141                                 $cached
142                         );
143                 }
144         }
145
146         /**
147          * (@inheritdoc)
148          */
149         public function delete(string $key): bool
150         {
151                 $cacheKey = $this->getCacheKey($key);
152                 $this->redis->del($cacheKey);
153                 // Redis doesn't have an error state for del()
154                 return true;
155         }
156
157         /**
158          * (@inheritdoc)
159          */
160         public function clear(bool $outdated = true): bool
161         {
162                 if ($outdated) {
163                         return true;
164                 } else {
165                         return $this->redis->flushAll();
166                 }
167         }
168
169         /**
170          * (@inheritdoc)
171          */
172         public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
173         {
174                 $cacheKey = $this->getCacheKey($key);
175                 $cached   = serialize($value);
176
177                 return $this->redis->setnx($cacheKey, $cached);
178         }
179
180         /**
181          * (@inheritdoc)
182          */
183         public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
184         {
185                 $cacheKey = $this->getCacheKey($key);
186
187                 $newCached = serialize($newValue);
188
189                 $this->redis->watch($cacheKey);
190                 // If the old value isn't what we expected, somebody else changed the key meanwhile
191                 if ($this->get($key) === $oldValue) {
192                         if ($ttl > 0) {
193                                 $result = $this->redis->multi()->setex($cacheKey, $ttl, $newCached)->exec();
194                         } else {
195                                 $result = $this->redis->multi()->set($cacheKey, $newCached)->exec();
196                         }
197                         return $result !== false;
198                 }
199                 $this->redis->unwatch();
200                 return false;
201         }
202
203         /**
204          * (@inheritdoc)
205          */
206         public function compareDelete(string $key, $value): bool
207         {
208                 $cacheKey = $this->getCacheKey($key);
209
210                 $this->redis->watch($cacheKey);
211                 // If the old value isn't what we expected, somebody else changed the key meanwhile
212                 if ($this->get($key) === $value) {
213                         $this->redis->multi()->del($cacheKey)->exec();
214                         return true;
215                 }
216                 $this->redis->unwatch();
217                 return false;
218         }
219 }