winzik/engine/tests/Net/HttpServerTest.php
David Nurdin 2648e71407 Réseau : salles privées par identifiant long (NetSession::enter) et serveur HTTP local non bloquant (HttpServer)
- NetSession::enter($id, $maxPeers) rejoint ou crée une salle d'identifiant long (room-id.patch du relais),
  newRoomId(), isRoomId(), attach() (autre transport / faux en test), MAX_PAYLOAD = 65535, erreur room-id
  si le relais ne garde pas l'identifiant
- HttpServer + HttpRequest + HttpResponse : HTTP/1.1 sur le bureau, poll() par frame, fichiers par blocs de
  64 Ko avec Range (206/416), HEAD, keep-alive, filtre d'adresse (isPrivateAddress), ports 47610+
- tests HttpServerTest, NetRoomTest (faux transport + vrai relais), docs/reseau.md, AGENTS.md §9

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 11:58:01 +01:00

283 lines
12 KiB
PHP

<?php
namespace JumPHP\Tests\Net;
use JumPHP\Net\HttpRequest;
use JumPHP\Net\HttpResponse;
use JumPHP\Net\HttpServer;
use PHPUnit\Framework\TestCase;
final class HttpServerTest extends TestCase
{
private HttpServer $server;
private int $port;
private string $file;
/** @var list<string> */
private array $temp = [];
protected function setUp(): void
{
$this->file = $this->tempFile(implode('', range('a', 'z')) . implode('', range('A', 'Z'))); // 52 bytes
$this->server = new HttpServer();
$this->server->handle('/hello', fn (HttpRequest $r) => HttpResponse::text('hi ' . ($r->query['name'] ?? '?')));
$this->server->handle('/f/', fn (HttpRequest $r) => $r->path === '/f/song' ? HttpResponse::file($this->file, 'audio/mpeg') : null);
$this->port = $this->server->listen(0, '127.0.0.1');
}
protected function tearDown(): void
{
$this->server->close();
foreach ($this->temp as $file) {
@unlink($file);
}
}
public function testAHandlerAnswersAGet(): void
{
$response = $this->request("GET /hello?name=Ada HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n");
self::assertSame(200, $response['status']);
self::assertSame('hi Ada', $response['body']);
self::assertSame('6', $response['headers']['content-length']);
}
public function testAFileIsServedWholeOrByRange(): void
{
$whole = $this->request("GET /f/song HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n");
self::assertSame(200, $whole['status']);
self::assertSame((string)file_get_contents($this->file), $whole['body']);
self::assertSame('audio/mpeg', $whole['headers']['content-type']);
self::assertSame('bytes', $whole['headers']['accept-ranges']);
$part = $this->request("GET /f/song HTTP/1.1\r\nHost: x\r\nRange: bytes=2-5\r\nConnection: close\r\n\r\n");
self::assertSame(206, $part['status']);
self::assertSame('cdef', $part['body']);
self::assertSame('bytes 2-5/52', $part['headers']['content-range']);
$tail = $this->request("GET /f/song HTTP/1.1\r\nHost: x\r\nRange: bytes=50-\r\nConnection: close\r\n\r\n");
self::assertSame('YZ', $tail['body']);
$last = $this->request("GET /f/song HTTP/1.1\r\nHost: x\r\nRange: bytes=-3\r\nConnection: close\r\n\r\n");
self::assertSame('XYZ', $last['body']);
}
public function testAnUnknownPathIs404AndARangeBeyondTheEndIs416(): void
{
self::assertSame(404, $this->request("GET /nothing HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")['status']);
self::assertSame(404, $this->request("GET /f/other HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")['status']);
$response = $this->request("GET /f/song HTTP/1.1\r\nHost: x\r\nRange: bytes=52-\r\nConnection: close\r\n\r\n");
self::assertSame(416, $response['status']);
self::assertSame('bytes */52', $response['headers']['content-range']);
}
public function testHeadGivesTheHeadersWithoutTheBody(): void
{
$response = $this->request("HEAD /f/song HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n", head: true);
self::assertSame(200, $response['status']);
self::assertSame('52', $response['headers']['content-length']);
self::assertSame('', $response['body']);
}
public function testKeepAliveAnswersTwoRequestsOnOneConnection(): void
{
$client = $this->connect();
fwrite($client, "GET /hello?name=a HTTP/1.1\r\nHost: x\r\n\r\nGET /f/song HTTP/1.1\r\nHost: x\r\nRange: bytes=0-0\r\n\r\n");
$first = $this->readResponse($client);
$second = $this->readResponse($client);
self::assertSame('hi a', $first['body']);
self::assertSame('keep-alive', $first['headers']['connection']);
self::assertSame('a', $second['body']);
fclose($client);
}
public function testTwoClientsAreServedAtTheSameTime(): void
{
$big = $this->tempFile(str_repeat('0123456789', 300000)); // 3 MB: several polls each
$this->server->handle('/big', fn () => HttpResponse::file($big));
$a = $this->connect();
$b = $this->connect();
fwrite($a, "GET /big HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n");
fwrite($b, "GET /big HTTP/1.1\r\nHost: x\r\nRange: bytes=1000000-\r\nConnection: close\r\n\r\n");
$streams = ['a' => $a, 'b' => $b];
$data = ['a' => '', 'b' => ''];
$interleaved = false;
for ($i = 0; $i < 5000 && !(feof($a) && feof($b)); $i++) {
$this->server->poll();
foreach ($streams as $k => $s) {
$chunk = (string)@fread($s, 1 << 20);
$data[$k] .= $chunk;
}
// both had started before either ended
$interleaved = $interleaved || (strlen($data['a']) > 1000 && strlen($data['b']) > 1000 && !(feof($a) || feof($b)));
usleep(500);
}
self::assertTrue($interleaved, 'the two downloads ran side by side');
self::assertSame(3000000, strlen($this->split($data['a'])['body']));
self::assertSame(substr((string)file_get_contents($big), 1000000), $this->split($data['b'])['body']);
self::assertSame(0, $this->server->clientCount());
}
public function testTheAddressFilterRefusesAClient(): void
{
$seen = [];
$this->server->allow(function (string $ip) use (&$seen): bool {
$seen[] = $ip;
return false;
});
$response = $this->request("GET /hello HTTP/1.1\r\nHost: x\r\n\r\n");
self::assertSame(403, $response['status']);
self::assertSame(['127.0.0.1'], $seen);
$this->server->allow(fn (string $ip) => HttpServer::isPrivateAddress($ip));
self::assertSame(200, $this->request("GET /hello HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")['status']);
}
public function testPrivateAddresses(): void
{
foreach (['10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.20', '127.0.0.1', '169.254.3.4', '::1', 'fd00::1', 'fe80::1', '::ffff:192.168.0.2'] as $ip) {
self::assertTrue(HttpServer::isPrivateAddress($ip), $ip);
}
foreach (['8.8.8.8', '172.32.0.1', '100.64.0.1', '2001:db8::1', '::ffff:1.2.3.4', 'nonsense', ''] as $ip) {
self::assertFalse(HttpServer::isPrivateAddress($ip), $ip);
}
}
public function testListenTakesTheNextFreePort(): void
{
$other = new HttpServer();
try {
self::assertSame($this->port + 1, $other->listen($this->port, '127.0.0.1', 5));
} catch (\RuntimeException) {
self::markTestSkipped('the next port is taken on this machine');
} finally {
$other->close();
}
}
public function testA20MegabyteFileIsStreamedInChunksWithoutLoadingIt(): void
{
$path = (string)tempnam(sys_get_temp_dir(), 'jhttp');
$this->temp[] = $path;
$out = fopen($path, 'wb');
$hash = hash_init('sha256');
for ($i = 0; $i < 20; $i++) {
$block = str_repeat(chr(65 + $i), 1 << 20);
fwrite($out, $block);
hash_update($hash, $block);
}
fclose($out);
unset($block);
$expected = hash_final($hash);
$this->server->handle('/twenty', fn () => HttpResponse::file($path));
$client = $this->connect();
fwrite($client, "GET /twenty HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n");
gc_collect_cycles();
memory_reset_peak_usage();
$before = memory_get_usage();
$head = '';
$received = 0;
$hash = hash_init('sha256');
$polls = 0;
while (!feof($client) && $polls < 20000) {
$this->server->poll();
$polls++;
while (($chunk = fread($client, 1 << 16)) !== false && $chunk !== '') {
if ($head !== null && !str_contains($head . $chunk, "\r\n\r\n")) {
$head .= $chunk;
continue;
}
if ($head !== null) {
[$headText, $chunk] = explode("\r\n\r\n", $head . $chunk, 2);
self::assertStringContainsString('Content-Length: 20971520', $headText);
$head = null;
}
$received += strlen($chunk);
hash_update($hash, $chunk);
}
}
$peak = memory_get_peak_usage() - $before;
self::assertSame(20 << 20, $received);
self::assertSame($expected, hash_final($hash));
self::assertGreaterThan(5, $polls, 'sent over many polls, never in one go');
self::assertLessThan(6 << 20, $peak, 'the file was never held whole in memory');
}
public function testNotAvailableInTheBrowserIsSaidByIsSupported(): void
{
self::assertTrue(HttpServer::isSupported()); // desktop PHP; Platform::isWasm() makes it false and listen() throw
}
// --- a small blocking-free client ---
private function tempFile(string $content): string
{
$path = (string)tempnam(sys_get_temp_dir(), 'jhttp');
file_put_contents($path, $content);
$this->temp[] = $path;
return $path;
}
/** @return resource */
private function connect()
{
$client = stream_socket_client("tcp://127.0.0.1:{$this->port}", $errno, $error, 2);
self::assertNotFalse($client, (string)$error);
stream_set_blocking($client, false);
return $client;
}
/** @return array{status: int, headers: array<string, string>, body: string} */
private function request(string $raw, bool $head = false): array
{
$client = $this->connect();
fwrite($client, $raw);
$response = $this->readResponse($client, $head);
fclose($client);
return $response;
}
/**
* Reads one response (Content-Length framed), polling the server meanwhile.
*
* @param resource $client
* @return array{status: int, headers: array<string, string>, body: string}
*/
private function readResponse($client, bool $head = false): array
{
static $buffers = [];
$key = (int)$client;
$buffer = $buffers[$key] ?? '';
for ($i = 0; $i < 4000; $i++) {
$this->server->poll();
$buffer .= (string)@fread($client, 1 << 16);
$end = strpos($buffer, "\r\n\r\n");
if ($end !== false) {
$parsed = $this->split(substr($buffer, 0, $end + 4));
$length = $head ? 0 : (int)($parsed['headers']['content-length'] ?? 0);
if (strlen($buffer) >= $end + 4 + $length) {
$parsed['body'] = substr($buffer, $end + 4, $length);
$buffers[$key] = (string)substr($buffer, $end + 4 + $length);
return $parsed;
}
}
if (feof($client) && $end === false) {
break;
}
usleep(500);
}
self::fail('no complete response: ' . $buffer);
}
/** @return array{status: int, headers: array<string, string>, body: string} */
private function split(string $raw): array
{
[$head, $body] = explode("\r\n\r\n", $raw, 2) + [1 => ''];
$lines = explode("\r\n", $head);
$status = (int)(explode(' ', (string)array_shift($lines))[1] ?? 0);
$headers = [];
foreach ($lines as $line) {
[$name, $value] = explode(':', $line, 2) + [1 => ''];
$headers[strtolower(trim($name))] = trim($value);
}
return ['status' => $status, 'headers' => $headers, 'body' => $body];
}
}