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