Skip to content
Merged
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
13 changes: 11 additions & 2 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ private function loop(): void
$this->forkNewConnection($clientSocket, $connectionId);
}

$secondsSinceLastMemoryLog = $this->lastMemoryLog->diff(new \DateTime)->format('%s');
if ($secondsSinceLastMemoryLog > $this->memoryLogInterval) {
if ($this->isMemoryLogDue()) {
$this->logMemoryUsage();
}
}
Expand Down Expand Up @@ -367,6 +366,16 @@ private function errorAndExit(string $text, int $exitCode = 1): void
exit($exitCode);
}

/**
* Determine whether the configured interval has fully elapsed.
*/
private function isMemoryLogDue(?\DateTimeImmutable $now = null): bool
{
$now ??= new \DateTimeImmutable;

return $now->getTimestamp() - $this->lastMemoryLog->getTimestamp() >= $this->memoryLogInterval;
}

private function logMemoryUsage(): void
{
$this->lastMemoryLog = new \DateTime;
Expand Down
44 changes: 44 additions & 0 deletions tests/Unit/MemoryLoggingTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

use Whisp\Server;

test('memory logging checks total elapsed seconds', function () {
// Avoid starting a server or writing host keys; only the interval calculation is tested.
$reflection = new ReflectionClass(Server::class);
$server = $reflection->newInstanceWithoutConstructor();
$server->memoryLogInterval = 180;

$utc = new DateTimeZone('UTC');
$reflection->getProperty('lastMemoryLog')->setValue(
$server,
new DateTime('2026-01-01 12:00:00', $utc),
);

$isMemoryLogDue = $reflection->getMethod('isMemoryLogDue');

// Below the configured interval: no log yet.
expect($isMemoryLogDue->invoke($server, new DateTimeImmutable('2026-01-01 12:02:59', $utc)))->toBeFalse();

// At the exact threshold and beyond: a memory log is due.
expect($isMemoryLogDue->invoke($server, new DateTimeImmutable('2026-01-01 12:03:00', $utc)))->toBeTrue();
expect($isMemoryLogDue->invoke($server, new DateTimeImmutable('2026-01-01 12:04:30', $utc)))->toBeTrue();
});

test('memory logging respects shorter custom intervals', function () {
$reflection = new ReflectionClass(Server::class);
$server = $reflection->newInstanceWithoutConstructor();
$server->memoryLogInterval = 30;

$utc = new DateTimeZone('UTC');
$reflection->getProperty('lastMemoryLog')->setValue(
$server,
new DateTime('2026-01-01 12:00:00', $utc),
);

$isMemoryLogDue = $reflection->getMethod('isMemoryLogDue');

expect($isMemoryLogDue->invoke($server, new DateTimeImmutable('2026-01-01 12:00:29', $utc)))->toBeFalse();
expect($isMemoryLogDue->invoke($server, new DateTimeImmutable('2026-01-01 12:00:30', $utc)))->toBeTrue();
});
Loading