Skip to content

Commit

Permalink
fixed races during process row creation using Laravel's upsert. (#23)
Browse files Browse the repository at this point in the history
Co-authored-by: Paul Rogers <[email protected]>
  • Loading branch information
solflare and paulrrogers authored Apr 5, 2021
1 parent f4a5ccc commit 167a87b
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']));
}

$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], [
// Workaround races with `firstOrCreate` by leveraging a no-change upsert.
// NOTE: Not using `insertOrIgnore` because of possible side-effects.
static::upsert(
[
[
'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 167a87b

Please sign in to comment.