Total Complexity | 57 |
Total Lines | 513 |
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 | //$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 |
||
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); |
||
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 |
||
524 | } |
||
525 | } |
||
526 | } |
||
527 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.