Passed
Push — main ( e10b1f...c5069f )
by
unknown
05:06 queued 01:27
created

processBatch()   F

Complexity

Conditions 14
Paths 336

Size

Total Lines 88
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 14
eloc 46
c 5
b 0
f 0
nc 336
nop 4
dl 0
loc 88
rs 3.7333

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
63
64
    /**
65
     * Process cache invalidation events.
66
     *
67
     * @param int $shardId      The shard number to process
68
     * @param int $priority     The priority level
69
     * @param int $limit        Maximum number of events to fetch per batch
70
     * @param int $tagBatchSize Number of identifiers to process per batch
71
     *
72
     * @throws \Exception
73
     * @throws \Throwable
74
     */
75
    protected function processEvents(int $shardId, int $priority, int $limit, int $tagBatchSize, string $connection_name): void
76
    {
77
        $processingStartTime = now();
78
        $invalidationWindow = config('super_cache_invalidate.invalidation_window');
79
80
        // Fetch a batch of unprocessed events
81
        $partitionCache_invalidation_events = $this->helper->getCacheInvalidationEventsUnprocessedPartitionName($shardId, $priority);
82
        //$this->info(now()->toDateTimeString() . ' - Partition=' . $partitionCache_invalidation_events);
83
        $events = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))
84
            ->where('processed', '=', 0)
85
            ->where('shard', '=', $shardId)
86
            ->where('priority', '=', $priority)
87
            ->where('event_time', '<', $processingStartTime)
88
            // Cerco tutte le chiavi/tag da invalidare per questo database redis
89
            ->where('connection_name', '=', $connection_name)
90
            ->orderBy('event_time')
91
            ->limit($limit)
92
            ->get()
93
        ;
94
        //$this->info(now()->toDateTimeString() . ' - Trovati Eventi=' . count($events));
95
        if ($events->isEmpty()) {
96
            // No more events to process
97
            return;
98
        }
99
100
        // Group events by type and identifier
101
        $eventsByIdentifier = $events->groupBy(function ($event) {
102
            return $event->type . ':' . $event->identifier;
103
        });
104
105
        $batchIdentifiers = [];
106
        $eventsToUpdate = [];
107
        $counter = 0;
108
109
        // Fetch associated identifiers for the events
110
        // TODO JB 31/12/2024: per adesso commentato, da riattivare quando tutto funziona alla perfezione usando la partizione e soprattutto quando l'insertGetId è stato riattivato nll'helper
111
        $associations = collect();
112
        /*
113
        $eventIds = $events->pluck('id')->all();
114
115
        //retrive associated identifiers related to fetched event id
116
        // Per le chiavi/tag associati non filtro per connection_name, potrebbero esserci associazioni anche in altri database
117
        $associations = DB::table('cache_invalidation_event_associations')
118
            ->whereIn('event_id', $eventIds)
119
            ->get()
120
            ->groupBy('event_id')
121
        ;
122
        */
123
124
        // Prepare list of all identifiers to fetch last invalidation times
125
        $allIdentifiers = [];
126
        foreach ($eventsByIdentifier as $key => $eventsGroup) {
127
            $allIdentifiers[] = $key;
128
            foreach ($eventsGroup as $event) {
129
                $eventAssociations = $associations->where('event_id', '=', $event->id);
130
                foreach ($eventAssociations as $assoc) {
131
                    $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier;
132
                    $allIdentifiers[] = $assocKey;
133
                }
134
            }
135
        }
136
        // Fetch last invalidation times in bulk
137
        $lastInvalidationTimes = $this->getLastInvalidationTimes(array_unique($allIdentifiers));
138
        //$this->info(now()->toDateTimeString() . ' - $lastInvalidationTimes=' . count($lastInvalidationTimes));
