-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathLimitConsumedMessagesExtension.php
More file actions
82 lines (72 loc) · 2.48 KB
/
LimitConsumedMessagesExtension.php
File metadata and controls
82 lines (72 loc) · 2.48 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
<?php
declare(strict_types=1);
namespace Cake\Queue\Consumption;
use Enqueue\Consumption\Context\PostConsume;
use Enqueue\Consumption\Context\PreConsume;
use Enqueue\Consumption\PostConsumeExtensionInterface;
use Enqueue\Consumption\PreConsumeExtensionInterface;
use Psr\Log\LoggerInterface;
/**
* A consumer extension to limit the number of messages that are processed.
*
* This is a place holder until the upstream enqueue project extension is merged.
*
* @see https://github.com/php-enqueue/enqueue-dev/pull/1244
*/
class LimitConsumedMessagesExtension implements PreConsumeExtensionInterface, PostConsumeExtensionInterface
{
protected int $messageConsumed = 0;
/**
* @param int $messageLimit The number of messages to process before exiting.
*/
public function __construct(
protected readonly int $messageLimit,
) {
}
/**
* Executed at every new cycle before calling SubscriptionConsumer::consume method.
* The consumption could be interrupted at this step.
*
* @param \Enqueue\Consumption\Context\PreConsume $context The PreConsume context.
* @return void
*/
public function onPreConsume(PreConsume $context): void
{
// this is added here to handle an edge case. when a user sets zero as limit.
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
/**
* The method is called after SubscriptionConsumer::consume method exits.
* The consumption could be interrupted at this point.
*
* @param \Enqueue\Consumption\Context\PostConsume $context The PostConsume context.
* @return void
*/
public function onPostConsume(PostConsume $context): void
{
++$this->messageConsumed;
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
/**
* Check if the consumer should be stopped.
*
* @param \Psr\Log\LoggerInterface $logger The logger where messages will be logged.
* @return bool
*/
protected function shouldBeStopped(LoggerInterface $logger): bool
{
if ($this->messageConsumed >= $this->messageLimit) {
$logger->debug(sprintf(
'[LimitConsumedMessagesExtension] Message consumption is interrupted since the message limit ' .
'reached. limit: "%s"',
$this->messageLimit,
));
return true;
}
return false;
}
}