Passed
Pull Request — main (#6)
by
unknown
03:41
created

SuperCacheManager::serializeForRedis()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
rs 10
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
The expression return $this->redis->get...n_name)->ttl($finalKey) could return the type true which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
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
        if (!$isCluster) {
88
            $this->redis->pipeline(function ($pipe) use ($finalKey, $value, $tags, $ttl) {
89
                // Qui devo mettere le {} perchè così mi assicuro che la chiave e i suoi tags stiano nello stesso has
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
                $pipe->sadd($this->prefix . 'tags:' . $finalKey, ...$tags);
102
            }, $connection_name);
103
        } else {
104
            if ($ttl !== null) {
105
                $this->redis->getRedisConnection($connection_name)->setEx($finalKey, $ttl, $this->serializeForRedis($value));
106
            } else {
107
                $result = $this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis($value));
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
108
            }
109
110
            foreach ($tags as $tag) {
111
                $shard = $this->getShardNameForTag($tag, $finalKey);
112
                $result = $this->redis->getRedisConnection($connection_name)->sadd($shard, $finalKey);
113
            }
114
115
            $this->redis->getRedisConnection($connection_name)->sadd($this->prefix . 'tags:' . $finalKey, ...$tags);
116
        }
117
    }
118
119
    /**
120
     * Memoizza un valore nella cache utilizzando tag specifici.
121
     *
122
     * Questa funzione memorizza un risultato di un callback in cache associato a dei tag specifici.
123
     * Se il valore esiste già nella cache, viene semplicemente restituito. Altrimenti, viene
124
     * eseguito il callback per ottenere il valore, che poi viene memorizzato con i tag specificati.
125
     *
126
     * @param  string      $key             La chiave sotto la quale memorizzare il valore.
127
     * @param  array       $tags            Un array di tag associati al valore memorizzato.
128
     * @param  \Closure    $callback        La funzione di callback che fornisce il valore da memorizzare se non esistente.
129
     * @param  int|null    $ttl             Tempe di vita (time-to-live) in secondi del valore memorizzato. (opzionale)
130
     * @param  string|null $connection_name Il nome della connessione cache da utilizzare. (opzionale)
131
     * @return mixed       Il valore memorizzato e/o recuperato dalla cache.
132
     */
133
    public function rememberWithTags($key, array $tags, \Closure $callback, ?int $ttl = null, ?string $connection_name = null)
134
    {
135
        $finalKey = $this->getFinalKey($key, true);
136
        $value = $this->get($finalKey, $connection_name);
137
138
        // Se esiste già, ok la ritorno
139
        if ($value !== null) {
140
            return $value;
141
        }
142
143
        $value = $callback();
144
145
        $this->putWithTags($key, $value, $tags, $ttl, $connection_name);
146
147
        return $value;
148
    }
149
150
    /**
151
     * Recupera un valore dalla cache.
152
     * Il valore della chiave sarà deserializzato tranne nel caso di valori numerici
153
     */
154
    public function get(string $key, ?string $connection_name = null, bool $isWithTags = false): mixed
155
    {
156
        $finalKey = $this->getFinalKey($key, $isWithTags);
157
158
        $value = $this->redis->getRedisConnection($connection_name)->get($finalKey);
159
160
        return $value ? $this->unserializeForRedis($value) : null;
161
    }
162
163
    /**
164
     * Rimuove una chiave dalla cache e dai suoi set di tag.
165
     */
166
    public function forget(string $key, ?string $connection_name = null, bool $isFinalKey = false, bool $isWithTags = false, bool $onlyTags = false): void
