Skip to content

Commit

Permalink
cache locking to avoid duplicate keys (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Schlick committed Oct 12, 2020
1 parent f53a74b commit 082db6d
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/ProcessStamp.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,23 @@ public static function firstOrCreateByProcess(array $process, ?string $hash = nu
$parent = static::firstOrCreateByProcess(static::getProcessName($process['type'], $process['parent_name']));
}

return static::lockForUpdate()->firstOrCreate(['hash' => $hash], [
'name' => trim($process['name']),
'type' => $process['type'],
'parent_id' => optional($parent)->getKey(),
]);
$stamp = static::where('hash', $hash)->first();

/*
* If stamp does not exist in the database yet, go ahead and obtain a lock to create it.
* This specifically doesn't lock as the first step to avoid all calls obtaining a lock from the cache if the item already exists in the DB.
*/
if (! $stamp) {
Cache::lock('process-stamps-hash-create-' . $hash, 10)->get(function() use (&$stamp, $hash, $process, $parent) {
$stamp = static::firstOrCreate(['hash' => $hash], [
'name' => trim($process['name']),
'type' => $process['type'],
'parent_id' => optional($parent)->getKey(),
]);
});
}

return $stamp;
}

/**
Expand Down

0 comments on commit 082db6d

Please sign in to comment.