47 lines
1.3 KiB
PHP
47 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Malware;
|
|
|
|
use App\Jobs\ScanDocumentForMalware;
|
|
use Closure;
|
|
use Illuminate\Bus\UniqueLock;
|
|
use Illuminate\Contracts\Cache\Repository;
|
|
use Illuminate\Foundation\Queue\InteractsWithUniqueJobs;
|
|
use Illuminate\Support\Facades\Bus;
|
|
|
|
/** Observe the existing unique-job lease without claiming that a worker ran. */
|
|
final class DocumentScanDelivery
|
|
{
|
|
use InteractsWithUniqueJobs;
|
|
|
|
/** @param Closure():bool|null $prepare */
|
|
public function dispatch(ScanDocumentForMalware $job, ?Closure $prepare = null): string
|
|
{
|
|
$lock = new UniqueLock(app(Repository::class));
|
|
if (! $lock->acquire($job)) {
|
|
return 'duplicate';
|
|
}
|
|
$attempted = false;
|
|
$contextAdded = false;
|
|
try {
|
|
if ($prepare !== null && ! $prepare()) {
|
|
return 'stale';
|
|
}
|
|
$this->addUniqueJobInformationToContext($job);
|
|
$contextAdded = true;
|
|
$attempted = true;
|
|
Bus::dispatch($job);
|
|
|
|
return 'accepted';
|
|
} finally {
|
|
if ($contextAdded) {
|
|
$this->removeUniqueJobInformationFromContext($job);
|
|
}
|
|
// A push error may follow acceptance. Keep its lease until the worker or expiry.
|
|
if (! $attempted) {
|
|
$lock->release($job);
|
|
}
|
|
}
|
|
}
|
|
}
|