Skip to content

Commit 894a349

Browse files
committed
ottimizzate update e insert
1 parent e5513d4 commit 894a349

File tree

2 files changed

+63
-31
lines changed

2 files changed

+63
-31
lines changed

src/Console/ProcessCacheInvalidationEventsCommand.php

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ protected function processEvents(int $shardId, int $priority, int $limit, int $t
109109
$counter = 0;
110110

111111
// 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
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
113113
$associations = collect();
114114
/*
115115
$eventIds = $events->pluck('id')->all();
@@ -255,6 +255,7 @@ protected function getRecordsFromDb(array $tuples): array
255255
$params[] = $identifier;
256256
}
257257

258+
// ATTENZIONE, qui non si può usare la partizione diretta perchè i record possono essere in partizioni diverse
258259
$sql = "SELECT identifier_type,
259260
identifier,
260261
last_invalidated
@@ -303,7 +304,11 @@ protected function updateLastInvalidationTimes(array $identifiers): void
303304

304305
foreach ($identifiers as $key) {
305306
[$type, $identifier] = explode(':', $key, 2);
306-
DB::table('cache_invalidation_timestamps')
307+
// Qui si può usare la partizione
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})"))
307312
->updateOrInsert(
308313
['identifier_type' => $type, 'identifier' => $identifier],
309314
['last_invalidated' => $now]
@@ -371,30 +376,39 @@ protected function processBatch(array $batchIdentifiers, array $eventsToUpdate,
371376
$this->invalidateTags($tags);
372377
}
373378

374-
while ($attempts < $maxAttempts && !$updatedOk) {
375-
// Begin transaction for the batch
376-
DB::beginTransaction();
377-
378-
try {
379-
// Mark events as processed
380-
$partitionCache_invalidation_events = $this->helper->getCacheInvalidationEventsPartitionName($shard, $priority);
381-
DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))
382-
->whereIn('id', $eventsToUpdate)
383-
->update(['processed' => 1])
384-
;
385-
386-
// Commit transaction
387-
DB::commit();
388-
$updatedOk = true;
389-
} catch (\Throwable $e) {
390-
// Rollback transaction on error
391-
DB::rollBack();
392-
$attempts++;
393-
$this->warn(now()->toDateTimeString() . ": Tentativo $attempts di $maxAttempts: " . $e->getMessage());
394-
// Logica per gestire i tentativi falliti
395-
if ($attempts >= $maxAttempts) {
396-
// Salta il record dopo il numero massimo di tentativi
397-
throw $e;
379+
$shards = config('super_cache_invalidate.total_shards', 10);
380+
$partitionCache_invalidation_events = $this->helper->getCacheInvalidationEventsPartitionName($shard, $priority);
381+
$partitionKey = ($priority * $shards) + $shard + 1;
382+
foreach ($eventsToUpdate as $eventToUpdateId) {
383+
while ($attempts < $maxAttempts && !$updatedOk) {
384+
// Begin transaction for the batch
385+
DB::beginTransaction();
386+
try {
387+
// Disabilita i controlli delle chiavi esterne e dei vincoli univoci
388+
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
389+
DB::statement('SET UNIQUE_CHECKS=0;');
390+
// Mark event as processed
391+
DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))
392+
->where('id', $eventToUpdateId)
393+
->where('partition_key', $partitionKey)
394+
->update(['processed' => 1])
395+
;
396+
// Riattiva i controlli
397+
DB::statement('SET UNIQUE_CHECKS=1;');
398+
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
399+
// Commit transaction
400+
DB::commit();
401+
$updatedOk = true;
402+
} catch (\Throwable $e) {
403+
// Rollback transaction on error
404+
DB::rollBack();
405+
$attempts++;
406+
$this->warn(now()->toDateTimeString() . ": Tentativo $attempts di $maxAttempts: " . $e->getMessage());
407+
// Logica per gestire i tentativi falliti
408+
if ($attempts >= $maxAttempts) {
409+
// Salta il record dopo il numero massimo di tentativi
410+
throw $e;
411+
}
398412
}
399413
}
400414
}

src/Helpers/SuperCacheInvalidationHelper.php

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,11 @@ public function insertInvalidationEvent(
5353
// Cerca di bloccare il record per l'inserimento
5454
$partitionCache_invalidation_events = $this->getCacheInvalidationEventsPartitionName($shard, $priority);
5555

56-
$eventId = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))->insertGetId($data);
57-
56+
//$eventId = DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))->insertGetId($data);
57+
DB::table(DB::raw("`cache_invalidation_events` PARTITION ({$partitionCache_invalidation_events})"))->insert($data);
5858
// Insert associated identifiers
59-
// TODO JB 31/12/2024: per adesso commentato, da riattivare quando tutto funziona alla perfezione usando la partizione
59+
// TODO JB 31/12/2024: per adesso commentato, da riattivare quando tutto funziona alla perfezione usando la partizione,
60+
// anche perchè la chiave primaria è data da id e partiton_key, per cui va capito cosa restituisce insertGetId e se è bloccante
6061
/*
6162
if (!empty($associatedIdentifiers)) {
6263
$associations = [];
@@ -136,8 +137,6 @@ public function getCacheInvalidationEventsPartitionName(int $shardId, int $prior
136137
$shards = config('super_cache_invalidate.total_shards', 10);
137138
$priorities = [0, 1];
138139

139-
$partitionStatements = [];
140-
141140
$partitionValueId = ($priorityId * $shards) + $shardId + 1;
142141

143142
// Partitions for unprocessed events
@@ -153,4 +152,23 @@ public function getCacheInvalidationEventsPartitionName(int $shardId, int $prior
153152

154153
return '';
155154
}
155+
156+
public function getCacheInvalidationTimestampsPartitionName(): string
157+
{
158+
$now = now();
159+
$partitionValueId = ($now->year * 100 + $now->weekOfYear) + 1;
160+
$startYear = 2024;
161+
$endYear = 2030;
162+
163+
for ($year = $startYear; $year <= $endYear; $year++) {
164+
for ($week = 1; $week <= 53; $week++) {
165+
$partitionName = "p_{$year}w{$week}";
166+
$partitionValue = ($year * 100 + $week) + 1;
167+
if ($partitionValueId < $partitionValue) {
168+
return $partitionName;
169+
}
170+
}
171+
}
172+
return '';
173+
}
156174
}

0 commit comments

Comments
 (0)