33namespace AlwaysOpen \ProcessStamps ;
44
55use Illuminate \Database \Eloquent \Model ;
6+ use Illuminate \Database \Eloquent \ModelNotFoundException ;
67use Illuminate \Database \Eloquent \Relations \BelongsTo ;
78use Illuminate \Database \Eloquent \Relations \HasMany ;
89use Illuminate \Support \Facades \Cache ;
9- use Illuminate \Support \Facades \DB ;
1010
1111class ProcessStamp extends Model
1212{
@@ -42,6 +42,8 @@ public function getTable() : string
4242 * @param null|string $hash
4343 *
4444 * @return ProcessStamp
45+ *
46+ * @throws ModelNotFoundException
4547 */
4648 public static function firstOrCreateByProcess (array $ process , ?string $ hash = null ) : self
4749 {
@@ -59,23 +61,31 @@ public static function firstOrCreateByProcess(array $process, ?string $hash = nu
5961 $ parent = static ::firstOrCreateByProcess (static ::getProcessName ($ process ['type ' ], $ process ['parent_name ' ]));
6062 }
6163
62- $ stamp = static ::where ('hash ' , $ hash )->first ();
64+ return retry (4 , function () use ($ hash , $ process , $ parent ) {
65+ $ stamp = static ::firstWhere ('hash ' , $ hash );
66+
67+ /*
68+ * If stamp does not exist in the database yet, go ahead and obtain a lock to create it.
69+ * This specifically doesn't lock as the first step to avoid all calls obtaining a lock from the cache if
70+ * the item already exists in the DB.
71+ */
72+ if (! $ stamp ) {
73+ Cache::lock ('process-stamps-hash-create- ' . $ hash , 10 )
74+ ->get (function () use (&$ stamp , $ hash , $ process , $ parent ) {
75+ $ stamp = static ::firstOrCreate (['hash ' => $ hash ], [
76+ 'name ' => trim ($ process ['name ' ]),
77+ 'type ' => $ process ['type ' ],
78+ 'parent_id ' => optional ($ parent )->getKey (),
79+ ]);
80+ });
81+ }
6382
64- /*
65- * If stamp does not exist in the database yet, go ahead and obtain a lock to create it.
66- * 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.
67- */
68- if (! $ stamp ) {
69- Cache::lock ('process-stamps-hash-create- ' . $ hash , 10 )->get (function () use (&$ stamp , $ hash , $ process , $ parent ) {
70- $ stamp = static ::firstOrCreate (['hash ' => $ hash ], [
71- 'name ' => trim ($ process ['name ' ]),
72- 'type ' => $ process ['type ' ],
73- 'parent_id ' => optional ($ parent )->getKey (),
74- ]);
75- });
76- }
83+ if (null === $ stamp ) {
84+ throw new ModelNotFoundException ();
85+ }
7786
78- return $ stamp ;
87+ return $ stamp ;
88+ }, 25 );
7989 }
8090
8191 /**
0 commit comments