Passed
Pull Request — main (#3)
by
unknown
02:49
created

processBatch()   C

Complexity

Conditions 14
Paths 73

Size

Total Lines 73
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 14
eloc 42
c 3
b 0
f 0
nc 73
nop 2
dl 0
loc 73
rs 6.2666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Padosoft\SuperCacheInvalidate\Console;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Facades\Cache;
7
use Illuminate\Support\Facades\DB;
8
use Carbon\Carbon;
9
use Padosoft\SuperCacheInvalidate\Helpers\SuperCacheInvalidationHelper;
10
11
class ProcessCacheInvalidationEventsCommand extends Command
12
{
13
    /**
14
     * The name and signature of the console command.
15
     *
16
     * @var string
17
     */
18
    protected $signature = 'supercache:process-invalidation
19
                            {--shard= : The shard number to process}
20
                            {--priority= : The priority level}
21
                            {--limit= : The maximum number of events to fetch per batch}
22
                            {--tag-batch-size= : The number of identifiers to process per invalidation batch}
23
                            {--connection_name= : The Redis connection name}';
24
25
    /**
26
     * The console command description.
27
     *
28
     * @var string
29
     */
30
    protected $description = 'Process cache invalidation events for a given shard and priority';
31
32
    /**
33
     * Cache invalidation helper instance.
34
     */
35
    protected SuperCacheInvalidationHelper $helper;
36
37
    /**
38
     * Create a new command instance.
39
     */
40
    public function __construct(SuperCacheInvalidationHelper $helper)
41
    {
42
        parent::__construct();
43
        $this->helper = $helper;
44
    }
45
46
    private function getStoreFromConnectionName(string $connection_name): ?string
47
    {
48
        // Cerca il nome dello store associato alla connessione Redis
49
        foreach (config('cache.stores') as $storeName => $storeConfig) {
50
            if (
51
                isset($storeConfig['driver'], $storeConfig['connection']) &&
52
                $storeConfig['driver'] === 'redis' &&
53
                $storeConfig['connection'] === $connection_name
54
            ) {
55
                return $storeName;
56
            }
57
        }
58
59
        return null;
60
    }
61
62
    protected function getCache_invalidation_eventsPartitionName(int $shardId, int $priorityId): string
63
    {
64
        // Calcola il valore della partizione
65
        $shards = config('super_cache_invalidate.total_shards', 10);
66
        $priorities = [0, 1];
67
68
        $partitionStatements = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $partitionStatements is dead and can be removed.
Loading history...
69
70
        $partitionValueId = ($priorityId * $shards) + $shardId + 1;
71
72
        // Partitions for unprocessed events
73
        foreach ($priorities as $priority) {
74
            for ($shard = 0; $shard < $shards; $shard++) {
75
                $partitionName = "p_unprocessed_s{$shard}_p{$priority}";
76
                $partitionValue = ($priority * $shards) + $shard + 1;
77
                if ($partitionValueId < $partitionValue) {
78
                    return $partitionName;
79
                }
80
            }
81
        }
82
83
        return '';
84
    }
85
86
    /**
87
     * Process cache invalidation events.
88
     *
89
     * @param int $shardId The shard number to process
90
     * @param int $priority The priority level
91
     * @param int $limit Maximum number of events to fetch per batch
92
     * @param int $tagBatchSize Number of identifiers to process per batch
93
     *
94
     * @throws \Exception
95
     * @throws \Throwable
96
     */
97
    protected function processEvents(int $shardId, int $priority, int $limit, int $tagBatchSize, string $connection_name): void
98
    {
99
        $processingStartTime = now();
100
        $invalidationWindow = config('super_cache_invalidate.invalidation_window');
101
102
        // Fetch a batch of unprocessed events
103
        $partitionCache_invalidation_events = $this->getCache_invalidation_eventsPartitionName($shardId, $priority, 0, $processingStartTime);
0 ignored issues
show
Unused Code introduced by
The call to Padosoft\SuperCacheInval...n_eventsPartitionName() has too many arguments starting with 0. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

103
        /** @scrutinizer ignore-call */ 
104
        $partitionCache_invalidation_events = $this->getCache_invalidation_eventsPartitionName($shardId, $priority, 0, $processingStartTime);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
104
105
        $events = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))
106
            //->from(DB::raw("`{$this->from}` PARTITION ({$partitionsString})"))
107
            ->where('processed', '=', 0)
108
            ->where('shard', '=', $shardId)
109
            ->where('priority', '=', $priority)
110
            ->where('event_time', '<', $processingStartTime)
111
            // Cerco tutte le chiavi/tag da invalidare per questo database redis
112
            ->where('connection_name', '=', $connection_name)
113
            ->orderBy('event_time')
114
            ->limit($limit)
115
            ->get()
116
        ;
117
118
        //ds($partitionCache_invalidation_events . ' -> Shard (' . $shardId . ') Priority (' . $priority . ') Record = ' . $events->count());
119
        if ($events->isEmpty()) {
120
            // No more events to process
121
            return;
122
        }
123
124
        // Group events by type and identifier
125
        $eventsByIdentifier = $events->groupBy(function ($event) {
126
            return $event->type . ':' . $event->identifier;
127
        });
128
129
        $batchIdentifiers = [];
130
        $eventsToUpdate = [];
131
        $counter = 0;
132
133
        // Fetch associated identifiers for the events
134
        $eventIds = $events->pluck('id')->all();
135
136
        //retrive associated identifiers related to fetched event id
137
        // Per le chiavi/tag associati non filtro per connection_name, potrebbero esserci associazioni anche in altri database
138
        $associations = DB::table('cache_invalidation_event_associations')
139
            ->whereIn('event_id', $eventIds)
140
            ->get()
141
            ->groupBy('event_id')
142
        ;
143
144
        // Prepare list of all identifiers to fetch last invalidation times
145
        $allIdentifiers = [];
146
        foreach ($eventsByIdentifier as $key => $eventsGroup) {
147
            $allIdentifiers[] = $key;
148
            foreach ($eventsGroup as $event) {
149
                $eventAssociations = $associations->where('event_id', '=', $event->id);
150
                foreach ($eventAssociations as $assoc) {
151
                    $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier;
152
                    $allIdentifiers[] = $assocKey;
153
                }
154
            }
155
        }
156
        // Fetch last invalidation times in bulk
157
        $lastInvalidationTimes = $this->getLastInvalidationTimes(array_unique($allIdentifiers));
158
159
        foreach ($eventsByIdentifier as $key => $eventsGroup) {
160
            // Extract type and identifier
161
            [$type, $identifier] = explode(':', $key, 2);
162
163
            // Get associated identifiers for the events
164
            $associatedIdentifiers = [];
165
            foreach ($eventsGroup as $event) {
166
                $eventAssociations = $associations->where('event_id', '=', $event->id);
167
                foreach ($eventAssociations as $assoc) {
168
                    $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier;
169
                    $associatedIdentifiers[$assocKey] = [
170
                        'type' => $assoc->associated_type,
171
                        'identifier' => $assoc->associated_identifier,
172
                        'connection_name' => $assoc->connection_name,
173
                    ];
174
                }
175
            }
176
177
            // Build a list of all identifiers to check
178
            $identifiersToCheck = [$key];
179
            $identifiersToCheck = array_merge($identifiersToCheck, array_keys($associatedIdentifiers));
180
            $lastInvalidationTimesSubset = array_intersect_key($lastInvalidationTimes, array_flip($identifiersToCheck));
181
182
            $shouldInvalidate = $this->shouldInvalidateMultiple($identifiersToCheck, $lastInvalidationTimesSubset, $invalidationWindow);
183
184
            if ($shouldInvalidate) {
185
                // Proceed to invalidate
186
                $latestEvent = $eventsGroup->last();
187
188
                // Accumulate identifiers and events
189
                $batchIdentifiers[] = [
190
                    'type' => $type,
191
                    'identifier' => $identifier,
192
                    'event' => $latestEvent,
193
                    'connection_name' => $connection_name,
194
                    'associated' => array_values($associatedIdentifiers),
195
                ];
196
197
                // Update last invalidation times for all identifiers
198
                $this->updateLastInvalidationTimes($identifiersToCheck);
199
200
                // Mark all events in the group as processed
201
                foreach ($eventsGroup as $event) {
202
                    $eventsToUpdate[] = $event->id;
203
                }
204
            } else {
205
                // Within the invalidation window, skip invalidation
206
                // Mark all events except the last one as processed
207
                $eventsToProcess = $eventsGroup->slice(0, -1);
208
                foreach ($eventsToProcess as $event) {
209
                    $eventsToUpdate[] = $event->id;
210
                }
211
                // The last event remains unprocessed
212
            }
213
214
            $counter++;
215
216
            // When we reach the batch size, process the accumulated identifiers
217
            if ($counter % $tagBatchSize === 0) {
218
                $this->processBatch($batchIdentifiers, $eventsToUpdate);
219
220
                // Reset the accumulators
221
                $batchIdentifiers = [];
222
                $eventsToUpdate = [];
223
            }
224
        }
225
226
        if (empty($batchIdentifiers)) {
227
            return;
228
        }
229
230
        // Process any remaining identifiers in the batch
231
        $this->processBatch($batchIdentifiers, $eventsToUpdate);
232
    }
