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
|
|
|
/** |
63
|
|
|
* $this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis($value)); |
64
|
|
|
* |
65
|
|
|
* if ($ttl !== null) { |
66
|
|
|
* $this->redis->getRedisConnection($connection_name)->expire($finalKey, $ttl); |
67
|
|
|
* } |
68
|
|
|
*/ |
69
|
|
|
if ($ttl !== null) { |
70
|
|
|
$this->redis->getRedisConnection($connection_name)->setEx($finalKey, $ttl, $this->serializeForRedis($value)); |
71
|
|
|
|
72
|
|
|
return; |
73
|
|
|
} |
74
|
|
|
$this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis($value)); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public function getTTLKey(string $key, ?string $connection_name = null, bool $isWithTags = false): int |
78
|
|
|
{ |
79
|
|
|
// Calcola la chiave con o senza namespace in base alla configurazione |
80
|
|
|
$finalKey = $this->getFinalKey($key, $isWithTags); |
81
|
|
|
|
82
|
|
|
return $this->redis->getRedisConnection($connection_name)->ttl($isWithTags ? ('{' . $finalKey . '}') : $finalKey); |
|
|
|
|
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Salva un valore nella cache con uno o più tag. |
87
|
|
|
* Il valore della chiave sarà serializzato tranne nel caso di valori numerici |
88
|
|
|
*/ |
89
|
|
|
public function putWithTags(string $key, mixed $value, array $tags, ?int $ttl = null, ?string $connection_name = null): void |
90
|
|
|
{ |
91
|
|
|
$finalKey = $this->getFinalKey($key, true); |
92
|
|
|
$finalTags = $this->getFinalTag($finalKey, true); |
93
|
|
|
// Usa pipeline solo se non è un cluster |
94
|
|
|
$isCluster = config('database.redis.clusters.' . ($connection_name ?? 'default')) !== null; |
95
|
|
|
if (!$isCluster) { |
96
|
|
|
$this->redis->pipeline(function ($pipe) use ($finalKey, $finalTags, $value, $tags, $ttl) { |
97
|
|
|
// Qui devo mettere le {} perchè così mi assicuro che la chiave e i suoi tags stiano nello stesso has |
98
|
|
|
if ($ttl !== null) { |
99
|
|
|
$pipe->setEx('{' . $finalKey . '}', $ttl, $this->serializeForRedis($value)); |
100
|
|
|
} else { |
101
|
|
|
$pipe->set('{' . $finalKey . '}', $this->serializeForRedis($value)); |
102
|
|
|
} |
103
|
|
|
|
104
|
|
|
foreach ($tags as $tag) { |
105
|
|
|
$shard = $this->getShardNameForTag($tag, '{' . $finalKey . '}'); |
106
|
|
|
$pipe->sadd($shard, '{' . $finalKey . '}'); |
107
|
|
|
} |
108
|
|
|
|
109
|
|
|
$pipe->sadd($finalTags, ...$tags); |
110
|
|
|
}, $connection_name); |
111
|
|
|
} else { |
112
|
|
|
if ($ttl !== null) { |
113
|
|
|
$this->redis->getRedisConnection($connection_name)->setEx('{' . $finalKey . '}', $ttl, $this->serializeForRedis($value)); |
114
|
|
|
} else { |
115
|
|
|
$result = $this->redis->getRedisConnection($connection_name)->set('{' . $finalKey . '}', $this->serializeForRedis($value)); |
|
|
|
|
116
|
|
|
} |
117
|
|
|
|
118
|
|
|
foreach ($tags as $tag) { |
119
|
|
|
$shard = $this->getShardNameForTag($tag, '{' . $finalKey . '}'); |
120
|
|
|
$result = $this->redis->getRedisConnection($connection_name)->sadd($shard, '{' . $finalKey . '}'); |
121
|
|
|
} |
122
|
|
|
|
123
|
|
|
$this->redis->getRedisConnection($connection_name)->sadd($finalTags, ...$tags); |
124
|
|
|
} |
125
|
|
|
} |
126
|
|
|
|
127
|
|
|
/** |
128
|
|
|
* Memoizza un valore nella cache utilizzando tag specifici. |
129
|
|
|
* |
130
|
|
|
* Questa funzione memorizza un risultato di un callback in cache associato a dei tag specifici. |
131
|
|
|
* Se il valore esiste già nella cache, viene semplicemente restituito. Altrimenti, viene |
132
|
|
|
* eseguito il callback per ottenere il valore, che poi viene memorizzato con i tag specificati. |
133
|
|
|
* |
134
|
|
|
* @param string $key La chiave sotto la quale memorizzare il valore. |
135
|
|
|
* @param array $tags Un array di tag associati al valore memorizzato. |
136
|
|
|
* @param \Closure $callback La funzione di callback che fornisce il valore da memorizzare se non esistente. |
137
|
|
|
* @param int|null $ttl Tempe di vita (time-to-live) in secondi del valore memorizzato. (opzionale) |
138
|
|
|
* @param string|null $connection_name Il nome della connessione cache da utilizzare. (opzionale) |
139
|
|
|
* @return mixed Il valore memorizzato e/o recuperato dalla cache. |
140
|
|
|
*/ |
141
|
|
|
public function rememberWithTags($key, array $tags, \Closure $callback, ?int $ttl = null, ?string $connection_name = null) |
142
|
|
|
{ |
143
|
|
|
$finalKey = $this->getFinalKey($key, true); |
144
|
|
|
$value = $this->get($finalKey, $connection_name); |
145
|
|
|
|
146
|
|
|
// Se esiste già, ok la ritorno |
147
|
|
|
if ($value !== null) { |
148
|
|
|
return $value; |
149
|
|
|
} |
150
|
|
|
|
151
|
|
|
$value = $callback(); |
152
|
|
|
|
153
|
|
|
$this->putWithTags($finalKey, $value, $tags, $ttl, $connection_name); |
154
|
|
|
|
155
|
|
|
return $value; |
156
|
|
|
} |
157
|
|
|
|
158
|
|
|
/** |
159
|
|
|
* Recupera un valore dalla cache. |
160
|
|
|
* Il valore della chiave sarà deserializzato tranne nel caso di valori numerici |
161
|
|
|
*/ |
162
|
|
|
public function get(string $key, ?string $connection_name = null, bool $isWithTags = false): mixed |
163
|
|
|
{ |
164
|
|
|
$finalKey = $this->getFinalKey($key, $isWithTags); |
165
|
|
|
if ($isWithTags) { |
166
|
|
|
$finalKey = '{' . $finalKey . '}'; |
167
|
|
|
} |
168
|
|
|
|
169
|
|
|
$value = $this->redis->getRedisConnection($connection_name)->get($finalKey); |
170
|
|
|
|
171
|
|
|
return $value ? $this->unserializeForRedis($value) : null; |
172
|
|
|
} |
173
|
|
|
|
174
|
|
|
/** |
175
|
|
|
* Rimuove una chiave dalla cache e dai suoi set di tag. |
176
|
|
|
*/ |
177
|
|
|
public function forget(string $key, ?string $connection_name = null, bool $isFinalKey = false, bool $isWithTags = false, bool $onlyTags = false): void |
178
|
|
|
{ |
179
|
|
|
if ($isFinalKey) { |
180
|
|
|
$finalKey = $key; |
181
|
|
|
} else { |
182
|
|
|
$finalKey = $this->getFinalKey($key, $isWithTags); |
183
|
|
|
} |
184
|
|
|
$finalTags = $this->getFinalTag($finalKey, $isWithTags); |
185
|
|
|
// Recupera i tag associati alla chiave |
186
|
|
|
$tags = $this->redis->getRedisConnection($connection_name)->smembers($finalTags); |
187
|
|
|
$isCluster = config('database.redis.clusters.' . ($connection_name ?? 'default')) !== null; |
188
|
|
|
if (!$isCluster) { |
189
|
|
|
$this->redis->pipeline(function ($pipe) use ($isWithTags, $onlyTags, $tags, $finalKey, $finalTags) { |
190
|
|
|
foreach ($tags as $tag) { |
191
|
|
|
$shard = $this->getShardNameForTag($tag, ($isWithTags ? ('{' . $finalKey . '}') : $finalKey)); |
192
|
|
|
$pipe->srem($shard, ($isWithTags ? ('{' . $finalKey . '}') : $finalKey)); |
193
|
|
|
} |
194
|
|
|
|
195
|
|
|
$pipe->del($finalTags); |
196
|
|
|
if (!$onlyTags) { |
197
|
|
|
$pipe->del($isWithTags ? ('{' . $finalKey . '}') : $finalKey); |
198
|
|
|
} |
199
|
|
|
}, $connection_name); |
200
|
|
|
} else { |
201
|
|
|
foreach ($tags as $tag) { |
202
|
|
|
$shard = $this->getShardNameForTag($tag, ($isWithTags ? ('{' . $finalKey . '}') : $finalKey)); |
203
|
|
|
$this->redis->getRedisConnection($connection_name)->srem($shard, ($isWithTags ? ('{' . $finalKey . '}') : $finalKey)); |
204
|
|
|
} |
205
|
|
|
|
206
|
|
|
$this->redis->getRedisConnection($connection_name)->del($finalTags); |
207
|
|
|
if (!$onlyTags) { |
208
|
|
|
$this->redis->getRedisConnection($connection_name)->del($isWithTags ? ('{' . $finalKey . '}') : $finalKey); |
209
|
|
|
} |
210
|
|
|
} |
211
|
|
|
} |
212
|
|
|
|
213
|
|
|
public function flushByTags(array $tags, ?string $connection_name = null): void |
214
|
|
|
{ |
215
|
|
|
// ATTENZIONE, non si può fare in pipeline perchè ci sono anche comandi Redis che hanno bisogno di una promise |
216
|
|
|
// perchè restituiscono dei valori necessari alle istruzioni successive |
217
|
|
|
foreach ($tags as $tag) { |
218
|
|
|
$keys = $this->getKeysOfTag($tag, $connection_name); |
219
|
|
|
foreach ($keys as $key) { |
220
|
|
|
// Con questo cancello sia i tag che le chiavi |
221
|
|
|
$this->forget($key, $connection_name, true, true); |
222
|
|
|
} |
223
|
|
|
} |
224
|
|
|
} |
225
|
|
|
|
226
|
|
|
/** |
227
|
|
|
* Recupera tutti i tag associati a una chiave. |
228
|
|
|
*/ |
229
|
|
|
public function getTagsOfKey(string $key, ?string $connection_name = null): array |
230
|
|
|
{ |
231
|
|
|
$finalKey = $this->getFinalKey($key, true); |
232
|
|
|
$finalTags = $this->getFinalTag($finalKey, true); |
233
|
|
|
|
234
|
|
|
return $this->redis->getRedisConnection($connection_name)->smembers($finalTags); |
235
|
|
|
} |
236
|
|
|
|
237
|
|
|
/** |
238
|
|
|
* Recupera tutte le chiavi associate a un tag. |
239
|
|
|
*/ |
240
|
|
|
public function getKeysOfTag(string $tag, ?string $connection_name = null, bool $isfinalTag = false): array |
241
|
|
|
{ |
242
|
|
|
if ($isfinalTag) { |
243
|
|
|
return $this->redis->getRedisConnection($connection_name)->smembers($tag); |
244
|
|
|
} |
245
|
|
|
$keys = []; |
246
|
|
|
|
247
|
|
|
// Itera attraverso tutti gli shard del tag |
248
|
|
|
for ($i = 0; $i < $this->numShards; $i++) { |
249
|
|
|
$shard = $this->prefix . 'tag:' . $tag . ':shard:' . $i; |
250
|
|
|
$keys = array_merge($keys, $this->redis->getRedisConnection($connection_name)->smembers($shard)); |
251
|
|
|
} |
252
|
|
|
|
253
|
|
|
return $keys; |
254
|
|
|
} |
255
|
|
|
|
256
|
|
|
/** |
257
|
|
|
* Ritorna il nome dello shard per una chiave e un tag. |
258
|
|
|
*/ |
259
|
|
|
public function getShardNameForTag(string $tag, string $key): string |
260
|
|
|
{ |
261
|
|
|
// Usa la funzione hash per calcolare lo shard della chiave |
262
|
|
|
$hash = crc32($key); |
263
|
|
|
$shardIndex = $hash % $this->numShards; |
264
|
|
|
|
265
|
|
|
return $this->prefix . 'tag:' . $tag . ':shard:' . $shardIndex; |
266
|
|
|
} |
267
|
|
|
|
268
|
|
|
/** |
269
|
|
|
* Aggiunge il namespace come suffisso alla chiave se abilitato. |
270
|
|
|
* |
271
|
|
|
* Se l'opzione 'use_namespace' è disattivata, la chiave sarà formata senza namespace. |
272
|
|
|
*/ |
273
|
|
|
public function getFinalKey(string $key, bool $isWithTags = false): string |
274
|
|
|
{ |
275
|
|
|
// Se il namespace è abilitato, calcola la chiave con namespace come suffisso |
276
|
|
|
if ($this->useNamespace) { |
277
|
|
|
$namespace = $this->calculateNamespace($key); |
278
|
|
|
|
279
|
|
|
return $this->prefix . $key . ':' . ($isWithTags ? 'byTags:' : '') . $namespace; |
280
|
|
|
} |
281
|
|
|
|
282
|
|
|
// Se il namespace è disabilitato, usa la chiave senza suffisso |
283
|
|
|
return $this->prefix . $key . ($isWithTags ? ':byTags' : ''); |
284
|
|
|
} |
285
|
|
|
|
286
|
|
|
public function getFinalTag(string $finalKey, bool $isWithTags = false): string |
287
|
|
|
{ |
288
|
|
|
if ($isWithTags) { |
289
|
|
|
return '{' . $finalKey . '}:tags'; |
290
|
|
|
} |
291
|
|
|
|
292
|
|
|
return $finalKey . ':tags'; |
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(($isWithTags && !$isfinalKey) ? ('{' . $finalKey . '}') : $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
|
|
|
|