From 09573b16b943e2d1758a83eb3a9fd38682e69140 Mon Sep 17 00:00:00 2001 From: Denis Mysenko Date: Sun, 27 Nov 2022 14:48:34 +1100 Subject: [PATCH] + custom queued handler --- README.md | 28 +++++++++++++++++ src/Exceptions/ExpiredJobException.php | 6 ++++ src/Jobs/CallQueuedHandler.php | 42 ++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 src/Exceptions/ExpiredJobException.php create mode 100644 src/Jobs/CallQueuedHandler.php diff --git a/README.md b/README.md index 5fb40a9..65df31a 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,34 @@ Please make sure that two special routes are not mounted behind a CSRF middlewar If your job fails, we will throw a ```FailedJobException```. If you want to customize error output – just customise your exception handler. Note that your HTTP status code must be different from 200 in order for AWS to realize the job has failed. +## Job expiration (retention) + +A new nice feature is being able to set a job expiration (retention in AWS terms) in seconds so +that low value jobs get skipped completely if there is temporary queue latency due to load. + +Let's say we have a spike in queued jobs and some of them don't even make sense anymore +now that a few minutes passed – we don't want to spend computing resources processing them +later. + +By setting a special property on a job or a listener class: +```php +class PurgeCache implements ShouldQueue +{ + public static int $retention = 300; // If this job is delayed more than 300 seconds, skip it +} +``` + +We can make sure that we won't run this job later than 300 seconds since it's been queued. +This is similar to AWS SQS "message retention" setting which can only be set globally for +the whole queue. + +To use this new feature, you have to use provided ```Jobs\CallQueuedHandler``` class that +extends Laravel's default ```CallQueuedHandler```. A special ```ExpiredJobException``` exception +will be thrown when expired jobs arrive and then it's up to you what to do with them. + +If you just catch these exceptions and therefore stop Laravel from returning code 500 +to AWS daemon, the job will be deleted by AWS automatically. + ## ToDo 1. Add support for AWS dead letter queue (retry jobs from that queue?) diff --git a/src/Exceptions/ExpiredJobException.php b/src/Exceptions/ExpiredJobException.php new file mode 100644 index 0000000..9fcbe20 --- /dev/null +++ b/src/Exceptions/ExpiredJobException.php @@ -0,0 +1,6 @@ +hasExpired($command, $job->timestamp())) { + throw new ExpiredJobException("This job has already expired"); + } + + return parent::dispatchThroughMiddleware($job, $command); + } + + /** + * @param $command + * @param $queuedAt + * @return bool + */ + protected function hasExpired($command, $queuedAt) { + if (! property_exists($command, 'class')) { + return false; + } + + if (! property_exists($command->class, 'retention')) { + return false; + } + + return time() > $queuedAt + $command->class::$retention; + } +}