1010use Hypervel \Database \Connection ;
1111use Hypervel \Database \ConnectionResolverInterface ;
1212use Hypervel \Database \Query \Builder ;
13+ use Hypervel \Redis \Exceptions \LuaScriptException ;
1314use Hypervel \Redis \RedisConnection ;
1415use Hypervel \Support \CarbonImmutable ;
1516use Hypervel \Support \Collection ;
1617use LogicException ;
1718use Redis ;
1819use RuntimeException ;
20+ use Throwable ;
1921
2022class RedisBatchRepository extends DatabaseBatchRepository
2123{
@@ -28,6 +30,13 @@ class RedisBatchRepository extends DatabaseBatchRepository
2830 tonumber(state[3]) or -1, tonumber(state[4]) or -1}
2931 LUA;
3032
33+ private const string FINISH_MARKER = <<<'LUA'
34+ local f = redis.call('HMGET', KEYS[1], 'finished_total', 'finished_at')
35+ return tonumber(f[1]) == tonumber(ARGV[1]) and tonumber(f[2]) or -1
36+ LUA;
37+
38+ private const string INVALIDATE_TOTAL = "return redis.call('HDEL', KEYS[1], 'known_total') " ;
39+
3140 private const string RECORD = <<<'LUA'
3241 local job, success = ARGV[1], ARGV[2] == 'success'
3342 if redis.call('SISMEMBER', KEYS[1], job) == 1 then return {} end
@@ -189,7 +198,7 @@ public function incrementTotalJobs(string $batchId, int $amount): void
189198 private function invalidateTotal (string $ batchId ): void
190199 {
191200 $ this ->withRedis (fn (RedisConnection $ redis ) => $ redis ->evalWithShaCache (
192- " return redis.call('HDEL', KEYS[1], 'known_total') " ,
201+ self :: INVALIDATE_TOTAL ,
193202 [$ this ->keys ($ batchId )[2 ]]
194203 ));
195204 }
@@ -214,7 +223,7 @@ protected function releaseFromBatch(Builder $parent, object $row, int $count): ?
214223 $ row ->failed_jobs = $ failed ;
215224 $ row ->previous_first_pass_total = max ((int ) $ row ->previous_first_pass_total , $ firstPass );
216225 $ row ->previous_success_total = max ((int ) $ row ->previous_success_total , $ successful );
217- if ($ finishTotal === (int ) $ row ->total_jobs - $ count && $ row ->previous_finished_total != $ finishTotal ) {
226+ if ($ finishTotal === (int ) $ row ->total_jobs - $ count && ( int ) $ row ->previous_finished_total != = $ finishTotal ) {
218227 // A Redis finish may have committed before its SQL projection.
219228 $ row ->previous_finished_total = $ finishTotal ;
220229 $ row ->previous_finished_at = $ finishTime ;
@@ -228,21 +237,20 @@ protected function releaseFromBatch(Builder $parent, object $row, int $count): ?
228237 */
229238 protected function recordJobResult (string $ batchId , string $ jobId , ?string $ retryId ): ?UpdatedBatchJobCounts
230239 {
231- $ connection = $ this ->getConnection ();
232240 if ($ this ->hasOwnerTransaction ()) {
233241 throw new LogicException ("Redis results for batch [ {$ batchId }] cannot be recorded inside its database transaction. " );
234242 }
235243
236244 $ keys = $ this ->keys ($ batchId );
237- $ args = [hash ('xxh128 ' , $ jobId ), $ retryId === null ? 'success ' : 'failure ' , $ retryId ?? '' ];
245+ $ arguments = [hash ('xxh128 ' , $ jobId ), $ retryId === null ? 'success ' : 'failure ' , $ retryId ?? '' ];
238246 $ result = $ this ->withRedis (static fn (RedisConnection $ redis ) => $ redis ->evalWithShaCache (
239247 self ::RECORD ,
240248 $ keys ,
241- [...$ args , '' , '' , '' , '' ]
249+ [...$ arguments , '' , '' , '' , '' ]
242250 ));
243251
244252 if ($ result === [-1 ]) {
245- $ result = $ connection -> transaction (function () use ($ keys , $ args , $ batchId ) {
253+ $ result = $ this -> getConnection ()-> transaction (function () use ($ keys , $ arguments , $ batchId ) {
246254 $ parent = $ this ->lockParents ([$ batchId ]);
247255 $ row = (clone $ parent )->first (['total_jobs ' , 'finished_at ' , 'options ' ]);
248256 if ($ row === null ) {
@@ -252,7 +260,7 @@ protected function recordJobResult(string $batchId, string $jobId, ?string $retr
252260 $ result = $ this ->withRedis (static fn (RedisConnection $ redis ) => $ redis ->evalWithShaCache (
253261 self ::RECORD ,
254262 $ keys ,
255- [...$ args , $ row ->total_jobs , (int ) $ allowsFailures , $ row ->finished_at ?? '' , time ()]
263+ [...$ arguments , $ row ->total_jobs , (int ) $ allowsFailures , $ row ->finished_at ?? '' , time ()]
256264 ));
257265 if ($ result !== [] && $ result [5 ] !== -1 && $ row ->finished_at === null ) {
258266 $ parent ->update (['finished_at ' => $ result [5 ]]);
@@ -318,7 +326,7 @@ public function prune(DateTimeInterface $before): int
318326 private function finishMarker (string $ batchId , int $ total ): ?int
319327 {
320328 $ finish = $ this ->withRedis (fn (RedisConnection $ redis ) => $ redis ->evalWithShaCache (
321- " local f = redis.call('HMGET', KEYS[1], 'finished_total', 'finished_at'); return tonumber(f[1]) == tonumber(ARGV[1]) and tonumber(f[2]) or -1 " ,
329+ self :: FINISH_MARKER ,
322330 [$ this ->keys ($ batchId )[2 ]],
323331 [$ total ]
324332 ));
@@ -338,19 +346,27 @@ protected function deleteBatches(Builder $query, array $ids, bool $retryIndividu
338346 $ connection = $ this ->getConnection ();
339347 return $ connection ->transaction (function () use ($ connection , $ query , $ ids ) {
340348 $ parents = $ this ->lockParents ($ ids )->get (['id ' , 'total_jobs ' , 'finished_at ' ]);
349+ $ markers = [];
341350 foreach ($ parents as $ row ) {
342- if ($ row ->finished_at === null && ($ finish = $ this ->finishMarker ($ row ->id , (int ) $ row ->total_jobs )) !== null ) {
343- $ connection ->table ($ this ->table )->where ('id ' , $ row ->id )->update (['finished_at ' => $ finish ]);
351+ if ($ row ->finished_at === null ) {
352+ $ markers [$ row ->id ] = [[$ this ->keys ($ row ->id )[2 ]], [(int ) $ row ->total_jobs ]];
353+ }
354+ }
355+ foreach ($ this ->evalEach (self ::FINISH_MARKER , $ markers ) as $ id => $ finish ) {
356+ if ($ finish !== -1 ) {
357+ $ connection ->table ($ this ->table )->where ('id ' , $ id )->update (['finished_at ' => $ finish ]);
344358 }
345359 }
346360
347361 $ eligible = (clone $ query )->whereIn ('id ' , $ parents ->pluck ('id ' ))->lockForUpdate ()->pluck ('id ' )->all ();
348362 if ($ eligible === []) {
349363 return 0 ;
350364 }
365+ $ totals = [];
351366 foreach ($ eligible as $ id ) {
352- $ this ->invalidateTotal ($ id );
367+ $ totals [ $ id ] = [[ $ this ->keys ($ id )[ 2 ]], []] ;
353368 }
369+ $ this ->evalEach (self ::INVALIDATE_TOTAL , $ totals );
354370 $ deleted = $ connection ->table ($ this ->table )->whereIn ('id ' , $ eligible )->delete ();
355371 $ this ->recordResultDeletions ($ eligible );
356372
@@ -363,11 +379,11 @@ protected function deleteBatches(Builder $query, array $ids, bool $retryIndividu
363379 */
364380 protected function deleteJobResults (array $ ids ): void
365381 {
366- $ this -> withRedis ( function ( RedisConnection $ redis ) use ( $ ids ) {
367- foreach ($ ids as $ id ) {
368- $ redis -> evalWithShaCache ( " return redis.call('UNLINK', unpack(KEYS)) " , $ this ->keys ($ id )) ;
369- }
370- } );
382+ $ results = [];
383+ foreach ($ ids as $ id ) {
384+ $ results [ $ id ] = [ $ this ->keys ($ id ), []] ;
385+ }
386+ $ this -> evalEach ( " return redis.call('UNLINK', unpack(KEYS)) " , $ results );
371387 }
372388
373389 /**
@@ -415,7 +431,9 @@ protected function loadSnapshots(array $rows): array
415431 $ live = $ this ->getConnection ()->table ($ this ->table )->useWritePdo ()->whereIn ('id ' , $ waiting )->get (['id ' , 'total_jobs ' , 'finished_at ' ]);
416432 foreach ($ live as $ row ) {
417433 $ id = $ row ->id ;
418- if ((int ) $ row ->total_jobs === (int ) $ rows [$ id ]->total_jobs && $ row ->finished_at == $ rows [$ id ]->finished_at ) {
434+ $ finishedAt = $ row ->finished_at === null ? null : (int ) $ row ->finished_at ;
435+ $ finishedAtLookup = $ rows [$ id ]->finished_at === null ? null : (int ) $ rows [$ id ]->finished_at ;
436+ if ((int ) $ row ->total_jobs === (int ) $ rows [$ id ]->total_jobs && $ finishedAt === $ finishedAtLookup ) {
419437 $ counts [$ id ] = $ this ->snapshotCounts ($ views [$ id ], (int ) $ row ->total_jobs , $ row ->finished_at );
420438 } else {
421439 $ conflicts [] = $ id ;
@@ -447,33 +465,60 @@ protected function loadSnapshots(array $rows): array
447465 */
448466 private function readSnapshots (array $ ids ): array
449467 {
450- if ($ ids === []) {
468+ $ snapshots = [];
469+ foreach ($ ids as $ id ) {
470+ $ snapshots [$ id ] = [$ this ->keys ($ id ), []];
471+ }
472+
473+ return $ this ->evalEach (self ::SNAPSHOT , $ snapshots );
474+ }
475+
476+ /**
477+ * Run a script once per batch, sharing one round trip when a single node holds every key.
478+ *
479+ * @param array<array-key, array{list<string>, list<int|string>}> $calls the keys and arguments keyed by batch ID
480+ * @return array<array-key, mixed>
481+ */
482+ private function evalEach (string $ script , array $ calls ): array
483+ {
484+ if ($ calls === []) {
451485 return [];
452486 }
453487
454- return $ this ->withRedis (function (RedisConnection $ redis ) use ($ ids ) {
455- if (count ($ ids ) === 1 || $ redis ->isCluster ()) {
456- $ views = [];
457- foreach ($ ids as $ id ) {
458- $ views [$ id ] = $ redis ->evalWithShaCache (self :: SNAPSHOT , $ this -> keys ( $ id ) );
488+ return $ this ->withRedis (static function (RedisConnection $ redis ) use ($ script , $ calls ) {
489+ if (count ($ calls ) === 1 || $ redis ->isCluster ()) {
490+ $ results = [];
491+ foreach ($ calls as $ id => [ $ keys , $ arguments ] ) {
492+ $ results [$ id ] = $ redis ->evalWithShaCache ($ script , $ keys, $ arguments );
459493 }
460494
461- return $ views ;
495+ return $ results ;
462496 }
463497
464498 // Send EVAL in pipelines so a cold script cache needs no mid-pipeline NOSCRIPT retry.
465499 $ client = $ redis ->client ();
466500 assert ($ client instanceof Redis);
501+ $ client ->clearLastError ();
467502 $ pipeline = $ client ->pipeline ();
468- foreach ($ ids as $ id ) {
469- $ pipeline ->eval (self :: SNAPSHOT , $ this -> keys ( $ id ), 3 );
503+ foreach ($ calls as [ $ keys , $ arguments ] ) {
504+ $ pipeline ->eval ($ script , [... $ keys, ... $ arguments ], count ( $ keys ) );
470505 }
471- $ results = $ pipeline ->exec ();
506+
507+ try {
508+ // The connection's own exec() would clear its WATCH tracking, which a pipeline does not consume.
509+ $ results = $ pipeline ->exec ();
510+ } catch (Throwable $ exception ) {
511+ // Keep a client that failed over or lost its transport out of the pool.
512+ $ redis ->invalidate ();
513+
514+ throw $ exception ;
515+ }
516+
472517 if ($ results === false || in_array (false , $ results , true )) {
473- throw new RuntimeException ('Unable to load Redis batch progress : ' . $ client ->getLastError ());
518+ throw new LuaScriptException ('Unable to run the Redis batch script : ' . $ client ->getLastError ());
474519 }
475520
476- return array_combine ($ ids , $ results );
521+ return array_combine (array_keys ( $ calls ) , $ results );
477522 });
478523 }
479524
0 commit comments