-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathLimitAttemptsExtension.php
More file actions
85 lines (67 loc) · 2.51 KB
/
LimitAttemptsExtension.php
File metadata and controls
85 lines (67 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace Cake\Queue\Consumption;
use Cake\Event\EventDispatcherTrait;
use Cake\Queue\Job\Message;
use Enqueue\Consumption\Context\MessageResult;
use Enqueue\Consumption\MessageResultExtensionInterface;
use Enqueue\Consumption\Result;
use Interop\Queue\Processor;
class LimitAttemptsExtension implements MessageResultExtensionInterface
{
/**
* @use \Cake\Event\EventDispatcherTrait<\Cake\Queue\Job\Message>
*/
use EventDispatcherTrait;
/**
* The property key used to set the number of times a message was attempted.
*
* @var string
*/
public const ATTEMPTS_PROPERTY = 'attempts';
/**
* @param int|null $maxAttempts The maximum number of times a job may be attempted. $maxAttempts defined on a Job will override this value.
*/
public function __construct(
protected readonly ?int $maxAttempts = null,
) {
}
/**
* @param \Enqueue\Consumption\Context\MessageResult $context The result of the message after it was processed.
* @return void
*/
public function onResult(MessageResult $context): void
{
if ($context->getResult() != Processor::REQUEUE) {
return;
}
$message = $context->getMessage();
$jobMessage = new Message($message, $context->getContext());
$maxAttempts = $jobMessage->getMaxAttempts() ?? $this->maxAttempts;
if ($maxAttempts === null) {
return;
}
$attemptNumber = $message->getProperty(self::ATTEMPTS_PROPERTY, 0) + 1;
if ($attemptNumber >= $maxAttempts) {
$context->changeResult(
Result::reject(sprintf('The maximum number of %d allowed attempts was reached.', $maxAttempts)),
);
$exception = (string)$message->getProperty('jobException');
$this->dispatchEvent(
'Consumption.LimitAttemptsExtension.failed',
['exception' => $exception, 'logger' => $context->getLogger()],
$jobMessage,
);
return;
}
$newMessage = clone $message;
$newMessage->setProperty(self::ATTEMPTS_PROPERTY, $attemptNumber);
$queueContext = $context->getContext();
$producer = $queueContext->createProducer();
$consumer = $context->getConsumer();
$producer->send($consumer->getQueue(), $newMessage);
$context->changeResult(
Result::reject('A copy of the message was sent with an incremented attempt count.'),
);
}
}