Total Complexity | 57 |
Total Lines | 507 |
Duplicated Lines | 0 % |
Changes | 5 | ||
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->getCacheInvalidationEventsPartitionName($shardId, $priority); |
||
82 | |||
83 | $events = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})")) |
||
84 | //->from(DB::raw("`{$this->from}` PARTITION ({$partitionsString})")) |
||
85 | ->where('processed', '=', 0) |
||
86 | ->where('shard', '=', $shardId) |
||
87 | ->where('priority', '=', $priority) |
||
88 | ->where('event_time', '<', $processingStartTime) |
||
89 | // Cerco tutte le chiavi/tag da invalidare per questo database redis |
||
90 | ->where('connection_name', '=', $connection_name) |
||
91 | ->orderBy('event_time') |
||
92 | ->limit($limit) |
||
93 | ->get() |
||
94 | ; |
||
95 | |||
96 | //ds($partitionCache_invalidation_events . ' -> Shard (' . $shardId . ') Priority (' . $priority . ') Record = ' . $events->count()); |
||
97 | if ($events->isEmpty()) { |
||
98 | // No more events to process |
||
99 | return; |
||
100 | } |
||
101 | |||
102 | // Group events by type and identifier |
||
103 | $eventsByIdentifier = $events->groupBy(function ($event) { |
||
104 | return $event->type . ':' . $event->identifier; |
||
105 | }); |
||
106 | |||
107 | $batchIdentifiers = []; |
||
108 | $eventsToUpdate = []; |
||
109 | $counter = 0; |
||
110 | |||
111 | // Fetch associated identifiers for the events |
||
112 | // 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 |
||
113 | $associations = collect(); |
||
114 | /* |
||
115 | $eventIds = $events->pluck('id')->all(); |
||
116 | |||
117 | //retrive associated identifiers related to fetched event id |
||
118 | // Per le chiavi/tag associati non filtro per connection_name, potrebbero esserci associazioni anche in altri database |
||
119 | $associations = DB::table('cache_invalidation_event_associations') |
||
120 | ->whereIn('event_id', $eventIds) |
||
121 | ->get() |
||
122 | ->groupBy('event_id') |
||
123 | ; |
||
124 | */ |
||
125 | |||
126 | // Prepare list of all identifiers to fetch last invalidation times |
||
127 | $allIdentifiers = []; |
||
128 | foreach ($eventsByIdentifier as $key => $eventsGroup) { |
||
129 | $allIdentifiers[] = $key; |
||
130 | foreach ($eventsGroup as $event) { |
||
131 | $eventAssociations = $associations->where('event_id', '=', $event->id); |
||
132 | foreach ($eventAssociations as $assoc) { |
||
133 | $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier; |
||
134 | $allIdentifiers[] = $assocKey; |
||
135 | } |
||
136 | } |
||
137 | } |
||
138 | // Fetch last invalidation times in bulk |
||
139 | $lastInvalidationTimes = $this->getLastInvalidationTimes(array_unique($allIdentifiers)); |
||
140 | |||
141 | foreach ($eventsByIdentifier as $key => $eventsGroup) { |
||
142 | // Extract type and identifier |
||
143 | [$type, $identifier] = explode(':', $key, 2); |
||
144 | |||
145 | // Get associated identifiers for the events |
||
146 | $associatedIdentifiers = []; |
||
147 | foreach ($eventsGroup as $event) { |
||
148 | $eventAssociations = $associations->where('event_id', '=', $event->id); |
||
149 | foreach ($eventAssociations as $assoc) { |
||
150 | $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier; |
||
151 | $associatedIdentifiers[$assocKey] = [ |
||
152 | 'type' => $assoc->associated_type, |
||
153 | 'identifier' => $assoc->associated_identifier, |
||
154 | 'connection_name' => $assoc->connection_name, |
||
155 | ]; |
||
156 | } |
||
157 | } |
||
158 | |||
159 | // Build a list of all identifiers to check |
||
160 | $identifiersToCheck = [$key]; |
||
161 | $identifiersToCheck = array_merge($identifiersToCheck, array_keys($associatedIdentifiers)); |
||
162 | $lastInvalidationTimesSubset = array_intersect_key($lastInvalidationTimes, array_flip($identifiersToCheck)); |
||
163 | |||
164 | $shouldInvalidate = $this->shouldInvalidateMultiple($identifiersToCheck, $lastInvalidationTimesSubset, $invalidationWindow); |
||
165 | |||
166 | if ($shouldInvalidate) { |
||
167 | // Proceed to invalidate |
||
168 | $latestEvent = $eventsGroup->last(); |
||
169 | |||
170 | // Accumulate identifiers and events |
||
171 | $batchIdentifiers[] = [ |
||
172 | 'type' => $type, |
||
173 | 'identifier' => $identifier, |
||
174 | 'event' => $latestEvent, |
||
175 | 'connection_name' => $connection_name, |
||
176 | 'associated' => array_values($associatedIdentifiers), |
||
177 | ]; |
||
178 | |||
179 | // Update last invalidation times for all identifiers |
||
180 | $this->updateLastInvalidationTimes($identifiersToCheck); |
||
181 | |||
182 | // Mark all events in the group as processed |
||
183 | foreach ($eventsGroup as $event) { |
||
184 | $eventsToUpdate[] = ['id' => $event->id, 'event_time' => $event->event_time, 'partition_key' => $event->partition_key]; |
||
185 | } |
||
186 | } else { |
||
187 | // Within the invalidation window, skip invalidation |
||
188 | // Mark all events except the last one as processed |
||
189 | $eventsToProcess = $eventsGroup->slice(0, -1); |
||
190 | foreach ($eventsToProcess as $event) { |
||
191 | $eventsToUpdate[] = ['id' => $event->id, 'event_time' => $event->event_time, 'partition_key' => $event->partition_key]; |
||
192 | } |
||
193 | // The last event remains unprocessed |
||
194 | } |
||
195 | |||
196 | $counter++; |
||
197 | |||
198 | // When we reach the batch size, process the accumulated identifiers |
||
199 | if ($counter % $tagBatchSize === 0) { |
||
200 | $this->processBatch($batchIdentifiers, $eventsToUpdate, $shardId, $priority); |
||
201 | |||
202 | // Reset the accumulators |
||
203 | $batchIdentifiers = []; |
||
204 | $eventsToUpdate = []; |
||
205 | } |
||
206 | } |
||
207 | |||
208 | if (empty($batchIdentifiers)) { |
||
209 | return; |
||
210 | } |
||
211 | |||
212 | // Process any remaining identifiers in the batch |
||
213 | $this->processBatch($batchIdentifiers, $eventsToUpdate, $shardId, $priority); |
||
214 | } |
||
215 | |||
216 | /** |
||
217 | * Fetch last invalidation times for identifiers in bulk. |
||
218 | * |
||
219 | * @param array $identifiers Array of 'type:identifier' strings |
||
220 | * @return array Associative array of last invalidation times |
||
221 | */ |
||
222 | protected function getLastInvalidationTimes(array $identifiers): array |
||
223 | { |
||
224 | // Extract types and identifiers into tuples |
||
225 | $tuples = array_map(static function ($key) { |
||
226 | return explode(':', $key, 2); |
||
227 | }, $identifiers); |
||
228 | |||
229 | if (empty($tuples)) { |
||
230 | return []; |
||
231 | } |
||
232 | |||
233 | $records = $this->getRecordsFromDb($tuples); |
||
234 | |||
235 | // Build associative array |
||
236 | $lastInvalidationTimes = []; |
||
237 | foreach ($records as $record) { |
||
238 | $key = $record->identifier_type . ':' . $record->identifier; |
||
239 | $lastInvalidationTimes[$key] = Carbon::parse($record->last_invalidated); |
||
240 | } |
||
241 | |||
242 | return $lastInvalidationTimes; |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * Execute Query to get records from DB |
||
247 | */ |
||
248 | protected function getRecordsFromDb(array $tuples): array |
||
249 | { |
||
250 | // Prepare placeholders and parameters |
||
251 | $placeholders = implode(',', array_fill(0, count($tuples), '(?, ?)')); |
||
252 | $params = []; |
||
253 | foreach ($tuples as [$type, $identifier]) { |
||
254 | $params[] = $type; |
||
255 | $params[] = $identifier; |
||
256 | } |
||
257 | |||
258 | // ATTENZIONE, qui non si può usare la partizione diretta perchè i record possono essere in partizioni diverse |
||
259 | $sql = "SELECT identifier_type, |
||
260 | identifier, |
||
261 | last_invalidated |
||
262 | FROM cache_invalidation_timestamps |
||
263 | WHERE (identifier_type, identifier) IN ($placeholders) |
||
264 | "; |
||
265 | |||
266 | return DB::select($sql, $params); |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * Determine whether to invalidate based on last invalidation times for multiple identifiers. |
||
271 | * |
||
272 | * @param array $identifiers Array of 'type:identifier' strings |
||
273 | * @param array $lastInvalidationTimes Associative array of last invalidation times |
||
274 | * @param int $invalidationWindow Invalidation window in seconds |
||
275 | * @return bool True if should invalidate, false otherwise |
||
276 | */ |
||
277 | protected function shouldInvalidateMultiple(array $identifiers, array $lastInvalidationTimes, int $invalidationWindow): bool |
||
278 | { |
||
279 | $now = now(); |
||
280 | foreach ($identifiers as $key) { |
||
281 | $lastInvalidated = $lastInvalidationTimes[$key] ?? null; |
||
282 | if (!$lastInvalidated) { |
||
283 | continue; |
||
284 | } |
||
285 | $elapsed = $now->diffInSeconds($lastInvalidated); |
||
286 | if ($elapsed < $invalidationWindow) { |
||
287 | // At least one identifier is within the invalidation window |
||
288 | return false; |
||
289 | } |
||
290 | } |
||
291 | |||
292 | // All identifiers are outside the invalidation window or have no record |
||
293 | return true; |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Update the last invalidation times for multiple identifiers. |
||
298 | * |
||
299 | * @param array $identifiers Array of 'type:identifier' strings |
||
300 | */ |
||
301 | protected function updateLastInvalidationTimes(array $identifiers): void |
||
302 | { |
||
303 | $now = now(); |
||
304 | |||
305 | foreach ($identifiers as $key) { |
||
306 | [$type, $identifier] = explode(':', $key, 2); |
||
307 | // Anche qui non si può usare la partizione perchè nel caso dell'update potrebbe non essere la partizione giusta temporalmente |
||
308 | //$partitionCache_invalidation_timestamps = $this->helper->getCacheInvalidationTimestampsPartitionName(); |
||
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 | } |
||
319 | |||
320 | /** |
||
321 | * Process a batch of identifiers and update events. |
||
322 | * |
||
323 | * @param array $batchIdentifiers Array of identifiers to invalidate |
||
324 | * @param array $eventsToUpdate Array of event IDs to mark as processed |
||
325 | * |
||
326 | * @throws \Throwable |
||
327 | */ |
||
328 | protected function processBatch(array $batchIdentifiers, array $eventsToUpdate, int $shard, int $priority): void |
||
329 | { |
||
330 | $maxAttempts = 5; |
||
331 | $attempts = 0; |
||
332 | $updatedOk = false; |
||
333 | |||
334 | // Separate keys and tags |
||
335 | $keys = []; |
||
336 | $tags = []; |
||
337 | |||
338 | foreach ($batchIdentifiers as $item) { |
||
339 | switch ($item['type']) { |
||
340 | case 'key': |
||
341 | $keys[] = $item['identifier'] . '§' . $item['connection_name']; |
||
342 | break; |
||
343 | case 'tag': |
||
344 | $tags[] = $item['identifier'] . '§' . $item['connection_name']; |
||
345 | break; |
||
346 | } |
||
347 | |||
348 | if (empty($item['associated'])) { |
||
349 | continue; |
||
350 | } |
||
351 | |||
352 | // Include associated identifiers |
||
353 | foreach ($item['associated'] as $assoc) { |
||
354 | switch ($assoc['type']) { |
||
355 | case 'key': |
||
356 | $keys[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
357 | break; |
||
358 | case 'tag': |
||
359 | $tags[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
360 | break; |
||
361 | } |
||
362 | } |
||
363 | } |
||
364 | |||
365 | // Remove duplicates |
||
366 | $keys = array_unique($keys); |
||
367 | $tags = array_unique($tags); |
||
368 | |||
369 | // Invalidate cache for keys |
||
370 | if (!empty($keys)) { |
||
371 | $this->invalidateKeys($keys); |
||
372 | } |
||
373 | |||
374 | // Invalidate cache for tags |
||
375 | if (!empty($tags)) { |
||
376 | $this->invalidateTags($tags); |
||
377 | } |
||
378 | |||
379 | $shards = config('super_cache_invalidate.total_shards', 10); |
||
380 | //$partitionCache_invalidation_events = $this->helper->getCacheInvalidationEventsPartitionName($shard, $priority); |
||
381 | |||
382 | while ($attempts < $maxAttempts && !$updatedOk) { |
||
383 | //$partitionCache_invalidation_events_processed = $this->helper->getCacheInvalidationEventsProcessedPartitionName($shard, $priority, $eventToUpdate['event_time']); |
||
384 | |||
385 | // Begin transaction for the batch |
||
386 | //DB::beginTransaction(); |
||
387 | try { |
||
388 | // Disabilita i controlli delle chiavi esterne e dei vincoli univoci |
||
389 | DB::statement('SET FOREIGN_KEY_CHECKS=0;'); |
||
390 | DB::statement('SET UNIQUE_CHECKS=0;'); |
||
391 | |||
392 | // Mark event as processed |
||
393 | //DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events}, {$partitionCache_invalidation_events_processed})")) |
||
394 | DB::table("cache_invalidation_events") |
||
395 | ->whereIn('id', array_column($eventsToUpdate, 'id')) |
||
396 | ->whereIn('partition_key', array_column($eventsToUpdate, 'partition_key')) |
||
397 | ->update(['processed' => 1]) |
||
398 | ; |
||
399 | // Riattiva i controlli |
||
400 | DB::statement('SET UNIQUE_CHECKS=1;'); |
||
401 | DB::statement('SET FOREIGN_KEY_CHECKS=1;'); |
||
402 | // Commit transaction |
||
403 | //DB::commit(); |
||
404 | $updatedOk = true; |
||
405 | } catch (\Throwable $e) { |
||
406 | // Rollback transaction on error |
||
407 | //DB::rollBack(); |
||
408 | $attempts++; |
||
409 | $this->warn(now()->toDateTimeString() . ": Tentativo $attempts di $maxAttempts: " . $e->getMessage()); |
||
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 |
||
518 | } |
||
519 | } |
||
520 | } |
||
521 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.