Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] [RFC] PoC for making chained jobs batchable #34337

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/Illuminate/Bus/Batch.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public function add($jobs)
$jobs->each->withBatchId($this->id);

$this->repository->transaction(function () use ($jobs) {
$this->repository->incrementTotalJobs($this->id, count($jobs));
$this->repository->incrementTotalJobs($this->id, $this->countJobs($jobs));

$this->queue->connection($this->options['connection'] ?? null)->bulk(
$jobs->all(),
Expand Down Expand Up @@ -427,4 +427,16 @@ public function jsonSerialize()
{
return $this->toArray();
}

/**
* @param Collection $jobs
*
* @return int
*/
private function countJobs(Collection $jobs)
{
return $jobs->reduce(function (int $count, $job) {
return $count + count($job->chained ?? []) + 1;
}, 0);
}
}
4 changes: 4 additions & 0 deletions src/Illuminate/Bus/Queueable.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ public function dispatchNextJobInChain()
{
if (! empty($this->chained)) {
dispatch(tap(unserialize(array_shift($this->chained)), function ($next) {
if (property_exists($this, 'batchId') && method_exists($next, 'withBatchId')) {
$next->withBatchId($this->batchId);
}

$next->chained = $this->chained;

$next->onConnection($next->connection ?: $this->chainConnection);
Expand Down
18 changes: 17 additions & 1 deletion src/Illuminate/Foundation/Bus/PendingChain.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ public function catchCallbacks()
* @return \Illuminate\Foundation\Bus\PendingDispatch
*/
public function dispatch()
{
return app(Dispatcher::class)->dispatch($this->prepareFirstJob());
}

/**
* @return CallQueuedClosure
*/
public function dispatchInBatch()
{
return $this->prepareFirstJob();
}

/**
* @return CallQueuedClosure|mixed
*/
public function prepareFirstJob()
{
if (is_string($this->job)) {
$firstJob = new $this->job(...func_get_args());
Expand All @@ -128,6 +144,6 @@ public function dispatch()
$firstJob->chain($this->chain);
$firstJob->chainCatchCallbacks = $this->catchCallbacks();

return app(Dispatcher::class)->dispatch($firstJob);
return $firstJob;
}
}