|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Stackkit\LaravelGoogleCloudTasksQueue; |
| 6 | + |
| 7 | +use Illuminate\Queue\Worker as LaravelWorker; |
| 8 | +use Illuminate\Queue\WorkerOptions; |
| 9 | + |
| 10 | +/** |
| 11 | + * Custom worker class to handle specific requirements for Google Cloud Tasks. |
| 12 | + * |
| 13 | + * This class modifies the behavior of the Laravel queue worker to better |
| 14 | + * integrate with Google Cloud Tasks, particularly focusing on job timeout |
| 15 | + * handling and graceful shutdowns to avoid interrupting the HTTP lifecycle. |
| 16 | + * |
| 17 | + * Firstly, the 'supportsAsyncSignals', 'listenForSignals', and 'registerTimeoutHandler' methods |
| 18 | + * are protected and called within the queue while(true) loop. We want (and need!) to have that |
| 19 | + * too in order to support job timeouts. So, to make it work, we create a public method that |
| 20 | + * can call the private signal methods. |
| 21 | + * |
| 22 | + * Secondly, we need to override the 'kill' method because it tends to kill the server process (artisan serve, octane), |
| 23 | + * as well as abort the HTTP request from Cloud Tasks. This is not the desired behavior. |
| 24 | + * Instead, it should just fire the WorkerStopped event and return a normal status code. |
| 25 | + */ |
| 26 | +class Worker extends LaravelWorker |
| 27 | +{ |
| 28 | + public function process($connectionName, $job, WorkerOptions $options) |
| 29 | + { |
| 30 | + if ($this->supportsAsyncSignals()) { |
| 31 | + $this->listenForSignals(); |
| 32 | + |
| 33 | + $this->registerTimeoutHandler($job, $options); |
| 34 | + } |
| 35 | + |
| 36 | + return parent::process($connectionName, $job, $options); |
| 37 | + } |
| 38 | + |
| 39 | + public function kill($status = 0, $options = null): void |
| 40 | + { |
| 41 | + parent::stop($status, $options); |
| 42 | + |
| 43 | + // When running tests, we cannot run exit because it will kill the PHPunit process. |
| 44 | + // So, to still test that the application has exited, we will simply rely on the |
| 45 | + // WorkerStopped event that is fired when the worker is stopped. |
| 46 | + if (app()->runningUnitTests()) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + exit($status); |
| 51 | + } |
| 52 | +} |
0 commit comments