139
        foreach ($eventsByIdentifier as $key => $eventsGroup) {
140
            // Extract type and identifier
141
            [$type, $identifier] = explode(':', $key, 2);
142
143
            // Get associated identifiers for the events
144
            $associatedIdentifiers = [];
145
            foreach ($eventsGroup as $event) {
146
                $eventAssociations = $associations->where('event_id', '=', $event->id);
147
                foreach ($eventAssociations as $assoc) {
148
                    $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier;
149
                    $associatedIdentifiers[$assocKey] = [
150
                        'type' => $assoc->associated_type,
151
                        'identifier' => $assoc->associated_identifier,
152
                        'connection_name' => $assoc->connection_name,
153
                    ];
154
                }
155
            }
156
157
            // Build a list of all identifiers to check
158
            $identifiersToCheck = [$key];
159
            $identifiersToCheck = array_merge($identifiersToCheck, array_keys($associatedIdentifiers));
160
            $lastInvalidationTimesSubset = array_intersect_key($lastInvalidationTimes, array_flip($identifiersToCheck));
161
162
            $shouldInvalidate = $this->shouldInvalidateMultiple($identifiersToCheck, $lastInvalidationTimesSubset, $invalidationWindow);
163
            //$this->info(now()->toDateTimeString() . ' - $shouldInvalidate=' . $shouldInvalidate);
164
            if ($shouldInvalidate) {
165
                // Proceed to invalidate
166
                $latestEvent = $eventsGroup->last();
167
168
                // Accumulate identifiers and events
169
                $batchIdentifiers[] = [
170
                    'type' => $type,
171
                    'identifier' => $identifier,
172
                    'event' => $latestEvent,
173
                    'connection_name' => $connection_name,
174
                    'associated' => array_values($associatedIdentifiers),
175
                ];
176
177
                // Update last invalidation times for all identifiers
178
                $this->updateLastInvalidationTimes($identifiersToCheck);
179
                //$this->info(now()->toDateTimeString() . ' - updateLastInvalidationTimes=OK');
180
                // Mark all events in the group as processed
181
                foreach ($eventsGroup as $event) {
182
                    $eventsToUpdate[] = ['id' => $event->id, 'event_time' => $event->event_time, 'partition_key' => $event->partition_key];
183
                }
184
            } else {
185
                // Within the invalidation window, skip invalidation
186
                // Mark all events except the last one as processed
187
                $eventsToProcess = $eventsGroup->slice(0, -1);
188
                foreach ($eventsToProcess as $event) {
189
                    $eventsToUpdate[] = ['id' => $event->id, 'event_time' => $event->event_time, 'partition_key' => $event->partition_key];
190
                }
191
                // The last event remains unprocessed
192
            }
193
194
            $counter++;
195
196
            // When we reach the batch size, process the accumulated identifiers
197
            if ($counter % $tagBatchSize === 0) {
198
                $this->processBatch($batchIdentifiers, $eventsToUpdate, $shardId, $priority);
199
200
                // Reset the accumulators
201
                $batchIdentifiers = [];
202
                $eventsToUpdate = [];
203
            }
204
        }
205
206
        if (empty($batchIdentifiers)) {
207
            return;
208
        }
209
210
        // Process any remaining identifiers in the batch
211
        $this->processBatch($batchIdentifiers, $eventsToUpdate, $shardId, $priority);
212
    }
213
214
    /**
215
     * Fetch last invalidation times for identifiers in bulk.
216
     *
217
     * @param  array $identifiers Array of 'type:identifier' strings
218
     * @return array Associative array of last invalidation times
219
     */
220
    protected function getLastInvalidationTimes(array $identifiers): array
221
    {
222
        // Extract types and identifiers into tuples
223
        $tuples = array_map(static function ($key) {
224
            return explode(':', $key, 2);
225
        }, $identifiers);
226
227
        if (empty($tuples)) {
228
            return [];
229
        }
230
231
        $records = $this->getRecordsFromDb($tuples);
232
233
        // Build associative array
234
        $lastInvalidationTimes = [];
235
        foreach ($records as $record) {
236
            $key = $record->identifier_type . ':' . $record->identifier;
237
            $lastInvalidationTimes[$key] = Carbon::parse($record->last_invalidated);
238
        }
239
240
        return $lastInvalidationTimes;
241
    }
