Skip to content

Commit

Permalink
Updated stamp creation to leverage the retry helper method (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
Quentin Schmick authored Jun 15, 2021
1 parent 12ee861 commit b852f93
Showing 1 changed file with 26 additions and 16 deletions.
42 changes: 26 additions & 16 deletions src/ProcessStamp.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace AlwaysOpen\ProcessStamps;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ProcessStamp extends Model
{
Expand Down Expand Up @@ -42,6 +42,8 @@ public function getTable() : string
* @param null|string $hash
*
* @return ProcessStamp
*
* @throws ModelNotFoundException
*/
public static function firstOrCreateByProcess(array $process, ?string $hash = null) : self
{
Expand All @@ -59,23 +61,31 @@ 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();
return retry(4, function() use ($hash, $process, $parent) {
$stamp = static::firstWhere('hash', $hash);

/*
* 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(),
]);
});
}

/*
* 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(),
]);
});
}
if (null === $stamp) {
throw new ModelNotFoundException();
}

return $stamp;
return $stamp;
}, 25);
}

/**
Expand Down

0 comments on commit b852f93

Please sign in to comment.