167
    {
168
        if ($isFinalKey) {
169
            $finalKey = $key;
170
        } else {
171
            $finalKey = $this->getFinalKey($key, $isWithTags);
172
        }
173
        // Recupera i tag associati alla chiave
174
        $tags = $this->redis->getRedisConnection($connection_name)->smembers($this->prefix . 'tags:' . $finalKey);
175
        $isCluster = config('database.redis.clusters.' . ($connection_name ?? 'default')) !== null;
176
        if (!$isCluster) {
177
            $this->redis->pipeline(function ($pipe) use ($isWithTags, $onlyTags, $tags, $finalKey) {
0 ignored issues
show
Unused Code introduced by
The import $isWithTags is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
178
                foreach ($tags as $tag) {
179
                    $shard = $this->getShardNameForTag($tag, $finalKey);
180
                    $pipe->srem($shard, $finalKey);
181
                }
182
183
                $pipe->del($this->prefix . 'tags:' . $finalKey);
184
                if (!$onlyTags) {
185
                    $pipe->del($finalKey);
186
                }
187
            }, $connection_name);
188
        } else {
189
            foreach ($tags as $tag) {
190
                $shard = $this->getShardNameForTag($tag, $finalKey);
191
                $this->redis->getRedisConnection($connection_name)->srem($shard, $finalKey);
192
            }
193
194
            $this->redis->getRedisConnection($connection_name)->del($this->prefix . 'tags:' . $finalKey);
195
            if (!$onlyTags) {
196
                $this->redis->getRedisConnection($connection_name)->del($finalKey);
197
            }
198
        }
199
    }
200
201
    public function flushByTags(array $tags, ?string $connection_name = null): void
202
    {
203
        // ATTENZIONE, non si può fare in pipeline perchè ci sono anche comandi Redis che hanno bisogno di una promise
204
        // perchè restituiscono dei valori necessari alle istruzioni successive
205
        foreach ($tags as $tag) {
206
            $keys = $this->getKeysOfTag($tag, $connection_name);
207
            foreach ($keys as $key) {
208
                // Con questo cancello sia i tag che le chiavi
209
                $this->forget($key, $connection_name, true, true);
210
            }
211
        }
212
    }
213
214
    /**
215
     * Recupera tutti i tag associati a una chiave.
216
     */
217
    public function getTagsOfKey(string $key, ?string $connection_name = null): array
218
    {
219
        $finalKey = $this->getFinalKey($key, true);
220
        return $this->redis->getRedisConnection($connection_name)->smembers($this->prefix . 'tags:' . $finalKey);
221
    }
222
223
    /**
224
     * Recupera tutte le chiavi associate a un tag.
225
     */
226
    public function getKeysOfTag(string $tag, ?string $connection_name = null, bool $isfinalTag = false): array
227
    {
228
        if ($isfinalTag) {
229
            return $this->redis->getRedisConnection($connection_name)->smembers($tag);
230
        }
231
        $keys = [];
232
233
        // Itera attraverso tutti gli shard del tag
234
        for ($i = 0; $i < $this->numShards; $i++) {
235
            $shard = $this->prefix . 'tag:' . $tag . ':shard:' . $i;
236
            $keys = array_merge($keys, $this->redis->getRedisConnection($connection_name)->smembers($shard));
237
        }
238
239
        return $keys;
240
    }
241
242
    /**
243
     * Ritorna il nome dello shard per una chiave e un tag.
244
     */
245
    public function getShardNameForTag(string $tag, string $key): string
246
    {
247
        // Usa la funzione hash per calcolare lo shard della chiave
248
        $hash = crc32($key);
249
        $shardIndex = $hash % $this->numShards;
250
251
        return $this->prefix . 'tag:' . $tag . ':shard:' . $shardIndex;
252
    }
253
254
    /**
255
     * Aggiunge il namespace come suffisso alla chiave se abilitato.
256
     *
257
     * Se l'opzione 'use_namespace' è disattivata, la chiave sarà formata senza namespace.
258
     */
259
    public function getFinalKey(string $key, bool $isWithTags = false): string
260
    {
261
        // Se il namespace è abilitato, calcola la chiave con namespace come suffisso
262
        if ($this->useNamespace) {
263
            $namespace = $this->calculateNamespace($key);
264
265
            return $this->prefix . $key . ':' . $namespace;
266
        }
267
268
        // Se il namespace è disabilitato, usa la chiave senza suffisso
269
        return $this->prefix . $key;
270
    }
271
272
    /**
273
     * Flush all cache entries.
274
     */
275
    public function flush(?string $connection_name = null): void
276
    {
277
        $this->redis->getRedisConnection($connection_name)->flushall(); // Svuota tutto il database Redis
278
    }
279
280
    /**
281
     * Check if a cache key exists without retrieving the value.
282
     */
283
    public function has(string $key, ?string $connection_name = null, bool $isWithTags = false, bool $isfinalKey = false): bool
