Passed
Pull Request — main (#3)
by
unknown
03:28
created

updateLastInvalidationTimes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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

325
    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

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