242
243
    /**
244
     * Execute Query to get records from DB
245
     */
246
    protected function getRecordsFromDb(array $tuples): array
247
    {
248
        // Prepare placeholders and parameters
249
        $placeholders = implode(',', array_fill(0, count($tuples), '(?, ?)'));
250
        $params = [];
251
        foreach ($tuples as [$type, $identifier]) {
252
            $params[] = $type;
253
            $params[] = $identifier;
254
        }
255
256
        // ATTENZIONE, qui non si può usare la partizione diretta perchè i record possono essere in partizioni diverse
257
        $sql = "SELECT identifier_type,
258
                        identifier,
259
                        last_invalidated
260
                FROM cache_invalidation_timestamps
261
                WHERE (identifier_type, identifier) IN ($placeholders)
262
                ";
263
264
        return DB::select($sql, $params);
265
    }
266
267
    /**
268
     * Determine whether to invalidate based on last invalidation times for multiple identifiers.
269
     *
270
     * @param  array $identifiers           Array of 'type:identifier' strings
271
     * @param  array $lastInvalidationTimes Associative array of last invalidation times
272
     * @param  int   $invalidationWindow    Invalidation window in seconds
273
     * @return bool  True if should invalidate, false otherwise
274
     */
275
    protected function shouldInvalidateMultiple(array $identifiers, array $lastInvalidationTimes, int $invalidationWindow): bool
276
    {
277
        $now = now();
278
        foreach ($identifiers as $key) {
279
            $lastInvalidated = $lastInvalidationTimes[$key] ?? null;
280
            if (!$lastInvalidated) {
281
                continue;
282
            }
283
            $elapsed = $now->diffInSeconds($lastInvalidated);
284
            if ($elapsed < $invalidationWindow) {
285
                // At least one identifier is within the invalidation window
286
                return false;
287
            }
288
        }
289
290
        // All identifiers are outside the invalidation window or have no record
291
        return true;
292
    }
293
294
    /**
295
     * Update the last invalidation times for multiple identifiers.
296
     *
297
     * @param array $identifiers Array of 'type:identifier' strings
298
     */
299
    protected function updateLastInvalidationTimes(array $identifiers): void
300
    {
301
        $now = now();
302
303
        foreach ($identifiers as $key) {
304
            [$type, $identifier] = explode(':', $key, 2);
305
            // Anche qui non si può usare la partizione perchè nel caso dell'update potrebbe non essere la partizione giusta temporalmente
306
            //$partitionCache_invalidation_timestamps = $this->helper->getCacheInvalidationTimestampsPartitionName();
307
            DB::statement('SET FOREIGN_KEY_CHECKS=0;');
308
            DB::statement('SET UNIQUE_CHECKS=0;');
309
310
            DB::table('cache_invalidation_timestamps')
311
                //DB::table(DB::raw("`cache_invalidation_timestamps` PARTITION ({$partitionCache_invalidation_timestamps})"))
312
                ->updateOrInsert(
313
                    ['identifier_type' => $type, 'identifier' => $identifier],
314
                    ['last_invalidated' => $now]
315
                )
316
            ;
317
318
            // Riattiva i controlli
319
            DB::statement('SET FOREIGN_KEY_CHECKS=1;');
320
            DB::statement('SET UNIQUE_CHECKS=1;');
321
        }
322
    }
323
324
    /**
325
     * Process a batch of identifiers and update events.
326
     *
327
     * @param array $batchIdentifiers Array of identifiers to invalidate
328
     * @param array $eventsToUpdate   Array of event IDs to mark as processed
329
     *
330
     * @throws \Throwable
331
     */
332
    protected function processBatch(array $batchIdentifiers, array $eventsToUpdate, int $shard, int $priority): void
0 ignored issues
show
Unused Code introduced by
The parameter $shard is not used and could be removed. ( Ignorable by Annotation )

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

