1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Padosoft\SuperCacheInvalidate\Console; |
4
|
|
|
|
5
|
|
|
use Illuminate\Console\Command; |
6
|
|
|
use Illuminate\Support\Facades\Cache; |
7
|
|
|
use Illuminate\Support\Facades\DB; |
8
|
|
|
use Carbon\Carbon; |
9
|
|
|
use Padosoft\SuperCacheInvalidate\Helpers\SuperCacheInvalidationHelper; |
10
|
|
|
|
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
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* The console command description. |
26
|
|
|
* |
27
|
|
|
* @var string |
28
|
|
|
*/ |
29
|
|
|
protected $description = 'Process cache invalidation events for a given shard and priority'; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Cache invalidation helper instance. |
33
|
|
|
*/ |
34
|
|
|
protected SuperCacheInvalidationHelper $helper; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Create a new command instance. |
38
|
|
|
*/ |
39
|
|
|
public function __construct(SuperCacheInvalidationHelper $helper) |
40
|
|
|
{ |
41
|
|
|
parent::__construct(); |
42
|
|
|
$this->helper = $helper; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Process cache invalidation events. |
47
|
|
|
* |
48
|
|
|
* @param int $shardId The shard number to process |
49
|
|
|
* @param int $priority The priority level |
50
|
|
|
* @param int $limit Maximum number of events to fetch per batch |
51
|
|
|
* @param int $tagBatchSize Number of identifiers to process per batch |
52
|
|
|
* |
53
|
|
|
* @throws \Exception |
54
|
|
|
*/ |
55
|
|
|
protected function processEvents(int $shardId, int $priority, int $limit, int $tagBatchSize): void |
56
|
|
|
{ |
57
|
|
|
$processingStartTime = now(); |
58
|
|
|
$invalidationWindow = config('super_cache_invalidate.invalidation_window'); |
59
|
|
|
|
60
|
|
|
// Fetch a batch of unprocessed events |
61
|
|
|
$events = DB::table('cache_invalidation_events') |
62
|
|
|
->where('processed', 0) |
63
|
|
|
->where('shard', $shardId) |
64
|
|
|
->where('priority', $priority) |
65
|
|
|
->where('event_time', '<', $processingStartTime) |
66
|
|
|
->orderBy('event_time') |
67
|
|
|
->limit($limit) |
68
|
|
|
->get() |
69
|
|
|
; |
70
|
|
|
|
71
|
|
|
if ($events->isEmpty()) { |
72
|
|
|
// No more events to process |
73
|
|
|
return; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
// Group events by type and identifier |
77
|
|
|
$eventsByIdentifier = $events->groupBy(function ($event) { |
78
|
|
|
return $event->type . ':' . $event->identifier; |
79
|
|
|
}); |
80
|
|
|
|
81
|
|
|
$batchIdentifiers = []; |
82
|
|
|
$eventsToUpdate = []; |
83
|
|
|
$counter = 0; |
84
|
|
|
|
85
|
|
|
// Fetch associated identifiers for the events |
86
|
|
|
$eventIds = $events->pluck('id')->all(); |
87
|
|
|
|
88
|
|
|
//retrive associated identifiers related to fetched event id |
89
|
|
|
$associations = DB::table('cache_invalidation_event_associations') |
90
|
|
|
->whereIn('event_id', $eventIds) |
91
|
|
|
->get() |
92
|
|
|
->groupBy('event_id') |
93
|
|
|
; |
94
|
|
|
|
95
|
|
|
// Prepare list of all identifiers to fetch last invalidation times |
96
|
|
|
$allIdentifiers = []; |
97
|
|
|
|
98
|
|
|
foreach ($eventsByIdentifier as $key => $eventsGroup) { |
99
|
|
|
$allIdentifiers[] = $key; |
100
|
|
|
foreach ($eventsGroup as $event) { |
101
|
|
|
$eventAssociations = $associations->get($event->id, collect()); |
102
|
|
|
foreach ($eventAssociations as $assoc) { |
103
|
|
|
$assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier; |
104
|
|
|
$allIdentifiers[] = $assocKey; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|
109
|
|
|
// Fetch last invalidation times in bulk |
110
|
|
|
$lastInvalidationTimes = $this->getLastInvalidationTimes(array_unique($allIdentifiers)); |
111
|
|
|
|
112
|
|
|
foreach ($eventsByIdentifier as $key => $eventsGroup) { |
113
|
|
|
// Extract type and identifier |
114
|
|
|
[$type, $identifier] = explode(':', $key, 2); |
115
|
|
|
|
116
|
|
|
// Get associated identifiers for the events |
117
|
|
|
$associatedIdentifiers = []; |
118
|
|
|
foreach ($eventsGroup as $event) { |
119
|
|
|
$eventAssociations = $associations->get($event->id, collect()); |
120
|
|
|
foreach ($eventAssociations as $assoc) { |
121
|
|
|
$assocKey = $assoc->associated_type . ':' . $assoc->associated_identifier; |
122
|
|
|
$associatedIdentifiers[$assocKey] = [ |
123
|
|
|
'type' => $assoc->associated_type, |
124
|
|
|
'identifier' => $assoc->associated_identifier, |
125
|
|
|
]; |
126
|
|
|
} |
127
|
|
|
} |
128
|
|
|
|
129
|
|
|
// Build a list of all identifiers to check |
130
|
|
|
$identifiersToCheck = [$key]; |
131
|
|
|
$identifiersToCheck = array_merge($identifiersToCheck, array_keys($associatedIdentifiers)); |
132
|
|
|
|
133
|
|
|
$lastInvalidationTimesSubset = array_intersect_key($lastInvalidationTimes, array_flip($identifiersToCheck)); |
134
|
|
|
|
135
|
|
|
$shouldInvalidate = $this->shouldInvalidateMultiple($identifiersToCheck, $lastInvalidationTimesSubset, $invalidationWindow); |
136
|
|
|
|
137
|
|
|
if ($shouldInvalidate) { |
138
|
|
|
// Proceed to invalidate |
139
|
|
|
$latestEvent = $eventsGroup->last(); |
140
|
|
|
|
141
|
|
|
// Accumulate identifiers and events |
142
|
|
|
$batchIdentifiers[] = [ |
143
|
|
|
'type' => $type, |
144
|
|
|
'identifier' => $identifier, |
145
|
|
|
'event' => $latestEvent, |
146
|
|
|
'associated' => array_values($associatedIdentifiers), |
147
|
|
|
]; |
148
|
|
|
|
149
|
|
|
// Update last invalidation times for all identifiers |
150
|
|
|
$this->updateLastInvalidationTimes($identifiersToCheck); |
151
|
|
|
|
152
|
|
|
// Mark all events in the group as processed |
153
|
|
|
foreach ($eventsGroup as $event) { |
154
|
|
|
$eventsToUpdate[] = $event->id; |
155
|
|
|
} |
156
|
|
|
} else { |
157
|
|
|
// Within the invalidation window, skip invalidation |
158
|
|
|
// Mark all events except the last one as processed |
159
|
|
|
$eventsToProcess = $eventsGroup->slice(0, -1); |
160
|
|
|
foreach ($eventsToProcess as $event) { |
161
|
|
|
$eventsToUpdate[] = $event->id; |
162
|
|
|
} |
163
|
|
|
// The last event remains unprocessed |
164
|
|
|
} |
165
|
|
|
|
166
|
|
|
$counter++; |
167
|
|
|
|
168
|
|
|
// When we reach the batch size, process the accumulated identifiers |
169
|
|
|
if ($counter % $tagBatchSize === 0) { |
170
|
|
|
$this->processBatch($batchIdentifiers, $eventsToUpdate); |
171
|
|
|
|
172
|
|
|
// Reset the accumulators |
173
|
|
|
$batchIdentifiers = []; |
174
|
|
|
$eventsToUpdate = []; |
175
|
|
|
} |
176
|
|
|
} |
177
|
|
|
|
178
|
|
|
// Process any remaining identifiers in the batch |
179
|
|
|
if (!empty($batchIdentifiers)) { |
180
|
|
|
$this->processBatch($batchIdentifiers, $eventsToUpdate); |
181
|
|
|
} |
182
|
|
|
} |
183
|
|
|
|
184
|
|
|
/** |
185
|
|
|
* Fetch last invalidation times for identifiers in bulk. |
186
|
|
|
* |
187
|
|
|
* @param array $identifiers Array of 'type:identifier' strings |
188
|
|
|
* @return array Associative array of last invalidation times |
189
|
|
|
*/ |
190
|
|
|
protected function getLastInvalidationTimes(array $identifiers): array |
191
|
|
|
{ |
192
|
|
|
// Extract types and identifiers into tuples |
193
|
|
|
$tuples = array_map(static function ($key) { |
194
|
|
|
return explode(':', $key, 2); |
195
|
|
|
}, $identifiers); |
196
|
|
|
|
197
|
|
|
if (empty($tuples)) { |
198
|
|
|
return []; |
199
|
|
|
} |
200
|
|
|
|
201
|
|
|
// Prepare placeholders and parameters |
202
|
|
|
$placeholders = implode(',', array_fill(0, count($tuples), '(?, ?)')); |
203
|
|
|
$params = []; |
204
|
|
|
foreach ($tuples as [$type, $identifier]) { |
205
|
|
|
$params[] = $type; |
206
|
|
|
$params[] = $identifier; |
207
|
|
|
} |
208
|
|
|
|
209
|
|
|
// Build and execute the query |
210
|
|
|
$sql = "SELECT identifier_type, |
211
|
|
|
identifier, |
212
|
|
|
last_invalidated |
213
|
|
|
FROM cache_invalidation_timestamps |
214
|
|
|
WHERE (identifier_type, identifier) IN ($placeholders) |
215
|
|
|
"; |
216
|
|
|
$records = DB::select($sql, $params); |
217
|
|
|
|
218
|
|
|
// Build associative array |
219
|
|
|
$lastInvalidationTimes = []; |
220
|
|
|
foreach ($records as $record) { |
221
|
|
|
$key = $record->identifier_type . ':' . $record->identifier; |
222
|
|
|
$lastInvalidationTimes[$key] = Carbon::parse($record->last_invalidated); |
223
|
|
|
} |
224
|
|
|
|
225
|
|
|
return $lastInvalidationTimes; |
226
|
|
|
} |
227
|
|
|
|
228
|
|
|
/** |
229
|
|
|
* Determine whether to invalidate based on last invalidation times for multiple identifiers. |
230
|
|
|
* |
231
|
|
|
* @param array $identifiers Array of 'type:identifier' strings |
232
|
|
|
* @param array $lastInvalidationTimes Associative array of last invalidation times |
233
|
|
|
* @param int $invalidationWindow Invalidation window in seconds |
234
|
|
|
* @return bool True if should invalidate, false otherwise |
235
|
|
|
*/ |
236
|
|
|
protected function shouldInvalidateMultiple(array $identifiers, array $lastInvalidationTimes, int $invalidationWindow): bool |
237
|
|
|
{ |
238
|
|
|
$now = now(); |
239
|
|
|
foreach ($identifiers as $key) { |
240
|
|
|
$lastInvalidated = $lastInvalidationTimes[$key] ?? null; |
241
|
|
|
if (!$lastInvalidated) { |
242
|
|
|
continue; |
243
|
|
|
} |
244
|
|
|
$elapsed = $now->diffInSeconds($lastInvalidated); |
245
|
|
|
if ($elapsed < $invalidationWindow) { |
246
|
|
|
// At least one identifier is within the invalidation window |
247
|
|
|
return false; |
248
|
|
|
} |
249
|
|
|
} |
250
|
|
|
|
251
|
|
|
// All identifiers are outside the invalidation window or have no record |
252
|
|
|
return true; |
253
|
|
|
} |
254
|
|
|
|
255
|
|
|
/** |
256
|
|
|
* Update the last invalidation times for multiple identifiers. |
257
|
|
|
* |
258
|
|
|
* @param array $identifiers Array of 'type:identifier' strings |
259
|
|
|
*/ |
260
|
|
|
protected function updateLastInvalidationTimes(array $identifiers): void |
261
|
|
|
{ |
262
|
|
|
$now = now(); |
263
|
|
|
|
264
|
|
|
foreach ($identifiers as $key) { |
265
|
|
|
[$type, $identifier] = explode(':', $key, 2); |
266
|
|
|
DB::table('cache_invalidation_timestamps') |
267
|
|
|
->updateOrInsert( |
268
|
|
|
['identifier_type' => $type, 'identifier' => $identifier], |
269
|
|
|
['last_invalidated' => $now] |
270
|
|
|
) |
271
|
|
|
; |
272
|
|
|
} |
273
|
|
|
} |
274
|
|
|
|
275
|
|
|
/** |
276
|
|
|
* Process a batch of identifiers and update events. |
277
|
|
|
* |
278
|
|
|
* @param array $batchIdentifiers Array of identifiers to invalidate |
279
|
|
|
* @param array $eventsToUpdate Array of event IDs to mark as processed |
280
|
|
|
* |
281
|
|
|
* @throws \Exception |
282
|
|
|
*/ |
283
|
|
|
protected function processBatch(array $batchIdentifiers, array $eventsToUpdate): void |
284
|
|
|
{ |
285
|
|
|
// Begin transaction for the batch |
286
|
|
|
DB::beginTransaction(); |
287
|
|
|
|
288
|
|
|
try { |
289
|
|
|
// Separate keys and tags |
290
|
|
|
$keys = []; |
291
|
|
|
$tags = []; |
292
|
|
|
foreach ($batchIdentifiers as $item) { |
293
|
|
|
if ($item['type'] === 'key') { |
294
|
|
|
$keys[] = $item['identifier']; |
295
|
|
|
} else { |
296
|
|
|
$tags[] = $item['identifier']; |
297
|
|
|
} |
298
|
|
|
|
299
|
|
|
// Include associated identifiers |
300
|
|
|
if (!empty($item['associated'])) { |
301
|
|
|
foreach ($item['associated'] as $assoc) { |
302
|
|
|
if ($assoc['type'] === 'key') { |
303
|
|
|
$keys[] = $assoc['identifier']; |
304
|
|
|
} else { |
305
|
|
|
$tags[] = $assoc['identifier']; |
306
|
|
|
} |
307
|
|
|
} |
308
|
|
|
} |
309
|
|
|
} |
310
|
|
|
|
311
|
|
|
// Remove duplicates |
312
|
|
|
$keys = array_unique($keys); |
313
|
|
|
$tags = array_unique($tags); |
314
|
|
|
|
315
|
|
|
// Invalidate cache for keys |
316
|
|
|
if (!empty($keys)) { |
317
|
|
|
$this->invalidateKeys($keys); |
318
|
|
|
} |
319
|
|
|
|
320
|
|
|
// Invalidate cache for tags |
321
|
|
|
if (!empty($tags)) { |
322
|
|
|
$this->invalidateTags($tags); |
323
|
|
|
} |
324
|
|
|
|
325
|
|
|
// Mark events as processed |
326
|
|
|
DB::table('cache_invalidation_events') |
327
|
|
|
->whereIn('id', $eventsToUpdate) |
328
|
|
|
->update(['processed' => 1]) |
329
|
|
|
; |
330
|
|
|
|
331
|
|
|
// Commit transaction |
332
|
|
|
DB::commit(); |
333
|
|
|
} catch (\Exception $e) { |
334
|
|
|
// Rollback transaction on error |
335
|
|
|
DB::rollBack(); |
336
|
|
|
throw $e; |
337
|
|
|
} |
338
|
|
|
} |
339
|
|
|
|
340
|
|
|
/** |
341
|
|
|
* Invalidate cache keys. |
342
|
|
|
* |
343
|
|
|
* @param array $keys Array of cache keys to invalidate |
344
|
|
|
*/ |
345
|
|
|
protected function invalidateKeys(array $keys): void |
346
|
|
|
{ |
347
|
|
|
$callback = config('super_cache_invalidate.key_invalidation_callback'); |
348
|
|
|
|
349
|
|
|
if (is_callable($callback)) { |
350
|
|
|
call_user_func($callback, $keys); |
351
|
|
|
|
352
|
|
|
return; |
353
|
|
|
} |
354
|
|
|
|
355
|
|
|
//default invalidation method |
356
|
|
|
foreach ($keys as $key) { |
357
|
|
|
Cache::forget($key); |
358
|
|
|
} |
359
|
|
|
} |
360
|
|
|
|
361
|
|
|
/** |
362
|
|
|
* Invalidate cache tags. |
363
|
|
|
* |
364
|
|
|
* @param array $tags Array of cache tags to invalidate |
365
|
|
|
*/ |
366
|
|
|
protected function invalidateTags(array $tags): void |
367
|
|
|
{ |
368
|
|
|
$callback = config('super_cache_invalidate.tag_invalidation_callback'); |
369
|
|
|
|
370
|
|
|
if (is_callable($callback)) { |
371
|
|
|
call_user_func($callback, $tags); |
372
|
|
|
|
373
|
|
|
return; |
374
|
|
|
} |
375
|
|
|
|
376
|
|
|
//default invalidation method |
377
|
|
|
Cache::tags($tags)->flush(); |
378
|
|
|
} |
379
|
|
|
|
380
|
|
|
/** |
381
|
|
|
* Execute the console command. |
382
|
|
|
*/ |
383
|
|
|
public function handle(): void |
384
|
|
|
{ |
385
|
|
|
$shardId = (int) $this->option('shard'); |
386
|
|
|
$priority = (int) $this->option('priority'); |
387
|
|
|
$limit = $this->option('limit') ?? config('super_cache_invalidate.processing_limit'); |
388
|
|
|
$tagBatchSize = $this->option('tag-batch-size') ?? config('super_cache_invalidate.tag_batch_size'); |
389
|
|
|
$lockTimeout = config('super_cache_invalidate.lock_timeout'); |
390
|
|
|
|
391
|
|
|
if ($shardId === 0 && $priority === 0) { |
392
|
|
|
$this->error('Shard and priority are required and must be non-zero integers.'); |
393
|
|
|
|
394
|
|
|
return; |
395
|
|
|
} |
396
|
|
|
|
397
|
|
|
$lockValue = $this->helper->acquireShardLock($shardId, $lockTimeout); |
398
|
|
|
|
399
|
|
|
if (!$lockValue) { |
400
|
|
|
$this->info("Another process is handling shard $shardId."); |
401
|
|
|
|
402
|
|
|
return; |
403
|
|
|
} |
404
|
|
|
|
405
|
|
|
try { |
406
|
|
|
$this->processEvents($shardId, $priority, $limit, $tagBatchSize); |
|
|
|
|
407
|
|
|
} catch (\Exception $e) { |
408
|
|
|
$this->error('An error occourred in ' . __METHOD__ . ': ' . $e->getTraceAsString()); |
409
|
|
|
} finally { |
410
|
|
|
$this->helper->releaseShardLock($shardId, $lockValue); |
411
|
|
|
} |
412
|
|
|
} |
413
|
|
|
} |
414
|
|
|
|