233
234
    /**
235
     * Fetch last invalidation times for identifiers in bulk.
236
     *
237
     * @param  array $identifiers Array of 'type:identifier' strings
238
     * @return array Associative array of last invalidation times
239
     */
240
    protected function getLastInvalidationTimes(array $identifiers): array
241
    {
242
        // Extract types and identifiers into tuples
243
        $tuples = array_map(static function ($key) {
244
            return explode(':', $key, 2);
245
        }, $identifiers);
246
247
        if (empty($tuples)) {
248
            return [];
249
        }
250
251
        $records = $this->getRecordsFromDb($tuples);
252
253
        // Build associative array
254
        $lastInvalidationTimes = [];
255
        foreach ($records as $record) {
256
            $key = $record->identifier_type . ':' . $record->identifier;
257
            $lastInvalidationTimes[$key] = Carbon::parse($record->last_invalidated);
258
        }
259
260
        return $lastInvalidationTimes;
261
    }
262
263
    /**
264
     * Execute Query to get records from DB
265
     */
266
    protected function getRecordsFromDb(array $tuples): array
267
    {
268
        // Prepare placeholders and parameters
269
        $placeholders = implode(',', array_fill(0, count($tuples), '(?, ?)'));
270
        $params = [];
271
        foreach ($tuples as [$type, $identifier]) {
272
            $params[] = $type;
273
            $params[] = $identifier;
274
        }
275
276
        $sql = "SELECT identifier_type,
277
                        identifier,
278
                        last_invalidated
279
                FROM cache_invalidation_timestamps
280
                WHERE (identifier_type, identifier) IN ($placeholders)
281
                ";
282
283
        return DB::select($sql, $params);
284
    }