332
    protected function processBatch(array $batchIdentifiers, array $eventsToUpdate, /** @scrutinizer ignore-unused */ int $shard, int $priority): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $priority is not used and could be removed. ( Ignorable by Annotation )

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

332
    protected function processBatch(array $batchIdentifiers, array $eventsToUpdate, int $shard, /** @scrutinizer ignore-unused */ int $priority): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
333
    {
334
        $maxAttempts = 5;
335
        $attempts = 0;
336
        $updatedOk = false;
337
338
        // Separate keys and tags
339
        $keys = [];
340
        $tags = [];
341
342
        foreach ($batchIdentifiers as $item) {
343
            switch ($item['type']) {
344
                case 'key':
345
                    $keys[] = $item['identifier'] . '§' . $item['connection_name'];
346
                    break;
347
                case 'tag':
348
                    $tags[] = $item['identifier'] . '§' . $item['connection_name'];
349
                    break;
350
            }
351
352
            if (empty($item['associated'])) {
353
                continue;
354
            }
355
356
            // Include associated identifiers
357
            foreach ($item['associated'] as $assoc) {
358
                switch ($assoc['type']) {
359
                    case 'key':
360
                        $keys[] = $assoc['identifier'] . '§' . $assoc['connection_name'];
361
                        break;
362
                    case 'tag':
363
                        $tags[] = $assoc['identifier'] . '§' . $assoc['connection_name'];
364
                        break;
365
                }
366
            }
367
        }
368
369
        // Remove duplicates
370
        $keys = array_unique($keys);
371
        $tags = array_unique($tags);
372
373
        //$this->info(now()->toDateTimeString() . ' - Invalido ' . count($keys) . ' chiavi e ' . count($tags) . ' tag');
374
375
        // Invalidate cache for keys
376
        if (!empty($keys)) {
377
            $this->invalidateKeys($keys);
378
        }
379
380
        // Invalidate cache for tags
381
        if (!empty($tags)) {
382
            $this->invalidateTags($tags);
383
        }
384
385
        $shards = config('super_cache_invalidate.total_shards', 10);
0 ignored issues
show
Unused Code introduced by
The assignment to $shards is dead and can be removed.
Loading history...
386
        while ($attempts < $maxAttempts && !$updatedOk) {
387
            //$partitionCache_invalidation_events_processed = $this->helper->getCacheInvalidationEventsProcessedPartitionName($shard, $priority, $eventToUpdate['event_time']);
388
389
            // Begin transaction for the batch
390
            //DB::beginTransaction();
391
            try {
392
                // Disabilita i controlli delle chiavi esterne e dei vincoli univoci
393
                DB::statement('SET FOREIGN_KEY_CHECKS=0;');
394
                DB::statement('SET UNIQUE_CHECKS=0;');
395
396
                // Mark event as processed
397
                // QUI NON VA USATA PARTITION perchè la cross partition è più lenta!!!
398
                DB::table('cache_invalidation_events')
399
                    ->whereIn('id', array_column($eventsToUpdate, 'id'))
400
                    ->whereIn('partition_key', array_column($eventsToUpdate, 'partition_key'))
401
                    ->update(['processed' => 1, 'updated_at' => now()])
402
                ;
403
                // Riattiva i controlli
404
                DB::statement('SET FOREIGN_KEY_CHECKS=1;');
405
                DB::statement('SET UNIQUE_CHECKS=1;');
406
                // Commit transaction
407
                //DB::commit();
408
                $updatedOk = true;
409
410
                //$this->info(now()->toDateTimeString() . ' - cache_invalidation_events UPDATED Ok - count( ' . count($eventsToUpdate) . ' )');
411
            } catch (\Throwable $e) {
412
                // Rollback transaction on error
413
                //DB::rollBack();
414
                $attempts++;
415
                $this->warn(now()->toDateTimeString() . ": Tentativo $attempts di $maxAttempts: " . $e->getMessage());
416
                // Logica per gestire i tentativi falliti
417
                if ($attempts >= $maxAttempts) {
418
                    // Salta il record dopo il numero massimo di tentativi
419
                    throw $e;
420
                }
421
            }
422
        }
423
    }
