1 | <?php |
||
2 | |||
3 | namespace Padosoft\SuperCache; |
||
4 | |||
5 | use Padosoft\SuperCache\Traits\ManagesLocksAndShardsTrait; |
||
6 | |||
7 | class SuperCacheManager |
||
8 | { |
||
9 | use ManagesLocksAndShardsTrait; |
||
10 | |||
11 | protected RedisConnector $redis; |
||
12 | protected int $numShards; |
||
13 | public string $prefix; |
||
14 | public bool $useNamespace; |
||
15 | |||
16 | /** |
||
17 | * Questa proprietà viene settata dinamicamente dove serve in base al nome della connessione |
||
18 | * |
||
19 | * @deprecated |
||
20 | */ |
||
21 | public bool $isCluster = false; |
||
22 | |||
23 | public function __construct(RedisConnector $redis) |
||
24 | { |
||
25 | $this->redis = $redis; |
||
26 | $this->prefix = config('supercache.prefix'); |
||
27 | $this->numShards = (int) config('supercache.num_shards'); // Numero di shard per tag |
||
28 | $this->useNamespace = (bool) config('supercache.use_namespace', false); // Flag per abilitare/disabilitare il namespace |
||
29 | } |
||
30 | |||
31 | private function serializeForRedis($value) |
||
32 | { |
||
33 | return is_numeric($value) ? $value : serialize($value); |
||
34 | } |
||
35 | |||
36 | private function unserializeForRedis($value) |
||
37 | { |
||
38 | return is_numeric($value) ? $value : unserialize($value); |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * Calcola il namespace in base alla chiave. |
||
43 | */ |
||
44 | protected function calculateNamespace(string $key): string |
||
45 | { |
||
46 | // Usa una funzione hash per ottenere un namespace coerente per la chiave |
||
47 | $hash = crc32($key); |
||
48 | $numNamespaces = (int) config('supercache.num_namespace', 16); // Numero di namespace configurabili |
||
49 | $namespaceIndex = $hash % $numNamespaces; |
||
50 | |||
51 | return 'ns' . $namespaceIndex; // Ad esempio, 'ns0', 'ns1', ..., 'ns15' |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Salva un valore nella cache senza tag. |
||
56 | * Il valore della chiave sarà serializzato tranne nel caso di valori numerici |
||
57 | */ |
||
58 | public function put(string $key, mixed $value, ?int $ttl = null, ?string $connection_name = null): void |
||
59 | { |
||
60 | // Calcola la chiave con o senza namespace in base alla configurazione |
||
61 | $finalKey = $this->getFinalKey($key); |
||
62 | if ($ttl !== null) { |
||
63 | $this->redis->getRedisConnection($connection_name)->setEx($finalKey, $ttl, $this->serializeForRedis($value)); |
||
64 | |||
65 | return; |
||
66 | } |
||
67 | $this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis($value)); |
||
68 | } |
||
69 | |||
70 | public function getTTLKey(string $key, ?string $connection_name = null, bool $isWithTags = false): int |
||
71 | { |
||
72 | // Calcola la chiave con o senza namespace in base alla configurazione |
||
73 | $finalKey = $this->getFinalKey($key, $isWithTags); |
||
74 | |||
75 | return $this->redis->getRedisConnection($connection_name)->ttl($finalKey); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
76 | } |
||
77 | |||
78 | /** |
||
79 | * Salva un valore nella cache con uno o più tag. |
||
80 | * Il valore della chiave sarà serializzato tranne nel caso di valori numerici |
||
81 | */ |
||
82 | public function putWithTags(string $key, mixed $value, array $tags, ?int $ttl = null, ?string $connection_name = null): void |
||
83 | { |
||
84 | $finalKey = $this->getFinalKey($key, true); |
||
85 | // Usa pipeline solo se non è un cluster |
||
86 | $isCluster = config('database.redis.clusters.' . ($connection_name ?? 'default')) !== null; |
||
87 | $advancedMode = (int) config('supercache.advancedMode', 0) === 1; |
||
88 | if (!$isCluster) { |
||
89 | $this->redis->pipeline(function ($pipe) use ($finalKey, $value, $tags, $ttl, $advancedMode) { |
||
90 | if ($ttl !== null) { |
||
91 | $pipe->setEx($finalKey, $ttl, $this->serializeForRedis($value)); |
||
92 | } else { |
||
93 | $pipe->set($finalKey, $this->serializeForRedis($value)); |
||
94 | } |
||
95 | |||
96 | foreach ($tags as $tag) { |
||
97 | $shard = $this->getShardNameForTag($tag, $finalKey); |
||
98 | $pipe->sadd($shard, $finalKey); |
||
99 | } |
||
100 | |||
101 | if ($advancedMode) { |
||
102 | $pipe->sadd($this->prefix . 'tags:' . $finalKey, ...$tags); |
||
103 | } |
||
104 | }, $connection_name); |
||
105 | } else { |
||
106 | if ($ttl !== null) { |
||
107 | $this->redis->getRedisConnection($connection_name)->setEx($finalKey, $ttl, $this->serializeForRedis($value)); |
||
108 | } else { |
||
109 | $this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis($value)); |
||
110 | } |
||
111 | foreach ($tags as $tag) { |
||
112 | $shard = $this->getShardNameForTag($tag, $finalKey); |
||
113 | $this->redis->getRedisConnection($connection_name)->sadd($shard, $finalKey); |
||
114 | } |
||
115 | if ($advancedMode) { |
||
116 | $this->redis->getRedisConnection($connection_name)->sadd($this->prefix . 'tags:' . $finalKey, ...$tags); |
||
117 | } |
||
118 | } |
||
119 | } |
||
120 | |||
121 | /** |
||
122 | * Memoizza un valore nella cache utilizzando tag specifici. |
||
123 | * |
||
124 | * Questa funzione memorizza un risultato di un callback in cache associato a dei tag specifici. |
||
125 | * Se il valore esiste già nella cache, viene semplicemente restituito. Altrimenti, viene |
||
126 | * eseguito il callback per ottenere il valore, che poi viene memorizzato con i tag specificati. |
||
127 | * |
||
128 | * @param string $key La chiave sotto la quale memorizzare il valore. |
||
129 | * @param array $tags Un array di tag associati al valore memorizzato. |
||
130 | * @param \Closure $callback La funzione di callback che fornisce il valore da memorizzare se non esistente. |
||
131 | * @param int|null $ttl Tempe di vita (time-to-live) in secondi del valore memorizzato. (opzionale) |
||
132 | * @param string|null $connection_name Il nome della connessione cache da utilizzare. (opzionale) |
||
133 | * @return mixed Il valore memorizzato e/o recuperato dalla cache. |
||
134 | */ |
||
135 | public function rememberWithTags($key, array $tags, \Closure $callback, ?int $ttl = null, ?string $connection_name = null) |
||
136 | { |
||
137 | $finalKey = $this->getFinalKey($key, true); |
||
138 | $value = $this->get($finalKey, $connection_name); |
||
139 | |||
140 | // Se esiste già , ok la ritorno |
||
141 | if ($value !== null) { |
||
142 | return $value; |
||
143 | } |
||
144 | |||
145 | $value = $callback(); |
||
146 | |||
147 | $this->putWithTags($key, $value, $tags, $ttl, $connection_name); |
||
148 | |||
149 | return $value; |
||
150 | } |
||
151 | |||
152 | /** |
||
153 | * Recupera un valore dalla cache. |
||
154 | * Il valore della chiave sarà deserializzato tranne nel caso di valori numerici |
||
155 | */ |
||
156 | public function get(string $key, ?string $connection_name = null, bool $isWithTags = false): mixed |
||
157 | { |
||
158 | $finalKey = $this->getFinalKey($key, $isWithTags); |
||
159 | |||
160 | $value = $this->redis->getRedisConnection($connection_name)->get($finalKey); |
||
161 | |||
162 | return $value ? $this->unserializeForRedis($value) : null; |
||
163 | } |
||
164 | |||
165 | /** |
||
166 | * Rimuove una chiave dalla cache e dai suoi set di tag. |
||
167 | */ |
||
168 | public function forget(string $key, ?string $connection_name = null, bool $isFinalKey = false, bool $isWithTags = false, bool $onlyTags = false): void |
||
169 | { |
||
170 | if ($isFinalKey) { |
||
171 | $finalKey = $key; |
||
172 | } else { |
||
173 | $finalKey = $this->getFinalKey($key, $isWithTags); |
||
174 | } |
||
175 | /* Inizio Log su Elastic */ |
||
176 | try { |
||
177 | $logToElasticFunction = config('supercache.log_to_elastic_function'); |
||
178 | // Metodo del progetto |
||
179 | if (is_callable($logToElasticFunction)) { |
||
180 | $logToElasticFunction('GESCAT_FORGET', $finalKey); |
||
181 | } |
||
182 | } catch (\Throwable $e) { |
||
0 ignored issues
–
show
Coding Style
Comprehensibility
introduced
by
|
|||
183 | } |
||
184 | /* Fine Log su Elastic */ |
||
185 | |||
186 | $advancedMode = (int) config('supercache.advancedMode', 0) === 1; |
||
187 | |||
188 | if (!$advancedMode) { |
||
189 | $this->redis->getRedisConnection($connection_name)->del($finalKey); |
||
190 | |||
191 | return; |
||
192 | } |
||
193 | |||
194 | // Recupera i tag associati alla chiave |
||
195 | $tags = $this->redis->getRedisConnection($connection_name)->smembers($this->prefix . 'tags:' . $finalKey); |
||
196 | $isCluster = config('database.redis.clusters.' . ($connection_name ?? 'default')) !== null; |
||
197 | if (!$isCluster) { |
||
198 | $this->redis->pipeline(function ($pipe) use ($tags, $finalKey) { |
||
199 | foreach ($tags as $tag) { |
||
200 | $shard = $this->getShardNameForTag($tag, $finalKey); |
||
201 | $pipe->srem($shard, $finalKey); |
||
202 | } |
||
203 | |||
204 | $pipe->del($this->prefix . 'tags:' . $finalKey); |
||
205 | $pipe->del($finalKey); |
||
206 | }, $connection_name); |
||
207 | } else { |
||
208 | foreach ($tags as $tag) { |
||
209 | $shard = $this->getShardNameForTag($tag, $finalKey); |
||
210 | $this->redis->getRedisConnection($connection_name)->srem($shard, $finalKey); |
||
211 | } |
||
212 | |||
213 | $this->redis->getRedisConnection($connection_name)->del($this->prefix . 'tags:' . $finalKey); |
||
214 | $this->redis->getRedisConnection($connection_name)->del($finalKey); |
||
215 | } |
||
216 | } |
||
217 | |||
218 | public function flushByTags(array $tags, ?string $connection_name = null): void |
||
219 | { |
||
220 | // ATTENZIONE, non si può fare in pipeline perchè ci sono anche comandi Redis che hanno bisogno di una promise |
||
221 | // perchè restituiscono dei valori necessari alle istruzioni successive |
||
222 | $advancedMode = (int) config('supercache.advancedMode', 0) === 1; |
||
223 | foreach ($tags as $tag) { |
||
224 | $keys = $this->getKeysOfTag($tag, $connection_name); |
||
225 | foreach ($keys as $key) { |
||
226 | // Con questo cancello sia i tag che le chiavi |
||
227 | $this->forget($key, $connection_name, true, true); |
||
228 | if (!$advancedMode) { |
||
229 | $shard = $this->getShardNameForTag($tag, $key); |
||
230 | $this->redis->getRedisConnection($connection_name)->srem($shard, $key); |
||
231 | } |
||
232 | } |
||
233 | } |
||
234 | } |
||
235 | |||
236 | /** |
||
237 | * Recupera tutti i tag associati a una chiave. |
||
238 | */ |
||
239 | public function getTagsOfKey(string $key, ?string $connection_name = null): array |
||
240 | { |
||
241 | $finalKey = $this->getFinalKey($key, true); |
||
242 | |||
243 | return $this->redis->getRedisConnection($connection_name)->smembers($this->prefix . 'tags:' . $finalKey); |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * Recupera tutte le chiavi associate a un tag. |
||
248 | */ |
||
249 | public function getKeysOfTag(string $tag, ?string $connection_name = null, bool $isfinalTag = false): array |
||
250 | { |
||
251 | if ($isfinalTag) { |
||
252 | return $this->redis->getRedisConnection($connection_name)->smembers($tag); |
||
253 | } |
||
254 | $keys = []; |
||
255 | |||
256 | // Itera attraverso tutti gli shard del tag |
||
257 | for ($i = 0; $i < $this->numShards; $i++) { |
||
258 | $shard = $this->prefix . 'tag:' . $tag . ':shard:' . $i; |
||
259 | $keys = array_merge($keys, $this->redis->getRedisConnection($connection_name)->smembers($shard)); |
||
260 | } |
||
261 | |||
262 | return $keys; |
||
263 | } |
||
264 | |||
265 | /** |
||
266 | * Ritorna il nome dello shard per una chiave e un tag. |
||
267 | */ |
||
268 | public function getShardNameForTag(string $tag, string $key): string |
||
269 | { |
||
270 | // Usa la funzione hash per calcolare lo shard della chiave |
||
271 | $hash = crc32($key); |
||
272 | $shardIndex = $hash % $this->numShards; |
||
273 | |||
274 | return $this->prefix . 'tag:' . $tag . ':shard:' . $shardIndex; |
||
275 | } |
||
276 | |||
277 | /** |
||
278 | * Aggiunge il namespace come suffisso alla chiave se abilitato. |
||
279 | * |
||
280 | * Se l'opzione 'use_namespace' è disattivata, la chiave sarà formata senza namespace. |
||
281 | */ |
||
282 | public function getFinalKey(string $key, bool $isWithTags = false): string |
||
283 | { |
||
284 | // Se il namespace è abilitato, calcola la chiave con namespace come suffisso |
||
285 | if ($this->useNamespace) { |
||
286 | $namespace = $this->calculateNamespace($key); |
||
287 | |||
288 | return $this->prefix . $key . ':' . $namespace; |
||
289 | } |
||
290 | |||
291 | // Se il namespace è disabilitato, usa la chiave senza suffisso |
||
292 | return $this->prefix . $key; |
||
293 | } |
||
294 | |||
295 | /** |
||
296 | * Flush all cache entries. |
||
297 | */ |
||
298 | public function flush(?string $connection_name = null): void |
||
299 | { |
||
300 | $this->redis->getRedisConnection($connection_name)->flushall(); // Svuota tutto il database Redis |
||
301 | } |
||
302 | |||
303 | /** |
||
304 | * Check if a cache key exists without retrieving the value. |
||
305 | */ |
||
306 | public function has(string $key, ?string $connection_name = null, bool $isWithTags = false, bool $isfinalKey = false): bool |
||
307 | { |
||
308 | if ($isfinalKey) { |
||
309 | $finalKey = $key; |
||
310 | } else { |
||
311 | $finalKey = $this->getFinalKey($key, $isWithTags); |
||
312 | } |
||
313 | |||
314 | return $this->redis->getRedisConnection($connection_name)->exists($finalKey) > 0; |
||
315 | } |
||
316 | |||
317 | /** |
||
318 | * Increment a cache key by a given amount. |
||
319 | * If the key does not exist, creates it with the increment value. |
||
320 | * |
||
321 | * @return int The new value after incrementing. |
||
322 | */ |
||
323 | public function increment(string $key, int $increment = 1, ?string $connection_name = null): int |
||
324 | { |
||
325 | $finalKey = $this->getFinalKey($key); |
||
326 | |||
327 | return $this->redis->getRedisConnection($connection_name)->incrby($finalKey, $increment); |
||
328 | } |
||
329 | |||
330 | /** |
||
331 | * Decrement a cache key by a given amount. |
||
332 | * If the key does not exist, creates it with the negative decrement value. |
||
333 | * |
||
334 | * @return int The new value after decrementing. |
||
335 | */ |
||
336 | public function decrement(string $key, int $decrement = 1, ?string $connection_name = null): int |
||
337 | { |
||
338 | $finalKey = $this->getFinalKey($key); |
||
339 | |||
340 | return $this->redis->getRedisConnection($connection_name)->decrby($finalKey, $decrement); |
||
341 | } |
||
342 | |||
343 | /** |
||
344 | * Get all keys matching given patterns. |
||
345 | * |
||
346 | * @param array $patterns An array of patterns (e.g. ["product:*"]) |
||
347 | * @return array Array of key-value pairs. |
||
348 | */ |
||
349 | public function getKeys(array $patterns, ?string $connection_name = null): array |
||
350 | { |
||
351 | $results = []; |
||
352 | foreach ($patterns as $pattern) { |
||
353 | // Trova le chiavi che corrispondono al pattern usando SCAN |
||
354 | $iterator = null; |
||
355 | // Keys terminato il loop ritorna un false |
||
356 | $tempArrKeys = []; |
||
357 | while ($keys = $this->redis->getRedisConnection($connection_name)->scan( |
||
358 | $iterator, |
||
359 | [ |
||
360 | 'match' => $pattern, |
||
361 | 'count' => 20, |
||
362 | ] |
||
363 | )) { |
||
364 | $iterator = $keys[0]; |
||
365 | |||
366 | foreach ($keys[1] as $key) { |
||
367 | if ($key === null) { |
||
368 | continue; |
||
369 | } |
||
370 | $tempArrKeys[] = $key; |
||
371 | |||
372 | $original_key = $this->getOriginalKey($key); |
||
373 | $value = $this->get($original_key); |
||
374 | $results[$original_key] = $value; |
||
375 | } |
||
376 | } |
||
377 | } |
||
378 | |||
379 | return $results; |
||
380 | } |
||
381 | |||
382 | public function getOriginalKey(string $finalKey): string |
||
383 | { |
||
384 | $originalKey = str_replace([config('database.redis.options')['prefix'], $this->prefix], '', $finalKey); |
||
385 | if (!$this->useNamespace) { |
||
386 | return $originalKey; |
||
387 | } |
||
388 | $pattern = '/:ns\d+/'; |
||
389 | |||
390 | return preg_replace($pattern, '', $originalKey); |
||
391 | } |
||
392 | |||
393 | /** |
||
394 | * Acquire a lock. |
||
395 | * |
||
396 | * @param string $key The lock key. |
||
397 | * @return bool True if the lock was acquired, false otherwise. |
||
398 | */ |
||
399 | public function lock(string $key, ?string $connection_name = null, int $ttl = 10, string $value = '1'): bool |
||
400 | { |
||
401 | $finalKey = $this->getFinalKey($key) . ':semaphore'; |
||
402 | $luaScript = <<<'LUA' |
||
403 | if redis.call("SET", KEYS[1], ARGV[2], "NX", "EX", tonumber(ARGV[1])) then |
||
404 | return 1 |
||
405 | else |
||
406 | return 0 |
||
407 | end |
||
408 | LUA; |
||
409 | |||
410 | $result = $this->redis->getRedisConnection($connection_name)->eval( |
||
411 | $luaScript, |
||
412 | 1, // Number of keys |
||
413 | $finalKey, |
||
414 | $ttl, |
||
415 | $value |
||
416 | ); |
||
417 | |||
418 | return $result === 1; |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * Rilascia un lock precedentemente acquisito. |
||
423 | * |
||
424 | * @param string $key La chiave del lock da rilasciare. |
||
425 | * @param string|null $connection_name Il nome della connessione opzionale da utilizzare. Se null, verrà utilizzata la connessione predefinita. |
||
426 | */ |
||
427 | public function unLock(string $key, ?string $connection_name = null): void |
||
428 | { |
||
429 | $finalKey = $this->getFinalKey($key) . ':semaphore'; |
||
430 | $luaScript = <<<'LUA' |
||
431 | redis.call('DEL', KEYS[1]); |
||
432 | LUA; |
||
433 | $this->redis->getRedisConnection($connection_name)->eval( |
||
434 | $luaScript, |
||
435 | 1, // Number of keys |
||
436 | $finalKey |
||
437 | ); |
||
438 | } |
||
439 | } |
||
440 |