Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/EventDispatcher/EventSubscribersCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
use RuntimeException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WonderNetwork\SlimKernel\ServiceFactory;
use WonderNetwork\SlimKernel\ServicesBuilder;
use function DI\decorate;

final readonly class EventSubscribersCollection {
final readonly class EventSubscribersCollection implements ServiceFactory {
public static function start(): self {
return new self([]);
}
Expand All @@ -21,6 +23,10 @@ public static function start(): self {
public function __construct(private array $subscribers) {
}

public function __invoke(ServicesBuilder $builder): iterable {
yield from $this->register();
}

/**
* @param class-string<EventSubscriberInterface> ...$subscribers
*/
Expand Down
67 changes: 67 additions & 0 deletions src/Messenger/WorkerMemoryUsageSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,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]);
}
}
1 change: 1 addition & 0 deletions src/Supervisor/GenerateSupervisorConfigCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
command=$fullCommand
process_name=$processName
numprocs=$concurrency
startretries=$program->startretries
user=www-data
autostart=true
autorestart=true
Expand Down
3 changes: 3 additions & 0 deletions src/Supervisor/SupervisorProgram.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ public static function single(string $name, string $command): self {
name: $name,
command: $command,
concurrency: 1,
startretries: 15,
);
}

/**
* @param positive-int $concurrency
* @param positive-int $startretries
*/
public function __construct(
public string $name,
public string $command,
public int $concurrency,
public int $startretries,
) {
}
}
11 changes: 11 additions & 0 deletions src/System/RealSystem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\System;

final readonly class RealSystem implements System {
public function memoryUsage(): int {
return memory_get_usage();
}
}
9 changes: 9 additions & 0 deletions src/System/System.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\System;

interface System {
public function memoryUsage(): int;
}
7 changes: 4 additions & 3 deletions tests/ConsoleLogger/ConsoleLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ public function testConsoleLogger(): void {
return $logger;
},
ConsoleHandlerEventSubscriber::class => autowire(),
...EventSubscribersCollection::start()
->add(ConsoleHandlerEventSubscriber::class)
->register(),
],
)
->register(
EventSubscribersCollection::start()
->add(ConsoleHandlerEventSubscriber::class),
)
->register(
new SymfonyConsoleServiceFactory(
path: '/src/*Command.php',
Expand Down
46 changes: 46 additions & 0 deletions tests/Messenger/WorkerMemoryUsageSubscriberTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\Messenger;

use Monolog\Handler\TestHandler;
use Monolog\Logger;
use PHPUnit\Framework\TestCase;
use WonderNetwork\SlimKernel\System\FakeSystem;

final class WorkerMemoryUsageSubscriberTest extends TestCase {
public function testReportsAboveCutoff(): void {
$buffer = new TestHandler();
$logger = new Logger('some');
$logger->pushHandler($buffer);

$system = new FakeSystem();

$sut = new WorkerMemoryUsageSubscriber(
logger: $logger,
cutoff: 10 * 1024,
system: $system,
);
$sut->onWorkerRunning();
self::assertEmpty($buffer->getRecords());

$system->setMemoryUsage(10 * 1024 - 1);
$sut->onWorkerRunning();
self::assertCount(0, $buffer->getRecords());

$system->setMemoryUsage(10 * 1024);
$sut->onWorkerRunning();
self::assertCount(1, $buffer->getRecords());
self::assertSame([
'current' => '10 KB',
'sign' => '+',
'difference' => '10 KB',
], $buffer->getRecords()[0]->context);

$sut->onWorkerRunning();
$system->setMemoryUsage(12 * 1024);
$sut->onWorkerRunning();
self::assertCount(1, $buffer->getRecords());
}
}
6 changes: 6 additions & 0 deletions tests/Supervisor/GenerateSupervisorConfigCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public function testGeneratesConfig(): void {
name: 'jobs',
command: 'bin/worker jobs',
concurrency: 3,
startretries: 10,
),
);
$configDir = __DIR__.'/../Resources/Supervisor';
Expand Down Expand Up @@ -47,6 +48,7 @@ public function testGeneratesConfig(): void {
command=/var/app/current/bin/worker jobs
process_name=%(program_name)s_%(process_num)02d
numprocs=3
startretries=10
user=www-data
autostart=true
autorestart=true
Expand All @@ -58,6 +60,7 @@ public function testGeneratesConfig(): void {
command=/var/app/current/bin/worker async
process_name=worker
numprocs=1
startretries=15
user=www-data
autostart=true
autorestart=true
Expand All @@ -84,6 +87,7 @@ public function testGeneratesConfigWithStdio(): void {
name: 'jobs',
command: 'bin/worker jobs',
concurrency: 3,
startretries: 10,
),
);
$configDir = __DIR__.'/../Resources/Supervisor';
Expand All @@ -105,6 +109,7 @@ public function testGeneratesConfigWithStdio(): void {
command=/var/app/current/bin/worker jobs
process_name=%(program_name)s_%(process_num)02d
numprocs=3
startretries=10
user=www-data
autostart=true
autorestart=true
Expand All @@ -116,6 +121,7 @@ public function testGeneratesConfigWithStdio(): void {
command=/var/app/current/bin/worker async
process_name=worker
numprocs=1
startretries=15
user=www-data
autostart=true
autorestart=true
Expand Down
17 changes: 17 additions & 0 deletions tests/System/FakeSystem.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace WonderNetwork\SlimKernel\System;

final class FakeSystem implements System {
private int $memoryUsage = 0;

public function setMemoryUsage(int $memoryUsage): void {
$this->memoryUsage = $memoryUsage;
}

public function memoryUsage(): int {
return $this->memoryUsage;
}
}