424
425
    /**
426
     * Invalidate cache keys.
427
     *
428
     * @param array $keys Array of cache keys to invalidate
429
     */
430
    protected function invalidateKeys(array $keys): void
431
    {
432
        $callback = config('super_cache_invalidate.key_invalidation_callback');
433
434
435
        // Anche in questo caso va fatto un loop perchè le chiavi potrebbero stare in database diversi
436
        foreach ($keys as $keyAndConnectionName) {
437
            [$key, $connection_name] = explode('§', $keyAndConnectionName);
438
439
            // Metodo del progetto
440
            if (is_callable($callback)) {
441
                $callback($key, $connection_name);
442
443
                return;
444
            }
445
446
            // oppure di default uso Laravel
447
            $storeName =  $this->getStoreFromConnectionName($connection_name);
448
449
            if ($storeName === null) {
450
                return;
451
            }
452
            Cache::store($storeName)->forget($key);
453
        }
454
    }
455
456
    /**
457
     * Invalidate cache tags.
458
     *
459
     * @param array $tags Array of cache tags to invalidate
460
     */
461
    protected function invalidateTags(array $tags): void
462
    {
463
        $callback = config('super_cache_invalidate.tag_invalidation_callback');
464
465
        $groupByConnection = [];
466
467
        // Anche in questo caso va fatto un loop perchè i tags potrebbero stare in database diversi,
468
        // ma per ottimizzare possiamo raggruppare le operazioni per connessione
469
        foreach ($tags as $tagAndConnectionName) {
470
            // chiave e connessione
471
            [$key, $connection] = explode('§', $tagAndConnectionName);
472
473
            // Aggiungo la chiave alla connessione appropriata
474
            $groupByConnection[$connection][] = $key;
475
        }
476
        if (is_callable($callback)) {
477
            foreach ($groupByConnection as $connection_name => $arrTags) {
478
                $callback($arrTags, $connection_name);
479
            }
480
481
            return;
482
        }
483
        foreach ($groupByConnection as $connection_name => $arrTags) {
484
            $storeName =  $this->getStoreFromConnectionName($connection_name);
485
            if ($storeName === null) {
486
                return;
487
            }
488
            Cache::store($storeName)->tags($arrTags)->flush();
489
        }
490
    }
491
492
    /**
493
     * Execute the console command.
494
     */
495
    public function handle(): void
496
    {
497
        $shardId = (int) $this->option('shard');
498
        $priority = (int) $this->option('priority');
499
        $limit = $this->option('limit') ?? config('super_cache_invalidate.processing_limit');
500
        $limit = (int)$limit;
501
        $tagBatchSize = $this->option('tag-batch-size') ?? config('super_cache_invalidate.tag_batch_size');
502
        $tagBatchSize = (int)$tagBatchSize;
503
        $lockTimeout = (int) config('super_cache_invalidate.lock_timeout');
504
        $connection_name = $this->option('connection_name') ?? config('super_cache_invalidate.default_connection_name');
505
        /*
506
        if ($shardId === 0 && $priority === 0) {
507
            $this->error('Shard and priority are required and must be non-zero integers.');
508
509
            return;
510
        }
511
        */
512
        $lockValue = $this->helper->acquireShardLock($shardId, $priority, $lockTimeout, $connection_name);
513
        //$this->info(now()->toDateTimeString() . ' Starting shard=' . $shardId . ' priority=' . $priority . ' lockValue=' . $lockValue);
514
        if (!$lockValue) {
515
            return;
516
        }
517
518
        try {
519
            $this->processEvents($shardId, $priority, $limit, $tagBatchSize, $connection_name);
520
        } catch (\Throwable $e) {
521
            $this->error(now()->toDateTimeString() . ': Si è verificato un errore in ' . __METHOD__ . ': ' . $e->getMessage());
522
        } finally {
523
            $this->helper->releaseShardLock($shardId, $priority, $lockValue, $connection_name);
524
        }
525
    }
526
}
527