285
286
    /**
287
     * Determine whether to invalidate based on last invalidation times for multiple identifiers.
288
     *
289
     * @param  array $identifiers           Array of 'type:identifier' strings
290
     * @param  array $lastInvalidationTimes Associative array of last invalidation times
291
     * @param  int   $invalidationWindow    Invalidation window in seconds
292
     * @return bool  True if should invalidate, false otherwise
293
     */
294
    protected function shouldInvalidateMultiple(array $identifiers, array $lastInvalidationTimes, int $invalidationWindow): bool
295
    {
296
        $now = now();
297
        foreach ($identifiers as $key) {
298
            $lastInvalidated = $lastInvalidationTimes[$key] ?? null;
299
            if (!$lastInvalidated) {
300
                continue;
301
            }
302
            $elapsed = $now->diffInSeconds($lastInvalidated);
303
            if ($elapsed < $invalidationWindow) {
304
                // At least one identifier is within the invalidation window
305
                return false;
306
            }
307
        }
308
309
        // All identifiers are outside the invalidation window or have no record
310
        return true;
311
    }
312
313
    /**
314
     * Update the last invalidation times for multiple identifiers.
315
     *
316
     * @param array $identifiers Array of 'type:identifier' strings
317
     */
318
    protected function updateLastInvalidationTimes(array $identifiers): void
319
    {
320
        $now = now();
321
322
        foreach ($identifiers as $key) {
323
            [$type, $identifier] = explode(':', $key, 2);
324
            DB::table('cache_invalidation_timestamps')
325
                ->updateOrInsert(
326
                    ['identifier_type' => $type, 'identifier' => $identifier],
327
                    ['last_invalidated' => $now]
328
                )
329
            ;
330
        }
331
    }
332
333
    /**
334
     * Process a batch of identifiers and update events.
335
     *
336
     * @param array $batchIdentifiers Array of identifiers to invalidate
337
     * @param array $eventsToUpdate   Array of event IDs to mark as processed
338
     *
339
     * @throws \Throwable
340
     */
341
    protected function processBatch(array $batchIdentifiers, array $eventsToUpdate): void
342
    {
343
        $maxAttempts = 5;
344
        $attempts = 0;
345
        $updatedOk = false;
346
347
        while ($attempts < $maxAttempts && !$updatedOk) {
348
            // Begin transaction for the batch
349
            DB::beginTransaction();
350
351
            try {
352
                // Separate keys and tags
353
                $keys = [];
354
                $tags = [];
355
356
                foreach ($batchIdentifiers as $item) {
357
                    switch ($item['type']) {
358
                        case 'key':
359
                            $keys[] = $item['identifier'] . '§' . $item['connection_name'];
360
                            break;
361
                        case 'tag':
362
                            $tags[] = $item['identifier'] . '§' . $item['connection_name'];
363
                            break;
364
                    }
365
366
                    if (empty($item['associated'])) {
367
                        continue;
368
                    }
369
370
                    // Include associated identifiers
371
                    foreach ($item['associated'] as $assoc) {
372
                        switch ($assoc['type']) {
373
                            case 'key':
374
                                $keys[] = $assoc['identifier'] . '§' . $assoc['connection_name'];
375
                                break;
376
                            case 'tag':
377
                                $tags[] = $assoc['identifier'] . '§' . $assoc['connection_name'];
378
                                break;
379
                        }
380
                    }
381
                }
382
383
                // Remove duplicates
384
                $keys = array_unique($keys);
385
                $tags = array_unique($tags);
386
387
                // Invalidate cache for keys
388
                if (!empty($keys)) {
389
                    $this->invalidateKeys($keys);
390
                }
391
392
                // Invalidate cache for tags
393
                if (!empty($tags)) {
394
                    $this->invalidateTags($tags);
395
                }
396
397
                // Mark events as processed
398
                DB::table('cache_invalidation_events')
399
                    ->whereIn('id', $eventsToUpdate)
400
                    ->update(['processed' => 1])
401
                ;
402
403
                // Commit transaction
404
                DB::commit();
405
                $updatedOk = true;
406
            } catch (\Throwable $e) {
407
                // Rollback transaction on error
408
                DB::rollBack();
409
                $attempts++;
410
                // Logica per gestire i tentativi falliti
411
                if ($attempts >= $maxAttempts) {
412
                    // Salta il record dopo il numero massimo di tentativi
413
                    throw $e;
414
                }
415
            }
416
        }
417
    }