284
    {
285
        if ($isfinalKey) {
286
            $finalKey = $key;
287
        } else {
288
            $finalKey = $this->getFinalKey($key, $isWithTags);
289
        }
290
291
        return $this->redis->getRedisConnection($connection_name)->exists($finalKey) > 0;
292
    }
293
294
    /**
295
     * Increment a cache key by a given amount.
296
     * If the key does not exist, creates it with the increment value.
297
     *
298
     * @return int The new value after incrementing.
299
     */
300
    public function increment(string $key, int $increment = 1, ?string $connection_name = null): int
301
    {
302
        $finalKey = $this->getFinalKey($key);
303
304
        return $this->redis->getRedisConnection($connection_name)->incrby($finalKey, $increment);
305
    }
306
307
    /**
308
     * Decrement a cache key by a given amount.
309
     * If the key does not exist, creates it with the negative decrement value.
310
     *
311
     * @return int The new value after decrementing.
312
     */
313
    public function decrement(string $key, int $decrement = 1, ?string $connection_name = null): int
314
    {
315
        $finalKey = $this->getFinalKey($key);
316
317
        return $this->redis->getRedisConnection($connection_name)->decrby($finalKey, $decrement);
318
    }
319
320
    /**
321
     * Get all keys matching given patterns.
322
     *
323
     * @param  array $patterns An array of patterns (e.g. ["product:*"])
324
     * @return array Array of key-value pairs.
325
     */
326
    public function getKeys(array $patterns, ?string $connection_name = null): array
327
    {
328
        $results = [];
329
        foreach ($patterns as $pattern) {
330
            // Trova le chiavi che corrispondono al pattern usando SCAN
331
            $iterator = null;
332
            // Keys terminato il loop ritorna un false
333
            $tempArrKeys = [];
334
            while ($keys = $this->redis->getRedisConnection($connection_name)->scan(
335
                $iterator,
336
                [
337
                    'match' => $pattern,
338
                    'count' => 20,
339
                ]
340
            )) {
341
                $iterator = $keys[0];
342
343
                foreach ($keys[1] as $key) {
344
                    if ($key === null) {
345
                        continue;
346
                    }
347
                    $tempArrKeys[] = $key;
348
349
                    $original_key = $this->getOriginalKey($key);
350
                    $value = $this->get($original_key);
351
                    $results[$original_key] = $value;
352
                }
353
            }
354
        }
355
356
        return $results;
357
    }
358
359
    public function getOriginalKey(string $finalKey): string
360
    {
361
        $originalKey = str_replace([config('database.redis.options')['prefix'], $this->prefix], '', $finalKey);
362
        if (!$this->useNamespace) {
363
            return $originalKey;
364
        }
365
        $pattern = '/:ns\d+/';
366
367
        return preg_replace($pattern, '', $originalKey);
368
    }
369
370
    /**
371
     * Acquire a lock.
372
     *
373
     * @param  string $key The lock key.
374
     * @return bool   True if the lock was acquired, false otherwise.
375
     */
376
    public function lock(string $key, ?string $connection_name = null, int $ttl = 10, string $value = '1'): bool
377
    {
378
        $finalKey = $this->getFinalKey($key) . ':semaphore';
379
        $luaScript = <<<'LUA'
380
        if redis.call("SET", KEYS[1], ARGV[2], "NX", "EX", tonumber(ARGV[1])) then
381
            return 1
382
        else
383
            return 0
384
        end
385
        LUA;
386
387
        $result = $this->redis->getRedisConnection($connection_name)->eval(
388
            $luaScript,
389
            1, // Number of keys
390
            $finalKey,
391
            $ttl,
392
            $value
393
        );
394
395
        return $result === 1;
396
    }
397
398
    /**
399
     * Rilascia un lock precedentemente acquisito.
400
     *
401
     * @param string      $key             La chiave del lock da rilasciare.
402
     * @param string|null $connection_name Il nome della connessione opzionale da utilizzare. Se null, verrà utilizzata la connessione predefinita.
403
     */
404
    public function unLock(string $key, ?string $connection_name = null): void
405
    {
406
        $finalKey = $this->getFinalKey($key) . ':semaphore';
407
        $luaScript = <<<'LUA'
408
        redis.call('DEL', KEYS[1]);
409
        LUA;
410
        $this->redis->getRedisConnection($connection_name)->eval(
411
            $luaScript,
412
            1, // Number of keys
413
            $finalKey
414
        );
415
    }
416
}
417