Skip to content

Commit

Permalink
Improved MemoryInterrupter testability
Browse files Browse the repository at this point in the history
  • Loading branch information
vudaltsov committed Jul 28, 2020
1 parent 3c6fbb0 commit 11ce5d6
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/MemoryInterrupter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,38 @@ final class MemoryInterrupter
*/
private $maxBytes;

public function __construct(int $maxBytes)
/**
* @psalm-var callable(): int
*/
private $memoryGetUsage;

/**
* @psalm-param ?callable(): int $memoryGetUsage
*/
public function __construct(int $maxBytes, ?callable $memoryGetUsage = null)
{
if ($maxBytes <= 0) {
throw new \InvalidArgumentException(sprintf('Parameter $maxBytes must be a positive integer, got %d.', $maxBytes));
}

$this->maxBytes = $maxBytes;
$this->memoryGetUsage = $memoryGetUsage ?? static function (): int { return memory_get_usage(true); };
}

public function __invoke(Context $context): void
{
$usedMemory = memory_get_usage(true);
$usedMemory = ($this->memoryGetUsage)();

if ($usedMemory < $this->maxBytes) {
return;
}

$context->stop();
$context->log('Worker stopped after exceeding the memory limit of {limit} bytes ({memory} bytes used).', [
'limit' => $this->maxBytes,
'memory' => $usedMemory,
], LogLevel::WARNING);

$context->log(
'Worker stopped after exceeding the memory limit of {limit} bytes ({memory} bytes used).',
['limit' => $this->maxBytes, 'memory' => $usedMemory],
LogLevel::WARNING
);
}
}

0 comments on commit 11ce5d6

Please sign in to comment.