-
Notifications
You must be signed in to change notification settings - Fork 437
/
LimitConsumerMemoryExtension.php
71 lines (60 loc) · 2.07 KB
/
LimitConsumerMemoryExtension.php
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
<?php
namespace Enqueue\Consumption\Extension;
use Enqueue\Consumption\Context\PostConsume;
use Enqueue\Consumption\Context\PostMessageReceived;
use Enqueue\Consumption\Context\PreConsume;
use Enqueue\Consumption\PostConsumeExtensionInterface;
use Enqueue\Consumption\PostMessageReceivedExtensionInterface;
use Enqueue\Consumption\PreConsumeExtensionInterface;
use Psr\Log\LoggerInterface;
class LimitConsumerMemoryExtension implements PreConsumeExtensionInterface, PostMessageReceivedExtensionInterface, PostConsumeExtensionInterface
{
/**
* @var int
*/
protected $memoryLimit;
/**
* @param int $memoryLimit Megabytes
*/
public function __construct($memoryLimit)
{
if (false == is_int($memoryLimit)) {
throw new \InvalidArgumentException(sprintf(
'Expected memory limit is int but got: "%s"',
is_object($memoryLimit) ? get_class($memoryLimit) : gettype($memoryLimit)
));
}
$this->memoryLimit = $memoryLimit * 1024 * 1024;
}
public function onPreConsume(PreConsume $context): void
{
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
public function onPostMessageReceived(PostMessageReceived $context): void
{
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
public function onPostConsume(PostConsume $context): void
{
if ($this->shouldBeStopped($context->getLogger())) {
$context->interruptExecution();
}
}
protected function shouldBeStopped(LoggerInterface $logger): bool
{
$memoryUsage = memory_get_usage(true);
if ($memoryUsage >= $this->memoryLimit) {
$logger->debug(sprintf(
'[LimitConsumerMemoryExtension] Interrupt execution as memory limit reached. limit: "%s", used: "%s"',
$this->memoryLimit,
$memoryUsage
));
return true;
}
return false;
}
}