-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkerMemoryUsageSubscriber.php
More file actions
67 lines (52 loc) · 1.91 KB
/
Copy pathWorkerMemoryUsageSubscriber.php
File metadata and controls
67 lines (52 loc) · 1.91 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
<?php
declare(strict_types=1);
namespace WonderNetwork\SlimKernel\Messenger;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerRunningEvent;
use WonderNetwork\SlimKernel\System\RealSystem;
use WonderNetwork\SlimKernel\System\System;
final class WorkerMemoryUsageSubscriber implements EventSubscriberInterface {
private int $memoryUsage;
private readonly System $system;
/**
* @return iterable<string,string>
*/
public static function getSubscribedEvents(): iterable {
return [
WorkerRunningEvent::class => 'onWorkerRunning',
];
}
public function __construct(
private readonly LoggerInterface $logger,
private readonly int $cutoff = 1024,
System $system = null,
) {
$this->system = $system ?? new RealSystem();
$this->memoryUsage = $this->system->memoryUsage();
}
public function onWorkerRunning(): void {
$currentUsage = $this->system->memoryUsage();
$difference = abs($this->memoryUsage - $currentUsage);
if ($difference < $this->cutoff) {
return;
}
$this->logger->debug(
"Memory usage changed: {current} ({sign}{difference})",
[
'current' => $this->formatBytes($currentUsage),
'sign' => ($this->memoryUsage > $currentUsage) ? "-" : "+",
'difference' => $this->formatBytes($difference),
],
);
$this->memoryUsage = $currentUsage;
}
private function formatBytes(int $bytes): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = (int) min($pow, count($units) - 1);
$bytes /= 1024 ** $pow;
return sprintf("%s %s", round($bytes, 2), $units[$pow]);
}
}