418
419
    /**
420
     * Invalidate cache keys.
421
     *
422
     * @param array $keys Array of cache keys to invalidate
423
     */
424
    protected function invalidateKeys(array $keys): void
425
    {
426
        $callback = config('super_cache_invalidate.key_invalidation_callback');
427
428
429
        // Anche in questo caso va fatto un loop perchè le chiavi potrebbero stare in database diversi
430
        foreach ($keys as $keyAndConnectionName) {
431
            [$key, $connection_name] = explode('§', $keyAndConnectionName);
432
433
            // Metodo del progetto
434
            if (is_callable($callback)) {
435
                $callback($key, $connection_name);
436
437
                return;
438
            }
439
440
            // oppure di default uso Laravel
441
            $storeName =  $this->getStoreFromConnectionName($connection_name);
442
443
            if ($storeName === null) {
444
                return;
445
            }
446
            Cache::store($storeName)->forget($key);
447
        }
448
    }
449
450
    /**
451
     * Invalidate cache tags.
452
     *
453
     * @param array $tags Array of cache tags to invalidate
454
     */
455
    protected function invalidateTags(array $tags): void
456
    {
457
        $callback = config('super_cache_invalidate.tag_invalidation_callback');
458
459
        $groupByConnection = [];
460
461
        // Anche in questo caso va fatto un loop perchè i tags potrebbero stare in database diversi,
462
        // ma per ottimizzare possiamo raggruppare le operazioni per connessione
463
        foreach ($tags as $tagAndConnectionName) {
464
            // chiave e connessione
465
            [$key, $connection] = explode('§', $tagAndConnectionName);
466
467
            // Aggiungo la chiave alla connessione appropriata
468
            $groupByConnection[$connection][] = $key;
469
        }
470
        if (is_callable($callback)) {
471
            foreach ($groupByConnection as $connection_name => $arrTags) {
472
                $callback($arrTags, $connection_name);
473
            }
474
475
            return;
476
        }
477
        foreach ($groupByConnection as $connection_name => $arrTags) {
478
            $storeName =  $this->getStoreFromConnectionName($connection_name);
479
            if ($storeName === null) {
480
                return;
481
            }
482
            Cache::store($storeName)->tags($arrTags)->flush();
483
        }
484
    }
485
486
    /**
487
     * Execute the console command.
488
     */
489
    public function handle(): void
490
    {
491
        $shardId = (int) $this->option('shard');
492
        $priority = (int) $this->option('priority');
493
        $limit = $this->option('limit') ?? config('super_cache_invalidate.processing_limit');
494
        $limit = (int)$limit;
495
        $tagBatchSize = $this->option('tag-batch-size') ?? config('super_cache_invalidate.tag_batch_size');
496
        $tagBatchSize = (int)$tagBatchSize;
497
        $lockTimeout = (int) config('super_cache_invalidate.lock_timeout');
498
        $connection_name = $this->option('connection_name') ?? config('super_cache_invalidate.default_connection_name');
499
        /*
500
        if ($shardId === 0 && $priority === 0) {
501
            $this->error('Shard and priority are required and must be non-zero integers.');
502
503
            return;
504
        }
505
        */
506
        $lockValue = $this->helper->acquireShardLock($shardId, $priority, $lockTimeout, $connection_name);
507
508
        if (!$lockValue) {
509
            return;
510
        }
511
512
        try {
513
            $this->processEvents($shardId, $priority, $limit, $tagBatchSize, $connection_name);
514
        } catch (\Throwable $e) {
515
            $this->error('Si è verificato un errore in ' . __METHOD__ . ': ' . $e->getMessage());
516
        } finally {
517
            $this->helper->releaseShardLock($shardId, $priority, $lockValue, $connection_name);
518
        }
519
    }
520
}
521