Skip to content

Commit 368a430

Browse files
authored
Merge pull request #777 from hypervel/improve/redis-batch-driver
Pipeline Redis batch pruning and keep custom repository lookups in Horizon search
2 parents 1d8a8fa + c40e5e0 commit 368a430

15 files changed

Lines changed: 637 additions & 150 deletions

File tree

‎src/bus/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ Overrides of `Batch::invokeCallbacks()` must accept the optional trailing `?int
1717

1818
Subclasses customizing `DatabaseBatchRepository` accounting should override the counting methods. Laravel's protected `updateAtomicValues()` hook is omitted.
1919

20+
`BatchRepository` resolves to a repository that reads each batch and routes it to the `DatabaseBatchRepository` or `RedisBatchRepository` binding for its results driver. Rebinding one of those classes customizes that driver's hydration, accounting and cleanup, including for batches returned by `Bus::findBatch()`. Lookups through `BatchRepository` do not call that class's `find()` or `get()`; to customize them, bind your repository to `BatchRepository` instead. That replacement owns hydration, accounting and pruning for every batch, so batches are no longer routed to the two driver bindings unless it does so itself.
21+
2022
Ported from: https://github.com/laravel/framework/tree/13.x/src/Illuminate/Bus

‎src/bus/src/DatabaseBatchRepository.php‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,42 @@ public function __construct(
4646
*/
4747
public function get(int $limit = 50, mixed $before = null): array
4848
{
49-
$rows = $this->getConnection()->table($this->table)
49+
return array_values($this->toBatches($this->getBatchRows($limit, $before)));
50+
}
51+
52+
/**
53+
* Retrieve a page of batches and its next cursor.
54+
*
55+
* Take the cursor from the rows read so a batch deleted while loading progress cannot hide the next page.
56+
*
57+
* @param positive-int $limit
58+
* @return array{list<Batch>, ?string}
59+
*/
60+
public function getPage(int $limit, mixed $before = null): array
61+
{
62+
$rows = $this->getBatchRows($limit + 1, $before);
63+
$next = null;
64+
if (count($rows) > $limit) {
65+
array_pop($rows);
66+
$next = $rows[array_key_last($rows)]->id;
67+
}
68+
69+
return [array_values($this->toBatches($rows)), $next];
70+
}
71+
72+
/**
73+
* Read batch rows in descending cursor order.
74+
*
75+
* @return array<array-key, object>
76+
*/
77+
private function getBatchRows(int $limit, mixed $before): array
78+
{
79+
return $this->getConnection()->table($this->table)
5080
->orderByDesc('id')
5181
->limit($limit)
5282
->when($before !== null && $before !== '', fn ($q) => $q->where('id', '<', $before))
53-
->get();
54-
55-
return array_values($this->toBatches($rows->all()));
83+
->get()
84+
->all();
5685
}
5786

5887
/**

‎src/bus/src/RedisBatchRepository.php‎

Lines changed: 74 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
use Hypervel\Database\Connection;
1111
use Hypervel\Database\ConnectionResolverInterface;
1212
use Hypervel\Database\Query\Builder;
13+
use Hypervel\Redis\Exceptions\LuaScriptException;
1314
use Hypervel\Redis\RedisConnection;
1415
use Hypervel\Support\CarbonImmutable;
1516
use Hypervel\Support\Collection;
1617
use LogicException;
1718
use Redis;
1819
use RuntimeException;
20+
use Throwable;
1921

2022
class 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

‎src/docs/queues.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2522,6 +2522,8 @@ class ImportCsv implements ShouldQueue
25222522
}
25232523
```
25242524

2525+
If a batchable job customizes how it is serialized or restored, such as by defining a `__serialize` or `__unserialize` method, it should keep the `batchId` and `batchPositionId` properties from the `Batchable` trait, along with any chain and routing properties the job uses, such as `chained`, `connection`, and `queue`. Hypervel relies on this state to count each job in a [chain](#chains-and-batches) once, even when the queue delivers the job more than once.
2526+
25252527
<a name="dispatching-batches"></a>
25262528
### Dispatching Batches
25272529

‎src/horizon/dist/app.js‎

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)