first commit
This commit is contained in:
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Attributes;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
class DeleteWhenMissingModels
|
||||
{
|
||||
//
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Attributes;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
|
||||
class WithoutRelations
|
||||
{
|
||||
//
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Support\Facades\Concurrency;
|
||||
|
||||
class BackgroundQueue extends SyncQueue
|
||||
{
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
Concurrency::driver('process')->defer(
|
||||
fn () => \Illuminate\Support\Facades\Queue::connection('sync')->push($job, $data, $queue)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Queue\Queue as QueueContract;
|
||||
use Illuminate\Queue\Jobs\BeanstalkdJob;
|
||||
use Pheanstalk\Contract\JobIdInterface;
|
||||
use Pheanstalk\Pheanstalk;
|
||||
use Pheanstalk\Values\Job;
|
||||
use Pheanstalk\Values\JobId;
|
||||
use Pheanstalk\Values\TubeName;
|
||||
|
||||
class BeanstalkdQueue extends Queue implements QueueContract
|
||||
{
|
||||
/**
|
||||
* The Pheanstalk instance.
|
||||
*
|
||||
* @var \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface
|
||||
*/
|
||||
protected $pheanstalk;
|
||||
|
||||
/**
|
||||
* The name of the default tube.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $default;
|
||||
|
||||
/**
|
||||
* The "time to run" for all pushed jobs.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $timeToRun;
|
||||
|
||||
/**
|
||||
* The maximum number of seconds to block for a job.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $blockFor;
|
||||
|
||||
/**
|
||||
* Create a new Beanstalkd queue instance.
|
||||
*
|
||||
* @param \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface $pheanstalk
|
||||
* @param string $default
|
||||
* @param int $timeToRun
|
||||
* @param int $blockFor
|
||||
* @param bool $dispatchAfterCommit
|
||||
*/
|
||||
public function __construct(
|
||||
$pheanstalk,
|
||||
$default,
|
||||
$timeToRun,
|
||||
$blockFor = 0,
|
||||
$dispatchAfterCommit = false,
|
||||
) {
|
||||
$this->default = $default;
|
||||
$this->blockFor = $blockFor;
|
||||
$this->timeToRun = $timeToRun;
|
||||
$this->pheanstalk = $pheanstalk;
|
||||
$this->dispatchAfterCommit = $dispatchAfterCommit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function size($queue = null)
|
||||
{
|
||||
$stats = $this->pheanstalk->statsTube(new TubeName($this->getQueue($queue)));
|
||||
|
||||
return $stats->currentJobsReady
|
||||
+ $stats->currentJobsDelayed
|
||||
+ $stats->currentJobsReserved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of pending jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function pendingSize($queue = null)
|
||||
{
|
||||
return $this->pheanstalk->statsTube(new TubeName($this->getQueue($queue)))->currentJobsReady;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function delayedSize($queue = null)
|
||||
{
|
||||
return $this->pheanstalk->statsTube(new TubeName($this->getQueue($queue)))->currentJobsDelayed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of reserved jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function reservedSize($queue = null)
|
||||
{
|
||||
return $this->pheanstalk->statsTube(new TubeName($this->getQueue($queue)))->currentJobsReserved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int|null
|
||||
*/
|
||||
public function creationTimeOfOldestPendingJob($queue = null)
|
||||
{
|
||||
// Not supported by Beanstalkd...
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data),
|
||||
$queue,
|
||||
null,
|
||||
function ($payload, $queue) {
|
||||
return $this->pushRaw($payload, $queue);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload onto the queue.
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @param array $options
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushRaw($payload, $queue = null, array $options = [])
|
||||
{
|
||||
$this->pheanstalk->useTube(new TubeName($this->getQueue($queue)));
|
||||
|
||||
return $this->pheanstalk->put(
|
||||
$payload, Pheanstalk::DEFAULT_PRIORITY, Pheanstalk::DEFAULT_DELAY, $this->timeToRun
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function later($delay, $job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data, $delay),
|
||||
$queue,
|
||||
$delay,
|
||||
function ($payload, $queue, $delay) {
|
||||
$this->pheanstalk->useTube(new TubeName($this->getQueue($queue)));
|
||||
|
||||
return $this->pheanstalk->put(
|
||||
$payload,
|
||||
Pheanstalk::DEFAULT_PRIORITY,
|
||||
$this->secondsUntil($delay),
|
||||
$this->timeToRun
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push an array of jobs onto the queue.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return void
|
||||
*/
|
||||
public function bulk($jobs, $data = '', $queue = null)
|
||||
{
|
||||
foreach ((array) $jobs as $job) {
|
||||
if (isset($job->delay)) {
|
||||
$this->later($job->delay, $job, $data, $queue);
|
||||
} else {
|
||||
$this->push($job, $data, $queue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the next job off of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public function pop($queue = null)
|
||||
{
|
||||
$this->pheanstalk->watch(
|
||||
$tube = new TubeName($queue = $this->getQueue($queue))
|
||||
);
|
||||
|
||||
foreach ($this->pheanstalk->listTubesWatched() as $watched) {
|
||||
if ($watched->value !== $tube->value) {
|
||||
$this->pheanstalk->ignore($watched);
|
||||
}
|
||||
}
|
||||
|
||||
$job = $this->pheanstalk->reserveWithTimeout($this->blockFor);
|
||||
|
||||
if ($job instanceof JobIdInterface) {
|
||||
return new BeanstalkdJob(
|
||||
$this->container, $this->pheanstalk, $job, $this->connectionName, $queue
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a message from the Beanstalk queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param string|int $id
|
||||
* @return void
|
||||
*/
|
||||
public function deleteMessage($queue, $id)
|
||||
{
|
||||
$this->pheanstalk->useTube(new TubeName($this->getQueue($queue)));
|
||||
|
||||
$this->pheanstalk->delete(new Job(new JobId($id), ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue or return the default.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return string
|
||||
*/
|
||||
public function getQueue($queue)
|
||||
{
|
||||
return $queue ?: $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Pheanstalk instance.
|
||||
*
|
||||
* @return \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface
|
||||
*/
|
||||
public function getPheanstalk()
|
||||
{
|
||||
return $this->pheanstalk;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Bus\Batchable;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Container\Container;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Laravel\SerializableClosure\SerializableClosure;
|
||||
use ReflectionFunction;
|
||||
|
||||
class CallQueuedClosure implements ShouldQueue
|
||||
{
|
||||
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/**
|
||||
* The serializable Closure instance.
|
||||
*
|
||||
* @var \Laravel\SerializableClosure\SerializableClosure
|
||||
*/
|
||||
public $closure;
|
||||
|
||||
/**
|
||||
* The name assigned to the job.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public $name = null;
|
||||
|
||||
/**
|
||||
* The callbacks that should be executed on failure.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $failureCallbacks = [];
|
||||
|
||||
/**
|
||||
* Indicate if the job should be deleted when models are missing.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $deleteWhenMissingModels = true;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Laravel\SerializableClosure\SerializableClosure $closure
|
||||
*/
|
||||
public function __construct($closure)
|
||||
{
|
||||
$this->closure = $closure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Closure $job
|
||||
* @return self
|
||||
*/
|
||||
public static function create(Closure $job)
|
||||
{
|
||||
return new self(new SerializableClosure($job));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Container\Container $container
|
||||
* @return void
|
||||
*/
|
||||
public function handle(Container $container)
|
||||
{
|
||||
$container->call($this->closure->getClosure(), ['job' => $this]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a callback to be executed if the job fails.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return $this
|
||||
*/
|
||||
public function onFailure($callback)
|
||||
{
|
||||
$this->failureCallbacks[] = $callback instanceof Closure
|
||||
? new SerializableClosure($callback)
|
||||
: $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a job failure.
|
||||
*
|
||||
* @param \Throwable $e
|
||||
* @return void
|
||||
*/
|
||||
public function failed($e)
|
||||
{
|
||||
foreach ($this->failureCallbacks as $callback) {
|
||||
$callback($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the display name for the queued job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function displayName()
|
||||
{
|
||||
$closure = $this->closure instanceof SerializableClosure
|
||||
? $this->closure->getClosure()
|
||||
: $this->closure;
|
||||
|
||||
$reflection = new ReflectionFunction($closure);
|
||||
|
||||
$prefix = is_null($this->name) ? '' : "{$this->name} - ";
|
||||
|
||||
return $prefix.'Closure ('.basename($reflection->getFileName()).':'.$reflection->getStartLine().')';
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a name to the job.
|
||||
*
|
||||
* @param string $name
|
||||
* @return $this
|
||||
*/
|
||||
public function name($name)
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Bus\Batchable;
|
||||
use Illuminate\Bus\BatchRepository;
|
||||
use Illuminate\Bus\UniqueLock;
|
||||
use Illuminate\Contracts\Bus\Dispatcher;
|
||||
use Illuminate\Contracts\Cache\Factory as CacheFactory;
|
||||
use Illuminate\Contracts\Cache\Repository as Cache;
|
||||
use Illuminate\Contracts\Container\Container;
|
||||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
use Illuminate\Contracts\Queue\Job;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Events\CallQueuedListener;
|
||||
use Illuminate\Log\Context\Repository as ContextRepository;
|
||||
use Illuminate\Pipeline\Pipeline;
|
||||
use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
|
||||
use ReflectionClass;
|
||||
use RuntimeException;
|
||||
|
||||
class CallQueuedHandler
|
||||
{
|
||||
/**
|
||||
* The bus dispatcher implementation.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Bus\Dispatcher
|
||||
*/
|
||||
protected $dispatcher;
|
||||
|
||||
/**
|
||||
* The container instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Container\Container
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* Create a new handler instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Bus\Dispatcher $dispatcher
|
||||
* @param \Illuminate\Contracts\Container\Container $container
|
||||
*/
|
||||
public function __construct(Dispatcher $dispatcher, Container $container)
|
||||
{
|
||||
$this->container = $container;
|
||||
$this->dispatcher = $dispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the queued job.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param array $data
|
||||
* @return void
|
||||
*/
|
||||
public function call(Job $job, array $data)
|
||||
{
|
||||
try {
|
||||
$command = $this->setJobInstanceIfNecessary(
|
||||
$job, $this->getCommand($data)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->handleModelNotFound($job, $e);
|
||||
}
|
||||
|
||||
$this->dispatchThroughMiddleware($job, $command);
|
||||
|
||||
if (! $job->isReleased() && ! $this->commandShouldBeUniqueUntilProcessing($command)) {
|
||||
$this->ensureUniqueJobLockIsReleased($command);
|
||||
}
|
||||
|
||||
if (! $job->hasFailed() && ! $job->isReleased()) {
|
||||
$this->ensureNextJobInChainIsDispatched($command);
|
||||
$this->ensureSuccessfulBatchJobIsRecorded($command);
|
||||
}
|
||||
|
||||
if (! $job->isDeletedOrReleased()) {
|
||||
$job->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the command from the given payload.
|
||||
*
|
||||
* @param array $data
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
protected function getCommand(array $data)
|
||||
{
|
||||
if (str_starts_with($data['command'], 'O:')) {
|
||||
return unserialize($data['command']);
|
||||
}
|
||||
|
||||
if ($this->container->bound(Encrypter::class)) {
|
||||
return unserialize($this->container[Encrypter::class]->decrypt($data['command']));
|
||||
}
|
||||
|
||||
throw new RuntimeException('Unable to extract job payload.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch the given job / command through its specified middleware.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param mixed $command
|
||||
* @return mixed
|
||||
*/
|
||||
protected function dispatchThroughMiddleware(Job $job, $command)
|
||||
{
|
||||
if ($command instanceof \__PHP_Incomplete_Class) {
|
||||
throw new Exception('Job is incomplete class: '.json_encode($command));
|
||||
}
|
||||
|
||||
$lockReleased = false;
|
||||
|
||||
return (new Pipeline($this->container))->send($command)
|
||||
->through(array_merge(method_exists($command, 'middleware') ? $command->middleware() : [], $command->middleware ?? []))
|
||||
->finally(function ($command) use (&$lockReleased) {
|
||||
if (! $lockReleased && $this->commandShouldBeUniqueUntilProcessing($command) && ! $command->job->isReleased()) {
|
||||
$this->ensureUniqueJobLockIsReleased($command);
|
||||
}
|
||||
})
|
||||
->then(function ($command) use ($job, &$lockReleased) {
|
||||
if ($this->commandShouldBeUniqueUntilProcessing($command)) {
|
||||
$this->ensureUniqueJobLockIsReleased($command);
|
||||
|
||||
$lockReleased = true;
|
||||
}
|
||||
|
||||
return $this->dispatcher->dispatchNow(
|
||||
$command, $this->resolveHandler($job, $command)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the handler for the given command.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param mixed $command
|
||||
* @return mixed
|
||||
*/
|
||||
protected function resolveHandler($job, $command)
|
||||
{
|
||||
$handler = $this->dispatcher->getCommandHandler($command) ?: null;
|
||||
|
||||
if ($handler) {
|
||||
$this->setJobInstanceIfNecessary($job, $handler);
|
||||
}
|
||||
|
||||
return $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the job instance of the given class if necessary.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param mixed $instance
|
||||
* @return mixed
|
||||
*/
|
||||
protected function setJobInstanceIfNecessary(Job $job, $instance)
|
||||
{
|
||||
if (in_array(InteractsWithQueue::class, class_uses_recursive($instance))) {
|
||||
$instance->setJob($job);
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the next job in the chain is dispatched if applicable.
|
||||
*
|
||||
* @param mixed $command
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureNextJobInChainIsDispatched($command)
|
||||
{
|
||||
if (method_exists($command, 'dispatchNextJobInChain')) {
|
||||
$command->dispatchNextJobInChain();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the batch is notified of the successful job completion.
|
||||
*
|
||||
* @param mixed $command
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureSuccessfulBatchJobIsRecorded($command)
|
||||
{
|
||||
$uses = class_uses_recursive($command);
|
||||
|
||||
if (! in_array(Batchable::class, $uses) ||
|
||||
! in_array(InteractsWithQueue::class, $uses)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($batch = $command->batch()) {
|
||||
$batch->recordSuccessfulJob($command->job->uuid());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the lock for a unique job is released.
|
||||
*
|
||||
* @param mixed $command
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureUniqueJobLockIsReleased($command)
|
||||
{
|
||||
if ($this->commandShouldBeUnique($command)) {
|
||||
(new UniqueLock($this->container->make(Cache::class)))->release($command);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given command should be unique.
|
||||
*/
|
||||
protected function commandShouldBeUnique(mixed $command): bool
|
||||
{
|
||||
return $command instanceof ShouldBeUnique ||
|
||||
($command instanceof CallQueuedListener && $command->shouldBeUnique());
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given command should be unique until processing begins.
|
||||
*/
|
||||
protected function commandShouldBeUniqueUntilProcessing(mixed $command): bool
|
||||
{
|
||||
return $command instanceof ShouldBeUniqueUntilProcessing ||
|
||||
($command instanceof CallQueuedListener && $command->shouldBeUniqueUntilProcessing());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a model not found exception.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param \Throwable $e
|
||||
* @return void
|
||||
*/
|
||||
protected function handleModelNotFound(Job $job, $e)
|
||||
{
|
||||
$class = $job->resolveQueuedJobClass();
|
||||
|
||||
try {
|
||||
$reflectionClass = new ReflectionClass($class);
|
||||
|
||||
$shouldDelete = $reflectionClass->getDefaultProperties()['deleteWhenMissingModels']
|
||||
?? count($reflectionClass->getAttributes(DeleteWhenMissingModels::class)) !== 0;
|
||||
} catch (Exception) {
|
||||
$shouldDelete = false;
|
||||
}
|
||||
|
||||
$this->ensureUniqueJobLockIsReleasedViaContext();
|
||||
|
||||
if ($shouldDelete) {
|
||||
$this->ensureSuccessfulBatchJobIsRecordedForMissingModel($job, $class);
|
||||
|
||||
return $job->delete();
|
||||
}
|
||||
|
||||
return $job->fail($e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the lock for a unique job is released via context.
|
||||
*
|
||||
* This is required when we can't unserialize the job due to missing models.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureUniqueJobLockIsReleasedViaContext()
|
||||
{
|
||||
if (! $this->container->bound(ContextRepository::class) ||
|
||||
! $this->container->bound(CacheFactory::class)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$context = $this->container->make(ContextRepository::class);
|
||||
|
||||
[$store, $key] = [
|
||||
$context->getHidden('laravel_unique_job_cache_store'),
|
||||
$context->getHidden('laravel_unique_job_key'),
|
||||
];
|
||||
|
||||
if ($store && $key) {
|
||||
$this->container->make(CacheFactory::class)
|
||||
->store($store)
|
||||
->lock($key)
|
||||
->forceRelease();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a potentially batched job as successful when deleted because models were missing.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param string $class
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureSuccessfulBatchJobIsRecordedForMissingModel(Job $job, string $class)
|
||||
{
|
||||
if (! in_array(Batchable::class, class_uses_recursive($class), true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $this->container->bound(BatchRepository::class)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$batchId = $job->payload()['data']['batchId'] ?? null;
|
||||
|
||||
if ((! is_string($batchId) || $batchId === '') ||
|
||||
! is_string($job->uuid()) || $job->uuid() === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($batch = $this->container->make(BatchRepository::class)->find($batchId)) {
|
||||
$batch->recordSuccessfulJob($job->uuid());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the failed method on the job instance.
|
||||
*
|
||||
* The exception that caused the failure will be passed.
|
||||
*
|
||||
* @param array $data
|
||||
* @param \Throwable|null $e
|
||||
* @param string $uuid
|
||||
* @param \Illuminate\Contracts\Queue\Job|null $job
|
||||
* @return void
|
||||
*/
|
||||
public function failed(array $data, $e, string $uuid, ?Job $job = null)
|
||||
{
|
||||
$command = $this->getCommand($data);
|
||||
|
||||
if (! is_null($job)) {
|
||||
$command = $this->setJobInstanceIfNecessary($job, $command);
|
||||
}
|
||||
|
||||
if (! $this->commandShouldBeUniqueUntilProcessing($command)) {
|
||||
$this->ensureUniqueJobLockIsReleased($command);
|
||||
}
|
||||
|
||||
if ($command instanceof \__PHP_Incomplete_Class) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->ensureFailedBatchJobIsRecorded($uuid, $command, $e);
|
||||
$this->ensureChainCatchCallbacksAreInvoked($uuid, $command, $e);
|
||||
|
||||
if (method_exists($command, 'failed')) {
|
||||
$command->failed($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the batch is notified of the failed job.
|
||||
*
|
||||
* @param string $uuid
|
||||
* @param mixed $command
|
||||
* @param \Throwable $e
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureFailedBatchJobIsRecorded(string $uuid, $command, $e)
|
||||
{
|
||||
if (! in_array(Batchable::class, class_uses_recursive($command))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($batch = $command->batch()) {
|
||||
$batch->recordFailedJob($uuid, $e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the chained job catch callbacks are invoked.
|
||||
*
|
||||
* @param string $uuid
|
||||
* @param mixed $command
|
||||
* @param \Throwable $e
|
||||
* @return void
|
||||
*/
|
||||
protected function ensureChainCatchCallbacksAreInvoked(string $uuid, $command, $e)
|
||||
{
|
||||
if (method_exists($command, 'invokeChainCatchCallbacks')) {
|
||||
$command->invokeChainCatchCallbacks($e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Capsule;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Queue\QueueManager;
|
||||
use Illuminate\Queue\QueueServiceProvider;
|
||||
use Illuminate\Support\Traits\CapsuleManagerTrait;
|
||||
|
||||
/**
|
||||
* @mixin \Illuminate\Queue\QueueManager
|
||||
* @mixin \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
class Manager
|
||||
{
|
||||
use CapsuleManagerTrait;
|
||||
|
||||
/**
|
||||
* The queue manager instance.
|
||||
*
|
||||
* @var \Illuminate\Queue\QueueManager
|
||||
*/
|
||||
protected $manager;
|
||||
|
||||
/**
|
||||
* Create a new queue capsule manager.
|
||||
*
|
||||
* @param \Illuminate\Container\Container|null $container
|
||||
*/
|
||||
public function __construct(?Container $container = null)
|
||||
{
|
||||
$this->setupContainer($container ?: new Container);
|
||||
|
||||
// Once we have the container setup, we will set up the default configuration
|
||||
// options in the container "config" bindings. This'll just make the queue
|
||||
// manager behave correctly since all the correct bindings are in place.
|
||||
$this->setupDefaultConfiguration();
|
||||
|
||||
$this->setupManager();
|
||||
|
||||
$this->registerConnectors();
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the default queue configuration options.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setupDefaultConfiguration()
|
||||
{
|
||||
$this->container['config']['queue.default'] = 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the queue manager instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setupManager()
|
||||
{
|
||||
$this->manager = new QueueManager($this->container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the default connectors that the component ships with.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerConnectors()
|
||||
{
|
||||
$provider = new QueueServiceProvider($this->container);
|
||||
|
||||
$provider->registerConnectors($this->manager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a connection instance from the global manager.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public static function connection($connection = null)
|
||||
{
|
||||
return static::$instance->getConnection($connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @param string|null $connection
|
||||
* @return mixed
|
||||
*/
|
||||
public static function push($job, $data = '', $queue = null, $connection = null)
|
||||
{
|
||||
return static::$instance->connection($connection)->push($job, $data, $queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new an array of jobs onto the queue.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @param string|null $connection
|
||||
* @return mixed
|
||||
*/
|
||||
public static function bulk($jobs, $data = '', $queue = null, $connection = null)
|
||||
{
|
||||
return static::$instance->connection($connection)->bulk($jobs, $data, $queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @param string|null $connection
|
||||
* @return mixed
|
||||
*/
|
||||
public static function later($delay, $job, $data = '', $queue = null, $connection = null)
|
||||
{
|
||||
return static::$instance->connection($connection)->later($delay, $job, $data, $queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a registered connection instance.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function getConnection($name = null)
|
||||
{
|
||||
return $this->manager->connection($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a connection with the manager.
|
||||
*
|
||||
* @param array $config
|
||||
* @param string $name
|
||||
* @return void
|
||||
*/
|
||||
public function addConnection(array $config, $name = 'default')
|
||||
{
|
||||
$this->container['config']["queue.connections.{$name}"] = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue manager instance.
|
||||
*
|
||||
* @return \Illuminate\Queue\QueueManager
|
||||
*/
|
||||
public function getQueueManager()
|
||||
{
|
||||
return $this->manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pass dynamic instance methods to the manager.
|
||||
*
|
||||
* @param string $method
|
||||
* @param array $parameters
|
||||
* @return mixed
|
||||
*/
|
||||
public function __call($method, $parameters)
|
||||
{
|
||||
return $this->manager->$method(...$parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically pass methods to the default connection.
|
||||
*
|
||||
* @param string $method
|
||||
* @param array $parameters
|
||||
* @return mixed
|
||||
*/
|
||||
public static function __callStatic($method, $parameters)
|
||||
{
|
||||
return static::connection()->$method(...$parameters);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Queue\BackgroundQueue;
|
||||
|
||||
class BackgroundConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new BackgroundQueue($config['after_commit'] ?? null);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Queue\BeanstalkdQueue;
|
||||
use Pheanstalk\Contract\SocketFactoryInterface;
|
||||
use Pheanstalk\Pheanstalk;
|
||||
use Pheanstalk\Values\Timeout;
|
||||
|
||||
class BeanstalkdConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new BeanstalkdQueue(
|
||||
$this->pheanstalk($config),
|
||||
$config['queue'],
|
||||
$config['retry_after'] ?? Pheanstalk::DEFAULT_TTR,
|
||||
$config['block_for'] ?? 0,
|
||||
$config['after_commit'] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Pheanstalk instance.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Pheanstalk\Pheanstalk
|
||||
*/
|
||||
protected function pheanstalk(array $config)
|
||||
{
|
||||
return Pheanstalk::create(
|
||||
$config['host'],
|
||||
$config['port'] ?? SocketFactoryInterface::DEFAULT_PORT,
|
||||
isset($config['timeout']) ? new Timeout($config['timeout']) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
interface ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Database\ConnectionResolverInterface;
|
||||
use Illuminate\Queue\DatabaseQueue;
|
||||
|
||||
class DatabaseConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Database connections.
|
||||
*
|
||||
* @var \Illuminate\Database\ConnectionResolverInterface
|
||||
*/
|
||||
protected $connections;
|
||||
|
||||
/**
|
||||
* Create a new connector instance.
|
||||
*
|
||||
* @param \Illuminate\Database\ConnectionResolverInterface $connections
|
||||
*/
|
||||
public function __construct(ConnectionResolverInterface $connections)
|
||||
{
|
||||
$this->connections = $connections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new DatabaseQueue(
|
||||
$this->connections->connection($config['connection'] ?? null),
|
||||
$config['table'],
|
||||
$config['queue'],
|
||||
$config['retry_after'] ?? 60,
|
||||
$config['after_commit'] ?? null
|
||||
);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Queue\DeferredQueue;
|
||||
|
||||
class DeferredConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new DeferredQueue($config['after_commit'] ?? null);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Queue\FailoverQueue;
|
||||
use Illuminate\Queue\QueueManager;
|
||||
|
||||
class FailoverConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Create a new connector instance.
|
||||
*/
|
||||
public function __construct(
|
||||
protected QueueManager $manager,
|
||||
protected Dispatcher $events
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new FailoverQueue(
|
||||
$this->manager,
|
||||
$this->events,
|
||||
$config['connections'],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Queue\NullQueue;
|
||||
|
||||
class NullConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new NullQueue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Contracts\Redis\Factory as Redis;
|
||||
use Illuminate\Queue\RedisQueue;
|
||||
|
||||
class RedisConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* The Redis database instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Redis\Factory
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
/**
|
||||
* The connection name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $connection;
|
||||
|
||||
/**
|
||||
* Create a new Redis queue connector instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Redis\Factory $redis
|
||||
* @param string|null $connection
|
||||
*/
|
||||
public function __construct(Redis $redis, $connection = null)
|
||||
{
|
||||
$this->redis = $redis;
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new RedisQueue(
|
||||
$this->redis, $config['queue'],
|
||||
$config['connection'] ?? $this->connection,
|
||||
$config['retry_after'] ?? 60,
|
||||
$config['block_for'] ?? null,
|
||||
$config['after_commit'] ?? null,
|
||||
$config['migration_batch_size'] ?? -1
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Aws\Credentials\CredentialProvider;
|
||||
use Aws\Sqs\SqsClient;
|
||||
use Illuminate\Queue\SqsQueue;
|
||||
use Illuminate\Support\Arr;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class SqsConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
$config = $this->getDefaultConfiguration($config);
|
||||
|
||||
if ($credentials = $this->resolveCredentialProvider($config)) {
|
||||
$config['credentials'] = $credentials;
|
||||
} elseif (! empty($config['key']) && ! empty($config['secret'])) {
|
||||
$config['credentials'] = Arr::only($config, ['key', 'secret']);
|
||||
|
||||
if (! empty($config['token'])) {
|
||||
$config['credentials']['token'] = $config['token'];
|
||||
}
|
||||
}
|
||||
|
||||
return new SqsQueue(
|
||||
new SqsClient(
|
||||
Arr::except($config, ['token'])
|
||||
),
|
||||
$config['queue'],
|
||||
$config['prefix'] ?? '',
|
||||
$config['suffix'] ?? '',
|
||||
$config['after_commit'] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a credential provider from the given config.
|
||||
*
|
||||
* @param array $config
|
||||
* @return callable|null
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
protected function resolveCredentialProvider(array $config)
|
||||
{
|
||||
$credentials = $config['credentials'] ?? null;
|
||||
|
||||
$provider = is_string($credentials) ? $credentials : ($credentials['provider'] ?? null);
|
||||
|
||||
if (is_null($provider)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$options = is_array($credentials) ? Arr::except($credentials, ['provider']) : [];
|
||||
|
||||
return match ($provider) {
|
||||
'ecs' => CredentialProvider::ecsCredentials($options),
|
||||
'instance' => CredentialProvider::instanceProfile($options),
|
||||
default => throw new InvalidArgumentException(
|
||||
"Invalid credential provider [{$provider}]."
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default configuration for SQS.
|
||||
*
|
||||
* @param array $config
|
||||
* @return array
|
||||
*/
|
||||
protected function getDefaultConfiguration(array $config)
|
||||
{
|
||||
return array_merge([
|
||||
'version' => 'latest',
|
||||
'http' => [
|
||||
'timeout' => 60,
|
||||
'connect_timeout' => 60,
|
||||
],
|
||||
], $config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Connectors;
|
||||
|
||||
use Illuminate\Queue\SyncQueue;
|
||||
|
||||
class SyncConnector implements ConnectorInterface
|
||||
{
|
||||
/**
|
||||
* Establish a queue connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connect(array $config)
|
||||
{
|
||||
return new SyncQueue($config['after_commit'] ?? null);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\MigrationGeneratorCommand;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
use function Illuminate\Filesystem\join_paths;
|
||||
|
||||
#[AsCommand(name: 'make:queue-batches-table', aliases: ['queue:batches-table'])]
|
||||
class BatchesTableCommand extends MigrationGeneratorCommand
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'make:queue-batches-table';
|
||||
|
||||
/**
|
||||
* The console command name aliases.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aliases = ['queue:batches-table'];
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Create a migration for the batches database table';
|
||||
|
||||
/**
|
||||
* Get the migration table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationTableName()
|
||||
{
|
||||
return $this->laravel['config']['queue.batching.table'] ?? 'job_batches';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the migration stub file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationStubFile()
|
||||
{
|
||||
return __DIR__.'/stubs/batches.stub';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a migration for the table already exists.
|
||||
*
|
||||
* @param string $table
|
||||
* @return bool
|
||||
*/
|
||||
protected function migrationExists($table)
|
||||
{
|
||||
if ($table !== 'job_batches') {
|
||||
return parent::migrationExists($table);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
join_paths($this->laravel->databasePath('migrations'), '*_*_*_*_create_'.$table.'_table.php'),
|
||||
join_paths($this->laravel->databasePath('migrations'), '0001_01_01_000002_create_jobs_table.php'),
|
||||
] as $path) {
|
||||
if (count($this->files->glob($path)) !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Console\ConfirmableTrait;
|
||||
use Illuminate\Contracts\Queue\ClearableQueue;
|
||||
use Illuminate\Support\Str;
|
||||
use ReflectionClass;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
|
||||
#[AsCommand(name: 'queue:clear')]
|
||||
class ClearCommand extends Command
|
||||
{
|
||||
use ConfirmableTrait;
|
||||
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'queue:clear';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Delete all of the jobs from the specified queue';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
if (! $this->confirmToProceed()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
$connection = $this->argument('connection')
|
||||
?: $this->laravel['config']['queue.default'];
|
||||
|
||||
// We need to get the right queue for the connection which is set in the queue
|
||||
// configuration file for the application. We will pull it based on the set
|
||||
// connection being run for the queue operation currently being executed.
|
||||
$queueName = $this->getQueue($connection);
|
||||
|
||||
$queue = $this->laravel['queue']->connection($connection);
|
||||
|
||||
if ($queue instanceof ClearableQueue) {
|
||||
$count = $queue->clear($queueName);
|
||||
|
||||
$this->components->info('Cleared '.$count.' '.Str::plural('job', $count).' from the ['.$queueName.'] queue');
|
||||
} else {
|
||||
$this->components->error('Clearing queues is not supported on ['.(new ReflectionClass($queue))->getShortName().']');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue name to clear.
|
||||
*
|
||||
* @param string $connection
|
||||
* @return string
|
||||
*/
|
||||
protected function getQueue($connection)
|
||||
{
|
||||
return $this->option('queue') ?: $this->laravel['config']->get(
|
||||
"queue.connections.{$connection}.queue", 'default'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the console command arguments.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getArguments()
|
||||
{
|
||||
return [
|
||||
['connection', InputArgument::OPTIONAL, 'The name of the queue connection to clear'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the console command options.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getOptions()
|
||||
{
|
||||
return [
|
||||
['queue', null, InputOption::VALUE_OPTIONAL, 'The name of the queue to clear'],
|
||||
|
||||
['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'],
|
||||
];
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console\Concerns;
|
||||
|
||||
trait ParsesQueue
|
||||
{
|
||||
/**
|
||||
* Parse the queue argument into connection and queue name.
|
||||
*
|
||||
* @param string $queue
|
||||
* @return array{string, string}
|
||||
*/
|
||||
protected function parseQueue($queue)
|
||||
{
|
||||
[$connection, $queue] = array_pad(explode(':', $queue, 2), -2, null);
|
||||
|
||||
return [
|
||||
$connection ?? $this->laravel['config']['queue.default'],
|
||||
$queue ?: 'default',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\MigrationGeneratorCommand;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
use function Illuminate\Filesystem\join_paths;
|
||||
|
||||
#[AsCommand(name: 'make:queue-failed-table', aliases: ['queue:failed-table'])]
|
||||
class FailedTableCommand extends MigrationGeneratorCommand
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'make:queue-failed-table';
|
||||
|
||||
/**
|
||||
* The console command name aliases.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aliases = ['queue:failed-table'];
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Create a migration for the failed queue jobs database table';
|
||||
|
||||
/**
|
||||
* Get the migration table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationTableName()
|
||||
{
|
||||
return $this->laravel['config']['queue.failed.table'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the migration stub file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationStubFile()
|
||||
{
|
||||
return __DIR__.'/stubs/failed_jobs.stub';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a migration for the table already exists.
|
||||
*
|
||||
* @param string $table
|
||||
* @return bool
|
||||
*/
|
||||
protected function migrationExists($table)
|
||||
{
|
||||
if ($table !== 'failed_jobs') {
|
||||
return parent::migrationExists($table);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
join_paths($this->laravel->databasePath('migrations'), '*_*_*_*_create_'.$table.'_table.php'),
|
||||
join_paths($this->laravel->databasePath('migrations'), '0001_01_01_000002_create_jobs_table.php'),
|
||||
] as $path) {
|
||||
if (count($this->files->glob($path)) !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:flush')]
|
||||
class FlushFailedCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:flush {--hours= : The number of hours to retain failed job data}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Flush all of the failed queue jobs';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->laravel['queue.failer']->flush($this->option('hours'));
|
||||
|
||||
if ($this->option('hours')) {
|
||||
$this->components->info("All jobs that failed more than {$this->option('hours')} hours ago have been deleted successfully.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->components->info('All failed jobs deleted successfully.');
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:forget')]
|
||||
class ForgetFailedCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command signature.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:forget {id : The ID of the failed job}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Delete a failed queue job';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
if ($this->laravel['queue.failer']->forget($this->argument('id'))) {
|
||||
$this->components->info('Failed job deleted successfully.');
|
||||
} else {
|
||||
$this->components->error('No failed job matches the given ID.');
|
||||
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:failed')]
|
||||
class ListFailedCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'queue:failed';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'List all of the failed queue jobs';
|
||||
|
||||
/**
|
||||
* The table headers for the command.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $headers = ['ID', 'Connection', 'Queue', 'Class', 'Failed At'];
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
if (count($jobs = $this->getFailedJobs()) === 0) {
|
||||
return $this->components->info('No failed jobs found.');
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->displayFailedJobs($jobs);
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile the failed jobs into a displayable format.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getFailedJobs()
|
||||
{
|
||||
$failed = $this->laravel['queue.failer']->all();
|
||||
|
||||
return (new Collection($failed))
|
||||
->map(fn ($failed) => $this->parseFailedJob((array) $failed))
|
||||
->filter()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the failed job row.
|
||||
*
|
||||
* @param array $failed
|
||||
* @return array
|
||||
*/
|
||||
protected function parseFailedJob(array $failed)
|
||||
{
|
||||
$row = array_values(Arr::except($failed, ['payload', 'exception']));
|
||||
|
||||
array_splice($row, 3, 0, $this->extractJobName($failed['payload']) ?: '');
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the failed job name from payload.
|
||||
*
|
||||
* @param string $payload
|
||||
* @return string|null
|
||||
*/
|
||||
private function extractJobName($payload)
|
||||
{
|
||||
$payload = json_decode($payload, true);
|
||||
|
||||
if ($payload && (! isset($payload['data']['command']))) {
|
||||
return $payload['job'] ?? null;
|
||||
} elseif ($payload && isset($payload['data']['command'])) {
|
||||
return $this->matchJobName($payload);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Match the job name from the payload.
|
||||
*
|
||||
* @param array $payload
|
||||
* @return string|null
|
||||
*/
|
||||
protected function matchJobName($payload)
|
||||
{
|
||||
preg_match('/"([^"]+)"/', $payload['data']['command'], $matches);
|
||||
|
||||
return $matches[1] ?? $payload['job'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the failed jobs in the console.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @return void
|
||||
*/
|
||||
protected function displayFailedJobs(array $jobs)
|
||||
{
|
||||
(new Collection($jobs))->each(
|
||||
fn ($job) => $this->components->twoColumnDetail(
|
||||
sprintf('<fg=gray>%s</> %s</>', $job[4], $job[0]),
|
||||
sprintf('<fg=gray>%s@%s</> %s', $job[1], $job[2], $job[3])
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Queue\Listener;
|
||||
use Illuminate\Queue\ListenerOptions;
|
||||
use Illuminate\Support\Stringable;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:listen')]
|
||||
class ListenCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:listen
|
||||
{connection? : The name of connection}
|
||||
{--name=default : The name of the worker}
|
||||
{--delay=0 : The number of seconds to delay failed jobs (Deprecated)}
|
||||
{--backoff=0 : The number of seconds to wait before retrying a job that encountered an uncaught exception}
|
||||
{--force : Force the worker to run even in maintenance mode}
|
||||
{--memory=128 : The memory limit in megabytes}
|
||||
{--queue= : The queue to listen on}
|
||||
{--sleep=3 : The number of seconds to sleep when no job is available}
|
||||
{--rest=0 : The number of seconds to rest between jobs}
|
||||
{--timeout=60 : The number of seconds a child process can run}
|
||||
{--tries=1 : The number of times to attempt a job before logging it failed}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Listen to a given queue';
|
||||
|
||||
/**
|
||||
* The queue listener instance.
|
||||
*
|
||||
* @var \Illuminate\Queue\Listener
|
||||
*/
|
||||
protected $listener;
|
||||
|
||||
/**
|
||||
* Create a new queue listen command.
|
||||
*
|
||||
* @param \Illuminate\Queue\Listener $listener
|
||||
*/
|
||||
public function __construct(Listener $listener)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->setOutputHandler($this->listener = $listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
// We need to get the right queue for the connection which is set in the queue
|
||||
// configuration file for the application. We will pull it based on the set
|
||||
// connection being run for the queue operation currently being executed.
|
||||
$queue = $this->getQueue(
|
||||
$connection = $this->input->getArgument('connection')
|
||||
);
|
||||
|
||||
$this->components->info(sprintf('Processing jobs from the [%s] %s.', $queue, (new Stringable('queue'))->plural(explode(',', $queue))));
|
||||
|
||||
$this->listener->listen(
|
||||
$connection, $queue, $this->gatherOptions()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the queue connection to listen on.
|
||||
*
|
||||
* @param string $connection
|
||||
* @return string
|
||||
*/
|
||||
protected function getQueue($connection)
|
||||
{
|
||||
$connection = $connection ?: $this->laravel['config']['queue.default'];
|
||||
|
||||
return $this->input->getOption('queue') ?: $this->laravel['config']->get(
|
||||
"queue.connections.{$connection}.queue", 'default'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the listener options for the command.
|
||||
*
|
||||
* @return \Illuminate\Queue\ListenerOptions
|
||||
*/
|
||||
protected function gatherOptions()
|
||||
{
|
||||
$backoff = $this->hasOption('backoff')
|
||||
? $this->option('backoff')
|
||||
: $this->option('delay');
|
||||
|
||||
return new ListenerOptions(
|
||||
name: $this->option('name'),
|
||||
environment: $this->option('env'),
|
||||
backoff: $backoff,
|
||||
memory: $this->option('memory'),
|
||||
timeout: $this->option('timeout'),
|
||||
sleep: $this->option('sleep'),
|
||||
rest: $this->option('rest'),
|
||||
maxTries: $this->option('tries'),
|
||||
force: $this->option('force')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the options on the queue listener.
|
||||
*
|
||||
* @param \Illuminate\Queue\Listener $listener
|
||||
* @return void
|
||||
*/
|
||||
protected function setOutputHandler(Listener $listener)
|
||||
{
|
||||
$listener->setOutputHandler(function ($type, $line) {
|
||||
$this->output->write($line);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Contracts\Queue\Factory;
|
||||
use Illuminate\Queue\Events\QueueBusy;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:monitor')]
|
||||
class MonitorCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:monitor
|
||||
{queues : The names of the queues to monitor}
|
||||
{--max=1000 : The maximum number of jobs that can be on the queue before an event is dispatched}
|
||||
{--json : Output the queue size as JSON}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Monitor the size of the specified queues';
|
||||
|
||||
/**
|
||||
* The queue manager instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Queue\Factory
|
||||
*/
|
||||
protected $manager;
|
||||
|
||||
/**
|
||||
* The events dispatcher instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Events\Dispatcher
|
||||
*/
|
||||
protected $events;
|
||||
|
||||
/**
|
||||
* Create a new queue monitor command.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Factory $manager
|
||||
* @param \Illuminate\Contracts\Events\Dispatcher $events
|
||||
*/
|
||||
public function __construct(Factory $manager, Dispatcher $events)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->manager = $manager;
|
||||
$this->events = $events;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$queues = $this->parseQueues($this->argument('queues'));
|
||||
|
||||
if ($this->option('json')) {
|
||||
$this->output->writeln((new Collection($queues))->map(function ($queue) {
|
||||
return array_merge($queue, [
|
||||
'status' => str_contains($queue['status'], 'ALERT') ? 'ALERT' : 'OK',
|
||||
]);
|
||||
})->toJson());
|
||||
} else {
|
||||
$this->displaySizes($queues);
|
||||
}
|
||||
|
||||
$this->dispatchEvents($queues);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the queues into an array of the connections and queues.
|
||||
*
|
||||
* @param string $queues
|
||||
* @return \Illuminate\Support\Collection
|
||||
*/
|
||||
protected function parseQueues($queues)
|
||||
{
|
||||
return (new Collection(explode(',', $queues)))->map(function ($queue) {
|
||||
[$connection, $queue] = array_pad(explode(':', $queue, 2), 2, null);
|
||||
|
||||
if (! isset($queue)) {
|
||||
$queue = $connection;
|
||||
$connection = $this->laravel['config']['queue.default'];
|
||||
}
|
||||
|
||||
return [
|
||||
'connection' => $connection,
|
||||
'queue' => $queue,
|
||||
'size' => $size = $this->manager->connection($connection)->size($queue),
|
||||
'pending' => method_exists($this->manager->connection($connection), 'pendingSize')
|
||||
? $this->manager->connection($connection)->pendingSize($queue)
|
||||
: null,
|
||||
'delayed' => method_exists($this->manager->connection($connection), 'delayedSize')
|
||||
? $this->manager->connection($connection)->delayedSize($queue)
|
||||
: null,
|
||||
'reserved' => method_exists($this->manager->connection($connection), 'reservedSize')
|
||||
? $this->manager->connection($connection)->reservedSize($queue)
|
||||
: null,
|
||||
'oldest_pending' => method_exists($this->manager->connection($connection), 'creationTimeOfOldestPendingJob')
|
||||
? $this->manager->connection($connection)->creationTimeOfOldestPendingJob($queue)
|
||||
: null,
|
||||
'status' => $size >= $this->option('max') ? '<fg=yellow;options=bold>ALERT</>' : '<fg=green;options=bold>OK</>',
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the queue sizes in the console.
|
||||
*
|
||||
* @param \Illuminate\Support\Collection $queues
|
||||
* @return void
|
||||
*/
|
||||
protected function displaySizes(Collection $queues)
|
||||
{
|
||||
$this->newLine();
|
||||
|
||||
$this->components->twoColumnDetail('<fg=gray>Queue name</>', '<fg=gray>Size / Status</>');
|
||||
|
||||
$queues->each(function ($queue) {
|
||||
$name = '['.$queue['connection'].'] '.$queue['queue'];
|
||||
$status = '['.$queue['size'].'] '.$queue['status'];
|
||||
|
||||
$this->components->twoColumnDetail($name, $status);
|
||||
$this->components->twoColumnDetail('Pending jobs', $queue['pending'] ?? 'N/A');
|
||||
$this->components->twoColumnDetail('Delayed jobs', $queue['delayed'] ?? 'N/A');
|
||||
$this->components->twoColumnDetail('Reserved jobs', $queue['reserved'] ?? 'N/A');
|
||||
$this->components->twoColumnDetail('Oldest pending job', $queue['oldest_pending']
|
||||
? Carbon::createFromTimestamp($queue['oldest_pending'])->diffForHumans()
|
||||
: 'N/A'
|
||||
);
|
||||
$this->line('');
|
||||
});
|
||||
|
||||
$this->newLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire the monitoring events.
|
||||
*
|
||||
* @param \Illuminate\Support\Collection $queues
|
||||
* @return void
|
||||
*/
|
||||
protected function dispatchEvents(Collection $queues)
|
||||
{
|
||||
foreach ($queues as $queue) {
|
||||
if ($queue['status'] == '<fg=green;options=bold>OK</>') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->events->dispatch(
|
||||
new QueueBusy(
|
||||
$queue['connection'],
|
||||
$queue['queue'],
|
||||
$queue['size'],
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Queue\Factory as QueueManager;
|
||||
use Illuminate\Queue\Console\Concerns\ParsesQueue;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:pause')]
|
||||
class PauseCommand extends Command
|
||||
{
|
||||
use ParsesQueue;
|
||||
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:pause {queue : The name of the queue to pause}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Pause job processing for a specific queue';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle(QueueManager $manager)
|
||||
{
|
||||
[$connection, $queue] = $this->parseQueue($this->argument('queue'));
|
||||
|
||||
$manager->pause($connection, $queue);
|
||||
|
||||
$this->components->info("Job processing on queue [{$connection}:{$queue}] has been paused.");
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Bus\BatchRepository;
|
||||
use Illuminate\Bus\DatabaseBatchRepository;
|
||||
use Illuminate\Bus\PrunableBatchRepository;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:prune-batches')]
|
||||
class PruneBatchesCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command signature.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:prune-batches
|
||||
{--hours=24 : The number of hours to retain batch data}
|
||||
{--unfinished= : The number of hours to retain unfinished batch data }
|
||||
{--cancelled= : The number of hours to retain cancelled batch data }';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Prune stale entries from the batches database';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$repository = $this->laravel[BatchRepository::class];
|
||||
|
||||
$count = 0;
|
||||
|
||||
if ($repository instanceof PrunableBatchRepository) {
|
||||
$count = $repository->prune(Carbon::now()->subHours($this->option('hours')));
|
||||
}
|
||||
|
||||
$this->components->info("{$count} entries deleted.");
|
||||
|
||||
if ($this->option('unfinished') !== null) {
|
||||
$count = 0;
|
||||
|
||||
if ($repository instanceof DatabaseBatchRepository) {
|
||||
$count = $repository->pruneUnfinished(Carbon::now()->subHours($this->option('unfinished')));
|
||||
}
|
||||
|
||||
$this->components->info("{$count} unfinished entries deleted.");
|
||||
}
|
||||
|
||||
if ($this->option('cancelled') !== null) {
|
||||
$count = 0;
|
||||
|
||||
if ($repository instanceof DatabaseBatchRepository) {
|
||||
$count = $repository->pruneCancelled(Carbon::now()->subHours($this->option('cancelled')));
|
||||
}
|
||||
|
||||
$this->components->info("{$count} cancelled entries deleted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Queue\Failed\PrunableFailedJobProvider;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:prune-failed')]
|
||||
class PruneFailedJobsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command signature.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:prune-failed
|
||||
{--hours=24 : The number of hours to retain failed jobs data}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Prune stale entries from the failed jobs table';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$failer = $this->laravel['queue.failer'];
|
||||
|
||||
if ($failer instanceof PrunableFailedJobProvider) {
|
||||
$count = $failer->prune(Carbon::now()->subHours($this->option('hours')));
|
||||
} else {
|
||||
$this->components->error('The ['.class_basename($failer).'] failed job storage driver does not support pruning.');
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$this->components->info("{$count} entries deleted.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Cache\Repository as Cache;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:restart')]
|
||||
class RestartCommand extends Command
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'queue:restart';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Restart queue worker daemons after their current job';
|
||||
|
||||
/**
|
||||
* The cache store implementation.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Cache\Repository
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* Create a new queue restart command.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Cache\Repository $cache
|
||||
*/
|
||||
public function __construct(Cache $cache)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->cache = $cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->cache->forever('illuminate:queue:restart', $this->currentTime());
|
||||
|
||||
$this->components->info('Broadcasting queue restart signal.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Queue\Factory as QueueManager;
|
||||
use Illuminate\Queue\Console\Concerns\ParsesQueue;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:resume', aliases: ['queue:continue'])]
|
||||
class ResumeCommand extends Command
|
||||
{
|
||||
use ParsesQueue;
|
||||
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:resume {queue : The name of the queue that should resume processing}';
|
||||
|
||||
/**
|
||||
* The console command name aliases.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected $aliases = ['queue:continue'];
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Resume job processing for a paused queue';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle(QueueManager $manager)
|
||||
{
|
||||
[$connection, $queue] = $this->parseQueue($this->argument('queue'));
|
||||
|
||||
$manager->resume($connection, $queue);
|
||||
|
||||
$this->components->info("Job processing on queue [{$connection}:{$queue}] has been resumed.");
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Bus\BatchRepository;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Console\Isolatable;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:retry-batch')]
|
||||
class RetryBatchCommand extends Command implements Isolatable
|
||||
{
|
||||
/**
|
||||
* The console command signature.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:retry-batch
|
||||
{id?* : The ID of the batch whose failed jobs should be retried}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Retry the failed jobs for a batch';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$batchesFound = count($ids = $this->getBatchJobIds()) > 0;
|
||||
|
||||
if ($batchesFound) {
|
||||
$this->components->info('Pushing failed batch jobs back onto the queue.');
|
||||
}
|
||||
|
||||
foreach ($ids as $batchId) {
|
||||
$batch = $this->laravel[BatchRepository::class]->find($batchId);
|
||||
|
||||
if (! $batch) {
|
||||
$this->components->error("Unable to find a batch with ID [{$batchId}].");
|
||||
} elseif (empty($batch->failedJobIds)) {
|
||||
$this->components->error('The given batch does not contain any failed jobs.');
|
||||
}
|
||||
|
||||
$this->components->info("Pushing failed queue jobs of the batch [$batchId] back onto the queue.");
|
||||
|
||||
foreach ($batch->failedJobIds as $failedJobId) {
|
||||
$this->components->task(
|
||||
$failedJobId,
|
||||
fn () => $this->callSilent('queue:retry', ['id' => $failedJobId]) == 0
|
||||
);
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the custom mutex name for an isolated command.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function isolatableId()
|
||||
{
|
||||
return $this->argument('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the batch IDs to be retried.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getBatchJobIds()
|
||||
{
|
||||
$ids = (array) $this->argument('id');
|
||||
|
||||
return array_values(array_filter(array_unique($ids)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
use Illuminate\Queue\Events\JobRetryRequested;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'queue:retry')]
|
||||
class RetryCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The console command signature.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:retry
|
||||
{id?* : The ID of the failed job or "all" to retry all jobs}
|
||||
{--queue= : Retry all of the failed jobs for the specified queue}
|
||||
{--range=* : Range of job IDs (numeric) to be retried (e.g. 1-5)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Retry a failed queue job';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$jobsFound = count($ids = $this->getJobIds()) > 0;
|
||||
|
||||
if ($jobsFound) {
|
||||
$this->components->info('Pushing failed queue jobs back onto the queue.');
|
||||
}
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$job = $this->laravel['queue.failer']->find($id);
|
||||
|
||||
if (is_null($job)) {
|
||||
$this->components->error("Unable to find failed job with ID [{$id}].");
|
||||
} else {
|
||||
$this->laravel['events']->dispatch(new JobRetryRequested($job));
|
||||
|
||||
$this->components->task($id, fn () => $this->retryJob($job));
|
||||
|
||||
$this->laravel['queue.failer']->forget($id);
|
||||
}
|
||||
}
|
||||
|
||||
$jobsFound ? $this->newLine() : $this->components->info('No retryable jobs found.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job IDs to be retried.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getJobIds()
|
||||
{
|
||||
$ids = (array) $this->argument('id');
|
||||
|
||||
if (count($ids) === 1 && $ids[0] === 'all') {
|
||||
$failer = $this->laravel['queue.failer'];
|
||||
|
||||
return method_exists($failer, 'ids')
|
||||
? $failer->ids()
|
||||
: Arr::pluck($failer->all(), 'id');
|
||||
}
|
||||
|
||||
if ($queue = $this->option('queue')) {
|
||||
return $this->getJobIdsByQueue($queue);
|
||||
}
|
||||
|
||||
if ($ranges = (array) $this->option('range')) {
|
||||
$ids = array_merge($ids, $this->getJobIdsByRanges($ranges));
|
||||
}
|
||||
|
||||
return array_values(array_filter(array_unique($ids)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job IDs by queue, if applicable.
|
||||
*
|
||||
* @param string $queue
|
||||
* @return array
|
||||
*/
|
||||
protected function getJobIdsByQueue($queue)
|
||||
{
|
||||
$failer = $this->laravel['queue.failer'];
|
||||
|
||||
$ids = method_exists($failer, 'ids')
|
||||
? $failer->ids($queue)
|
||||
: (new Collection($failer->all()))
|
||||
->where('queue', $queue)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
|
||||
if (count($ids) === 0) {
|
||||
$this->components->error("Unable to find failed jobs for queue [{$queue}].");
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job IDs ranges, if applicable.
|
||||
*
|
||||
* @param array $ranges
|
||||
* @return array
|
||||
*/
|
||||
protected function getJobIdsByRanges(array $ranges)
|
||||
{
|
||||
$ids = [];
|
||||
|
||||
foreach ($ranges as $range) {
|
||||
if (preg_match('/^[0-9]+\-[0-9]+$/', $range)) {
|
||||
$ids = array_merge($ids, range(...explode('-', $range)));
|
||||
}
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry the queue job.
|
||||
*
|
||||
* @param \stdClass $job
|
||||
* @return void
|
||||
*/
|
||||
protected function retryJob($job)
|
||||
{
|
||||
$queue = $this->laravel['queue']->connection($job->connection);
|
||||
|
||||
$this->laravel['queue']->connection($job->connection)->pushRaw(
|
||||
$this->refreshRetryUntil($this->resetAttempts($job->payload)),
|
||||
$job->queue,
|
||||
$this->getQueueableOptions($queue, $job)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the payload attempts.
|
||||
*
|
||||
* Applicable to Redis and other jobs which store attempts in their payload.
|
||||
*
|
||||
* @param string $payload
|
||||
* @return string
|
||||
*/
|
||||
protected function resetAttempts($payload)
|
||||
{
|
||||
$payload = json_decode($payload, true);
|
||||
|
||||
if (isset($payload['attempts'])) {
|
||||
$payload['attempts'] = 0;
|
||||
}
|
||||
|
||||
return json_encode($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the "retry until" timestamp for the job.
|
||||
*
|
||||
* @param string $payload
|
||||
* @return string
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
protected function refreshRetryUntil($payload)
|
||||
{
|
||||
$payload = json_decode($payload, true);
|
||||
|
||||
if (! isset($payload['data']['command'])) {
|
||||
return json_encode($payload);
|
||||
}
|
||||
|
||||
$instance = $this->getInstanceFromPayload($payload);
|
||||
|
||||
if (is_object($instance) && ! $instance instanceof \__PHP_Incomplete_Class && method_exists($instance, 'retryUntil')) {
|
||||
$retryUntil = $instance->retryUntil();
|
||||
|
||||
$payload['retryUntil'] = $retryUntil instanceof DateTimeInterface
|
||||
? $retryUntil->getTimestamp()
|
||||
: $retryUntil;
|
||||
}
|
||||
|
||||
return json_encode($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queueable options from the job.
|
||||
*
|
||||
* @param $queue
|
||||
* @param \stdClass $job
|
||||
* @return array
|
||||
*/
|
||||
protected function getQueueableOptions($queue, $job)
|
||||
{
|
||||
if (! method_exists($queue, 'getQueueableOptions')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$payload = json_decode($job->payload, true);
|
||||
|
||||
if (! isset($payload['data']['command'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $queue->getQueueableOptions($this->getInstanceFromPayload($payload), $job->queue, $job->payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job instance from the given payload.
|
||||
*
|
||||
* @param array $payload
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
protected function getInstanceFromPayload($payload)
|
||||
{
|
||||
if (str_starts_with($payload['data']['command'], 'O:')) {
|
||||
return unserialize($payload['data']['command']);
|
||||
}
|
||||
|
||||
if ($this->laravel->bound(Encrypter::class)) {
|
||||
return unserialize($this->laravel->make(Encrypter::class)->decrypt($payload['data']['command']));
|
||||
}
|
||||
|
||||
throw new RuntimeException('Unable to extract job payload.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\MigrationGeneratorCommand;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
use function Illuminate\Filesystem\join_paths;
|
||||
|
||||
#[AsCommand(name: 'make:queue-table', aliases: ['queue:table'])]
|
||||
class TableCommand extends MigrationGeneratorCommand
|
||||
{
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'make:queue-table';
|
||||
|
||||
/**
|
||||
* The console command name aliases.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $aliases = ['queue:table'];
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Create a migration for the queue jobs database table';
|
||||
|
||||
/**
|
||||
* Get the migration table name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationTableName()
|
||||
{
|
||||
return $this->laravel['config']['queue.connections.database.table'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the migration stub file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function migrationStubFile()
|
||||
{
|
||||
return __DIR__.'/stubs/jobs.stub';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a migration for the table already exists.
|
||||
*
|
||||
* @param string $table
|
||||
* @return bool
|
||||
*/
|
||||
protected function migrationExists($table)
|
||||
{
|
||||
if ($table !== 'jobs') {
|
||||
return parent::migrationExists($table);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
join_paths($this->laravel->databasePath('migrations'), '*_*_*_*_create_'.$table.'_table.php'),
|
||||
join_paths($this->laravel->databasePath('migrations'), '0001_01_01_000002_create_jobs_table.php'),
|
||||
] as $path) {
|
||||
if (count($this->files->glob($path)) !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Contracts\Cache\Repository as Cache;
|
||||
use Illuminate\Contracts\Queue\Job;
|
||||
use Illuminate\Queue\Events\JobFailed;
|
||||
use Illuminate\Queue\Events\JobProcessed;
|
||||
use Illuminate\Queue\Events\JobProcessing;
|
||||
use Illuminate\Queue\Events\JobReleasedAfterException;
|
||||
use Illuminate\Queue\Worker;
|
||||
use Illuminate\Queue\WorkerOptions;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use Illuminate\Support\Stringable;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Terminal;
|
||||
use Throwable;
|
||||
|
||||
use function Termwind\terminal;
|
||||
|
||||
#[AsCommand(name: 'queue:work')]
|
||||
class WorkCommand extends Command
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The console command name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'queue:work
|
||||
{connection? : The name of the queue connection to work}
|
||||
{--name=default : The name of the worker}
|
||||
{--queue= : The names of the queues to work}
|
||||
{--daemon : Run the worker in daemon mode (Deprecated)}
|
||||
{--once : Only process the next job on the queue}
|
||||
{--stop-when-empty : Stop when the queue is empty}
|
||||
{--delay=0 : The number of seconds to delay failed jobs (Deprecated)}
|
||||
{--backoff=0 : The number of seconds to wait before retrying a job that encountered an uncaught exception}
|
||||
{--max-jobs=0 : The number of jobs to process before stopping}
|
||||
{--max-time=0 : The maximum number of seconds the worker should run}
|
||||
{--force : Force the worker to run even in maintenance mode}
|
||||
{--memory=128 : The memory limit in megabytes}
|
||||
{--sleep=3 : The number of seconds to sleep when no job is available}
|
||||
{--rest=0 : The number of seconds to rest between jobs}
|
||||
{--timeout=60 : The number of seconds a child process can run}
|
||||
{--tries=1 : The number of times to attempt a job before logging it failed}
|
||||
{--json : Output the queue worker information as JSON}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Start processing jobs on the queue as a daemon';
|
||||
|
||||
/**
|
||||
* The queue worker instance.
|
||||
*
|
||||
* @var \Illuminate\Queue\Worker
|
||||
*/
|
||||
protected $worker;
|
||||
|
||||
/**
|
||||
* The cache store implementation.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Cache\Repository
|
||||
*/
|
||||
protected $cache;
|
||||
|
||||
/**
|
||||
* Holds the start time of the last processed job, if any.
|
||||
*
|
||||
* @var float|null
|
||||
*/
|
||||
protected $latestStartedAt;
|
||||
|
||||
/**
|
||||
* Indicates if the worker's event listeners have been registered.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private static $hasRegisteredListeners = false;
|
||||
|
||||
/**
|
||||
* Create a new queue work command.
|
||||
*
|
||||
* @param \Illuminate\Queue\Worker $worker
|
||||
* @param \Illuminate\Contracts\Cache\Repository $cache
|
||||
*/
|
||||
public function __construct(Worker $worker, Cache $cache)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->cache = $cache;
|
||||
$this->worker = $worker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
if ($this->downForMaintenance() && $this->option('once')) {
|
||||
return $this->worker->sleep($this->option('sleep'));
|
||||
}
|
||||
|
||||
// We'll listen to the processed and failed events so we can write information
|
||||
// to the console as jobs are processed, which will let the developer watch
|
||||
// which jobs are coming through a queue and be informed on its progress.
|
||||
$this->listenForEvents();
|
||||
|
||||
$connection = $this->argument('connection')
|
||||
?: $this->laravel['config']['queue.default'];
|
||||
|
||||
// We need to get the right queue for the connection which is set in the queue
|
||||
// configuration file for the application. We will pull it based on the set
|
||||
// connection being run for the queue operation currently being executed.
|
||||
$queue = $this->getQueue($connection);
|
||||
|
||||
if (! $this->outputUsingJson() && Terminal::hasSttyAvailable()) {
|
||||
$this->components->info(
|
||||
sprintf('Processing jobs from the [%s] %s.', $queue, (new Stringable('queue'))->plural(explode(',', $queue)))
|
||||
);
|
||||
}
|
||||
|
||||
return $this->runWorker(
|
||||
$connection, $queue
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the worker instance.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @return int|null
|
||||
*/
|
||||
protected function runWorker($connection, $queue)
|
||||
{
|
||||
return $this->worker
|
||||
->setName($this->option('name'))
|
||||
->setCache($this->cache)
|
||||
->{$this->option('once') ? 'runNextJob' : 'daemon'}(
|
||||
$connection, $queue, $this->gatherWorkerOptions()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gather all of the queue worker options as a single object.
|
||||
*
|
||||
* @return \Illuminate\Queue\WorkerOptions
|
||||
*/
|
||||
protected function gatherWorkerOptions()
|
||||
{
|
||||
return new WorkerOptions(
|
||||
$this->option('name'),
|
||||
max($this->option('backoff'), $this->option('delay')),
|
||||
$this->option('memory'),
|
||||
$this->option('timeout'),
|
||||
$this->option('sleep'),
|
||||
$this->option('tries'),
|
||||
$this->option('force'),
|
||||
$this->option('stop-when-empty'),
|
||||
$this->option('max-jobs'),
|
||||
$this->option('max-time'),
|
||||
$this->option('rest'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for the queue events in order to update the console output.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function listenForEvents()
|
||||
{
|
||||
if (static::$hasRegisteredListeners) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->laravel['events']->listen(JobProcessing::class, function ($event) {
|
||||
$this->writeOutput($event->job, 'starting');
|
||||
});
|
||||
|
||||
$this->laravel['events']->listen(JobProcessed::class, function ($event) {
|
||||
$this->writeOutput($event->job, 'success');
|
||||
});
|
||||
|
||||
$this->laravel['events']->listen(JobReleasedAfterException::class, function ($event) {
|
||||
$this->writeOutput($event->job, 'released_after_exception');
|
||||
});
|
||||
|
||||
$this->laravel['events']->listen(JobFailed::class, function ($event) {
|
||||
$this->writeOutput($event->job, 'failed', $event->exception);
|
||||
|
||||
$this->logFailedJob($event);
|
||||
});
|
||||
|
||||
static::$hasRegisteredListeners = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the status output for the queue worker for JSON or TTY.
|
||||
*
|
||||
* @param Job $job
|
||||
* @param string $status
|
||||
* @param \Throwable|null $exception
|
||||
* @return void
|
||||
*/
|
||||
protected function writeOutput(Job $job, $status, ?Throwable $exception = null)
|
||||
{
|
||||
if ($this->output->isQuiet() || $this->output->isSilent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->outputUsingJson()
|
||||
? $this->writeOutputAsJson($job, $status, $exception)
|
||||
: $this->writeOutputForCli($job, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the status output for the queue worker.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param string $status
|
||||
* @return void
|
||||
*/
|
||||
protected function writeOutputForCli(Job $job, $status)
|
||||
{
|
||||
$isVerbose = $this->output->isVerbose();
|
||||
|
||||
$this->output->write(rtrim(sprintf(
|
||||
' <fg=gray>%s</> %s %s',
|
||||
$this->now()->format('Y-m-d H:i:s'),
|
||||
$job->resolveName(),
|
||||
$isVerbose
|
||||
? sprintf('<fg=gray>%s</> <fg=blue>%s</> <fg=blue>%s</>', $job->getJobId(), $job->getConnectionName(), $job->getQueue())
|
||||
: ''
|
||||
)));
|
||||
|
||||
if ($status == 'starting') {
|
||||
$this->latestStartedAt = microtime(true);
|
||||
|
||||
$dots = max(terminal()->width() - mb_strlen($job->resolveName()) - (
|
||||
$isVerbose ? mb_strlen($job->getJobId()) + mb_strlen($job->getConnectionName()) + mb_strlen($job->getQueue()) + 2 : 0
|
||||
) - 33, 0);
|
||||
|
||||
$this->output->write(' '.str_repeat('<fg=gray>.</>', $dots));
|
||||
|
||||
return $this->output->writeln(' <fg=yellow;options=bold>RUNNING</>');
|
||||
}
|
||||
|
||||
$runTime = $this->runTimeForHumans($this->latestStartedAt);
|
||||
|
||||
$dots = max(terminal()->width() - mb_strlen($job->resolveName()) - (
|
||||
$isVerbose ? mb_strlen($job->getJobId()) + mb_strlen($job->getConnectionName()) + mb_strlen($job->getQueue()) + 2 : 0
|
||||
) - mb_strlen($runTime) - 31, 0);
|
||||
|
||||
$this->output->write(' '.str_repeat('<fg=gray>.</>', $dots));
|
||||
$this->output->write(" <fg=gray>$runTime</>");
|
||||
|
||||
$this->output->writeln(match ($status) {
|
||||
'success' => ' <fg=green;options=bold>DONE</>',
|
||||
'released_after_exception' => ' <fg=yellow;options=bold>FAIL</>',
|
||||
default => ' <fg=red;options=bold>FAIL</>',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the status output for the queue worker in JSON format.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @param string $status
|
||||
* @param \Throwable|null $exception
|
||||
* @return void
|
||||
*/
|
||||
protected function writeOutputAsJson(Job $job, $status, ?Throwable $exception = null)
|
||||
{
|
||||
$log = array_filter([
|
||||
'level' => $status === 'starting' || $status === 'success' ? 'info' : 'warning',
|
||||
'id' => $job->getJobId(),
|
||||
'uuid' => $job->uuid(),
|
||||
'connection' => $job->getConnectionName(),
|
||||
'queue' => $job->getQueue(),
|
||||
'job' => $job->resolveName(),
|
||||
'status' => $status,
|
||||
'result' => match (true) {
|
||||
$job->isDeleted() => 'deleted',
|
||||
$job->isReleased() => 'released',
|
||||
$job->hasFailed() => 'failed',
|
||||
default => '',
|
||||
},
|
||||
'attempts' => $job->attempts(),
|
||||
'exception' => $exception ? $exception::class : '',
|
||||
'message' => $exception?->getMessage(),
|
||||
'timestamp' => $this->now()->format('Y-m-d\TH:i:s.uP'),
|
||||
]);
|
||||
|
||||
if ($status === 'starting') {
|
||||
$this->latestStartedAt = microtime(true);
|
||||
} else {
|
||||
$log['duration'] = round(microtime(true) - $this->latestStartedAt, 6);
|
||||
}
|
||||
|
||||
$this->output->writeln(json_encode($log));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current date / time.
|
||||
*
|
||||
* @return \Illuminate\Support\Carbon
|
||||
*/
|
||||
protected function now()
|
||||
{
|
||||
$queueTimezone = $this->laravel['config']->get('queue.output_timezone');
|
||||
|
||||
if ($queueTimezone &&
|
||||
$queueTimezone !== $this->laravel['config']->get('app.timezone')) {
|
||||
return Carbon::now()->setTimezone($queueTimezone);
|
||||
}
|
||||
|
||||
return Carbon::now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a failed job event.
|
||||
*
|
||||
* @param \Illuminate\Queue\Events\JobFailed $event
|
||||
* @return void
|
||||
*/
|
||||
protected function logFailedJob(JobFailed $event)
|
||||
{
|
||||
$this->laravel['queue.failer']->log(
|
||||
$event->connectionName,
|
||||
$event->job->getQueue(),
|
||||
$event->job->getRawBody(),
|
||||
$event->exception
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue name for the worker.
|
||||
*
|
||||
* @param string $connection
|
||||
* @return string
|
||||
*/
|
||||
protected function getQueue($connection)
|
||||
{
|
||||
return $this->option('queue') ?: $this->laravel['config']->get(
|
||||
"queue.connections.{$connection}.queue", 'default'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the worker should run in maintenance mode.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function downForMaintenance()
|
||||
{
|
||||
return $this->option('force') ? false : $this->laravel->isDownForMaintenance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the worker should output using JSON.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function outputUsingJson()
|
||||
{
|
||||
if (! $this->hasOption('json')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->option('json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset static variables.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function flushState()
|
||||
{
|
||||
static::$hasRegisteredListeners = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('{{table}}', function (Blueprint $table) {
|
||||
$table->string('id')->primary();
|
||||
$table->string('name');
|
||||
$table->integer('total_jobs');
|
||||
$table->integer('pending_jobs');
|
||||
$table->integer('failed_jobs');
|
||||
$table->longText('failed_job_ids');
|
||||
$table->mediumText('options')->nullable();
|
||||
$table->integer('cancelled_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('finished_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('{{table}}');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('{{table}}', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('uuid')->unique();
|
||||
$table->text('connection');
|
||||
$table->text('queue');
|
||||
$table->longText('payload');
|
||||
$table->longText('exception');
|
||||
$table->timestamp('failed_at')->useCurrent();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('{{table}}');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('{{table}}', function (Blueprint $table) {
|
||||
$table->bigIncrements('id');
|
||||
$table->string('queue')->index();
|
||||
$table->longText('payload');
|
||||
$table->unsignedTinyInteger('attempts');
|
||||
$table->unsignedInteger('reserved_at')->nullable();
|
||||
$table->unsignedInteger('available_at');
|
||||
$table->unsignedInteger('created_at');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('{{table}}');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,500 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Queue\ClearableQueue;
|
||||
use Illuminate\Contracts\Queue\Queue as QueueContract;
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Queue\Jobs\DatabaseJob;
|
||||
use Illuminate\Queue\Jobs\DatabaseJobRecord;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Support\Stringable;
|
||||
use PDO;
|
||||
use Throwable;
|
||||
|
||||
class DatabaseQueue extends Queue implements QueueContract, ClearableQueue
|
||||
{
|
||||
/**
|
||||
* The database connection instance.
|
||||
*
|
||||
* @var \Illuminate\Database\Connection
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The database table that holds the jobs.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* The name of the default queue.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $default;
|
||||
|
||||
/**
|
||||
* The expiration time of a job.
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected $retryAfter = 60;
|
||||
|
||||
/**
|
||||
* Create a new database queue instance.
|
||||
*
|
||||
* @param \Illuminate\Database\Connection $database
|
||||
* @param string $table
|
||||
* @param string $default
|
||||
* @param int $retryAfter
|
||||
* @param bool $dispatchAfterCommit
|
||||
*/
|
||||
public function __construct(
|
||||
Connection $database,
|
||||
$table,
|
||||
$default = 'default',
|
||||
$retryAfter = 60,
|
||||
$dispatchAfterCommit = false,
|
||||
) {
|
||||
$this->table = $table;
|
||||
$this->default = $default;
|
||||
$this->database = $database;
|
||||
$this->retryAfter = $retryAfter;
|
||||
$this->dispatchAfterCommit = $dispatchAfterCommit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function size($queue = null)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of pending jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function pendingSize($queue = null)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->whereNull('reserved_at')
|
||||
->where('available_at', '<=', $this->currentTime())
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function delayedSize($queue = null)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->whereNull('reserved_at')
|
||||
->where('available_at', '>', $this->currentTime())
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of reserved jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function reservedSize($queue = null)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->whereNotNull('reserved_at')
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int|null
|
||||
*/
|
||||
public function creationTimeOfOldestPendingJob($queue = null)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->whereNull('reserved_at')
|
||||
->where('available_at', '<=', $this->currentTime())
|
||||
->oldest('available_at')
|
||||
->value('available_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data),
|
||||
$queue,
|
||||
null,
|
||||
function ($payload, $queue) {
|
||||
return $this->pushToDatabase($queue, $payload);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload onto the queue.
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @param array $options
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushRaw($payload, $queue = null, array $options = [])
|
||||
{
|
||||
return $this->pushToDatabase($queue, $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function later($delay, $job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data, $delay),
|
||||
$queue,
|
||||
$delay,
|
||||
function ($payload, $queue, $delay) {
|
||||
return $this->pushToDatabase($queue, $payload, $delay);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push an array of jobs onto the queue.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function bulk($jobs, $data = '', $queue = null)
|
||||
{
|
||||
$queue = $this->getQueue($queue);
|
||||
|
||||
$now = $this->availableAt();
|
||||
|
||||
return $this->database->table($this->table)->insert((new Collection((array) $jobs))->map(
|
||||
function ($job) use ($queue, $data, $now) {
|
||||
return $this->buildDatabaseRecord(
|
||||
$queue,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data),
|
||||
isset($job->delay) ? $this->availableAt($job->delay) : $now,
|
||||
);
|
||||
}
|
||||
)->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a reserved job back onto the queue after (n) seconds.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
|
||||
* @param int $delay
|
||||
* @return mixed
|
||||
*/
|
||||
public function release($queue, $job, $delay)
|
||||
{
|
||||
return $this->pushToDatabase($queue, $job->payload, $delay, $job->attempts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload to the database with a given delay of (n) seconds.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @param string $payload
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param int $attempts
|
||||
* @return mixed
|
||||
*/
|
||||
protected function pushToDatabase($queue, $payload, $delay = 0, $attempts = 0)
|
||||
{
|
||||
return $this->database->table($this->table)->insertGetId($this->buildDatabaseRecord(
|
||||
$this->getQueue($queue),
|
||||
$payload,
|
||||
$this->availableAt($delay),
|
||||
$attempts
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an array to insert for the given job.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @param string $payload
|
||||
* @param int $availableAt
|
||||
* @param int $attempts
|
||||
* @return array
|
||||
*/
|
||||
protected function buildDatabaseRecord($queue, $payload, $availableAt, $attempts = 0)
|
||||
{
|
||||
return [
|
||||
'queue' => $queue,
|
||||
'attempts' => $attempts,
|
||||
'reserved_at' => null,
|
||||
'available_at' => $availableAt,
|
||||
'created_at' => $this->currentTime(),
|
||||
'payload' => $payload,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the next job off of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return \Illuminate\Contracts\Queue\Job|null
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function pop($queue = null)
|
||||
{
|
||||
$queue = $this->getQueue($queue);
|
||||
|
||||
$jobRecord = null;
|
||||
|
||||
try {
|
||||
return $this->database->transaction(function () use ($queue, &$jobRecord) {
|
||||
if ($jobRecord = $this->getNextAvailableJob($queue)) {
|
||||
return $this->marshalJob($queue, $jobRecord);
|
||||
}
|
||||
});
|
||||
} catch (Throwable $e) {
|
||||
// Potentially invalid job that we need to fail (#58978)...
|
||||
if ($jobRecord) {
|
||||
try {
|
||||
(new DatabaseJob(
|
||||
$this->container, $this, $jobRecord, $this->connectionName, $queue
|
||||
))->fail($e);
|
||||
} catch (Throwable) {
|
||||
// Ignore and throw the original exception...
|
||||
}
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next available job for the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return \Illuminate\Queue\Jobs\DatabaseJobRecord|null
|
||||
*/
|
||||
protected function getNextAvailableJob($queue)
|
||||
{
|
||||
$job = $this->database->table($this->table)
|
||||
->lock($this->getLockForPopping())
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->where(function ($query) {
|
||||
$this->isAvailable($query);
|
||||
$this->isReservedButExpired($query);
|
||||
})
|
||||
->orderBy('id', 'asc')
|
||||
->first();
|
||||
|
||||
return $job ? new DatabaseJobRecord((object) $job) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the lock required for popping the next job.
|
||||
*
|
||||
* @return string|bool
|
||||
*/
|
||||
protected function getLockForPopping()
|
||||
{
|
||||
$databaseEngine = $this->database->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
$databaseVersion = $this->database->getConfig('version') ?? $this->database->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION);
|
||||
|
||||
if ((new Stringable($databaseVersion))->contains('MariaDB')) {
|
||||
$databaseEngine = 'mariadb';
|
||||
$databaseVersion = Str::before(Str::after($databaseVersion, '5.5.5-'), '-');
|
||||
} elseif ((new Stringable($databaseVersion))->contains(['vitess', 'PlanetScale'])) {
|
||||
$databaseEngine = 'vitess';
|
||||
$databaseVersion = Str::before($databaseVersion, '-');
|
||||
}
|
||||
|
||||
if (($databaseEngine === 'mysql' && version_compare($databaseVersion, '8.0.1', '>=')) ||
|
||||
($databaseEngine === 'mariadb' && version_compare($databaseVersion, '10.6.0', '>=')) ||
|
||||
($databaseEngine === 'pgsql' && version_compare($databaseVersion, '9.5', '>=')) ||
|
||||
($databaseEngine === 'vitess' && version_compare($databaseVersion, '19.0', '>='))
|
||||
) {
|
||||
return 'FOR UPDATE SKIP LOCKED';
|
||||
}
|
||||
|
||||
if ($databaseEngine === 'sqlsrv') {
|
||||
return 'with(rowlock,updlock,readpast)';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the query to check for available jobs.
|
||||
*
|
||||
* @param \Illuminate\Database\Query\Builder $query
|
||||
* @return void
|
||||
*/
|
||||
protected function isAvailable($query)
|
||||
{
|
||||
$query->where(function ($query) {
|
||||
$query->whereNull('reserved_at')
|
||||
->where('available_at', '<=', $this->currentTime());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the query to check for jobs that are reserved but have expired.
|
||||
*
|
||||
* @param \Illuminate\Database\Query\Builder $query
|
||||
* @return void
|
||||
*/
|
||||
protected function isReservedButExpired($query)
|
||||
{
|
||||
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
|
||||
|
||||
$query->orWhere(function ($query) use ($expiration) {
|
||||
$query->where('reserved_at', '<=', $expiration);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Marshal the reserved job into a DatabaseJob instance.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
|
||||
* @return \Illuminate\Queue\Jobs\DatabaseJob
|
||||
*/
|
||||
protected function marshalJob($queue, $job)
|
||||
{
|
||||
return new DatabaseJob(
|
||||
$this->container,
|
||||
$this,
|
||||
$this->markJobAsReserved($job),
|
||||
$this->connectionName,
|
||||
$queue,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the given job ID as reserved.
|
||||
*
|
||||
* @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
|
||||
* @return \Illuminate\Queue\Jobs\DatabaseJobRecord
|
||||
*/
|
||||
protected function markJobAsReserved($job)
|
||||
{
|
||||
$this->database->table($this->table)->where('id', $job->id)->update([
|
||||
'reserved_at' => $job->touch(),
|
||||
'attempts' => $job->increment(),
|
||||
]);
|
||||
|
||||
return $job;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a reserved job from the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param string $id
|
||||
* @return void
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function deleteReserved($queue, $id)
|
||||
{
|
||||
$this->database->transaction(function () use ($id) {
|
||||
if ($this->database->table($this->table)->lockForUpdate()->find($id)) {
|
||||
$this->database->table($this->table)->where('id', $id)->delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a reserved job from the reserved queue and release it.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\Jobs\DatabaseJob $job
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function deleteAndRelease($queue, $job, $delay)
|
||||
{
|
||||
$this->database->transaction(function () use ($queue, $job, $delay) {
|
||||
if ($this->database->table($this->table)->lockForUpdate()->find($job->getJobId())) {
|
||||
$this->database->table($this->table)->where('id', $job->getJobId())->delete();
|
||||
}
|
||||
|
||||
$this->release($queue, $job->getJobRecord(), $delay);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all of the jobs from the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @return int
|
||||
*/
|
||||
public function clear($queue)
|
||||
{
|
||||
return $this->database->table($this->table)
|
||||
->where('queue', $this->getQueue($queue))
|
||||
->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue or return the default.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return string
|
||||
*/
|
||||
public function getQueue($queue)
|
||||
{
|
||||
return $queue ?: $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying database instance.
|
||||
*
|
||||
* @return \Illuminate\Database\Connection
|
||||
*/
|
||||
public function getDatabase()
|
||||
{
|
||||
return $this->database;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
class DeferredQueue extends SyncQueue
|
||||
{
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
return \Illuminate\Support\defer(fn () => parent::push($job, $data, $queue));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobAttempted
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
* @param bool $exceptionOccurred Indicates if an exception occurred while processing the job.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
public $exceptionOccurred = false,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job completed with failing or an unhandled exception occurring.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function successful(): bool
|
||||
{
|
||||
return ! $this->job->hasFailed() && ! $this->exceptionOccurred;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobExceptionOccurred
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
* @param \Throwable $exception The exception instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
public $exception,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobFailed
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
* @param \Throwable $exception The exception that caused the job to fail.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
public $exception,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobPopped
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job|null $job The job instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobPopping
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param string|null $queue The queue name.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $queue = null
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobProcessed
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobProcessing
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobQueued
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param string|null $queue The queue name.
|
||||
* @param string|int|null $id The job ID.
|
||||
* @param \Closure|string|object $job The job instance.
|
||||
* @param string $payload The job payload.
|
||||
* @param int|null $delay The amount of time the job was delayed.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $queue,
|
||||
public $id,
|
||||
public $job,
|
||||
public $payload,
|
||||
public $delay,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decoded job payload.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function payload()
|
||||
{
|
||||
return json_decode($this->payload, true, flags: JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobQueueing
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param string|null $queue The queue name.
|
||||
* @param \Closure|string|object $job The job instance.
|
||||
* @param string $payload The job payload.
|
||||
* @param int|null $delay The number of seconds the job was delayed.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $queue,
|
||||
public $job,
|
||||
public $payload,
|
||||
public $delay,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decoded job payload.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function payload()
|
||||
{
|
||||
return json_decode($this->payload, true, flags: JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobReleasedAfterException
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
* @param int|null $backoff The backoff delay.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
public $backoff = null
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobRetryRequested
|
||||
{
|
||||
/**
|
||||
* The decoded job payload.
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
protected $payload = null;
|
||||
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param \stdClass $job The job instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $job,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The job payload.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function payload()
|
||||
{
|
||||
if (is_null($this->payload)) {
|
||||
$this->payload = json_decode($this->job->payload, true);
|
||||
}
|
||||
|
||||
return $this->payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class JobTimedOut
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param \Illuminate\Contracts\Queue\Job $job The job instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $job,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class Looping
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName The connection name.
|
||||
* @param string $queue The queue name.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $queue,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class QueueBusy
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connection The connection name.
|
||||
* @param string $queue The queue name.
|
||||
* @param int $size The size of the queue.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connection,
|
||||
public $queue,
|
||||
public $size,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
use Throwable;
|
||||
|
||||
class QueueFailedOver
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string|null $connectionName The queue connection that failed.
|
||||
* @param \Closure|string|object $command The job instance.
|
||||
* @param \Throwable $exception The exception that was thrown.
|
||||
*/
|
||||
public function __construct(
|
||||
public ?string $connectionName,
|
||||
public mixed $command,
|
||||
public Throwable $exception,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class QueuePaused
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connection The connection name.
|
||||
* @param string $queue The queue name.
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $ttl
|
||||
*/
|
||||
public function __construct(
|
||||
public $connection,
|
||||
public $queue,
|
||||
public $ttl = null,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class QueueResumed
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connection The connection name.
|
||||
* @param string $queue The queue name.
|
||||
*/
|
||||
public function __construct(
|
||||
public $connection,
|
||||
public $queue,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class WorkerStarting
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\WorkerOptions $workerOptions
|
||||
*/
|
||||
public function __construct(
|
||||
public $connectionName,
|
||||
public $queue,
|
||||
public $workerOptions,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Events;
|
||||
|
||||
class WorkerStopping
|
||||
{
|
||||
/**
|
||||
* Create a new event instance.
|
||||
*
|
||||
* @param int $status The worker exit status.
|
||||
* @param \Illuminate\Queue\WorkerOptions|null $workerOptions The worker options.
|
||||
*/
|
||||
public function __construct(
|
||||
public $status = 0,
|
||||
public $workerOptions = null,
|
||||
) {
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
interface CountableFailedJobProvider
|
||||
{
|
||||
/**
|
||||
* Count the failed jobs.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function count($connection = null, $queue = null);
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Database\ConnectionResolverInterface;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
class DatabaseFailedJobProvider implements CountableFailedJobProvider, FailedJobProviderInterface, PrunableFailedJobProvider
|
||||
{
|
||||
/**
|
||||
* The connection resolver implementation.
|
||||
*
|
||||
* @var \Illuminate\Database\ConnectionResolverInterface
|
||||
*/
|
||||
protected $resolver;
|
||||
|
||||
/**
|
||||
* The database connection name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The database table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* Create a new database failed job provider.
|
||||
*
|
||||
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
|
||||
* @param string $database
|
||||
* @param string $table
|
||||
*/
|
||||
public function __construct(ConnectionResolverInterface $resolver, $database, $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
$this->resolver = $resolver;
|
||||
$this->database = $database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return int|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception)
|
||||
{
|
||||
$failed_at = Date::now();
|
||||
|
||||
$exception = (string) mb_convert_encoding($exception, 'UTF-8');
|
||||
|
||||
return $this->getTable()->insertGetId(compact(
|
||||
'connection', 'queue', 'payload', 'exception', 'failed_at'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null)
|
||||
{
|
||||
return $this->getTable()
|
||||
->when(! is_null($queue), fn ($query) => $query->where('queue', $queue))
|
||||
->orderBy('id', 'desc')
|
||||
->pluck('id')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return $this->getTable()->orderBy('id', 'desc')->get()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
return $this->getTable()->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id)
|
||||
{
|
||||
return $this->getTable()->where('id', $id)->delete() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*/
|
||||
public function flush($hours = null)
|
||||
{
|
||||
$this->getTable()->when($hours, function ($query, $hours) {
|
||||
$query->where('failed_at', '<=', Date::now()->subHours($hours));
|
||||
})->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune all of the entries older than the given date.
|
||||
*
|
||||
* @param \DateTimeInterface $before
|
||||
* @return int
|
||||
*/
|
||||
public function prune(DateTimeInterface $before)
|
||||
{
|
||||
$query = $this->getTable()->where('failed_at', '<', $before);
|
||||
|
||||
$totalDeleted = 0;
|
||||
|
||||
do {
|
||||
$deleted = $query->limit(1000)->delete();
|
||||
|
||||
$totalDeleted += $deleted;
|
||||
} while ($deleted !== 0);
|
||||
|
||||
return $totalDeleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the failed jobs.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function count($connection = null, $queue = null)
|
||||
{
|
||||
return $this->getTable()
|
||||
->when($connection, fn ($builder) => $builder->whereConnection($connection))
|
||||
->when($queue, fn ($builder) => $builder->whereQueue($queue))
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new query builder instance for the table.
|
||||
*
|
||||
* @return \Illuminate\Database\Query\Builder
|
||||
*/
|
||||
public function getTable()
|
||||
{
|
||||
return $this->resolver->connection($this->database)->table($this->table);
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Database\ConnectionResolverInterface;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
class DatabaseUuidFailedJobProvider implements CountableFailedJobProvider, FailedJobProviderInterface, PrunableFailedJobProvider
|
||||
{
|
||||
/**
|
||||
* The connection resolver implementation.
|
||||
*
|
||||
* @var \Illuminate\Database\ConnectionResolverInterface
|
||||
*/
|
||||
protected $resolver;
|
||||
|
||||
/**
|
||||
* The database connection name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The database table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* Create a new database failed job provider.
|
||||
*
|
||||
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
|
||||
* @param string $database
|
||||
* @param string $table
|
||||
*/
|
||||
public function __construct(ConnectionResolverInterface $resolver, $database, $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
$this->resolver = $resolver;
|
||||
$this->database = $database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return string|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception)
|
||||
{
|
||||
$this->getTable()->insert([
|
||||
'uuid' => $uuid = json_decode($payload, true)['uuid'],
|
||||
'connection' => $connection,
|
||||
'queue' => $queue,
|
||||
'payload' => $payload,
|
||||
'exception' => (string) mb_convert_encoding($exception, 'UTF-8'),
|
||||
'failed_at' => Date::now(),
|
||||
]);
|
||||
|
||||
return $uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null)
|
||||
{
|
||||
return $this->getTable()
|
||||
->when(! is_null($queue), fn ($query) => $query->where('queue', $queue))
|
||||
->orderBy('id', 'desc')
|
||||
->pluck('uuid')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return $this->getTable()->orderBy('id', 'desc')->get()->map(function ($record) {
|
||||
$record->id = $record->uuid;
|
||||
unset($record->uuid);
|
||||
|
||||
return $record;
|
||||
})->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
if ($record = $this->getTable()->where('uuid', $id)->first()) {
|
||||
$record->id = $record->uuid;
|
||||
unset($record->uuid);
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id)
|
||||
{
|
||||
return $this->getTable()->where('uuid', $id)->delete() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*/
|
||||
public function flush($hours = null)
|
||||
{
|
||||
$this->getTable()->when($hours, function ($query, $hours) {
|
||||
$query->where('failed_at', '<=', Date::now()->subHours($hours));
|
||||
})->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune all of the entries older than the given date.
|
||||
*
|
||||
* @param \DateTimeInterface $before
|
||||
* @return int
|
||||
*/
|
||||
public function prune(DateTimeInterface $before)
|
||||
{
|
||||
$query = $this->getTable()->where('failed_at', '<', $before);
|
||||
|
||||
$totalDeleted = 0;
|
||||
|
||||
do {
|
||||
$deleted = $query->limit(1000)->delete();
|
||||
|
||||
$totalDeleted += $deleted;
|
||||
} while ($deleted !== 0);
|
||||
|
||||
return $totalDeleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the failed jobs.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function count($connection = null, $queue = null)
|
||||
{
|
||||
return $this->getTable()
|
||||
->when($connection, fn ($builder) => $builder->whereConnection($connection))
|
||||
->when($queue, fn ($builder) => $builder->whereQueue($queue))
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new query builder instance for the table.
|
||||
*
|
||||
* @return \Illuminate\Database\Query\Builder
|
||||
*/
|
||||
public function getTable()
|
||||
{
|
||||
return $this->resolver->connection($this->database)->table($this->table);
|
||||
}
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
use Aws\DynamoDb\DynamoDbClient;
|
||||
use DateTimeInterface;
|
||||
use Exception;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
class DynamoDbFailedJobProvider implements FailedJobProviderInterface
|
||||
{
|
||||
/**
|
||||
* The DynamoDB client instance.
|
||||
*
|
||||
* @var \Aws\DynamoDb\DynamoDbClient
|
||||
*/
|
||||
protected $dynamo;
|
||||
|
||||
/**
|
||||
* The application name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $applicationName;
|
||||
|
||||
/**
|
||||
* The table name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* Create a new DynamoDb failed job provider.
|
||||
*
|
||||
* @param \Aws\DynamoDb\DynamoDbClient $dynamo
|
||||
* @param string $applicationName
|
||||
* @param string $table
|
||||
*/
|
||||
public function __construct(DynamoDbClient $dynamo, $applicationName, $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
$this->dynamo = $dynamo;
|
||||
$this->applicationName = $applicationName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return string|int|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception)
|
||||
{
|
||||
$id = json_decode($payload, true)['uuid'];
|
||||
|
||||
$failedAt = Date::now();
|
||||
|
||||
$this->dynamo->putItem([
|
||||
'TableName' => $this->table,
|
||||
'Item' => [
|
||||
'application' => ['S' => $this->applicationName],
|
||||
'uuid' => ['S' => $id],
|
||||
'connection' => ['S' => $connection],
|
||||
'queue' => ['S' => $queue],
|
||||
'payload' => ['S' => $payload],
|
||||
'exception' => ['S' => (string) $exception],
|
||||
'failed_at' => ['N' => (string) $failedAt->getTimestamp()],
|
||||
'expires_at' => ['N' => (string) $failedAt->addDays(7)->getTimestamp()],
|
||||
],
|
||||
]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null)
|
||||
{
|
||||
return (new Collection($this->all()))
|
||||
->when(! is_null($queue), fn ($collect) => $collect->where('queue', $queue))
|
||||
->pluck('id')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
$results = $this->dynamo->query([
|
||||
'TableName' => $this->table,
|
||||
'Select' => 'ALL_ATTRIBUTES',
|
||||
'KeyConditionExpression' => 'application = :application',
|
||||
'ExpressionAttributeValues' => [
|
||||
':application' => ['S' => $this->applicationName],
|
||||
],
|
||||
'ScanIndexForward' => false,
|
||||
]);
|
||||
|
||||
return (new Collection($results['Items']))
|
||||
->sortByDesc(fn ($result) => (int) $result['failed_at']['N'])
|
||||
->map(function ($result) {
|
||||
return (object) [
|
||||
'id' => $result['uuid']['S'],
|
||||
'connection' => $result['connection']['S'],
|
||||
'queue' => $result['queue']['S'],
|
||||
'payload' => $result['payload']['S'],
|
||||
'exception' => $result['exception']['S'],
|
||||
'failed_at' => Carbon::createFromTimestamp(
|
||||
(int) $result['failed_at']['N'], date_default_timezone_get()
|
||||
)->format(DateTimeInterface::ISO8601),
|
||||
];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
$result = $this->dynamo->getItem([
|
||||
'TableName' => $this->table,
|
||||
'Key' => [
|
||||
'application' => ['S' => $this->applicationName],
|
||||
'uuid' => ['S' => $id],
|
||||
],
|
||||
]);
|
||||
|
||||
if (! isset($result['Item'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (object) [
|
||||
'id' => $result['Item']['uuid']['S'],
|
||||
'connection' => $result['Item']['connection']['S'],
|
||||
'queue' => $result['Item']['queue']['S'],
|
||||
'payload' => $result['Item']['payload']['S'],
|
||||
'exception' => $result['Item']['exception']['S'],
|
||||
'failed_at' => Carbon::createFromTimestamp(
|
||||
(int) $result['Item']['failed_at']['N'], date_default_timezone_get()
|
||||
)->format(DateTimeInterface::ISO8601),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id)
|
||||
{
|
||||
$this->dynamo->deleteItem([
|
||||
'TableName' => $this->table,
|
||||
'Key' => [
|
||||
'application' => ['S' => $this->applicationName],
|
||||
'uuid' => ['S' => $id],
|
||||
],
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function flush($hours = null)
|
||||
{
|
||||
throw new Exception("DynamoDb failed job storage may not be flushed. Please use DynamoDb's TTL features on your expires_at attribute.");
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
interface FailedJobProviderInterface
|
||||
{
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return string|int|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception);
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null);
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all();
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id);
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id);
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*/
|
||||
public function flush($hours = null);
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
use Closure;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
class FileFailedJobProvider implements CountableFailedJobProvider, FailedJobProviderInterface, PrunableFailedJobProvider
|
||||
{
|
||||
/**
|
||||
* The file path where the failed job file should be stored.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $path;
|
||||
|
||||
/**
|
||||
* The maximum number of failed jobs to retain.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $limit;
|
||||
|
||||
/**
|
||||
* The lock provider resolver.
|
||||
*
|
||||
* @var \Closure
|
||||
*/
|
||||
protected $lockProviderResolver;
|
||||
|
||||
/**
|
||||
* Create a new file failed job provider.
|
||||
*
|
||||
* @param string $path
|
||||
* @param int $limit
|
||||
* @param \Closure|null $lockProviderResolver
|
||||
*/
|
||||
public function __construct($path, $limit = 100, ?Closure $lockProviderResolver = null)
|
||||
{
|
||||
$this->path = $path;
|
||||
$this->limit = $limit;
|
||||
$this->lockProviderResolver = $lockProviderResolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return int|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception)
|
||||
{
|
||||
return $this->lock(function () use ($connection, $queue, $payload, $exception) {
|
||||
$id = json_decode($payload, true)['uuid'];
|
||||
|
||||
$jobs = $this->read();
|
||||
|
||||
$failedAt = Date::now();
|
||||
|
||||
array_unshift($jobs, [
|
||||
'id' => $id,
|
||||
'connection' => $connection,
|
||||
'queue' => $queue,
|
||||
'payload' => $payload,
|
||||
'exception' => (string) mb_convert_encoding($exception, 'UTF-8'),
|
||||
'failed_at' => $failedAt->format('Y-m-d H:i:s'),
|
||||
'failed_at_timestamp' => $failedAt->getTimestamp(),
|
||||
]);
|
||||
|
||||
$this->write(array_slice($jobs, 0, $this->limit));
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null)
|
||||
{
|
||||
return (new Collection($this->all()))
|
||||
->when(! is_null($queue), fn ($collect) => $collect->where('queue', $queue))
|
||||
->pluck('id')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return $this->read();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
return (new Collection($this->read()))
|
||||
->first(fn ($job) => $job->id === $id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id)
|
||||
{
|
||||
return $this->lock(function () use ($id) {
|
||||
$this->write($pruned = (new Collection($jobs = $this->read()))
|
||||
->reject(fn ($job) => $job->id === $id)
|
||||
->values()
|
||||
->all());
|
||||
|
||||
return count($jobs) !== count($pruned);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*/
|
||||
public function flush($hours = null)
|
||||
{
|
||||
$this->prune(Date::now()->subHours($hours ?: 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prune all of the entries older than the given date.
|
||||
*
|
||||
* @param \DateTimeInterface $before
|
||||
* @return int
|
||||
*/
|
||||
public function prune(DateTimeInterface $before)
|
||||
{
|
||||
return $this->lock(function () use ($before) {
|
||||
$jobs = $this->read();
|
||||
|
||||
$this->write($prunedJobs = (new Collection($jobs))
|
||||
->reject(fn ($job) => $job->failed_at_timestamp <= $before->getTimestamp())
|
||||
->values()
|
||||
->all()
|
||||
);
|
||||
|
||||
return count($jobs) - count($prunedJobs);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the given callback while holding a lock.
|
||||
*
|
||||
* @param \Closure $callback
|
||||
* @return mixed
|
||||
*/
|
||||
protected function lock(Closure $callback)
|
||||
{
|
||||
if (! $this->lockProviderResolver) {
|
||||
return $callback();
|
||||
}
|
||||
|
||||
return ($this->lockProviderResolver)()
|
||||
->lock('laravel-failed-jobs', 5)
|
||||
->block(10, function () use ($callback) {
|
||||
return $callback();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the failed jobs file.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function read()
|
||||
{
|
||||
if (! file_exists($this->path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$content = file_get_contents($this->path);
|
||||
|
||||
if (empty(trim($content))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$content = json_decode($content);
|
||||
|
||||
return is_array($content) ? $content : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the given array of jobs to the failed jobs file.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @return void
|
||||
*/
|
||||
protected function write(array $jobs)
|
||||
{
|
||||
file_put_contents(
|
||||
$this->path,
|
||||
json_encode($jobs, JSON_PRETTY_PRINT)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the failed jobs.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function count($connection = null, $queue = null)
|
||||
{
|
||||
if (($connection ?? $queue) === null) {
|
||||
return count($this->read());
|
||||
}
|
||||
|
||||
return (new Collection($this->read()))
|
||||
->filter(fn ($job) => $job->connection === ($connection ?? $job->connection) && $job->queue === ($queue ?? $job->queue))
|
||||
->count();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
class NullFailedJobProvider implements CountableFailedJobProvider, FailedJobProviderInterface
|
||||
{
|
||||
/**
|
||||
* Log a failed job into storage.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param string $payload
|
||||
* @param \Throwable $exception
|
||||
* @return int|null
|
||||
*/
|
||||
public function log($connection, $queue, $payload, $exception)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the IDs of all of the failed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return array
|
||||
*/
|
||||
public function ids($queue = null)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all of the failed jobs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single failed job.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return object|null
|
||||
*/
|
||||
public function find($id)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a single failed job from storage.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @return bool
|
||||
*/
|
||||
public function forget($id)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush all of the failed jobs from storage.
|
||||
*
|
||||
* @param int|null $hours
|
||||
* @return void
|
||||
*/
|
||||
public function flush($hours = null)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the failed jobs.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function count($connection = null, $queue = null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Failed;
|
||||
|
||||
use DateTimeInterface;
|
||||
|
||||
interface PrunableFailedJobProvider
|
||||
{
|
||||
/**
|
||||
* Prune all of the entries older than the given date.
|
||||
*
|
||||
* @param \DateTimeInterface $before
|
||||
* @return int
|
||||
*/
|
||||
public function prune(DateTimeInterface $before);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
|
||||
use Illuminate\Contracts\Queue\Queue as QueueContract;
|
||||
use Illuminate\Queue\Events\QueueFailedOver;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class FailoverQueue extends Queue implements QueueContract
|
||||
{
|
||||
/**
|
||||
* The queues which failed on the last action.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $failingQueues = [];
|
||||
|
||||
/**
|
||||
* Create a new failover queue instance.
|
||||
*/
|
||||
public function __construct(
|
||||
public QueueManager $manager,
|
||||
public EventDispatcher $events,
|
||||
public array $connections
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function size($queue = null)
|
||||
{
|
||||
return $this->manager->connection($this->connections[0])->size($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of pending jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function pendingSize($queue = null)
|
||||
{
|
||||
return $this->manager->connection($this->connections[0])->pendingSize($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function delayedSize($queue = null)
|
||||
{
|
||||
return $this->manager->connection($this->connections[0])->delayedSize($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of reserved jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function reservedSize($queue = null)
|
||||
{
|
||||
return $this->manager->connection($this->connections[0])->reservedSize($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int|null
|
||||
*/
|
||||
public function creationTimeOfOldestPendingJob($queue = null)
|
||||
{
|
||||
return $this->manager
|
||||
->connection($this->connections[0])
|
||||
->creationTimeOfOldestPendingJob($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param object|string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->attemptOnAllConnections(__FUNCTION__, func_get_args(), $job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload onto the queue.
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushRaw($payload, $queue = null, array $options = [])
|
||||
{
|
||||
return $this->attemptOnAllConnections(__FUNCTION__, func_get_args());
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function later($delay, $job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->attemptOnAllConnections(__FUNCTION__, func_get_args(), $job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the next job off of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public function pop($queue = null)
|
||||
{
|
||||
return $this->manager->connection($this->connections[0])->pop($queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt the given method on all connections.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
protected function attemptOnAllConnections(string $method, array $arguments, $job = null)
|
||||
{
|
||||
[$lastException, $failedQueues] = [null, []];
|
||||
|
||||
try {
|
||||
foreach ($this->connections as $connection) {
|
||||
try {
|
||||
return $this->manager->connection($connection)->{$method}(...$arguments);
|
||||
} catch (Throwable $e) {
|
||||
$lastException = $e;
|
||||
|
||||
$failedQueues[] = $connection;
|
||||
|
||||
if ($job !== null && ! in_array($connection, $this->failingQueues)) {
|
||||
$this->events->dispatch(new QueueFailedOver($connection, $job, $e));
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$this->failingQueues = $failedQueues;
|
||||
}
|
||||
|
||||
throw $lastException ?? new RuntimeException('All failover queue connections failed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
use Illuminate\Queue\Jobs\FakeJob;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use InvalidArgumentException;
|
||||
use PHPUnit\Framework\Assert as PHPUnit;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
trait InteractsWithQueue
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The underlying queue job instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public $job;
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return $this->job ? $this->job->attempts() : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
if ($this->job) {
|
||||
return $this->job->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail the job from the queue.
|
||||
*
|
||||
* @param \Throwable|string|null $exception
|
||||
* @return void
|
||||
*/
|
||||
public function fail($exception = null)
|
||||
{
|
||||
if (is_string($exception)) {
|
||||
$exception = new ManuallyFailedException($exception);
|
||||
}
|
||||
|
||||
if ($exception instanceof Throwable || is_null($exception)) {
|
||||
if ($this->job) {
|
||||
return $this->job->fail($exception);
|
||||
}
|
||||
} else {
|
||||
throw new InvalidArgumentException('The fail method requires a string or an instance of Throwable.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
$delay = $delay instanceof DateTimeInterface
|
||||
? $this->secondsUntil($delay)
|
||||
: $delay;
|
||||
|
||||
if ($this->job) {
|
||||
return $this->job->release($delay);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that queue interactions like fail, delete, and release should be faked.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function withFakeQueueInteractions()
|
||||
{
|
||||
$this->job = new FakeJob;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was deleted from the queue.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function assertDeleted()
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
$this->job->isDeleted(),
|
||||
'Job was expected to be deleted, but was not.'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was not deleted from the queue.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function assertNotDeleted()
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
! $this->job->isDeleted(),
|
||||
'Job was unexpectedly deleted.'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was manually failed.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function assertFailed()
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
$this->job->hasFailed(),
|
||||
'Job was expected to be manually failed, but was not.'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was manually failed with a specific exception.
|
||||
*
|
||||
* @param \Throwable|string $exception
|
||||
* @return $this
|
||||
*/
|
||||
public function assertFailedWith($exception)
|
||||
{
|
||||
$this->assertFailed();
|
||||
|
||||
if (is_string($exception) && class_exists($exception)) {
|
||||
PHPUnit::assertInstanceOf(
|
||||
$exception,
|
||||
$this->job->failedWith,
|
||||
'Expected job to be manually failed with ['.$exception.'] but job failed with ['.get_class($this->job->failedWith).'].'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_string($exception)) {
|
||||
$exception = new ManuallyFailedException($exception);
|
||||
}
|
||||
|
||||
if ($exception instanceof Throwable) {
|
||||
PHPUnit::assertInstanceOf(
|
||||
get_class($exception),
|
||||
$this->job->failedWith,
|
||||
'Expected job to be manually failed with ['.get_class($exception).'] but job failed with ['.get_class($this->job->failedWith).'].'
|
||||
);
|
||||
|
||||
PHPUnit::assertEquals(
|
||||
$exception->getCode(),
|
||||
$this->job->failedWith->getCode(),
|
||||
'Expected exception code ['.$exception->getCode().'] but job failed with exception code ['.$this->job->failedWith->getCode().'].'
|
||||
);
|
||||
|
||||
PHPUnit::assertEquals(
|
||||
$exception->getMessage(),
|
||||
$this->job->failedWith->getMessage(),
|
||||
'Expected exception message ['.$exception->getMessage().'] but job failed with exception message ['.$this->job->failedWith->getMessage().'].');
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was not manually failed.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function assertNotFailed()
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
! $this->job->hasFailed(),
|
||||
'Job was unexpectedly failed manually.'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was released back onto the queue.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $delay
|
||||
* @return $this
|
||||
*/
|
||||
public function assertReleased($delay = null)
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
$delay = $delay instanceof DateTimeInterface
|
||||
? $this->secondsUntil($delay)
|
||||
: $delay;
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
$this->job->isReleased(),
|
||||
'Job was expected to be released, but was not.'
|
||||
);
|
||||
|
||||
if (! is_null($delay)) {
|
||||
PHPUnit::assertSame(
|
||||
$delay,
|
||||
$this->job->releaseDelay,
|
||||
"Expected job to be released with delay of [{$delay}] seconds, but was released with delay of [{$this->job->releaseDelay}] seconds."
|
||||
);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the job was not released back onto the queue.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function assertNotReleased()
|
||||
{
|
||||
$this->ensureQueueInteractionsHaveBeenFaked();
|
||||
|
||||
PHPUnit::assertTrue(
|
||||
! $this->job->isReleased(),
|
||||
'Job was unexpectedly released.'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that queue interactions have been faked.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function ensureQueueInteractionsHaveBeenFaked()
|
||||
{
|
||||
if (! $this->job instanceof FakeJob) {
|
||||
throw new RuntimeException('Queue interactions have not been faked.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the base queue job instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @return $this
|
||||
*/
|
||||
public function setJob(JobContract $job)
|
||||
{
|
||||
$this->job = $job;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class InvalidPayloadException extends InvalidArgumentException
|
||||
{
|
||||
/**
|
||||
* The value that failed to decode.
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
public $value;
|
||||
|
||||
/**
|
||||
* Create a new exception instance.
|
||||
*
|
||||
* @param string|null $message
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function __construct($message = null, $value = null)
|
||||
{
|
||||
parent::__construct($message ?: json_last_error());
|
||||
|
||||
$this->value = $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
use Pheanstalk\Contract\JobIdInterface;
|
||||
use Pheanstalk\Pheanstalk;
|
||||
|
||||
class BeanstalkdJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The Pheanstalk instance.
|
||||
*
|
||||
* @var \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface
|
||||
*/
|
||||
protected $pheanstalk;
|
||||
|
||||
/**
|
||||
* The Pheanstalk job instance.
|
||||
*
|
||||
* @var \Pheanstalk\Job
|
||||
*/
|
||||
protected $job;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @param \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface $pheanstalk
|
||||
* @param \Pheanstalk\Contract\JobIdInterface $job
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
*/
|
||||
public function __construct(Container $container, $pheanstalk, JobIdInterface $job, $connectionName, $queue)
|
||||
{
|
||||
$this->job = $job;
|
||||
$this->queue = $queue;
|
||||
$this->container = $container;
|
||||
$this->pheanstalk = $pheanstalk;
|
||||
$this->connectionName = $connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
parent::release($delay);
|
||||
|
||||
$priority = Pheanstalk::DEFAULT_PRIORITY;
|
||||
|
||||
$this->pheanstalk->release($this->job, $priority, $delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bury the job in the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function bury()
|
||||
{
|
||||
parent::release();
|
||||
|
||||
$this->pheanstalk->bury($this->job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
parent::delete();
|
||||
|
||||
$this->pheanstalk->delete($this->job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
$stats = $this->pheanstalk->statsJob($this->job);
|
||||
|
||||
return (int) $stats->reserves;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return $this->job->getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body string for the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return $this->job->getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Pheanstalk instance.
|
||||
*
|
||||
* @return \Pheanstalk\Contract\PheanstalkManagerInterface&\Pheanstalk\Contract\PheanstalkPublisherInterface&\Pheanstalk\Contract\PheanstalkSubscriberInterface
|
||||
*/
|
||||
public function getPheanstalk()
|
||||
{
|
||||
return $this->pheanstalk;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Pheanstalk job.
|
||||
*
|
||||
* @return \Pheanstalk\Contract\JobIdInterface
|
||||
*/
|
||||
public function getPheanstalkJob()
|
||||
{
|
||||
return $this->job;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
use Illuminate\Queue\DatabaseQueue;
|
||||
|
||||
class DatabaseJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The database queue instance.
|
||||
*
|
||||
* @var \Illuminate\Queue\DatabaseQueue
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The database job payload.
|
||||
*
|
||||
* @var \Illuminate\Queue\Jobs\DatabaseJobRecord
|
||||
*/
|
||||
protected $job;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @param \Illuminate\Queue\DatabaseQueue $database
|
||||
* @param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
*/
|
||||
public function __construct(Container $container, DatabaseQueue $database, $job, $connectionName, $queue)
|
||||
{
|
||||
$this->job = $job;
|
||||
$this->queue = $queue;
|
||||
$this->database = $database;
|
||||
$this->container = $container;
|
||||
$this->connectionName = $connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
parent::release($delay);
|
||||
|
||||
$this->database->deleteAndRelease($this->queue, $this, $delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
parent::delete();
|
||||
|
||||
$this->database->deleteReserved($this->queue, $this->job->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return (int) $this->job->attempts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string|int
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return $this->job->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body string for the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return $this->job->payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the database job record.
|
||||
*
|
||||
* @return \Illuminate\Queue\Jobs\DatabaseJobRecord
|
||||
*/
|
||||
public function getJobRecord()
|
||||
{
|
||||
return $this->job;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
|
||||
class DatabaseJobRecord
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The underlying job record.
|
||||
*
|
||||
* @var \stdClass
|
||||
*/
|
||||
protected $record;
|
||||
|
||||
/**
|
||||
* Create a new job record instance.
|
||||
*
|
||||
* @param \stdClass $record
|
||||
*/
|
||||
public function __construct($record)
|
||||
{
|
||||
$this->record = $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function increment()
|
||||
{
|
||||
$this->record->attempts++;
|
||||
|
||||
return $this->record->attempts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the "reserved at" timestamp of the job.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function touch()
|
||||
{
|
||||
$this->record->reserved_at = $this->currentTime();
|
||||
|
||||
return $this->record->reserved_at;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically access the underlying job information.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($key)
|
||||
{
|
||||
return $this->record->{$key};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class FakeJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The number of seconds the released job was delayed.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $releaseDelay;
|
||||
|
||||
/**
|
||||
* The number of attempts made to process the job.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $attempts = 1;
|
||||
|
||||
/**
|
||||
* The exception the job failed with.
|
||||
*
|
||||
* @var \Throwable
|
||||
*/
|
||||
public $failedWith;
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return once(fn () => (string) Str::uuid());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body of the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
$this->released = true;
|
||||
$this->releaseDelay = $delay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return $this->attempts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
$this->deleted = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job, call the "failed" method, and raise the failed job event.
|
||||
*
|
||||
* @param \Throwable|null $exception
|
||||
* @return void
|
||||
*/
|
||||
public function fail($exception = null)
|
||||
{
|
||||
$this->failed = true;
|
||||
$this->failedWith = $exception;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Bus\Batchable;
|
||||
use Illuminate\Bus\BatchRepository;
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Queue\Events\JobFailed;
|
||||
use Illuminate\Queue\ManuallyFailedException;
|
||||
use Illuminate\Queue\TimeoutExceededException;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use Throwable;
|
||||
|
||||
abstract class Job
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The job handler instance.
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $instance;
|
||||
|
||||
/**
|
||||
* The IoC container instance.
|
||||
*
|
||||
* @var \Illuminate\Container\Container
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* Indicates if the job has been deleted.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $deleted = false;
|
||||
|
||||
/**
|
||||
* Indicates if the job has been released.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $released = false;
|
||||
|
||||
/**
|
||||
* Indicates if the job has failed.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $failed = false;
|
||||
|
||||
/**
|
||||
* The name of the connection the job belongs to.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $connectionName;
|
||||
|
||||
/**
|
||||
* The name of the queue the job belongs to.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $queue;
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string|int|null
|
||||
*/
|
||||
abstract public function getJobId();
|
||||
|
||||
/**
|
||||
* Get the raw body of the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function getRawBody();
|
||||
|
||||
/**
|
||||
* Get the UUID of the job.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function uuid()
|
||||
{
|
||||
return $this->payload()['uuid'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function fire()
|
||||
{
|
||||
$payload = $this->payload();
|
||||
|
||||
[$class, $method] = JobName::parse($payload['job']);
|
||||
|
||||
($this->instance = $this->resolve($class))->{$method}($this, $payload['data']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
$this->deleted = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job has been deleted.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isDeleted()
|
||||
{
|
||||
return $this->deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
$this->released = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job was released back into the queue.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isReleased()
|
||||
{
|
||||
return $this->released;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job has been deleted or released.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isDeletedOrReleased()
|
||||
{
|
||||
return $this->isDeleted() || $this->isReleased();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job has been marked as a failure.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasFailed()
|
||||
{
|
||||
return $this->failed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the job as "failed".
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function markAsFailed()
|
||||
{
|
||||
$this->failed = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job, call the "failed" method, and raise the failed job event.
|
||||
*
|
||||
* @param \Throwable|null $e
|
||||
* @return void
|
||||
*/
|
||||
public function fail($e = null)
|
||||
{
|
||||
$this->markAsFailed();
|
||||
|
||||
if ($this->isDeleted()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$commandName = $this->payload()['data']['commandName'] ?? false;
|
||||
|
||||
// If the exception is due to a job timing out, we need to rollback the current
|
||||
// database transaction so that the failed job count can be incremented with
|
||||
// the proper value. Otherwise, the current transaction will never commit.
|
||||
if ($e instanceof TimeoutExceededException &&
|
||||
$commandName &&
|
||||
in_array(Batchable::class, class_uses_recursive($commandName))) {
|
||||
$batchRepository = $this->resolve(BatchRepository::class);
|
||||
|
||||
try {
|
||||
$batchRepository->rollBack();
|
||||
} catch (Throwable $e) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->shouldRollBackDatabaseTransaction($e)) {
|
||||
$this->container->make('db')
|
||||
->connection($this->container['config']['queue.failed.database'])
|
||||
->rollBack(toLevel: 0);
|
||||
}
|
||||
|
||||
try {
|
||||
// If the job has failed, we will delete it, call the "failed" method and then call
|
||||
// an event indicating the job has failed so it can be logged if needed. This is
|
||||
// to allow every developer to better keep monitor of their failed queue jobs.
|
||||
$this->delete();
|
||||
|
||||
$this->failed($e);
|
||||
} finally {
|
||||
$this->resolve(Dispatcher::class)->dispatch(new JobFailed(
|
||||
$this->connectionName, $this, $e ?: new ManuallyFailedException
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the current database transaction should be rolled back to level zero.
|
||||
*
|
||||
* @param \Throwable $e
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldRollBackDatabaseTransaction($e)
|
||||
{
|
||||
return $e instanceof TimeoutExceededException &&
|
||||
$this->container['config']['queue.failed.database'] &&
|
||||
in_array($this->container['config']['queue.failed.driver'], ['database', 'database-uuids']) &&
|
||||
$this->container->bound('db');
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an exception that caused the job to fail.
|
||||
*
|
||||
* @param \Throwable|null $e
|
||||
* @return void
|
||||
*/
|
||||
protected function failed($e)
|
||||
{
|
||||
$payload = $this->payload();
|
||||
|
||||
[$class] = JobName::parse($payload['job']);
|
||||
|
||||
if (method_exists($this->instance = $this->resolve($class), 'failed')) {
|
||||
$this->instance->failed($payload['data'], $e, $payload['uuid'] ?? '', $this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the given class.
|
||||
*
|
||||
* @param string $class
|
||||
* @return mixed
|
||||
*/
|
||||
protected function resolve($class)
|
||||
{
|
||||
return $this->container->make($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the resolved job handler instance.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getResolvedJob()
|
||||
{
|
||||
return $this->instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decoded body of the job.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function payload()
|
||||
{
|
||||
return json_decode($this->getRawBody(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times to attempt a job.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function maxTries()
|
||||
{
|
||||
return $this->payload()['maxTries'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times to attempt a job after an exception.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function maxExceptions()
|
||||
{
|
||||
return $this->payload()['maxExceptions'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job should fail when it timeouts.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function shouldFailOnTimeout()
|
||||
{
|
||||
return $this->payload()['failOnTimeout'] ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of seconds to wait before retrying a job that encountered an uncaught exception.
|
||||
*
|
||||
* @return int|int[]|null
|
||||
*/
|
||||
public function backoff()
|
||||
{
|
||||
return $this->payload()['backoff'] ?? $this->payload()['delay'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds the job can run.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function timeout()
|
||||
{
|
||||
return $this->payload()['timeout'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp indicating when the job should timeout.
|
||||
*
|
||||
* @return int|null
|
||||
*/
|
||||
public function retryUntil()
|
||||
{
|
||||
return $this->payload()['retryUntil'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the queued job class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->payload()['job'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the resolved display name of the queued job class.
|
||||
*
|
||||
* Resolves the name of "wrapped" jobs such as class-based handlers.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function resolveName()
|
||||
{
|
||||
return JobName::resolve($this->getName(), $this->payload());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class of the queued job.
|
||||
*
|
||||
* Resolves the class of "wrapped" jobs such as class-based handlers.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function resolveQueuedJobClass()
|
||||
{
|
||||
return JobName::resolveClassName($this->getName(), $this->payload());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the connection the job belongs to.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getConnectionName()
|
||||
{
|
||||
return $this->connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the queue the job belongs to.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getQueue()
|
||||
{
|
||||
return $this->queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the service container instance.
|
||||
*
|
||||
* @return \Illuminate\Container\Container
|
||||
*/
|
||||
public function getContainer()
|
||||
{
|
||||
return $this->container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class JobName
|
||||
{
|
||||
/**
|
||||
* Parse the given job name into a class / method array.
|
||||
*
|
||||
* @param string $job
|
||||
* @return array
|
||||
*/
|
||||
public static function parse($job)
|
||||
{
|
||||
return Str::parseCallback($job, 'fire');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the resolved name of the queued job class.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $payload
|
||||
* @return string
|
||||
*/
|
||||
public static function resolve($name, $payload)
|
||||
{
|
||||
if (! empty($payload['displayName'])) {
|
||||
return $payload['displayName'];
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class name for queued job class.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array<string, mixed> $payload
|
||||
* @return string
|
||||
*/
|
||||
public static function resolveClassName($name, $payload)
|
||||
{
|
||||
if (is_string($payload['data']['commandName'] ?? null)) {
|
||||
return $payload['data']['commandName'];
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
use Illuminate\Queue\RedisQueue;
|
||||
|
||||
class RedisJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The Redis queue instance.
|
||||
*
|
||||
* @var \Illuminate\Queue\RedisQueue
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
/**
|
||||
* The Redis raw job payload.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $job;
|
||||
|
||||
/**
|
||||
* The decoded JSON version of "$job".
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $decoded;
|
||||
|
||||
/**
|
||||
* The Redis job payload inside the reserved queue.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $reserved;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @param \Illuminate\Queue\RedisQueue $redis
|
||||
* @param string $job
|
||||
* @param string $reserved
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
*/
|
||||
public function __construct(Container $container, RedisQueue $redis, $job, $reserved, $connectionName, $queue)
|
||||
{
|
||||
// The $job variable is the original job JSON as it existed in the ready queue while
|
||||
// the $reserved variable is the raw JSON in the reserved queue. The exact format
|
||||
// of the reserved job is required in order for us to properly delete its data.
|
||||
$this->job = $job;
|
||||
$this->redis = $redis;
|
||||
$this->queue = $queue;
|
||||
$this->reserved = $reserved;
|
||||
$this->container = $container;
|
||||
$this->connectionName = $connectionName;
|
||||
|
||||
$this->decoded = $this->payload();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body string for the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return $this->job;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
parent::delete();
|
||||
|
||||
$this->redis->deleteReserved($this->queue, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
parent::release($delay);
|
||||
|
||||
$this->redis->deleteAndRelease($this->queue, $this, $delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return ($this->decoded['attempts'] ?? null) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return $this->decoded['id'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Redis factory implementation.
|
||||
*
|
||||
* @return \Illuminate\Queue\RedisQueue
|
||||
*/
|
||||
public function getRedisQueue()
|
||||
{
|
||||
return $this->redis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying reserved Redis job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getReservedJob()
|
||||
{
|
||||
return $this->reserved;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Aws\Sqs\SqsClient;
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
|
||||
class SqsJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The Amazon SQS client instance.
|
||||
*
|
||||
* @var \Aws\Sqs\SqsClient
|
||||
*/
|
||||
protected $sqs;
|
||||
|
||||
/**
|
||||
* The Amazon SQS job instance.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $job;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @param \Aws\Sqs\SqsClient $sqs
|
||||
* @param array $job
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
*/
|
||||
public function __construct(Container $container, SqsClient $sqs, array $job, $connectionName, $queue)
|
||||
{
|
||||
$this->sqs = $sqs;
|
||||
$this->job = $job;
|
||||
$this->queue = $queue;
|
||||
$this->container = $container;
|
||||
$this->connectionName = $connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
parent::release($delay);
|
||||
|
||||
$this->sqs->changeMessageVisibility([
|
||||
'QueueUrl' => $this->queue,
|
||||
'ReceiptHandle' => $this->job['ReceiptHandle'],
|
||||
'VisibilityTimeout' => $delay,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the job from the queue.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function delete()
|
||||
{
|
||||
parent::delete();
|
||||
|
||||
$this->sqs->deleteMessage([
|
||||
'QueueUrl' => $this->queue, 'ReceiptHandle' => $this->job['ReceiptHandle'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return (int) $this->job['Attributes']['ApproximateReceiveCount'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return $this->job['MessageId'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body string for the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return $this->job['Body'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying SQS client instance.
|
||||
*
|
||||
* @return \Aws\Sqs\SqsClient
|
||||
*/
|
||||
public function getSqs()
|
||||
{
|
||||
return $this->sqs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying raw SQS job.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getSqsJob()
|
||||
{
|
||||
return $this->job;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Jobs;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Queue\Job as JobContract;
|
||||
|
||||
class SyncJob extends Job implements JobContract
|
||||
{
|
||||
/**
|
||||
* The class name of the job.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $job;
|
||||
|
||||
/**
|
||||
* The queue message data.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $payload;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @param string $payload
|
||||
* @param string $connectionName
|
||||
* @param string $queue
|
||||
*/
|
||||
public function __construct(Container $container, $payload, $connectionName, $queue)
|
||||
{
|
||||
$this->queue = $queue;
|
||||
$this->payload = $payload;
|
||||
$this->container = $container;
|
||||
$this->connectionName = $connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the job back into the queue after (n) seconds.
|
||||
*
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function release($delay = 0)
|
||||
{
|
||||
parent::release($delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of times the job has been attempted.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function attempts()
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the job identifier.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getJobId()
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the raw body string for the job.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRawBody()
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the queue the job belongs to.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getQueue()
|
||||
{
|
||||
return 'sync';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Taylor Otwell
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,237 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Closure;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
use function Illuminate\Support\artisan_binary;
|
||||
use function Illuminate\Support\php_binary;
|
||||
|
||||
class Listener
|
||||
{
|
||||
/**
|
||||
* The command working path.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $commandPath;
|
||||
|
||||
/**
|
||||
* The environment the workers should run under.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $environment;
|
||||
|
||||
/**
|
||||
* The amount of seconds to wait before polling the queue.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $sleep = 3;
|
||||
|
||||
/**
|
||||
* The number of times to try a job before logging it failed.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $maxTries = 0;
|
||||
|
||||
/**
|
||||
* The output handler callback.
|
||||
*
|
||||
* @var \Closure|null
|
||||
*/
|
||||
protected $outputHandler;
|
||||
|
||||
/**
|
||||
* Create a new queue listener.
|
||||
*
|
||||
* @param string $commandPath
|
||||
*/
|
||||
public function __construct($commandPath)
|
||||
{
|
||||
$this->commandPath = $commandPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the PHP binary.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function phpBinary()
|
||||
{
|
||||
return php_binary();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Artisan binary.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function artisanBinary()
|
||||
{
|
||||
return artisan_binary();
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen to the given queue connection.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\ListenerOptions $options
|
||||
* @return void
|
||||
*/
|
||||
public function listen($connection, $queue, ListenerOptions $options)
|
||||
{
|
||||
$process = $this->makeProcess($connection, $queue, $options);
|
||||
|
||||
while (true) {
|
||||
$this->runProcess($process, $options->memory);
|
||||
|
||||
if ($options->rest) {
|
||||
sleep($options->rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Symfony process for the worker.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\ListenerOptions $options
|
||||
* @return \Symfony\Component\Process\Process
|
||||
*/
|
||||
public function makeProcess($connection, $queue, ListenerOptions $options)
|
||||
{
|
||||
$command = $this->createCommand(
|
||||
$connection,
|
||||
$queue,
|
||||
$options
|
||||
);
|
||||
|
||||
// If the environment is set, we will append it to the command array so the
|
||||
// workers will run under the specified environment. Otherwise, they will
|
||||
// just run under the production environment which is not always right.
|
||||
if (isset($options->environment)) {
|
||||
$command = $this->addEnvironment($command, $options);
|
||||
}
|
||||
|
||||
return new Process(
|
||||
$command,
|
||||
$this->commandPath,
|
||||
null,
|
||||
null,
|
||||
$options->timeout
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the environment option to the given command.
|
||||
*
|
||||
* @param array $command
|
||||
* @param \Illuminate\Queue\ListenerOptions $options
|
||||
* @return array
|
||||
*/
|
||||
protected function addEnvironment($command, ListenerOptions $options)
|
||||
{
|
||||
return array_merge($command, ["--env={$options->environment}"]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the command with the listener options.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\ListenerOptions $options
|
||||
* @return array
|
||||
*/
|
||||
protected function createCommand($connection, $queue, ListenerOptions $options)
|
||||
{
|
||||
return array_filter([
|
||||
$this->phpBinary(),
|
||||
$this->artisanBinary(),
|
||||
'queue:work',
|
||||
$connection,
|
||||
'--once',
|
||||
"--name={$options->name}",
|
||||
"--queue={$queue}",
|
||||
"--backoff={$options->backoff}",
|
||||
"--memory={$options->memory}",
|
||||
"--sleep={$options->sleep}",
|
||||
"--tries={$options->maxTries}",
|
||||
$options->force ? '--force' : null,
|
||||
], function ($value) {
|
||||
return ! is_null($value);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the given process.
|
||||
*
|
||||
* @param \Symfony\Component\Process\Process $process
|
||||
* @param int $memory
|
||||
* @return void
|
||||
*/
|
||||
public function runProcess(Process $process, $memory)
|
||||
{
|
||||
$process->run(function ($type, $line) {
|
||||
$this->handleWorkerOutput($type, $line);
|
||||
});
|
||||
|
||||
// Once we have run the job we'll go check if the memory limit has been exceeded
|
||||
// for the script. If it has, we will kill this script so the process manager
|
||||
// will restart this with a clean slate of memory automatically on exiting.
|
||||
if ($this->memoryExceeded($memory)) {
|
||||
$this->stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle output from the worker process.
|
||||
*
|
||||
* @param int $type
|
||||
* @param string $line
|
||||
* @return void
|
||||
*/
|
||||
protected function handleWorkerOutput($type, $line)
|
||||
{
|
||||
if (isset($this->outputHandler)) {
|
||||
call_user_func($this->outputHandler, $type, $line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the memory limit has been exceeded.
|
||||
*
|
||||
* @param int $memoryLimit
|
||||
* @return bool
|
||||
*/
|
||||
public function memoryExceeded($memoryLimit)
|
||||
{
|
||||
return (memory_get_usage(true) / 1024 / 1024) >= $memoryLimit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop listening and bail out of the script.
|
||||
*
|
||||
* @return never
|
||||
*/
|
||||
public function stop()
|
||||
{
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the output handler callback.
|
||||
*
|
||||
* @param \Closure $outputHandler
|
||||
* @return void
|
||||
*/
|
||||
public function setOutputHandler(Closure $outputHandler)
|
||||
{
|
||||
$this->outputHandler = $outputHandler;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
class ListenerOptions extends WorkerOptions
|
||||
{
|
||||
/**
|
||||
* The environment the worker should run in.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $environment;
|
||||
|
||||
/**
|
||||
* Create a new listener options instance.
|
||||
*
|
||||
* @param string $name
|
||||
* @param string|null $environment
|
||||
* @param int|int[] $backoff
|
||||
* @param int $memory
|
||||
* @param int $timeout
|
||||
* @param int $sleep
|
||||
* @param int $maxTries
|
||||
* @param bool $force
|
||||
* @param int $rest
|
||||
*/
|
||||
public function __construct($name = 'default', $environment = null, $backoff = 0, $memory = 128, $timeout = 60, $sleep = 3, $maxTries = 1, $force = false, $rest = 0)
|
||||
{
|
||||
$this->environment = $environment;
|
||||
|
||||
parent::__construct($name, $backoff, $memory, $timeout, $sleep, $maxTries, $force, false, 0, 0, $rest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
class LuaScripts
|
||||
{
|
||||
/**
|
||||
* Get the Lua script for computing the size of queue.
|
||||
*
|
||||
* KEYS[1] - The name of the primary queue
|
||||
* KEYS[2] - The name of the "delayed" queue
|
||||
* KEYS[3] - The name of the "reserved" queue
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function size()
|
||||
{
|
||||
return <<<'LUA'
|
||||
return redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script for pushing jobs onto the queue.
|
||||
*
|
||||
* KEYS[1] - The queue to push the job onto, for example: queues:foo
|
||||
* KEYS[2] - The notification list for the queue we are pushing jobs onto, for example: queues:foo:notify
|
||||
* ARGV[1] - The job payload
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function push()
|
||||
{
|
||||
return <<<'LUA'
|
||||
-- Push the job onto the queue...
|
||||
redis.call('rpush', KEYS[1], ARGV[1])
|
||||
-- Push a notification onto the "notify" queue...
|
||||
redis.call('rpush', KEYS[2], 1)
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script for pushing delayed jobs onto the queue.
|
||||
*
|
||||
* KEYS[1] - The delayed queue to push the job onto, for example: queues:foo:delayed
|
||||
* ARGV[1] - The UNIX timestamp at which the job should become available
|
||||
* ARGV[2] - The job payload
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function later()
|
||||
{
|
||||
return <<<'LUA'
|
||||
-- Push the job onto the delayed queue...
|
||||
redis.call('zadd', KEYS[1], ARGV[1], ARGV[2])
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script for popping the next job off of the queue.
|
||||
*
|
||||
* KEYS[1] - The queue to pop jobs from, for example: queues:foo
|
||||
* KEYS[2] - The queue to place reserved jobs on, for example: queues:foo:reserved
|
||||
* KEYS[3] - The notify queue
|
||||
* ARGV[1] - The time at which the reserved job will expire
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function pop()
|
||||
{
|
||||
return <<<'LUA'
|
||||
-- Pop the first job off of the queue...
|
||||
local job = redis.call('lpop', KEYS[1])
|
||||
local reserved = false
|
||||
|
||||
if(job ~= false) then
|
||||
-- Increment the attempt count and place job on the reserved queue...
|
||||
reserved = cjson.decode(job)
|
||||
reserved['attempts'] = reserved['attempts'] + 1
|
||||
reserved = cjson.encode(reserved)
|
||||
redis.call('zadd', KEYS[2], ARGV[1], reserved)
|
||||
redis.call('lpop', KEYS[3])
|
||||
end
|
||||
|
||||
return {job, reserved}
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script for releasing reserved jobs.
|
||||
*
|
||||
* KEYS[1] - The "delayed" queue we release jobs onto, for example: queues:foo:delayed
|
||||
* KEYS[2] - The queue the jobs are currently on, for example: queues:foo:reserved
|
||||
* ARGV[1] - The raw payload of the job to add to the "delayed" queue
|
||||
* ARGV[2] - The UNIX timestamp at which the job should become available
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function release()
|
||||
{
|
||||
return <<<'LUA'
|
||||
-- Remove the job from the current queue...
|
||||
redis.call('zrem', KEYS[2], ARGV[1])
|
||||
|
||||
-- Add the job onto the "delayed" queue...
|
||||
redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
|
||||
|
||||
return true
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script to migrate expired jobs back onto the queue.
|
||||
*
|
||||
* KEYS[1] - The queue we are removing jobs from, for example: queues:foo:reserved
|
||||
* KEYS[2] - The queue we are moving jobs to, for example: queues:foo
|
||||
* KEYS[3] - The notification list for the queue we are moving jobs to, for example queues:foo:notify
|
||||
* ARGV[1] - The current UNIX timestamp
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function migrateExpiredJobs()
|
||||
{
|
||||
return <<<'LUA'
|
||||
-- Get all of the jobs with an expired "score"...
|
||||
local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1], 'limit', 0, ARGV[2])
|
||||
|
||||
-- If we have values in the array, we will remove them from the first queue
|
||||
-- and add them onto the destination queue in chunks of 100, which moves
|
||||
-- all of the appropriate jobs onto the destination queue very safely.
|
||||
if(next(val) ~= nil) then
|
||||
redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)
|
||||
|
||||
for i = 1, #val, 100 do
|
||||
redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))
|
||||
-- Push a notification for every job that was migrated...
|
||||
for j = i, math.min(i+99, #val) do
|
||||
redis.call('rpush', KEYS[3], 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return val
|
||||
LUA;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Lua script for removing all jobs from the queue.
|
||||
*
|
||||
* KEYS[1] - The name of the primary queue
|
||||
* KEYS[2] - The name of the "delayed" queue
|
||||
* KEYS[3] - The name of the "reserved" queue
|
||||
* KEYS[4] - The name of the "notify" queue
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function clear()
|
||||
{
|
||||
return <<<'LUA'
|
||||
local size = redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])
|
||||
redis.call('del', KEYS[1], KEYS[2], KEYS[3], KEYS[4])
|
||||
return size
|
||||
LUA;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ManuallyFailedException extends RuntimeException
|
||||
{
|
||||
//
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class MaxAttemptsExceededException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* The job instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public $job;
|
||||
|
||||
/**
|
||||
* Create a new instance for the job.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Queue\Job $job
|
||||
* @return static
|
||||
*/
|
||||
public static function forJob($job)
|
||||
{
|
||||
return tap(new static($job->resolveName().' has been attempted too many times.'), function ($e) use ($job) {
|
||||
$e->job = $job;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Throwable;
|
||||
|
||||
class FailOnException
|
||||
{
|
||||
/**
|
||||
* The truth-test callback to determine if the job should fail.
|
||||
*
|
||||
* @var \Closure(\Throwable, mixed): bool
|
||||
*/
|
||||
protected Closure $callback;
|
||||
|
||||
/**
|
||||
* Create a middleware instance.
|
||||
*
|
||||
* @param (\Closure(\Throwable, mixed): bool)|array<array-key, class-string<\Throwable>> $callback
|
||||
*/
|
||||
public function __construct($callback)
|
||||
{
|
||||
if (is_array($callback)) {
|
||||
$callback = $this->failForExceptions($callback);
|
||||
}
|
||||
|
||||
$this->callback = $callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the job should fail if it encounters the given exceptions.
|
||||
*
|
||||
* @param array<array-key, class-string<\Throwable>> $exceptions
|
||||
* @return \Closure(\Throwable, mixed): bool
|
||||
*/
|
||||
protected function failForExceptions(array $exceptions)
|
||||
{
|
||||
return static function (Throwable $throwable) use ($exceptions) {
|
||||
foreach ($exceptions as $exception) {
|
||||
if ($throwable instanceof $exception) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the job as failed if an exception is thrown that passes a truth-test callback.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function handle($job, callable $next)
|
||||
{
|
||||
try {
|
||||
return $next($job);
|
||||
} catch (Throwable $e) {
|
||||
if (call_user_func($this->callback, $e, $job) === true) {
|
||||
$job->fail($e);
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Illuminate\Cache\RateLimiter;
|
||||
use Illuminate\Cache\RateLimiting\Unlimited;
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
use function Illuminate\Support\enum_value;
|
||||
|
||||
class RateLimited
|
||||
{
|
||||
/**
|
||||
* The rate limiter instance.
|
||||
*
|
||||
* @var \Illuminate\Cache\RateLimiter
|
||||
*/
|
||||
protected $limiter;
|
||||
|
||||
/**
|
||||
* The name of the rate limiter.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $limiterName;
|
||||
|
||||
/**
|
||||
* The number of seconds before a job should be available again if the limit is exceeded.
|
||||
*
|
||||
* @var \DateTimeInterface|int|null
|
||||
*/
|
||||
public $releaseAfter;
|
||||
|
||||
/**
|
||||
* Indicates if the job should be released if the limit is exceeded.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $shouldRelease = true;
|
||||
|
||||
/**
|
||||
* Create a new middleware instance.
|
||||
*
|
||||
* @param \UnitEnum|string $limiterName
|
||||
*/
|
||||
public function __construct($limiterName)
|
||||
{
|
||||
$this->limiter = Container::getInstance()->make(RateLimiter::class);
|
||||
|
||||
$this->limiterName = (string) enum_value($limiterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($job, $next)
|
||||
{
|
||||
if (is_null($limiter = $this->limiter->limiter($this->limiterName))) {
|
||||
return $next($job);
|
||||
}
|
||||
|
||||
$limiterResponse = $limiter($job);
|
||||
|
||||
if ($limiterResponse instanceof Unlimited) {
|
||||
return $next($job);
|
||||
}
|
||||
|
||||
return $this->handleJob(
|
||||
$job,
|
||||
$next,
|
||||
Collection::wrap($limiterResponse)->map(function ($limit) {
|
||||
return (object) [
|
||||
'key' => md5($this->limiterName.$limit->key),
|
||||
'maxAttempts' => $limit->maxAttempts,
|
||||
'decaySeconds' => $limit->decaySeconds,
|
||||
];
|
||||
})->all()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a rate limited job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @param array $limits
|
||||
* @return mixed
|
||||
*/
|
||||
protected function handleJob($job, $next, array $limits)
|
||||
{
|
||||
foreach ($limits as $limit) {
|
||||
if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) {
|
||||
return $this->shouldRelease
|
||||
? $job->release($this->releaseAfter ?: $this->getTimeUntilNextRetry($limit->key))
|
||||
: false;
|
||||
}
|
||||
|
||||
$this->limiter->hit($limit->key, $limit->decaySeconds);
|
||||
}
|
||||
|
||||
return $next($job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the delay (in seconds) to release the job back to the queue.
|
||||
*
|
||||
* @param \DateTimeInterface|int $releaseAfter
|
||||
* @return $this
|
||||
*/
|
||||
public function releaseAfter($releaseAfter)
|
||||
{
|
||||
$this->releaseAfter = $releaseAfter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do not release the job back to the queue if the limit is exceeded.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function dontRelease()
|
||||
{
|
||||
$this->shouldRelease = false;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds that should elapse before the job is retried.
|
||||
*
|
||||
* @param string $key
|
||||
* @return int
|
||||
*/
|
||||
protected function getTimeUntilNextRetry($key)
|
||||
{
|
||||
return $this->limiter->availableIn($key) + 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the object for serialization.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return [
|
||||
'limiterName',
|
||||
'shouldRelease',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the object after unserialization.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
$this->limiter = Container::getInstance()->make(RateLimiter::class);
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Redis\Factory as Redis;
|
||||
use Illuminate\Redis\Limiters\DurationLimiter;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
|
||||
class RateLimitedWithRedis extends RateLimited
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The name of the Redis connection that should be used.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connectionName = null;
|
||||
|
||||
/**
|
||||
* The timestamp of the end of the current duration by key.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public $decaysAt = [];
|
||||
|
||||
/**
|
||||
* Create a new middleware instance.
|
||||
*
|
||||
* @param string $limiterName
|
||||
*/
|
||||
public function __construct($limiterName, ?string $connection = null)
|
||||
{
|
||||
parent::__construct($limiterName);
|
||||
|
||||
$this->connectionName = $connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a rate limited job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @param array $limits
|
||||
* @return mixed
|
||||
*/
|
||||
protected function handleJob($job, $next, array $limits)
|
||||
{
|
||||
foreach ($limits as $limit) {
|
||||
if ($this->tooManyAttempts($limit->key, $limit->maxAttempts, $limit->decaySeconds)) {
|
||||
return $this->shouldRelease
|
||||
? $job->release($this->releaseAfter ?: $this->getTimeUntilNextRetry($limit->key))
|
||||
: false;
|
||||
}
|
||||
}
|
||||
|
||||
return $next($job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given key has been "accessed" too many times.
|
||||
*
|
||||
* @param string $key
|
||||
* @param int $maxAttempts
|
||||
* @param int $decaySeconds
|
||||
* @return bool
|
||||
*/
|
||||
protected function tooManyAttempts($key, $maxAttempts, $decaySeconds)
|
||||
{
|
||||
$redis = Container::getInstance()
|
||||
->make(Redis::class)
|
||||
->connection($this->connectionName);
|
||||
|
||||
$limiter = new DurationLimiter(
|
||||
$redis, $key, $maxAttempts, $decaySeconds
|
||||
);
|
||||
|
||||
return tap(! $limiter->acquire(), function () use ($key, $limiter) {
|
||||
$this->decaysAt[$key] = $limiter->decaysAt;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds that should elapse before the job is retried.
|
||||
*
|
||||
* @param string $key
|
||||
* @return int
|
||||
*/
|
||||
protected function getTimeUntilNextRetry($key)
|
||||
{
|
||||
return ($this->decaysAt[$key] - $this->currentTime()) + 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the Redis connection that should be used.
|
||||
*
|
||||
* @param string $name
|
||||
* @return $this
|
||||
*/
|
||||
public function connection(string $name)
|
||||
{
|
||||
$this->connectionName = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the object for serialization.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
return array_merge(parent::__sleep(), ['connectionName']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the object after unserialization.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
parent::__wakeup();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Closure;
|
||||
|
||||
class Skip
|
||||
{
|
||||
public function __construct(protected bool $skip = false)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the middleware if the given condition is truthy.
|
||||
*
|
||||
* @param bool|Closure(): bool $condition
|
||||
*/
|
||||
public static function when(Closure|bool $condition): self
|
||||
{
|
||||
return new self(value($condition));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the middleware unless the given condition is truthy.
|
||||
*
|
||||
* @param bool|Closure(): bool $condition
|
||||
*/
|
||||
public static function unless(Closure|bool $condition): self
|
||||
{
|
||||
return new self(! value($condition));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the job.
|
||||
*/
|
||||
public function handle(mixed $job, callable $next): mixed
|
||||
{
|
||||
if ($this->skip) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $next($job);
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
class SkipIfBatchCancelled
|
||||
{
|
||||
/**
|
||||
* Process the job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($job, $next)
|
||||
{
|
||||
if (method_exists($job, 'batch') && $job->batch()?->cancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$next($job);
|
||||
}
|
||||
}
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Illuminate\Cache\RateLimiter;
|
||||
use Illuminate\Container\Container;
|
||||
use Throwable;
|
||||
|
||||
class ThrottlesExceptions
|
||||
{
|
||||
/**
|
||||
* The developer specified key that the rate limiter should use.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $key;
|
||||
|
||||
/**
|
||||
* Indicates whether the throttle key should use the job's UUID.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $byJob = false;
|
||||
|
||||
/**
|
||||
* The maximum number of attempts allowed before rate limiting applies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $maxAttempts;
|
||||
|
||||
/**
|
||||
* The number of seconds until the maximum attempts are reset.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $decaySeconds;
|
||||
|
||||
/**
|
||||
* The number of minutes to wait before retrying the job after an exception.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $retryAfterMinutes = 0;
|
||||
|
||||
/**
|
||||
* The callback that determines if the exception should be reported.
|
||||
*
|
||||
* @var callable
|
||||
*/
|
||||
protected $reportCallback;
|
||||
|
||||
/**
|
||||
* The callback that determines if rate limiting should apply.
|
||||
*
|
||||
* @var callable
|
||||
*/
|
||||
protected $whenCallback;
|
||||
|
||||
/**
|
||||
* The callbacks that determine if the job should be deleted.
|
||||
*
|
||||
* @var callable[]
|
||||
*/
|
||||
protected array $deleteWhenCallbacks = [];
|
||||
|
||||
/**
|
||||
* The callbacks that determine if the job should be failed.
|
||||
*
|
||||
* @var callable[]
|
||||
*/
|
||||
protected array $failWhenCallbacks = [];
|
||||
|
||||
/**
|
||||
* The prefix of the rate limiter key.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $prefix = 'laravel_throttles_exceptions:';
|
||||
|
||||
/**
|
||||
* The rate limiter instance.
|
||||
*
|
||||
* @var \Illuminate\Cache\RateLimiter
|
||||
*/
|
||||
protected $limiter;
|
||||
|
||||
/**
|
||||
* Create a new middleware instance.
|
||||
*
|
||||
* @param int $maxAttempts
|
||||
* @param int $decaySeconds
|
||||
*/
|
||||
public function __construct($maxAttempts = 10, $decaySeconds = 600)
|
||||
{
|
||||
$this->maxAttempts = $maxAttempts;
|
||||
$this->decaySeconds = $decaySeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($job, $next)
|
||||
{
|
||||
$this->limiter = Container::getInstance()->make(RateLimiter::class);
|
||||
|
||||
if ($this->limiter->tooManyAttempts($jobKey = $this->getKey($job), $this->maxAttempts)) {
|
||||
return $job->release($this->getTimeUntilNextRetry($jobKey));
|
||||
}
|
||||
|
||||
try {
|
||||
$next($job);
|
||||
|
||||
$this->limiter->clear($jobKey);
|
||||
} catch (Throwable $throwable) {
|
||||
if ($this->whenCallback && ! call_user_func($this->whenCallback, $throwable, $this->limiter)) {
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
if ($this->reportCallback && call_user_func($this->reportCallback, $throwable, $this->limiter)) {
|
||||
report($throwable);
|
||||
}
|
||||
|
||||
if ($this->shouldDelete($throwable)) {
|
||||
return $job->delete();
|
||||
}
|
||||
|
||||
if ($this->shouldFail($throwable)) {
|
||||
return $job->fail($throwable);
|
||||
}
|
||||
|
||||
$this->limiter->hit($jobKey, $this->decaySeconds);
|
||||
|
||||
return $job->release($this->retryAfterMinutes * 60);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify a callback that should determine if rate limiting behavior should apply.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @return $this
|
||||
*/
|
||||
public function when(callable $callback)
|
||||
{
|
||||
$this->whenCallback = $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a callback that should determine if the job should be deleted.
|
||||
*
|
||||
* @param callable|string $callback
|
||||
* @return $this
|
||||
*/
|
||||
public function deleteWhen(callable|string $callback)
|
||||
{
|
||||
$this->deleteWhenCallbacks[] = is_string($callback)
|
||||
? fn (Throwable $e) => $e instanceof $callback
|
||||
: $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a callback that should determine if the job should be failed.
|
||||
*
|
||||
* @param callable|string $callback
|
||||
* @return $this
|
||||
*/
|
||||
public function failWhen(callable|string $callback)
|
||||
{
|
||||
$this->failWhenCallbacks[] = is_string($callback)
|
||||
? fn (Throwable $e) => $e instanceof $callback
|
||||
: $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the skip / delete callbacks to determine if the job should be deleted for the given exception.
|
||||
*
|
||||
* @param \Throwable $throwable
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldDelete(Throwable $throwable): bool
|
||||
{
|
||||
foreach ($this->deleteWhenCallbacks as $callback) {
|
||||
if (call_user_func($callback, $throwable)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the skip / fail callbacks to determine if the job should be failed for the given exception.
|
||||
*
|
||||
* @param \Throwable $throwable
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldFail(Throwable $throwable): bool
|
||||
{
|
||||
foreach ($this->failWhenCallbacks as $callback) {
|
||||
if (call_user_func($callback, $throwable)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prefix of the rate limiter key.
|
||||
*
|
||||
* @param string $prefix
|
||||
* @return $this
|
||||
*/
|
||||
public function withPrefix(string $prefix)
|
||||
{
|
||||
$this->prefix = $prefix;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the number of minutes a job should be delayed when it is released (before it has reached its max exceptions).
|
||||
*
|
||||
* @param int $backoff
|
||||
* @return $this
|
||||
*/
|
||||
public function backoff($backoff)
|
||||
{
|
||||
$this->retryAfterMinutes = $backoff;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cache key associated for the rate limiter.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return string
|
||||
*/
|
||||
protected function getKey($job)
|
||||
{
|
||||
if ($this->key) {
|
||||
return $this->prefix.$this->key;
|
||||
} elseif ($this->byJob) {
|
||||
return $this->prefix.$job->job->uuid();
|
||||
}
|
||||
|
||||
$jobName = method_exists($job, 'displayName')
|
||||
? $job->displayName()
|
||||
: get_class($job);
|
||||
|
||||
return $this->prefix.hash('xxh128', $jobName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value that the rate limiter should be keyed by.
|
||||
*
|
||||
* @param string $key
|
||||
* @return $this
|
||||
*/
|
||||
public function by($key)
|
||||
{
|
||||
$this->key = $key;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the throttle key should use the job's UUID.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function byJob()
|
||||
{
|
||||
$this->byJob = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Report exceptions and optionally specify a callback that determines if the exception should be reported.
|
||||
*
|
||||
* @param callable|null $callback
|
||||
* @return $this
|
||||
*/
|
||||
public function report(?callable $callback = null)
|
||||
{
|
||||
$this->reportCallback = $callback ?? fn () => true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds that should elapse before the job is retried.
|
||||
*
|
||||
* @param string $key
|
||||
* @return int
|
||||
*/
|
||||
protected function getTimeUntilNextRetry($key)
|
||||
{
|
||||
return $this->limiter->availableIn($key) + 3;
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Redis\Connection;
|
||||
use Illuminate\Contracts\Redis\Factory as Redis;
|
||||
use Illuminate\Redis\Limiters\DurationLimiter;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use Throwable;
|
||||
|
||||
class ThrottlesExceptionsWithRedis extends ThrottlesExceptions
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The Redis connection instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Redis\Connection
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
/**
|
||||
* The Redis connection that should be used.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $connectionName = null;
|
||||
|
||||
/**
|
||||
* The rate limiter instance.
|
||||
*
|
||||
* @var \Illuminate\Redis\Limiters\DurationLimiter
|
||||
*/
|
||||
protected $limiter;
|
||||
|
||||
/**
|
||||
* Process the job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($job, $next)
|
||||
{
|
||||
$this->redis = Container::getInstance()
|
||||
->make(Redis::class)
|
||||
->connection($this->connectionName);
|
||||
|
||||
$this->limiter = new DurationLimiter(
|
||||
$this->redis, $this->getKey($job), $this->maxAttempts, $this->decaySeconds
|
||||
);
|
||||
|
||||
if ($this->limiter->tooManyAttempts()) {
|
||||
return $job->release($this->limiter->decaysAt - $this->currentTime());
|
||||
}
|
||||
|
||||
try {
|
||||
$next($job);
|
||||
|
||||
$this->limiter->clear();
|
||||
} catch (Throwable $throwable) {
|
||||
if ($this->whenCallback && ! call_user_func($this->whenCallback, $throwable, $this->limiter)) {
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
if ($this->reportCallback && call_user_func($this->reportCallback, $throwable, $this->limiter)) {
|
||||
report($throwable);
|
||||
}
|
||||
|
||||
if ($this->shouldDelete($throwable)) {
|
||||
return $job->delete();
|
||||
}
|
||||
|
||||
if ($this->shouldFail($throwable)) {
|
||||
return $job->fail($throwable);
|
||||
}
|
||||
|
||||
$this->limiter->acquire();
|
||||
|
||||
return $job->release($this->retryAfterMinutes * 60);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the Redis connection that should be used.
|
||||
*
|
||||
* @param string $name
|
||||
* @return $this
|
||||
*/
|
||||
public function connection(string $name)
|
||||
{
|
||||
$this->connectionName = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue\Middleware;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Cache\Repository as Cache;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
|
||||
class WithoutOverlapping
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The job's unique key used for preventing overlaps.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $key;
|
||||
|
||||
/**
|
||||
* The number of seconds before a job should be available again if no lock was acquired.
|
||||
*
|
||||
* @var \DateTimeInterface|int|null
|
||||
*/
|
||||
public $releaseAfter;
|
||||
|
||||
/**
|
||||
* The number of seconds before the lock should expire.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $expiresAfter;
|
||||
|
||||
/**
|
||||
* The prefix of the lock key.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $prefix = 'laravel-queue-overlap:';
|
||||
|
||||
/**
|
||||
* Share the key across different jobs.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $shareKey = false;
|
||||
|
||||
/**
|
||||
* Create a new middleware instance.
|
||||
*
|
||||
* @param string $key
|
||||
* @param \DateTimeInterface|int|null $releaseAfter
|
||||
* @param \DateTimeInterface|int $expiresAfter
|
||||
*/
|
||||
public function __construct($key = '', $releaseAfter = 0, $expiresAfter = 0)
|
||||
{
|
||||
$this->key = $key;
|
||||
$this->releaseAfter = $releaseAfter;
|
||||
$this->expiresAfter = $this->secondsUntil($expiresAfter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @param callable $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($job, $next)
|
||||
{
|
||||
$lock = Container::getInstance()->make(Cache::class)->lock(
|
||||
$this->getLockKey($job), $this->expiresAfter
|
||||
);
|
||||
|
||||
if ($lock->get()) {
|
||||
try {
|
||||
$next($job);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
} elseif (! is_null($this->releaseAfter)) {
|
||||
$job->release($this->releaseAfter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the delay (in seconds) to release the job back to the queue.
|
||||
*
|
||||
* @param \DateTimeInterface|int $releaseAfter
|
||||
* @return $this
|
||||
*/
|
||||
public function releaseAfter($releaseAfter)
|
||||
{
|
||||
$this->releaseAfter = $releaseAfter;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do not release the job back to the queue if no lock can be acquired.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function dontRelease()
|
||||
{
|
||||
$this->releaseAfter = null;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the maximum number of seconds that can elapse before the lock is released.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $expiresAfter
|
||||
* @return $this
|
||||
*/
|
||||
public function expireAfter($expiresAfter)
|
||||
{
|
||||
$this->expiresAfter = $this->secondsUntil($expiresAfter);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prefix of the lock key.
|
||||
*
|
||||
* @param string $prefix
|
||||
* @return $this
|
||||
*/
|
||||
public function withPrefix(string $prefix)
|
||||
{
|
||||
$this->prefix = $prefix;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the lock key should be shared across job classes.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function shared()
|
||||
{
|
||||
$this->shareKey = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the lock key for the given job.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return string
|
||||
*/
|
||||
public function getLockKey($job)
|
||||
{
|
||||
if ($this->shareKey) {
|
||||
return $this->prefix.$this->key;
|
||||
}
|
||||
|
||||
$jobName = method_exists($job, 'displayName')
|
||||
? hash('xxh128', $job->displayName())
|
||||
: get_class($job);
|
||||
|
||||
return $this->prefix.$jobName.':'.$this->key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Queue\Queue as QueueContract;
|
||||
|
||||
class NullQueue extends Queue implements QueueContract
|
||||
{
|
||||
/**
|
||||
* Get the size of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function size($queue = null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of pending jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function pendingSize($queue = null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function delayedSize($queue = null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of reserved jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function reservedSize($queue = null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int|null
|
||||
*/
|
||||
public function creationTimeOfOldestPendingJob($queue = null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload onto the queue.
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @param array $options
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushRaw($payload, $queue = null, array $options = [])
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function later($delay, $job, $data = '', $queue = null)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the next job off of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public function pop($queue = null)
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Closure;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Bus\UniqueLock;
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Contracts\Cache\Repository as Cache;
|
||||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||
use Illuminate\Queue\Events\JobQueued;
|
||||
use Illuminate\Queue\Events\JobQueueing;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\InteractsWithTime;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
abstract class Queue
|
||||
{
|
||||
use InteractsWithTime;
|
||||
|
||||
/**
|
||||
* The IoC container instance.
|
||||
*
|
||||
* @var \Illuminate\Container\Container
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* The connection name for the queue.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $connectionName;
|
||||
|
||||
/**
|
||||
* The original configuration for the queue.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* Indicates that jobs should be dispatched after all database transactions have committed.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $dispatchAfterCommit;
|
||||
|
||||
/**
|
||||
* The create payload callbacks.
|
||||
*
|
||||
* @var callable[]
|
||||
*/
|
||||
protected static $createPayloadCallbacks = [];
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushOn($queue, $job, $data = '')
|
||||
{
|
||||
return $this->push($job, $data, $queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto a specific queue after (n) seconds.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $job
|
||||
* @param mixed $data
|
||||
* @return mixed
|
||||
*/
|
||||
public function laterOn($queue, $delay, $job, $data = '')
|
||||
{
|
||||
return $this->later($delay, $job, $data, $queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push an array of jobs onto the queue.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return void
|
||||
*/
|
||||
public function bulk($jobs, $data = '', $queue = null)
|
||||
{
|
||||
foreach ((array) $jobs as $job) {
|
||||
$this->push($job, $data, $queue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a payload string from the given job and data.
|
||||
*
|
||||
* @param \Closure|string|object $job
|
||||
* @param string $queue
|
||||
* @param mixed $data
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $delay
|
||||
* @return string
|
||||
*
|
||||
* @throws \Illuminate\Queue\InvalidPayloadException
|
||||
*/
|
||||
protected function createPayload($job, $queue, $data = '', $delay = null)
|
||||
{
|
||||
if ($job instanceof Closure) {
|
||||
$job = CallQueuedClosure::create($job);
|
||||
}
|
||||
|
||||
$value = $this->createPayloadArray($job, $queue, $data);
|
||||
|
||||
$value['delay'] = isset($delay)
|
||||
? $this->secondsUntil($delay)
|
||||
: null;
|
||||
|
||||
$payload = json_encode($value, \JSON_UNESCAPED_UNICODE);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new InvalidPayloadException(
|
||||
'Unable to JSON encode payload. Error ('.json_last_error().'): '.json_last_error_msg(), $value
|
||||
);
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a payload array from the given job and data.
|
||||
*
|
||||
* @param string|object $job
|
||||
* @param string $queue
|
||||
* @param mixed $data
|
||||
* @return array
|
||||
*/
|
||||
protected function createPayloadArray($job, $queue, $data = '')
|
||||
{
|
||||
return is_object($job)
|
||||
? $this->createObjectPayload($job, $queue)
|
||||
: $this->createStringPayload($job, $queue, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a payload for an object-based queue handler.
|
||||
*
|
||||
* @param object $job
|
||||
* @param string $queue
|
||||
* @return array
|
||||
*/
|
||||
protected function createObjectPayload($job, $queue)
|
||||
{
|
||||
$payload = $this->withCreatePayloadHooks($queue, [
|
||||
'uuid' => (string) Str::uuid(),
|
||||
'displayName' => $this->getDisplayName($job),
|
||||
'job' => 'Illuminate\Queue\CallQueuedHandler@call',
|
||||
'maxTries' => $this->getJobTries($job),
|
||||
'maxExceptions' => $job->maxExceptions ?? null,
|
||||
'failOnTimeout' => $job->failOnTimeout ?? false,
|
||||
'backoff' => $this->getJobBackoff($job),
|
||||
'timeout' => $job->timeout ?? null,
|
||||
'retryUntil' => $this->getJobExpiration($job),
|
||||
'data' => [
|
||||
'commandName' => $job,
|
||||
'command' => $job,
|
||||
'batchId' => $job->batchId ?? null,
|
||||
],
|
||||
'createdAt' => Carbon::now()->getTimestamp(),
|
||||
]);
|
||||
|
||||
try {
|
||||
$command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class)
|
||||
? $this->container[Encrypter::class]->encrypt(serialize(clone $job))
|
||||
: serialize(clone $job);
|
||||
} catch (Throwable $e) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Failed to serialize job of type [%s]: %s', get_class($job), $e->getMessage()),
|
||||
0,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
return array_merge($payload, [
|
||||
'data' => array_merge($payload['data'], [
|
||||
'commandName' => get_class($job),
|
||||
'command' => $command,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the display name for the given job.
|
||||
*
|
||||
* @param object $job
|
||||
* @return string
|
||||
*/
|
||||
protected function getDisplayName($job)
|
||||
{
|
||||
return method_exists($job, 'displayName')
|
||||
? $job->displayName()
|
||||
: get_class($job);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum number of attempts for an object-based queue handler.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return mixed
|
||||
*/
|
||||
public function getJobTries($job)
|
||||
{
|
||||
if (! method_exists($job, 'tries') && ! isset($job->tries)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_null($tries = $job->tries ?? $job->tries())) {
|
||||
return;
|
||||
}
|
||||
|
||||
return $tries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the backoff for an object-based queue handler.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return mixed
|
||||
*/
|
||||
public function getJobBackoff($job)
|
||||
{
|
||||
if (! method_exists($job, 'backoff') && ! isset($job->backoff)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_null($backoff = $job->backoff ?? $job->backoff())) {
|
||||
return;
|
||||
}
|
||||
|
||||
return Collection::wrap($backoff)
|
||||
->map(fn ($backoff) => $backoff instanceof DateTimeInterface ? $this->secondsUntil($backoff) : $backoff)
|
||||
->implode(',');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the expiration timestamp for an object-based queue handler.
|
||||
*
|
||||
* @param mixed $job
|
||||
* @return mixed
|
||||
*/
|
||||
public function getJobExpiration($job)
|
||||
{
|
||||
if (! method_exists($job, 'retryUntil') && ! isset($job->retryUntil)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$expiration = $job->retryUntil ?? $job->retryUntil();
|
||||
|
||||
return $expiration instanceof DateTimeInterface
|
||||
? $expiration->getTimestamp()
|
||||
: $expiration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job should be encrypted.
|
||||
*
|
||||
* @param object $job
|
||||
* @return bool
|
||||
*/
|
||||
protected function jobShouldBeEncrypted($job)
|
||||
{
|
||||
if ($job instanceof ShouldBeEncrypted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isset($job->shouldBeEncrypted) && $job->shouldBeEncrypted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a typical, string based queue payload array.
|
||||
*
|
||||
* @param string $job
|
||||
* @param string $queue
|
||||
* @param mixed $data
|
||||
* @return array
|
||||
*/
|
||||
protected function createStringPayload($job, $queue, $data)
|
||||
{
|
||||
return $this->withCreatePayloadHooks($queue, [
|
||||
'uuid' => (string) Str::uuid(),
|
||||
'displayName' => is_string($job) ? explode('@', $job)[0] : null,
|
||||
'job' => $job,
|
||||
'maxTries' => null,
|
||||
'maxExceptions' => null,
|
||||
'failOnTimeout' => false,
|
||||
'backoff' => null,
|
||||
'timeout' => null,
|
||||
'data' => $data,
|
||||
'createdAt' => Carbon::now()->getTimestamp(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a callback to be executed when creating job payloads.
|
||||
*
|
||||
* @param callable|null $callback
|
||||
* @return void
|
||||
*/
|
||||
public static function createPayloadUsing($callback)
|
||||
{
|
||||
if (is_null($callback)) {
|
||||
static::$createPayloadCallbacks = [];
|
||||
} else {
|
||||
static::$createPayloadCallbacks[] = $callback;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the given payload using any registered payload hooks.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param array $payload
|
||||
* @return array
|
||||
*/
|
||||
protected function withCreatePayloadHooks($queue, array $payload)
|
||||
{
|
||||
if (! empty(static::$createPayloadCallbacks)) {
|
||||
foreach (static::$createPayloadCallbacks as $callback) {
|
||||
$payload = array_merge($payload, $callback($this->getConnectionName(), $queue, $payload));
|
||||
}
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue a job using the given callback.
|
||||
*
|
||||
* @param \Closure|string|object $job
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $delay
|
||||
* @param callable $callback
|
||||
* @return mixed
|
||||
*/
|
||||
protected function enqueueUsing($job, $payload, $queue, $delay, $callback)
|
||||
{
|
||||
if ($this->shouldDispatchAfterCommit($job) &&
|
||||
$this->container->bound('db.transactions')) {
|
||||
if ($job instanceof ShouldBeUnique) {
|
||||
$this->container->make('db.transactions')->addCallbackForRollback(
|
||||
function () use ($job) {
|
||||
(new UniqueLock($this->container->make(Cache::class)))->release($job);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return $this->container->make('db.transactions')->addCallback(
|
||||
function () use ($queue, $job, $payload, $delay, $callback) {
|
||||
$this->raiseJobQueueingEvent($queue, $job, $payload, $delay);
|
||||
|
||||
return tap($callback($payload, $queue, $delay), function ($jobId) use ($queue, $job, $payload, $delay) {
|
||||
$this->raiseJobQueuedEvent($queue, $jobId, $job, $payload, $delay);
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$this->raiseJobQueueingEvent($queue, $job, $payload, $delay);
|
||||
|
||||
return tap($callback($payload, $queue, $delay), function ($jobId) use ($queue, $job, $payload, $delay) {
|
||||
$this->raiseJobQueuedEvent($queue, $jobId, $job, $payload, $delay);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the job should be dispatched after all database transactions have committed.
|
||||
*
|
||||
* @param \Closure|string|object $job
|
||||
* @return bool
|
||||
*/
|
||||
protected function shouldDispatchAfterCommit($job)
|
||||
{
|
||||
if ($job instanceof ShouldQueueAfterCommit) {
|
||||
return ! (isset($job->afterCommit) && $job->afterCommit === false);
|
||||
}
|
||||
|
||||
if (! $job instanceof Closure && is_object($job) && isset($job->afterCommit)) {
|
||||
return $job->afterCommit;
|
||||
}
|
||||
|
||||
return $this->dispatchAfterCommit ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raise the job queueing event.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Closure|string|object $job
|
||||
* @param string $payload
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $delay
|
||||
* @return void
|
||||
*/
|
||||
protected function raiseJobQueueingEvent($queue, $job, $payload, $delay)
|
||||
{
|
||||
if ($this->container->bound('events')) {
|
||||
$delay = ! is_null($delay) ? $this->secondsUntil($delay) : $delay;
|
||||
|
||||
$this->container['events']->dispatch(new JobQueueing($this->connectionName, $queue, $job, $payload, $delay));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Raise the job queued event.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @param string|int|null $jobId
|
||||
* @param \Closure|string|object $job
|
||||
* @param string $payload
|
||||
* @param \DateTimeInterface|\DateInterval|int|null $delay
|
||||
* @return void
|
||||
*/
|
||||
protected function raiseJobQueuedEvent($queue, $jobId, $job, $payload, $delay)
|
||||
{
|
||||
if ($this->container->bound('events')) {
|
||||
$delay = ! is_null($delay) ? $this->secondsUntil($delay) : $delay;
|
||||
|
||||
$this->container['events']->dispatch(new JobQueued($this->connectionName, $queue, $jobId, $job, $payload, $delay));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the connection name for the queue.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getConnectionName()
|
||||
{
|
||||
return $this->connectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the connection name for the queue.
|
||||
*
|
||||
* @param string $name
|
||||
* @return $this
|
||||
*/
|
||||
public function setConnectionName($name)
|
||||
{
|
||||
$this->connectionName = $name;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue configuration array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getConfig()
|
||||
{
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the queue configuration array.
|
||||
*
|
||||
* @param array $config
|
||||
* @return $this
|
||||
*/
|
||||
public function setConfig(array $config)
|
||||
{
|
||||
$this->config = $config;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the container instance being used by the connection.
|
||||
*
|
||||
* @return \Illuminate\Container\Container
|
||||
*/
|
||||
public function getContainer()
|
||||
{
|
||||
return $this->container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the IoC container instance.
|
||||
*
|
||||
* @param \Illuminate\Container\Container $container
|
||||
* @return void
|
||||
*/
|
||||
public function setContainer(Container $container)
|
||||
{
|
||||
$this->container = $container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Queue\Factory as FactoryContract;
|
||||
use Illuminate\Contracts\Queue\Monitor as MonitorContract;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* @mixin \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
class QueueManager implements FactoryContract, MonitorContract
|
||||
{
|
||||
/**
|
||||
* The application instance.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Foundation\Application
|
||||
*/
|
||||
protected $app;
|
||||
|
||||
/**
|
||||
* The array of resolved queue connections.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $connections = [];
|
||||
|
||||
/**
|
||||
* The array of resolved queue connectors.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $connectors = [];
|
||||
|
||||
/**
|
||||
* Create a new queue manager instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Foundation\Application $app
|
||||
*/
|
||||
public function __construct($app)
|
||||
{
|
||||
$this->app = $app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the before job event.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function before($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\JobProcessing::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the after job event.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function after($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\JobProcessed::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the exception occurred job event.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function exceptionOccurred($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\JobExceptionOccurred::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the daemon queue loop.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function looping($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\Looping::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the failed job event.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function failing($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\JobFailed::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the daemon queue starting.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function starting($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\WorkerStarting::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener for the daemon queue stopping.
|
||||
*
|
||||
* @param mixed $callback
|
||||
* @return void
|
||||
*/
|
||||
public function stopping($callback)
|
||||
{
|
||||
$this->app['events']->listen(Events\WorkerStopping::class, $callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the driver is connected.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @return bool
|
||||
*/
|
||||
public function connected($name = null)
|
||||
{
|
||||
return isset($this->connections[$name ?: $this->getDefaultDriver()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a queue connection instance.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*/
|
||||
public function connection($name = null)
|
||||
{
|
||||
$name = $name ?: $this->getDefaultDriver();
|
||||
|
||||
// If the connection has not been resolved yet we will resolve it now as all
|
||||
// of the connections are resolved when they are actually needed so we do
|
||||
// not make any unnecessary connection to the various queue end-points.
|
||||
if (! isset($this->connections[$name])) {
|
||||
$this->connections[$name] = $this->resolve($name);
|
||||
|
||||
$this->connections[$name]->setContainer($this->app);
|
||||
}
|
||||
|
||||
return $this->connections[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a queue connection.
|
||||
*
|
||||
* @param string $name
|
||||
* @return \Illuminate\Contracts\Queue\Queue
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
protected function resolve($name)
|
||||
{
|
||||
$config = $this->getConfig($name);
|
||||
|
||||
if (is_null($config)) {
|
||||
throw new InvalidArgumentException("The [{$name}] queue connection has not been configured.");
|
||||
}
|
||||
|
||||
$queue = $this->getConnector($config['driver'])
|
||||
->connect($config)
|
||||
->setConnectionName($name);
|
||||
|
||||
if (method_exists($queue, 'setConfig')) {
|
||||
$queue->setConfig($config);
|
||||
}
|
||||
|
||||
return $queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the connector for a given driver.
|
||||
*
|
||||
* @param string $driver
|
||||
* @return \Illuminate\Queue\Connectors\ConnectorInterface
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
protected function getConnector($driver)
|
||||
{
|
||||
if (! isset($this->connectors[$driver])) {
|
||||
throw new InvalidArgumentException("No connector for [$driver].");
|
||||
}
|
||||
|
||||
return call_user_func($this->connectors[$driver]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause a queue by its connection and name.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @return void
|
||||
*/
|
||||
public function pause($connection, $queue)
|
||||
{
|
||||
$this->app['cache']
|
||||
->store()
|
||||
->forever("illuminate:queue:paused:{$connection}:{$queue}", true);
|
||||
|
||||
$this->app['events']->dispatch(
|
||||
new Events\QueuePaused($connection, $queue)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause a queue by its connection and name for a given amount of time.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @param \DateTimeInterface|\DateInterval|int $ttl
|
||||
* @return void
|
||||
*/
|
||||
public function pauseFor($connection, $queue, $ttl)
|
||||
{
|
||||
$this->app['cache']
|
||||
->store()
|
||||
->put("illuminate:queue:paused:{$connection}:{$queue}", true, $ttl);
|
||||
|
||||
$this->app['events']->dispatch(
|
||||
new Events\QueuePaused($connection, $queue, $ttl)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a paused queue by its connection and name.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @return void
|
||||
*/
|
||||
public function resume($connection, $queue)
|
||||
{
|
||||
$this->app['cache']
|
||||
->store()
|
||||
->forget("illuminate:queue:paused:{$connection}:{$queue}");
|
||||
|
||||
$this->app['events']->dispatch(
|
||||
new Events\QueueResumed($connection, $queue)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a queue is paused.
|
||||
*
|
||||
* @param string $connection
|
||||
* @param string $queue
|
||||
* @return bool
|
||||
*/
|
||||
public function isPaused($connection, $queue)
|
||||
{
|
||||
return (bool) $this->app['cache']
|
||||
->store()
|
||||
->get("illuminate:queue:paused:{$connection}:{$queue}", false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that queue workers should not poll for restart or pause signals.
|
||||
*
|
||||
* This prevents the workers from hitting the application cache to determine if they need to pause or restart.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function withoutInterruptionPolling()
|
||||
{
|
||||
Worker::$restartable = false;
|
||||
Worker::$pausable = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a queue connection resolver.
|
||||
*
|
||||
* @param string $driver
|
||||
* @param \Closure $resolver
|
||||
* @return void
|
||||
*/
|
||||
public function extend($driver, Closure $resolver)
|
||||
{
|
||||
$this->addConnector($driver, $resolver);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a queue connection resolver.
|
||||
*
|
||||
* @param string $driver
|
||||
* @param \Closure $resolver
|
||||
* @return void
|
||||
*/
|
||||
public function addConnector($driver, Closure $resolver)
|
||||
{
|
||||
$this->connectors[$driver] = $resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue connection configuration.
|
||||
*
|
||||
* @param string $name
|
||||
* @return array|null
|
||||
*/
|
||||
protected function getConfig($name)
|
||||
{
|
||||
if (! is_null($name) && $name !== 'null') {
|
||||
return $this->app['config']["queue.connections.{$name}"];
|
||||
}
|
||||
|
||||
return ['driver' => 'null'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the default queue connection.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getDefaultDriver()
|
||||
{
|
||||
return $this->app['config']['queue.default'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the name of the default queue connection.
|
||||
*
|
||||
* @param string $name
|
||||
* @return void
|
||||
*/
|
||||
public function setDefaultDriver($name)
|
||||
{
|
||||
$this->app['config']['queue.default'] = $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full name for the given connection.
|
||||
*
|
||||
* @param string|null $connection
|
||||
* @return string
|
||||
*/
|
||||
public function getName($connection = null)
|
||||
{
|
||||
return $connection ?: $this->getDefaultDriver();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the application instance used by the manager.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Foundation\Application
|
||||
*/
|
||||
public function getApplication()
|
||||
{
|
||||
return $this->app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the application instance used by the manager.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Foundation\Application $app
|
||||
* @return $this
|
||||
*/
|
||||
public function setApplication($app)
|
||||
{
|
||||
$this->app = $app;
|
||||
|
||||
foreach ($this->connections as $connection) {
|
||||
$connection->setContainer($app);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically pass calls to the default connection.
|
||||
*
|
||||
* @param string $method
|
||||
* @param array $parameters
|
||||
* @return mixed
|
||||
*/
|
||||
public function __call($method, $parameters)
|
||||
{
|
||||
return $this->connection()->$method(...$parameters);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Aws\DynamoDb\DynamoDbClient;
|
||||
use Illuminate\Contracts\Debug\ExceptionHandler;
|
||||
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
|
||||
use Illuminate\Contracts\Support\DeferrableProvider;
|
||||
use Illuminate\Queue\Connectors\BackgroundConnector;
|
||||
use Illuminate\Queue\Connectors\BeanstalkdConnector;
|
||||
use Illuminate\Queue\Connectors\DatabaseConnector;
|
||||
use Illuminate\Queue\Connectors\DeferredConnector;
|
||||
use Illuminate\Queue\Connectors\FailoverConnector;
|
||||
use Illuminate\Queue\Connectors\NullConnector;
|
||||
use Illuminate\Queue\Connectors\RedisConnector;
|
||||
use Illuminate\Queue\Connectors\SqsConnector;
|
||||
use Illuminate\Queue\Connectors\SyncConnector;
|
||||
use Illuminate\Queue\Failed\DatabaseFailedJobProvider;
|
||||
use Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider;
|
||||
use Illuminate\Queue\Failed\DynamoDbFailedJobProvider;
|
||||
use Illuminate\Queue\Failed\FileFailedJobProvider;
|
||||
use Illuminate\Queue\Failed\NullFailedJobProvider;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Laravel\SerializableClosure\SerializableClosure;
|
||||
|
||||
class QueueServiceProvider extends ServiceProvider implements DeferrableProvider
|
||||
{
|
||||
use SerializesAndRestoresModelIdentifiers;
|
||||
|
||||
/**
|
||||
* Register the service provider.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
$this->configureSerializableClosureUses();
|
||||
|
||||
$this->registerManager();
|
||||
$this->registerConnection();
|
||||
$this->registerWorker();
|
||||
$this->registerListener();
|
||||
$this->registerFailedJobServices();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure serializable closures uses.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configureSerializableClosureUses()
|
||||
{
|
||||
SerializableClosure::transformUseVariablesUsing(function ($data) {
|
||||
foreach ($data as $key => $value) {
|
||||
$data[$key] = $this->getSerializedPropertyValue($value);
|
||||
}
|
||||
|
||||
return $data;
|
||||
});
|
||||
|
||||
SerializableClosure::resolveUseVariablesUsing(function ($data) {
|
||||
foreach ($data as $key => $value) {
|
||||
$data[$key] = $this->getRestoredPropertyValue($value);
|
||||
}
|
||||
|
||||
return $data;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the queue manager.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerManager()
|
||||
{
|
||||
$this->app->singleton('queue', function ($app) {
|
||||
// Once we have an instance of the queue manager, we will register the various
|
||||
// resolvers for the queue connectors. These connectors are responsible for
|
||||
// creating the classes that accept queue configs and instantiate queues.
|
||||
return tap(new QueueManager($app), function ($manager) {
|
||||
$this->registerConnectors($manager);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the default queue connection binding.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerConnection()
|
||||
{
|
||||
$this->app->singleton('queue.connection', function ($app) {
|
||||
return $app['queue']->connection();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the connectors on the queue manager.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
public function registerConnectors($manager)
|
||||
{
|
||||
foreach (['Null', 'Sync', 'Deferred', 'Background', 'Failover', 'Database', 'Redis', 'Beanstalkd', 'Sqs'] as $connector) {
|
||||
$this->{"register{$connector}Connector"}($manager);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Null queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerNullConnector($manager)
|
||||
{
|
||||
$manager->addConnector('null', function () {
|
||||
return new NullConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Sync queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerSyncConnector($manager)
|
||||
{
|
||||
$manager->addConnector('sync', function () {
|
||||
return new SyncConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Deferred queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerDeferredConnector($manager)
|
||||
{
|
||||
$manager->addConnector('deferred', function () {
|
||||
return new DeferredConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Background queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerBackgroundConnector($manager)
|
||||
{
|
||||
$manager->addConnector('background', function () {
|
||||
return new BackgroundConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Failover queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerFailoverConnector($manager)
|
||||
{
|
||||
$manager->addConnector('failover', function () use ($manager) {
|
||||
return new FailoverConnector(
|
||||
$manager,
|
||||
$this->app->make(EventDispatcher::class)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the database queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerDatabaseConnector($manager)
|
||||
{
|
||||
$manager->addConnector('database', function () {
|
||||
return new DatabaseConnector($this->app['db']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Redis queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerRedisConnector($manager)
|
||||
{
|
||||
$manager->addConnector('redis', function () {
|
||||
return new RedisConnector($this->app['redis']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Beanstalkd queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerBeanstalkdConnector($manager)
|
||||
{
|
||||
$manager->addConnector('beanstalkd', function () {
|
||||
return new BeanstalkdConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the Amazon SQS queue connector.
|
||||
*
|
||||
* @param \Illuminate\Queue\QueueManager $manager
|
||||
* @return void
|
||||
*/
|
||||
protected function registerSqsConnector($manager)
|
||||
{
|
||||
$manager->addConnector('sqs', function () {
|
||||
return new SqsConnector;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the queue worker.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerWorker()
|
||||
{
|
||||
$this->app->singleton('queue.worker', function ($app) {
|
||||
$isDownForMaintenance = function () {
|
||||
return $this->app->isDownForMaintenance();
|
||||
};
|
||||
|
||||
$resetScope = function () use ($app) {
|
||||
if (method_exists($app['log'], 'flushSharedContext')) {
|
||||
$app['log']->flushSharedContext();
|
||||
}
|
||||
|
||||
if (method_exists($app['log'], 'withoutContext')) {
|
||||
$app['log']->withoutContext();
|
||||
}
|
||||
|
||||
if (method_exists($app['db'], 'getConnections')) {
|
||||
foreach ($app['db']->getConnections() as $connection) {
|
||||
$connection->resetTotalQueryDuration();
|
||||
$connection->allowQueryDurationHandlersToRunAgain();
|
||||
}
|
||||
}
|
||||
|
||||
$app->forgetScopedInstances();
|
||||
|
||||
Facade::clearResolvedInstances();
|
||||
|
||||
memory_reset_peak_usage();
|
||||
};
|
||||
|
||||
return new Worker(
|
||||
$app['queue'],
|
||||
$app['events'],
|
||||
$app[ExceptionHandler::class],
|
||||
$isDownForMaintenance,
|
||||
$resetScope
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the queue listener.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerListener()
|
||||
{
|
||||
$this->app->singleton('queue.listener', function ($app) {
|
||||
return new Listener($app->basePath());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the failed job services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function registerFailedJobServices()
|
||||
{
|
||||
$this->app->singleton('queue.failer', function ($app) {
|
||||
$config = $app['config']['queue.failed'];
|
||||
|
||||
if (array_key_exists('driver', $config) &&
|
||||
(is_null($config['driver']) || $config['driver'] === 'null')) {
|
||||
return new NullFailedJobProvider;
|
||||
}
|
||||
|
||||
if (isset($config['driver']) && $config['driver'] === 'file') {
|
||||
return new FileFailedJobProvider(
|
||||
$config['path'] ?? $this->app->storagePath('framework/cache/failed-jobs.json'),
|
||||
$config['limit'] ?? 100,
|
||||
fn () => $app['cache']->store('file'),
|
||||
);
|
||||
} elseif (isset($config['driver']) && $config['driver'] === 'dynamodb') {
|
||||
return $this->dynamoFailedJobProvider($config);
|
||||
} elseif (isset($config['driver']) && $config['driver'] === 'database-uuids') {
|
||||
return $this->databaseUuidFailedJobProvider($config);
|
||||
} elseif (isset($config['table'])) {
|
||||
return $this->databaseFailedJobProvider($config);
|
||||
} else {
|
||||
return new NullFailedJobProvider;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new database failed job provider.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Queue\Failed\DatabaseFailedJobProvider
|
||||
*/
|
||||
protected function databaseFailedJobProvider($config)
|
||||
{
|
||||
return new DatabaseFailedJobProvider(
|
||||
$this->app['db'], $config['database'], $config['table']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new database failed job provider that uses UUIDs as IDs.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Queue\Failed\DatabaseUuidFailedJobProvider
|
||||
*/
|
||||
protected function databaseUuidFailedJobProvider($config)
|
||||
{
|
||||
return new DatabaseUuidFailedJobProvider(
|
||||
$this->app['db'], $config['database'], $config['table']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new DynamoDb failed job provider.
|
||||
*
|
||||
* @param array $config
|
||||
* @return \Illuminate\Queue\Failed\DynamoDbFailedJobProvider
|
||||
*/
|
||||
protected function dynamoFailedJobProvider($config)
|
||||
{
|
||||
$dynamoConfig = [
|
||||
'region' => $config['region'],
|
||||
'version' => 'latest',
|
||||
'endpoint' => $config['endpoint'] ?? null,
|
||||
];
|
||||
|
||||
if (! empty($config['key']) && ! empty($config['secret'])) {
|
||||
$dynamoConfig['credentials'] = Arr::only($config, ['key', 'secret']);
|
||||
|
||||
if (! empty($config['token'])) {
|
||||
$dynamoConfig['credentials']['token'] = $config['token'];
|
||||
}
|
||||
}
|
||||
|
||||
return new DynamoDbFailedJobProvider(
|
||||
new DynamoDbClient($dynamoConfig),
|
||||
$this->app['config']['app.name'],
|
||||
$config['table']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the services provided by the provider.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function provides()
|
||||
{
|
||||
return [
|
||||
'queue',
|
||||
'queue.connection',
|
||||
'queue.failer',
|
||||
'queue.listener',
|
||||
'queue.worker',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
## Illuminate Queue
|
||||
|
||||
The Laravel Queue component provides a unified API across a variety of different queue services. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time, thus drastically speeding up the web requests to your application.
|
||||
|
||||
### Usage Instructions
|
||||
|
||||
First, create a new Queue `Capsule` manager instance. Similar to the "Capsule" provided for the Eloquent ORM, the queue Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible.
|
||||
|
||||
```PHP
|
||||
use Illuminate\Queue\Capsule\Manager as Queue;
|
||||
|
||||
$queue = new Queue;
|
||||
|
||||
$queue->addConnection([
|
||||
'driver' => 'beanstalkd',
|
||||
'host' => 'localhost',
|
||||
'queue' => 'default',
|
||||
]);
|
||||
|
||||
// Make this Capsule instance available globally via static methods... (optional)
|
||||
$queue->setAsGlobal();
|
||||
```
|
||||
|
||||
Once the Capsule instance has been registered. You may use it like so:
|
||||
|
||||
```PHP
|
||||
// As an instance...
|
||||
$queue->push('SendEmail', ['message' => $message]);
|
||||
|
||||
// If setAsGlobal has been called...
|
||||
Queue::push('SendEmail', ['message' => $message]);
|
||||
```
|
||||
|
||||
For further documentation on using the queue, consult the [Laravel framework documentation](https://laravel.com/docs).
|
||||
@@ -0,0 +1,464 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Queue\ClearableQueue;
|
||||
use Illuminate\Contracts\Queue\Queue as QueueContract;
|
||||
use Illuminate\Contracts\Redis\Factory as Redis;
|
||||
use Illuminate\Queue\Jobs\RedisJob;
|
||||
use Illuminate\Redis\Connections\PhpRedisClusterConnection;
|
||||
use Illuminate\Redis\Connections\PredisClusterConnection;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RedisQueue extends Queue implements QueueContract, ClearableQueue
|
||||
{
|
||||
/**
|
||||
* The Redis factory implementation.
|
||||
*
|
||||
* @var \Illuminate\Contracts\Redis\Factory
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
/**
|
||||
* The connection name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $connection;
|
||||
|
||||
/**
|
||||
* The name of the default queue.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $default;
|
||||
|
||||
/**
|
||||
* The expiration time of a job.
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected $retryAfter = 60;
|
||||
|
||||
/**
|
||||
* The maximum number of seconds to block for a job.
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected $blockFor = null;
|
||||
|
||||
/**
|
||||
* The batch size to use when migrating delayed / expired jobs onto the primary queue.
|
||||
*
|
||||
* Negative values are infinite.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $migrationBatchSize = -1;
|
||||
|
||||
/**
|
||||
* Indicates if a secondary queue had a job available between checks of the primary queue.
|
||||
*
|
||||
* Only applicable when monitoring multiple named queues with a single instance.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $secondaryQueueHadJob = false;
|
||||
|
||||
/**
|
||||
* Create a new Redis queue instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Redis\Factory $redis
|
||||
* @param string $default
|
||||
* @param string|null $connection
|
||||
* @param int $retryAfter
|
||||
* @param int|null $blockFor
|
||||
* @param bool $dispatchAfterCommit
|
||||
* @param int $migrationBatchSize
|
||||
*/
|
||||
public function __construct(
|
||||
Redis $redis,
|
||||
$default = 'default',
|
||||
$connection = null,
|
||||
$retryAfter = 60,
|
||||
$blockFor = null,
|
||||
$dispatchAfterCommit = false,
|
||||
$migrationBatchSize = -1,
|
||||
) {
|
||||
$this->redis = $redis;
|
||||
$this->default = $default;
|
||||
$this->blockFor = $blockFor;
|
||||
$this->connection = $connection;
|
||||
$this->retryAfter = $retryAfter;
|
||||
$this->dispatchAfterCommit = $dispatchAfterCommit;
|
||||
$this->migrationBatchSize = $migrationBatchSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function size($queue = null)
|
||||
{
|
||||
$queue = $this->getQueue($queue);
|
||||
|
||||
return $this->getConnection()->eval(
|
||||
LuaScripts::size(), 3, $queue, $queue.':delayed', $queue.':reserved'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of pending jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function pendingSize($queue = null)
|
||||
{
|
||||
return $this->getConnection()->llen($this->getQueue($queue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function delayedSize($queue = null)
|
||||
{
|
||||
return $this->getConnection()->zcard($this->getQueue($queue).':delayed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of reserved jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int
|
||||
*/
|
||||
public function reservedSize($queue = null)
|
||||
{
|
||||
return $this->getConnection()->zcard($this->getQueue($queue).':reserved');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the creation timestamp of the oldest pending job, excluding delayed jobs.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return int|null
|
||||
*/
|
||||
public function creationTimeOfOldestPendingJob($queue = null)
|
||||
{
|
||||
$payload = $this->getConnection()->lindex($this->getQueue($queue), 0);
|
||||
|
||||
if (! $payload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = json_decode($payload, true);
|
||||
|
||||
return $data['createdAt'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push an array of jobs onto the queue.
|
||||
*
|
||||
* @param array $jobs
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return void
|
||||
*/
|
||||
public function bulk($jobs, $data = '', $queue = null)
|
||||
{
|
||||
$connection = $this->getConnection();
|
||||
|
||||
$bulk = function () use ($jobs, $data, $queue) {
|
||||
foreach ((array) $jobs as $job) {
|
||||
if (isset($job->delay)) {
|
||||
$this->later($job->delay, $job, $data, $queue);
|
||||
} else {
|
||||
$this->push($job, $data, $queue);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if ($connection instanceof PhpRedisClusterConnection) {
|
||||
$connection->transaction($bulk);
|
||||
} elseif ($connection instanceof PredisClusterConnection) {
|
||||
$connection->pipeline($bulk);
|
||||
} else {
|
||||
$connection->pipeline(fn () => $connection->transaction($bulk));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue.
|
||||
*
|
||||
* @param object|string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function push($job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data),
|
||||
$queue,
|
||||
null,
|
||||
function ($payload, $queue) {
|
||||
return $this->pushRaw($payload, $queue);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw payload onto the queue.
|
||||
*
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @param array $options
|
||||
* @return mixed
|
||||
*/
|
||||
public function pushRaw($payload, $queue = null, array $options = [])
|
||||
{
|
||||
$this->getConnection()->eval(
|
||||
LuaScripts::push(), 2, $this->getQueue($queue),
|
||||
$this->getQueue($queue).':notify', $payload
|
||||
);
|
||||
|
||||
return json_decode($payload, true)['id'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a new job onto the queue after a delay.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param object|string $job
|
||||
* @param mixed $data
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
public function later($delay, $job, $data = '', $queue = null)
|
||||
{
|
||||
return $this->enqueueUsing(
|
||||
$job,
|
||||
$this->createPayload($job, $this->getQueue($queue), $data, $delay),
|
||||
$queue,
|
||||
$delay,
|
||||
function ($payload, $queue, $delay) {
|
||||
return $this->laterRaw($delay, $payload, $queue);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a raw job onto the queue after (n) seconds.
|
||||
*
|
||||
* @param \DateTimeInterface|\DateInterval|int $delay
|
||||
* @param string $payload
|
||||
* @param string|null $queue
|
||||
* @return mixed
|
||||
*/
|
||||
protected function laterRaw($delay, $payload, $queue = null)
|
||||
{
|
||||
$this->getConnection()->eval(
|
||||
LuaScripts::later(), 1, $this->getQueue($queue).':delayed',
|
||||
$this->availableAt($delay), $payload
|
||||
);
|
||||
|
||||
return json_decode($payload, true)['id'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a payload string from the given job and data.
|
||||
*
|
||||
* @param string $job
|
||||
* @param string $queue
|
||||
* @param mixed $data
|
||||
* @return array
|
||||
*/
|
||||
protected function createPayloadArray($job, $queue, $data = '')
|
||||
{
|
||||
return array_merge(parent::createPayloadArray($job, $queue, $data), [
|
||||
'id' => $this->getRandomId(),
|
||||
'attempts' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the next job off of the queue.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @param int $index
|
||||
* @return \Illuminate\Contracts\Queue\Job|null
|
||||
*/
|
||||
public function pop($queue = null, $index = 0)
|
||||
{
|
||||
$this->migrate($prefixed = $this->getQueue($queue));
|
||||
|
||||
$block = ! $this->secondaryQueueHadJob && $index == 0;
|
||||
|
||||
[$job, $reserved] = $this->retrieveNextJob($prefixed, $block);
|
||||
|
||||
if ($index == 0) {
|
||||
$this->secondaryQueueHadJob = false;
|
||||
}
|
||||
|
||||
if ($reserved) {
|
||||
if ($index > 0) {
|
||||
$this->secondaryQueueHadJob = true;
|
||||
}
|
||||
|
||||
return new RedisJob(
|
||||
$this->container, $this, $job,
|
||||
$reserved, $this->connectionName, $queue ?: $this->default
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate any delayed or expired jobs onto the primary queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @return void
|
||||
*/
|
||||
protected function migrate($queue)
|
||||
{
|
||||
$this->migrateExpiredJobs($queue.':delayed', $queue);
|
||||
|
||||
if (! is_null($this->retryAfter)) {
|
||||
$this->migrateExpiredJobs($queue.':reserved', $queue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate the delayed jobs that are ready to the regular queue.
|
||||
*
|
||||
* @param string $from
|
||||
* @param string $to
|
||||
* @return array
|
||||
*/
|
||||
public function migrateExpiredJobs($from, $to)
|
||||
{
|
||||
return $this->getConnection()->eval(
|
||||
LuaScripts::migrateExpiredJobs(), 3, $from, $to, $to.':notify', $this->currentTime(), $this->migrationBatchSize
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the next job from the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param bool $block
|
||||
* @return array
|
||||
*/
|
||||
protected function retrieveNextJob($queue, $block = true)
|
||||
{
|
||||
$nextJob = $this->getConnection()->eval(
|
||||
LuaScripts::pop(), 3, $queue, $queue.':reserved', $queue.':notify',
|
||||
$this->availableAt($this->retryAfter)
|
||||
);
|
||||
|
||||
if (empty($nextJob)) {
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
[$job, $reserved] = $nextJob;
|
||||
|
||||
if (! $job && ! is_null($this->blockFor) && $block &&
|
||||
$this->getConnection()->blpop([$queue.':notify'], $this->blockFor)) {
|
||||
return $this->retrieveNextJob($queue, false);
|
||||
}
|
||||
|
||||
return [$job, $reserved];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a reserved job from the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\Jobs\RedisJob $job
|
||||
* @return void
|
||||
*/
|
||||
public function deleteReserved($queue, $job)
|
||||
{
|
||||
$this->getConnection()->zrem($this->getQueue($queue).':reserved', $job->getReservedJob());
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a reserved job from the reserved queue and release it.
|
||||
*
|
||||
* @param string $queue
|
||||
* @param \Illuminate\Queue\Jobs\RedisJob $job
|
||||
* @param int $delay
|
||||
* @return void
|
||||
*/
|
||||
public function deleteAndRelease($queue, $job, $delay)
|
||||
{
|
||||
$queue = $this->getQueue($queue);
|
||||
|
||||
$this->getConnection()->eval(
|
||||
LuaScripts::release(), 2, $queue.':delayed', $queue.':reserved',
|
||||
$job->getReservedJob(), $this->availableAt($delay)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all of the jobs from the queue.
|
||||
*
|
||||
* @param string $queue
|
||||
* @return int
|
||||
*/
|
||||
public function clear($queue)
|
||||
{
|
||||
$queue = $this->getQueue($queue);
|
||||
|
||||
return $this->getConnection()->eval(
|
||||
LuaScripts::clear(), 4, $queue, $queue.':delayed',
|
||||
$queue.':reserved', $queue.':notify'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a random ID string.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getRandomId()
|
||||
{
|
||||
return Str::random(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queue or return the default.
|
||||
*
|
||||
* @param string|null $queue
|
||||
* @return string
|
||||
*/
|
||||
public function getQueue($queue)
|
||||
{
|
||||
return 'queues:'.($queue ?: $this->default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the connection for the queue.
|
||||
*
|
||||
* @return \Illuminate\Redis\Connections\Connection
|
||||
*/
|
||||
public function getConnection()
|
||||
{
|
||||
return $this->redis->connection($this->connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Redis instance.
|
||||
*
|
||||
* @return \Illuminate\Contracts\Redis\Factory
|
||||
*/
|
||||
public function getRedis()
|
||||
{
|
||||
return $this->redis;
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace Illuminate\Queue;
|
||||
|
||||
use Illuminate\Contracts\Database\ModelIdentifier;
|
||||
use Illuminate\Contracts\Queue\QueueableCollection;
|
||||
use Illuminate\Contracts\Queue\QueueableEntity;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
|
||||
use Illuminate\Database\Eloquent\Relations\Pivot;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
trait SerializesAndRestoresModelIdentifiers
|
||||
{
|
||||
/**
|
||||
* Get the property value prepared for serialization.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param bool $withRelations
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getSerializedPropertyValue($value, $withRelations = true)
|
||||
{
|
||||
if ($value instanceof QueueableCollection) {
|
||||
return (new ModelIdentifier(
|
||||
$value->getQueueableClass(),
|
||||
$value->getQueueableIds(),
|
||||
$withRelations ? $value->getQueueableRelations() : [],
|
||||
$value->getQueueableConnection()
|
||||
))->useCollectionClass(
|
||||
($collectionClass = get_class($value)) !== EloquentCollection::class
|
||||
? $collectionClass
|
||||
: null
|
||||
);
|
||||
}
|
||||
|
||||
if ($value instanceof QueueableEntity) {
|
||||
return new ModelIdentifier(
|
||||
get_class($value),
|
||||
$value->getQueueableId(),
|
||||
$withRelations ? $value->getQueueableRelations() : [],
|
||||
$value->getQueueableConnection()
|
||||
);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the restored property value after deserialization.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getRestoredPropertyValue($value)
|
||||
{
|
||||
if (! $value instanceof ModelIdentifier) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return is_array($value->id)
|
||||
? $this->restoreCollection($value)
|
||||
: $this->restoreModel($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore a queueable collection instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Database\ModelIdentifier $value
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
*/
|
||||
protected function restoreCollection($value)
|
||||
{
|
||||
$class = $value->getClass();
|
||||
|
||||
if (! $class || count($value->id) === 0) {
|
||||
return ! is_null($value->collectionClass ?? null)
|
||||
? new $value->collectionClass
|
||||
: new EloquentCollection;
|
||||
}
|
||||
|
||||
$collection = $this->getQueryForModelRestoration(
|
||||
(new $class)->setConnection($value->connection), $value->id
|
||||
)->useWritePdo()->get();
|
||||
|
||||
if (is_a($class, Pivot::class, true) ||
|
||||
in_array(AsPivot::class, class_uses($class))) {
|
||||
return $collection;
|
||||
}
|
||||
|
||||
$collection = $collection->keyBy->getKey();
|
||||
|
||||
$collectionClass = get_class($collection);
|
||||
|
||||
return new $collectionClass(
|
||||
(new Collection($value->id))
|
||||
->map(fn ($id) => $collection[$id] ?? null)
|
||||
->filter()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore the model from the model identifier instance.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Database\ModelIdentifier $value
|
||||
* @return \Illuminate\Database\Eloquent\Model
|
||||
*/
|
||||
public function restoreModel($value)
|
||||
{
|
||||
return $this->getQueryForModelRestoration(
|
||||
(new ($value->getClass()))->setConnection($value->connection), $value->id
|
||||
)->useWritePdo()->firstOrFail()->loadMissing($value->relations ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the query for model restoration.
|
||||
*
|
||||
* @template TModel of \Illuminate\Database\Eloquent\Model
|
||||
*
|
||||
* @param TModel $model
|
||||
* @param array|int $ids
|
||||
* @return \Illuminate\Database\Eloquent\Builder<TModel>
|
||||
*/
|
||||
protected function getQueryForModelRestoration($model, $ids)
|
||||
{
|
||||
return $model->newQueryForRestoration($ids);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user