Total Complexity | 57 |
Total Lines | 508 |
Duplicated Lines | 0 % |
Changes | 6 | ||
Bugs | 0 | Features | 0 |
Complex classes like ProcessCacheInvalidationEventsCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ProcessCacheInvalidationEventsCommand, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
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) |
||
44 | } |
||
45 | |||
46 | private function getStoreFromConnectionName(string $connection_name): ?string |
||
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 |
||
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 |
||
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 | DB::statement('SET FOREIGN_KEY_CHECKS=0;'); |
||
307 | DB::statement('SET UNIQUE_CHECKS=0;'); |
||
308 | |||
309 | DB::table('cache_invalidation_timestamps') |
||
310 | //DB::table(DB::raw("`cache_invalidation_timestamps` PARTITION ({$partitionCache_invalidation_timestamps})")) |
||
311 | ->updateOrInsert( |
||
312 | ['identifier_type' => $type, 'identifier' => $identifier], |
||
313 | ['last_invalidated' => $now] |
||
314 | ) |
||
315 | ; |
||
316 | |||
317 | // Riattiva i controlli |
||
318 | DB::statement('SET UNIQUE_CHECKS=1;'); |
||
319 | DB::statement('SET FOREIGN_KEY_CHECKS=1;'); |
||
320 | } |
||
321 | } |
||
322 | |||
323 | /** |
||
324 | * Process a batch of identifiers and update events. |
||
325 | * |
||
326 | * @param array $batchIdentifiers Array of identifiers to invalidate |
||
327 | * @param array $eventsToUpdate Array of event IDs to mark as processed |
||
328 | * |
||
329 | * @throws \Throwable |
||
330 | */ |
||
331 | protected function processBatch(array $batchIdentifiers, array $eventsToUpdate, int $shard, int $priority): void |
||
332 | { |
||
333 | $maxAttempts = 5; |
||
334 | $attempts = 0; |
||
335 | $updatedOk = false; |
||
336 | |||
337 | // Separate keys and tags |
||
338 | $keys = []; |
||
339 | $tags = []; |
||
340 | |||
341 | foreach ($batchIdentifiers as $item) { |
||
342 | switch ($item['type']) { |
||
343 | case 'key': |
||
344 | $keys[] = $item['identifier'] . '§' . $item['connection_name']; |
||
345 | break; |
||
346 | case 'tag': |
||
347 | $tags[] = $item['identifier'] . '§' . $item['connection_name']; |
||
348 | break; |
||
349 | } |
||
350 | |||
351 | if (empty($item['associated'])) { |
||
352 | continue; |
||
353 | } |
||
354 | |||
355 | // Include associated identifiers |
||
356 | foreach ($item['associated'] as $assoc) { |
||
357 | switch ($assoc['type']) { |
||
358 | case 'key': |
||
359 | $keys[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
360 | break; |
||
361 | case 'tag': |
||
362 | $tags[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
363 | break; |
||
364 | } |
||
365 | } |
||
366 | } |
||
367 | |||
368 | // Remove duplicates |
||
369 | $keys = array_unique($keys); |
||
370 | $tags = array_unique($tags); |
||
371 | |||
372 | // Invalidate cache for keys |
||
373 | if (!empty($keys)) { |
||
374 | $this->invalidateKeys($keys); |
||
375 | } |
||
376 | |||
377 | // Invalidate cache for tags |
||
378 | if (!empty($tags)) { |
||
379 | $this->invalidateTags($tags); |
||
380 | } |
||
381 | |||
382 | $shards = config('super_cache_invalidate.total_shards', 10); |
||
383 | while ($attempts < $maxAttempts && !$updatedOk) { |
||
384 | //$partitionCache_invalidation_events_processed = $this->helper->getCacheInvalidationEventsProcessedPartitionName($shard, $priority, $eventToUpdate['event_time']); |
||
385 | |||
386 | // Begin transaction for the batch |
||
387 | //DB::beginTransaction(); |
||
388 | try { |
||
389 | // Disabilita i controlli delle chiavi esterne e dei vincoli univoci |
||
390 | DB::statement('SET FOREIGN_KEY_CHECKS=0;'); |
||
391 | DB::statement('SET UNIQUE_CHECKS=0;'); |
||
392 | |||
393 | // Mark event as processed |
||
394 | // QUI NON VA USATA PARTITION perchè la cross partition è più lenta!!! |
||
395 | DB::table('cache_invalidation_events') |
||
396 | ->whereIn('id', array_column($eventsToUpdate, 'id')) |
||
397 | ->whereIn('partition_key', array_column($eventsToUpdate, 'partition_key')) |
||
398 | ->update(['processed' => 1, 'updated_at' => now()]) |
||
399 | ; |
||
400 | // Riattiva i controlli |
||
401 | DB::statement('SET UNIQUE_CHECKS=1;'); |
||
402 | DB::statement('SET FOREIGN_KEY_CHECKS=1;'); |
||
403 | // Commit transaction |
||
404 | //DB::commit(); |
||
405 | $updatedOk = true; |
||
406 | } catch (\Throwable $e) { |
||
407 | // Rollback transaction on error |
||
408 | //DB::rollBack(); |
||
409 | $attempts++; |
||
410 | $this->warn(now()->toDateTimeString() . ": Tentativo $attempts di $maxAttempts: " . $e->getMessage()); |
||
411 | // Logica per gestire i tentativi falliti |
||
412 | if ($attempts >= $maxAttempts) { |
||
413 | // Salta il record dopo il numero massimo di tentativi |
||
414 | throw $e; |
||
415 | } |
||
416 | } |
||
417 | } |
||
418 | } |
||
419 | |||
420 | /** |
||
421 | * Invalidate cache keys. |
||
422 | * |
||
423 | * @param array $keys Array of cache keys to invalidate |
||
424 | */ |
||
425 | protected function invalidateKeys(array $keys): void |
||
426 | { |
||
427 | $callback = config('super_cache_invalidate.key_invalidation_callback'); |
||
428 | |||
429 | |||
430 | // Anche in questo caso va fatto un loop perchè le chiavi potrebbero stare in database diversi |
||
431 | foreach ($keys as $keyAndConnectionName) { |
||
432 | [$key, $connection_name] = explode('§', $keyAndConnectionName); |
||
433 | |||
434 | // Metodo del progetto |
||
435 | if (is_callable($callback)) { |
||
436 | $callback($key, $connection_name); |
||
437 | |||
438 | return; |
||
439 | } |
||
440 | |||
441 | // oppure di default uso Laravel |
||
442 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
443 | |||
444 | if ($storeName === null) { |
||
445 | return; |
||
446 | } |
||
447 | Cache::store($storeName)->forget($key); |
||
448 | } |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * Invalidate cache tags. |
||
453 | * |
||
454 | * @param array $tags Array of cache tags to invalidate |
||
455 | */ |
||
456 | protected function invalidateTags(array $tags): void |
||
457 | { |
||
458 | $callback = config('super_cache_invalidate.tag_invalidation_callback'); |
||
459 | |||
460 | $groupByConnection = []; |
||
461 | |||
462 | // Anche in questo caso va fatto un loop perchè i tags potrebbero stare in database diversi, |
||
463 | // ma per ottimizzare possiamo raggruppare le operazioni per connessione |
||
464 | foreach ($tags as $tagAndConnectionName) { |
||
465 | // chiave e connessione |
||
466 | [$key, $connection] = explode('§', $tagAndConnectionName); |
||
467 | |||
468 | // Aggiungo la chiave alla connessione appropriata |
||
469 | $groupByConnection[$connection][] = $key; |
||
470 | } |
||
471 | if (is_callable($callback)) { |
||
472 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
473 | $callback($arrTags, $connection_name); |
||
474 | } |
||
475 | |||
476 | return; |
||
477 | } |
||
478 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
479 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
480 | if ($storeName === null) { |
||
481 | return; |
||
482 | } |
||
483 | Cache::store($storeName)->tags($arrTags)->flush(); |
||
484 | } |
||
485 | } |
||
486 | |||
487 | /** |
||
488 | * Execute the console command. |
||
489 | */ |
||
490 | public function handle(): void |
||
519 | } |
||
520 | } |
||
521 | } |
||
522 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.