| 1 | <?php |
||
| 2 | |||
| 3 | namespace Padosoft\SuperCacheInvalidate\Console; |
||
| 4 | |||
| 5 | use Illuminate\Console\Command; |
||
| 6 | use Illuminate\Support\Carbon; |
||
| 7 | use Illuminate\Support\Facades\Cache; |
||
| 8 | use Illuminate\Support\Facades\DB; |
||
| 9 | use Illuminate\Support\Str; |
||
| 10 | use Padosoft\SuperCacheInvalidate\Events\BatchCompletedEvent; |
||
| 11 | use Padosoft\SuperCacheInvalidate\Helpers\SuperCacheInvalidationHelper; |
||
| 12 | |||
| 13 | class ProcessCacheInvalidationEventsCommand extends Command |
||
| 14 | { |
||
| 15 | protected $signature = 'supercache:process-invalidation |
||
| 16 | {--shard= : The shard number to process} |
||
| 17 | {--priority= : The priority level} |
||
| 18 | {--limit= : The maximum number of events to fetch per batch} |
||
| 19 | {--tag-batch-size= : The number of identifiers to process per invalidation batch} |
||
| 20 | {--connection_name= : The Redis connection name} |
||
| 21 | {--log_attivo= : Indica se il log delle operazioni รจ attivo (0=no, 1=si)}'; |
||
| 22 | protected $description = 'Process cache invalidation events for a given shard and priority'; |
||
| 23 | protected SuperCacheInvalidationHelper $helper; |
||
| 24 | protected bool $log_attivo = false; |
||
| 25 | protected string $connection_name = 'cache'; |
||
| 26 | protected int $tagBatchSize = 100; |
||
| 27 | protected int $limit = 1000; |
||
| 28 | protected int $priority = 0; |
||
| 29 | protected int $shardId = 0; |
||
| 30 | protected int $invalidation_window = 600; |
||
| 31 | |||
| 32 | public function __construct(SuperCacheInvalidationHelper $helper) |
||
| 33 | { |
||
| 34 | parent::__construct(); |
||
| 35 | $this->helper = $helper; |
||
| 36 | } |
||
| 37 | |||
| 38 | private function getEventsToInvalidate(Carbon $processingStartTime): array |
||
| 39 | { |
||
| 40 | $partitionCache_invalidation_events = $this->helper->getCacheInvalidationEventsUnprocessedPartitionName($this->shardId, $this->priority); |
||
| 41 | |||
| 42 | return DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})")) |
||
| 43 | ->select(['id', 'type', 'identifier', 'connection_name', 'partition_key', 'event_time']) |
||
| 44 | ->where('processed', '=', 0) |
||
| 45 | ->where('shard', '=', $this->shardId) |
||
| 46 | ->where('priority', '=', $this->priority) |
||
| 47 | // Cerco tutte le chiavi/tag da invalidare per questo database redis |
||
| 48 | ->where('connection_name', '=', $this->connection_name) |
||
| 49 | ->where('event_time', '<', $processingStartTime) |
||
| 50 | ->orderBy('event_time') |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 51 | ->limit($this->limit) |
||
| 52 | ->get() |
||
| 53 | ->toArray() |
||
| 54 | ; |
||
| 55 | } |
||
| 56 | |||
| 57 | private function getStoreFromConnectionName(string $connection_name): ?string |
||
| 58 | { |
||
| 59 | // Cerca il nome dello store associato alla connessione Redis |
||
| 60 | foreach (config('cache.stores') as $storeName => $storeConfig) { |
||
| 61 | if ( |
||
| 62 | isset($storeConfig['driver'], $storeConfig['connection']) && |
||
| 63 | $storeConfig['driver'] === 'redis' && |
||
| 64 | $storeConfig['connection'] === $connection_name |
||
| 65 | ) { |
||
| 66 | return $storeName; |
||
| 67 | } |
||
| 68 | } |
||
| 69 | |||
| 70 | return null; |
||
| 71 | } |
||
| 72 | |||
| 73 | private function logIf(string $message, string $level = 'info') |
||
| 74 | { |
||
| 75 | if (!$this->log_attivo && $level === 'info') { |
||
| 76 | return; |
||
| 77 | } |
||
| 78 | $this->$level(now()->toDateTimeString() . ' Shard[' . $this->shardId . '] Priority[' . $this->priority . '] Connection[' . $this->connection_name . '] : ' . PHP_EOL . $message); |
||
| 79 | } |
||
| 80 | |||
| 81 | protected function processEvents(): void |
||
| 82 | { |
||
| 83 | $processingStartTime = now(); |
||
| 84 | // Recupero gli eventi da invalidare |
||
| 85 | $events = $this->getEventsToInvalidate($processingStartTime); |
||
| 86 | $this->logIf('Trovati ' . count($events) . ' Eventi da invalidare'); |
||
| 87 | if (count($events) === 0) { |
||
| 88 | return; |
||
| 89 | } |
||
| 90 | |||
| 91 | // Creiamo un array per memorizzare il valore piรน vecchio per ogni coppia (type, identifier) cosรฌ elimino i doppioni che si sono accumulati nel tempo di apertura della finestra |
||
| 92 | $unique_events = []; |
||
| 93 | |||
| 94 | foreach ($events as $event) { |
||
| 95 | $key = $event->type . ':' . $event->identifier; // Chiave univoca per type + identifier |
||
| 96 | $event->event_time = \Illuminate\Support\Carbon::parse($event->event_time); |
||
| 97 | // Quando la chiave non esiste o il nuovo valore ha un event_time piรน vecchio, lo sostituisco cosรฌ a paritร di tag ho sempre quello piรน vecchio e mi baso su quello per verificare la finestra |
||
| 98 | if (!isset($unique_events[$key]) || $event->event_time <= $unique_events[$key]->event_time) { |
||
| 99 | $unique_events[$key] = $event; |
||
| 100 | } |
||
| 101 | } |
||
| 102 | |||
| 103 | $unique_events = array_values($unique_events); |
||
| 104 | |||
| 105 | $this->logIf('Eventi unici ' . count($unique_events)); |
||
| 106 | // Quando il numero di eventi unici รจ inferiore al batchSize e quello piรน vecchio aspetta da almeno due minuti, mando l'invalidazione. |
||
| 107 | // Questo serve per i siti piccoli che hanno pochi eventi, altrimenti si rischia di attendere troppo per invalidare i tags |
||
| 108 | // In questo caso invalido i tag/key "unici" e setto a processed = 1 tutti quelli recuperati |
||
| 109 | if (count($unique_events) < $this->tagBatchSize && $processingStartTime->diffInSeconds($unique_events[0]->event_time) >= 120) { |
||
| 110 | $this->logIf('Il numero di eventi unici รจ inferiore al batchSize ( ' . $this->tagBatchSize . ' ) e sono passati piรน di due minuti, procedo'); |
||
| 111 | $this->processBatch($events, $unique_events); |
||
| 112 | |||
| 113 | return; |
||
| 114 | } |
||
| 115 | |||
| 116 | // Altrimenti ho raggiunto il tagbatchsize e devo prendere solo quelli che hanno la finestra di invalidazione attiva |
||
| 117 | $eventsToUpdate = []; |
||
| 118 | $eventsAll = []; |
||
| 119 | foreach ($unique_events as $event) { |
||
| 120 | $elapsed = $processingStartTime->diffInSeconds($event->event_time, true); |
||
| 121 | $typeFilter = $event->type; |
||
| 122 | $identifierFilter = $event->identifier; |
||
| 123 | if ($elapsed < $this->invalidation_window) { |
||
| 124 | // Se la richiesta (cmq del piรน vecchio) non รจ nella finestra di invalidazione salto l'evento |
||
| 125 | continue; |
||
| 126 | } |
||
| 127 | // altrimenti aggiungo l'evento a quelli da processare |
||
| 128 | $eventsToUpdate[] = $event; |
||
| 129 | // e recupero tutti gli ID che hanno quel tag/key |
||
| 130 | $eventsAll[] = array_filter($events, function ($event) use ($typeFilter, $identifierFilter) { |
||
| 131 | return $event->type === $typeFilter && $event->identifier === $identifierFilter; |
||
| 132 | }); |
||
| 133 | } |
||
| 134 | if (count($eventsToUpdate) === 0) { |
||
| 135 | return; |
||
| 136 | } |
||
| 137 | |||
| 138 | $this->processBatch(array_merge(...$eventsAll), $eventsToUpdate); |
||
| 139 | } |
||
| 140 | |||
| 141 | protected function processBatch(array $allEvents, array $eventsToInvalidate): void |
||
| 142 | { |
||
| 143 | // Separo le chiavi dai tags |
||
| 144 | $keys = []; |
||
| 145 | $tags = []; |
||
| 146 | // Prima di processare tutti gli eventi, assegno un batch_ID univoco a tutti gli eventi |
||
| 147 | $batch_ID = (string) Str::uuid(); |
||
| 148 | |||
| 149 | foreach ($eventsToInvalidate as $item) { |
||
| 150 | switch ($item->type) { |
||
| 151 | case 'key': |
||
| 152 | $keys[] = $item->identifier . 'ยง' . $item->connection_name; |
||
| 153 | break; |
||
| 154 | case 'tag': |
||
| 155 | $tags[] = $item->identifier . 'ยง' . $item->connection_name; |
||
| 156 | break; |
||
| 157 | } |
||
| 158 | } |
||
| 159 | |||
| 160 | $this->logIf('Invalido ' . count($keys) . ' chiavi e ' . count($tags) . ' tags' . ' per un totale di ' . count($allEvents) . ' events_ID'); |
||
| 161 | |||
| 162 | if (!empty($keys)) { |
||
| 163 | $this->invalidateKeys($keys); |
||
| 164 | } |
||
| 165 | |||
| 166 | if (!empty($tags)) { |
||
| 167 | // Escludo i tag fullpage |
||
| 168 | $tags = array_filter($tags, function ($item) { |
||
| 169 | return !str_contains($item, 'fullpage'); |
||
| 170 | }); |
||
| 171 | $this->invalidateTags($tags); |
||
| 172 | } |
||
| 173 | |||
| 174 | // Disabilita i controlli delle chiavi esterne e dei vincoli univoci |
||
| 175 | DB::statement('SET FOREIGN_KEY_CHECKS=0;'); |
||
| 176 | DB::statement('SET UNIQUE_CHECKS=0;'); |
||
| 177 | |||
| 178 | // Mark event as processed |
||
| 179 | // QUI NON VA USATA PARTITION perchรจ la cross partition รจ piรน lenta! Perรฒ รจ necessario utilizzare la $partition_key per sfruttare l'indice della primary key (id+partition_key) |
||
| 180 | DB::table('cache_invalidation_events') |
||
| 181 | ->whereIn('id', array_map(fn ($event) => $event->id, $allEvents)) |
||
| 182 | ->whereIn('partition_key', array_map(fn ($event) => $event->partition_key, $allEvents)) |
||
| 183 | ->update(['processed' => 1, 'batch_ID' => $batch_ID, 'updated_at' => now()]) |
||
| 184 | ; |
||
| 185 | // Riattiva i controlli |
||
| 186 | DB::statement('SET FOREIGN_KEY_CHECKS=1;'); |
||
| 187 | DB::statement('SET UNIQUE_CHECKS=1;'); |
||
| 188 | |||
| 189 | // A questo punto avviso il gescat che le chiavi/tags sono stati puliti, per cui puรฒ procedere alla pulizia della CDN |
||
| 190 | event(new BatchCompletedEvent($batch_ID, $this->shardId)); |
||
| 191 | } |
||
| 192 | |||
| 193 | /** |
||
| 194 | * Invalidate cache keys. |
||
| 195 | * |
||
| 196 | * @param array $keys Array of cache keys to invalidate |
||
| 197 | */ |
||
| 198 | protected function invalidateKeys(array $keys): void |
||
| 199 | { |
||
| 200 | $callback = config('super_cache_invalidate.key_invalidation_callback'); |
||
| 201 | |||
| 202 | // Anche in questo caso va fatto un loop perchรจ le chiavi potrebbero stare in database diversi |
||
| 203 | foreach ($keys as $keyAndConnectionName) { |
||
| 204 | [$key, $connection_name] = explode('ยง', $keyAndConnectionName); |
||
| 205 | |||
| 206 | // Metodo del progetto |
||
| 207 | if (is_callable($callback)) { |
||
| 208 | $callback($key, $connection_name); |
||
| 209 | continue; |
||
| 210 | } |
||
| 211 | // oppure di default uso Laravel |
||
| 212 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
| 213 | |||
| 214 | if ($storeName === null) { |
||
| 215 | continue; |
||
| 216 | } |
||
| 217 | Cache::store($storeName)->forget($key); |
||
| 218 | } |
||
| 219 | } |
||
| 220 | |||
| 221 | /** |
||
| 222 | * Invalidate cache tags. |
||
| 223 | * |
||
| 224 | * @param array $tags Array of cache tags to invalidate |
||
| 225 | */ |
||
| 226 | protected function invalidateTags(array $tags): void |
||
| 227 | { |
||
| 228 | $callback = config('super_cache_invalidate.tag_invalidation_callback'); |
||
| 229 | |||
| 230 | $groupByConnection = []; |
||
| 231 | |||
| 232 | // Anche in questo caso va fatto un loop perchรจ i tags potrebbero stare in database diversi, |
||
| 233 | // ma per ottimizzare possiamo raggruppare le operazioni per connessione |
||
| 234 | foreach ($tags as $tagAndConnectionName) { |
||
| 235 | // chiave e connessione |
||
| 236 | [$key, $connection] = explode('ยง', $tagAndConnectionName); |
||
| 237 | |||
| 238 | // Aggiungo la chiave alla connessione appropriata |
||
| 239 | $groupByConnection[$connection][] = $key; |
||
| 240 | } |
||
| 241 | if (is_callable($callback)) { |
||
| 242 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
| 243 | $callback($arrTags, $connection_name); |
||
| 244 | } |
||
| 245 | |||
| 246 | return; |
||
| 247 | } |
||
| 248 | foreach ($groupByConnection as $connection_name => $arrTags) { |
||
| 249 | $storeName = $this->getStoreFromConnectionName($connection_name); |
||
| 250 | if ($storeName === null) { |
||
| 251 | continue; |
||
| 252 | } |
||
| 253 | Cache::store($storeName)->tags($arrTags)->flush(); |
||
| 254 | } |
||
| 255 | } |
||
| 256 | |||
| 257 | /** |
||
| 258 | * Execute the console command. |
||
| 259 | */ |
||
| 260 | public function handle(): void |
||
| 261 | { |
||
| 262 | // Recupero dei parametri impostati nel command |
||
| 263 | $this->shardId = (int) $this->option('shard'); |
||
| 264 | $this->priority = (int) $this->option('priority'); |
||
| 265 | $limit = $this->option('limit') ?? config('super_cache_invalidate.processing_limit'); |
||
| 266 | $this->limit = (int) $limit; |
||
| 267 | $tagBatchSize = $this->option('tag-batch-size') ?? config('super_cache_invalidate.tag_batch_size'); |
||
| 268 | $this->tagBatchSize = (int) $tagBatchSize; |
||
| 269 | $this->connection_name = $this->option('connection_name') ?? config('super_cache_invalidate.default_connection_name'); |
||
| 270 | $this->log_attivo = $this->option('log_attivo') && (int)$this->option('log_attivo') === 1; |
||
| 271 | $this->invalidation_window = (int) config('super_cache_invalidate.invalidation_window'); |
||
| 272 | $lockTimeout = (int) config('super_cache_invalidate.lock_timeout'); |
||
|
0 ignored issues
–
show
|
|||
| 273 | |||
| 274 | // Acquisisco il lock in modo da essere sicura che le esecuzioni non si accavallino |
||
| 275 | // $lockValue = $this->helper->acquireShardLock($this->shardId, $this->priority, $lockTimeout, $this->connection_name); |
||
| 276 | $this->logIf('Starting Elaborazione ...' . $this->invalidation_window); |
||
| 277 | // if (!$lockValue) { |
||
| 278 | // return; |
||
| 279 | // } |
||
| 280 | $startTime = microtime(true); |
||
| 281 | try { |
||
| 282 | $this->processEvents(); |
||
| 283 | } catch (\Throwable $e) { |
||
| 284 | $this->logIf(sprintf( |
||
| 285 | "Eccezione: %s in %s on line %d\nStack trace:\n%s", |
||
| 286 | $e->getMessage(), |
||
| 287 | $e->getFile(), |
||
| 288 | $e->getLine(), |
||
| 289 | $e->getTraceAsString() |
||
| 290 | ), 'error'); |
||
| 291 | } |
||
| 292 | $executionTime = (microtime(true) - $startTime) * 1000; |
||
| 293 | $this->logIf('Fine Elaborazione - Tempo di esecuzione: ' . $executionTime . ' millisec.'); |
||
| 294 | } |
||
| 295 | } |
||
| 296 |