Total Complexity | 58 |
Total Lines | 493 |
Duplicated Lines | 0 % |
Changes | 3 | ||
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 | protected function getCache_invalidation_eventsPartitionName(int $shardId, int $priorityId): string |
||
63 | { |
||
64 | // Calcola il valore della partizione |
||
65 | $shards = config('super_cache_invalidate.total_shards', 10); |
||
66 | $priorities = [0, 1]; |
||
67 | |||
68 | $partitionStatements = []; |
||
|
|||
69 | |||
70 | $partitionValueId = ($priorityId * $shards) + $shardId + 1; |
||
71 | |||
72 | // Partitions for unprocessed events |
||
73 | foreach ($priorities as $priority) { |
||
74 | for ($shard = 0; $shard < $shards; $shard++) { |
||
75 | $partitionName = "p_unprocessed_s{$shard}_p{$priority}"; |
||
76 | $partitionValue = ($priority * $shards) + $shard + 1; |
||
77 | if ($partitionValueId < $partitionValue) { |
||
78 | return $partitionName; |
||
79 | } |
||
80 | } |
||
81 | } |
||
82 | |||
83 | return ''; |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * Process cache invalidation events. |
||
88 | * |
||
89 | * @param int $shardId The shard number to process |
||
90 | * @param int $priority The priority level |
||
91 | * @param int $limit Maximum number of events to fetch per batch |
||
92 | * @param int $tagBatchSize Number of identifiers to process per batch |
||
93 | * |
||
94 | * @throws \Exception |
||
95 | */ |
||
96 | protected function processEvents(int $shardId, int $priority, int $limit, int $tagBatchSize, string $connection_name): void |
||
97 | { |
||
98 | $processingStartTime = now(); |
||
99 | $invalidationWindow = config('super_cache_invalidate.invalidation_window'); |
||
100 | |||
101 | // Fetch a batch of unprocessed events |
||
102 | $partitionCache_invalidation_events = $this->getCache_invalidation_eventsPartitionName($shardId, $priority, 0, $processingStartTime); |
||
103 | |||
104 | $events = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})")) |
||
105 | //->from(DB::raw("`{$this->from}` PARTITION ({$partitionsString})")) |
||
106 | ->where('processed', '=', 0) |
||
107 | ->where('shard', '=', $shardId) |
||
108 | ->where('priority', '=', $priority) |
||
109 | ->where('event_time', '<', $processingStartTime) |
||
110 | // Cerco tutte le chiavi/tag da invalidare per questo database redis |
||
111 | ->where('connection_name', '=', $connection_name) |
||
112 | ->orderBy('event_time') |
||
113 | ->limit($limit) |
||
114 | ->get() |
||
115 | ; |
||
116 | |||
117 | //ds($partitionCache_invalidation_events . ' -> Shard (' . $shardId . ') Priority (' . $priority . ') Record = ' . $events->count()); |
||
118 | if ($events->isEmpty()) { |
||
119 | // No more events to process |
||
120 | return; |
||
121 | } |
||
122 | |||
123 | // Group events by type and identifier |
||
124 | $eventsByIdentifier = $events->groupBy(function ($event) { |
||
125 | return $event->type . ':' . $event->identifier; |
||
126 | }); |
||
127 | |||
128 | $batchIdentifiers = []; |
||
129 | $eventsToUpdate = []; |
||
130 | $counter = 0; |
||
131 | |||
132 | // Fetch associated identifiers for the events |
||
133 | $eventIds = $events->pluck('id')->all(); |
||
134 | |||
135 | //retrive associated identifiers related to fetched event id |
||
136 | // Per le chiavi/tag associati non filtro per connection_name, potrebbero esserci associazioni anche in altri database |
||
137 | $associations = DB::table('cache_invalidation_event_associations') |
||
138 | ->whereIn('event_id', $eventIds) |
||
139 | ->get() |
||
140 | ->groupBy('event_id') |
||
141 | ; |
||
142 | |||
143 | // Prepare list of all identifiers to fetch last invalidation times |
||
144 | $allIdentifiers = []; |
||
145 | foreach ($eventsByIdentifier as $key => $eventsGroup) { |
||
146 | $allIdentifiers[] = $key; |
||
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 | $allIdentifiers[] = $assocKey; |
||
152 | } |
||
153 | } |
||
154 | } |
||
155 | // Fetch last invalidation times in bulk |
||
156 | $lastInvalidationTimes = $this->getLastInvalidationTimes(array_unique($allIdentifiers)); |
||
157 | |||
158 | foreach ($eventsByIdentifier as $key => $eventsGroup) { |
||
159 | // Extract type and identifier |
||
160 | [$type, $identifier] = explode(':', $key, 2); |
||
161 | |||
162 | // Get associated identifiers for the events |
||
163 | $associatedIdentifiers = []; |
||
164 | foreach ($eventsGroup as $event) { |
||
165 | $eventAssociations = $associations->where('event_id', '=', $event->id); |
||
166 | foreach ($eventAssociations as $assoc) { |
||
167 | $assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier; |
||
168 | $associatedIdentifiers[$assocKey] = [ |
||
169 | 'type' => $assoc->associated_type, |
||
170 | 'identifier' => $assoc->associated_identifier, |
||
171 | 'connection_name' => $assoc->connection_name, |
||
172 | ]; |
||
173 | } |
||
174 | } |
||
175 | |||
176 | // Build a list of all identifiers to check |
||
177 | $identifiersToCheck = [$key]; |
||
178 | $identifiersToCheck = array_merge($identifiersToCheck, array_keys($associatedIdentifiers)); |
||
179 | $lastInvalidationTimesSubset = array_intersect_key($lastInvalidationTimes, array_flip($identifiersToCheck)); |
||
180 | |||
181 | $shouldInvalidate = $this->shouldInvalidateMultiple($identifiersToCheck, $lastInvalidationTimesSubset, $invalidationWindow); |
||
182 | |||
183 | if ($shouldInvalidate) { |
||
184 | // Proceed to invalidate |
||
185 | $latestEvent = $eventsGroup->last(); |
||
186 | |||
187 | // Accumulate identifiers and events |
||
188 | $batchIdentifiers[] = [ |
||
189 | 'type' => $type, |
||
190 | 'identifier' => $identifier, |
||
191 | 'event' => $latestEvent, |
||
192 | 'connection_name' => $connection_name, |
||
193 | 'associated' => array_values($associatedIdentifiers), |
||
194 | ]; |
||
195 | |||
196 | // Update last invalidation times for all identifiers |
||
197 | $this->updateLastInvalidationTimes($identifiersToCheck); |
||
198 | |||
199 | // Mark all events in the group as processed |
||
200 | foreach ($eventsGroup as $event) { |
||
201 | $eventsToUpdate[] = $event->id; |
||
202 | } |
||
203 | } else { |
||
204 | // Within the invalidation window, skip invalidation |
||
205 | // Mark all events except the last one as processed |
||
206 | $eventsToProcess = $eventsGroup->slice(0, -1); |
||
207 | foreach ($eventsToProcess as $event) { |
||
208 | $eventsToUpdate[] = $event->id; |
||
209 | } |
||
210 | // The last event remains unprocessed |
||
211 | } |
||
212 | |||
213 | $counter++; |
||
214 | |||
215 | // When we reach the batch size, process the accumulated identifiers |
||
216 | if ($counter % $tagBatchSize === 0) { |
||
217 | $this->processBatch($batchIdentifiers, $eventsToUpdate); |
||
218 | |||
219 | // Reset the accumulators |
||
220 | $batchIdentifiers = []; |
||
221 | $eventsToUpdate = []; |
||
222 | } |
||
223 | } |
||
224 | |||
225 | if (empty($batchIdentifiers)) { |
||
226 | return; |
||
227 | } |
||
228 | |||
229 | // Process any remaining identifiers in the batch |
||
230 | $this->processBatch($batchIdentifiers, $eventsToUpdate); |
||
231 | } |
||
232 | |||
233 | /** |
||
234 | * Fetch last invalidation times for identifiers in bulk. |
||
235 | * |
||
236 | * @param array $identifiers Array of 'type:identifier' strings |
||
237 | * @return array Associative array of last invalidation times |
||
238 | */ |
||
239 | protected function getLastInvalidationTimes(array $identifiers): array |
||
240 | { |
||
241 | // Extract types and identifiers into tuples |
||
242 | $tuples = array_map(static function ($key) { |
||
243 | return explode(':', $key, 2); |
||
244 | }, $identifiers); |
||
245 | |||
246 | if (empty($tuples)) { |
||
247 | return []; |
||
248 | } |
||
249 | |||
250 | $records = $this->getRecordsFromDb($tuples); |
||
251 | |||
252 | // Build associative array |
||
253 | $lastInvalidationTimes = []; |
||
254 | foreach ($records as $record) { |
||
255 | $key = $record->identifier_type . ':' . $record->identifier; |
||
256 | $lastInvalidationTimes[$key] = Carbon::parse($record->last_invalidated); |
||
257 | } |
||
258 | |||
259 | return $lastInvalidationTimes; |
||
260 | } |
||
261 | |||
262 | /** |
||
263 | * Execute Query to get records from DB |
||
264 | */ |
||
265 | protected function getRecordsFromDb(array $tuples): array |
||
266 | { |
||
267 | // Prepare placeholders and parameters |
||
268 | $placeholders = implode(',', array_fill(0, count($tuples), '(?, ?)')); |
||
269 | $params = []; |
||
270 | foreach ($tuples as [$type, $identifier]) { |
||
271 | $params[] = $type; |
||
272 | $params[] = $identifier; |
||
273 | } |
||
274 | |||
275 | $sql = "SELECT identifier_type, |
||
276 | identifier, |
||
277 | last_invalidated |
||
278 | FROM cache_invalidation_timestamps |
||
279 | WHERE (identifier_type, identifier) IN ($placeholders) |
||
280 | "; |
||
281 | |||
282 | return DB::select($sql, $params); |
||
283 | } |
||
284 | |||
285 | /** |
||
286 | * Determine whether to invalidate based on last invalidation times for multiple identifiers. |
||
287 | * |
||
288 | * @param array $identifiers Array of 'type:identifier' strings |
||
289 | * @param array $lastInvalidationTimes Associative array of last invalidation times |
||
290 | * @param int $invalidationWindow Invalidation window in seconds |
||
291 | * @return bool True if should invalidate, false otherwise |
||
292 | */ |
||
293 | protected function shouldInvalidateMultiple(array $identifiers, array $lastInvalidationTimes, int $invalidationWindow): bool |
||
294 | { |
||
295 | $now = now(); |
||
296 | foreach ($identifiers as $key) { |
||
297 | $lastInvalidated = $lastInvalidationTimes[$key] ?? null; |
||
298 | if (!$lastInvalidated) { |
||
299 | continue; |
||
300 | } |
||
301 | $elapsed = $now->diffInSeconds($lastInvalidated); |
||
302 | if ($elapsed < $invalidationWindow) { |
||
303 | // At least one identifier is within the invalidation window |
||
304 | return false; |
||
305 | } |
||
306 | } |
||
307 | |||
308 | // All identifiers are outside the invalidation window or have no record |
||
309 | return true; |
||
310 | } |
||
311 | |||
312 | /** |
||
313 | * Update the last invalidation times for multiple identifiers. |
||
314 | * |
||
315 | * @param array $identifiers Array of 'type:identifier' strings |
||
316 | */ |
||
317 | protected function updateLastInvalidationTimes(array $identifiers): void |
||
318 | { |
||
319 | $now = now(); |
||
320 | |||
321 | foreach ($identifiers as $key) { |
||
322 | [$type, $identifier] = explode(':', $key, 2); |
||
323 | DB::table('cache_invalidation_timestamps') |
||
324 | ->updateOrInsert( |
||
325 | ['identifier_type' => $type, 'identifier' => $identifier], |
||
326 | ['last_invalidated' => $now] |
||
327 | ) |
||
328 | ; |
||
329 | } |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * Process a batch of identifiers and update events. |
||
334 | * |
||
335 | * @param array $batchIdentifiers Array of identifiers to invalidate |
||
336 | * @param array $eventsToUpdate Array of event IDs to mark as processed |
||
337 | * |
||
338 | * @throws \Exception |
||
339 | */ |
||
340 | protected function processBatch(array $batchIdentifiers, array $eventsToUpdate): void |
||
341 | { |
||
342 | |||
343 | // Begin transaction for the batch |
||
344 | // DB::beginTransaction(); |
||
345 | |||
346 | try { |
||
347 | // Separate keys and tags |
||
348 | $keys = []; |
||
349 | $tags = []; |
||
350 | |||
351 | foreach ($batchIdentifiers as $item) { |
||
352 | switch ($item['type']) { |
||
353 | case 'key': |
||
354 | $keys[] = $item['identifier'] . '§' . $item['connection_name']; |
||
355 | break; |
||
356 | case 'tag': |
||
357 | $tags[] = $item['identifier'] . '§' . $item['connection_name']; |
||
358 | break; |
||
359 | } |
||
360 | |||
361 | if (empty($item['associated'])) { |
||
362 | continue; |
||
363 | } |
||
364 | |||
365 | // Include associated identifiers |
||
366 | foreach ($item['associated'] as $assoc) { |
||
367 | switch ($assoc['type']) { |
||
368 | case 'key': |
||
369 | $keys[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
370 | break; |
||
371 | case 'tag': |
||
372 | $tags[] = $assoc['identifier'] . '§' . $assoc['connection_name']; |
||
373 | break; |
||
374 | } |
||
375 | } |
||
376 | } |
||
377 | |||
378 | // Remove duplicates |
||
379 | $keys = array_unique($keys); |
||
380 | $tags = array_unique($tags); |
||
381 | |||
382 | // Invalidate cache for keys |
||
383 | if (!empty($keys)) { |
||
384 | $this->invalidateKeys($keys); |
||
385 | } |
||
386 | |||
387 | // Invalidate cache for tags |
||
388 | if (!empty($tags)) { |
||
389 | $this->invalidateTags($tags); |
||
390 | } |
||
391 | |||
392 | // Mark events as processed |
||
393 | DB::table('cache_invalidation_events') |
||
394 | ->whereIn('id', $eventsToUpdate) |
||
395 | ->update(['processed' => 1]) |
||
396 | ; |
||
397 | |||
398 | // Commit transaction |
||
399 | //DB::commit(); |
||
400 | } catch (\Exception $e) { |
||
401 | // Rollback transaction on error |
||
402 | // DB::rollBack(); |
||
403 | throw $e; |
||
404 | } |
||
405 | } |
||
406 | |||
407 | /** |
||
408 | * Invalidate cache keys. |
||
409 | * |
||
410 | * @param array $keys Array of cache keys to invalidate |
||
411 | */ |
||
412 | protected function invalidateKeys(array $keys): void |
||
413 | { |
||
414 | $callback = config('super_cache_invalidate.key_invalidation_callback'); |
||
415 | |||
416 | |||
417 | // Anche in questo caso va fatto un loop perchè le chiavi potrebbero stare in database diversi |
||
418 | foreach ($keys as $keyAndConnectionName) { |
||
419 | [$key, $connection_name] = explode('§', $keyAndConnectionName); |
||
420 | |||
421 | // Metodo del progetto |
||
422 | if (is_callable($callback)) { |
||
423 | $callback($key, $connection_name); |
||
424 | return; |
||
425 | } |
||
426 | |||
427 | // oppure di default uso Laravel |
||
428 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
429 | |||
430 | if ($storeName === null) { |
||
431 | return; |
||
432 | } |
||
433 | Cache::store($storeName)->forget($key); |
||
434 | } |
||
435 | } |
||
436 | |||
437 | /** |
||
438 | * Invalidate cache tags. |
||
439 | * |
||
440 | * @param array $tags Array of cache tags to invalidate |
||
441 | */ |
||
442 | protected function invalidateTags(array $tags): void |
||
443 | { |
||
444 | $callback = config('super_cache_invalidate.tag_invalidation_callback'); |
||
445 | |||
446 | $groupByConnection = []; |
||
447 | |||
448 | // Anche in questo caso va fatto un loop perchè i tags potrebbero stare in database diversi, |
||
449 | // ma per ottimizzare possiamo raggruppare le operazioni per connessione |
||
450 | foreach ($tags as $tagAndConnectionName) { |
||
451 | // chiave e connessione |
||
452 | [$key, $connection] = explode('§', $tagAndConnectionName); |
||
453 | |||
454 | // Aggiungo la chiave alla connessione appropriata |
||
455 | $groupByConnection[$connection][] = $key; |
||
456 | } |
||
457 | if (is_callable($callback)) { |
||
458 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
459 | $callback($arrTags, $connection_name); |
||
460 | } |
||
461 | return; |
||
462 | } |
||
463 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
464 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
465 | if ($storeName === null) { |
||
466 | return; |
||
467 | } |
||
468 | Cache::store($storeName)->tags($arrTags)->flush(); |
||
469 | } |
||
470 | } |
||
471 | |||
472 | /** |
||
473 | * Execute the console command. |
||
474 | */ |
||
475 | public function handle(): void |
||
504 | } |
||
505 | } |
||
506 | } |
||
507 |