Skip to content

Commit

Permalink
Revert back to cache lock w/ firstOrCreate (#24)
Browse files Browse the repository at this point in the history
While in a transaction upsert will lock the row until the transaction is
finished. Using a cache lock avoids this but also introduces a possible
duplicate exception in rare cases

Co-authored-by: Lucas Graciano <[email protected]>
  • Loading branch information
solflare and Lucas Graciano authored Apr 15, 2021
1 parent 167a87b commit c745f54
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions src/ProcessStamp.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,21 @@ public static function firstOrCreateByProcess(array $process, ?string $hash = nu
$parent = static::firstOrCreateByProcess(static::getProcessName($process['type'], $process['parent_name']));
}

// Workaround races with `firstOrCreate` by leveraging a no-change upsert.
// NOTE: Not using `insertOrIgnore` because of possible side-effects.
static::upsert(
[
[
'hash' => $hash,
$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(),
],
],
['hash'], // Should be unique to hash.
[] // Update nothing.
);
$stamp = static::where('hash', $hash)->first();
]);
});
}

return $stamp;
}
Expand Down

0 comments on commit c745f54

Please sign in to comment.