winzik/engine/tests/Net/NetRoomTest.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

230 lines
8.7 KiB
PHP

<?php
namespace JumPHP\Tests\Net;
use JumPHP\Kernel\GameConfig;
use JumPHP\Net\MessageCodec;
use JumPHP\Net\NetSession;
use PhpWasmNetwork\Connection;
use PhpWasmNetwork\Event;
use PHPUnit\Framework\TestCase;
/** A transport that records what NetSession asks and replays the relay's answers. */
final class FakeConnection implements Connection
{
/** @var list<array> */
public array $controls = [];
/** @var list<array{0: string, 1: ?int}> */
public array $sent = [];
/** @var list<Event> */
public array $events = [];
public int $state = self::OPEN;
public function control(array $message): void
{
$this->controls[] = $message;
}
public function createRoom(int $maxPeers = 8, array $meta = [], bool $public = false): void
{
$this->controls[] = ['t' => 'create', 'max' => $maxPeers];
}
public function quickJoin(int $maxPeers = 8, array $meta = []): void
{
}
public function lockRoom(bool $locked): void
{
}
public function joinRoom(string $code): void
{
$this->controls[] = ['t' => 'join', 'room' => $code];
}
public function leaveRoom(): void
{
$this->controls[] = ['t' => 'leave'];
}
public function setRoomInfo(array $info): void
{
}
public function send(string $data, ?int $to = null, bool $reliable = true): bool
{
$this->sent[] = [$data, $to];
return true;
}
public function ping(): void
{
}
public function poll(): array
{
$events = $this->events;
$this->events = [];
return $events;
}
public function state(): int
{
return $this->state;
}
public function close(): void
{
$this->state = self::CLOSED;
}
}
final class NetRoomTest extends TestCase
{
public function testEnterAsksTheRelayToCreateOrEnterThePrivateRoom(): void
{
$net = new NetSession(new GameConfig(['id' => 'winzik']));
$fake = new FakeConnection();
$net->attach($fake);
$room = NetSession::newRoomId();
self::assertSame(32, strlen($room));
self::assertTrue(NetSession::isRoomId($room));
$net->enter($room, 4);
self::assertSame('create', $fake->controls[0]['t']);
self::assertSame($room, $fake->controls[0]['room']);
self::assertSame(4, $fake->controls[0]['max']);
self::assertFalse($fake->controls[0]['public']);
$events = [];
$net->on('room', function (array $info) use (&$events): void { $events[] = 'room'; });
$net->on('peerJoin', function (int $p) use (&$events): void { $events[] = "join:$p"; });
$net->on('peerLeave', function (int $p) use (&$events): void { $events[] = "leave:$p"; });
$net->on('message', function (int $from, int $type, string $payload) use (&$events): void { $events[] = "msg:$from:$type:" . strlen($payload); });
$fake->events = [
new Event(Event::ROOM, -1, json_encode(['t' => 'room', 'room' => $room, 'peer' => 1, 'host' => 0, 'peers' => [0]])),
new Event(Event::PEER_JOIN, 2),
new Event(Event::MESSAGE, 2, MessageCodec::encode(41, str_repeat('x', 49152))),
new Event(Event::PEER_LEAVE, 0),
];
$net->poll();
self::assertSame(['room', 'join:2', 'msg:2:41:49152', 'leave:0'], $events);
self::assertSame($room, $net->roomCode());
self::assertSame([2], $net->peers());
}
public function testPayloadsUpTo64KilobytesAreSentLargerOnesRefused(): void
{
$net = new NetSession(new GameConfig(['id' => 'winzik']));
$fake = new FakeConnection();
$net->attach($fake);
$room = str_repeat('A', 40);
$net->enter($room);
$fake->events = [new Event(Event::ROOM, -1, json_encode(['room' => $room, 'peer' => 0, 'host' => 0, 'peers' => []]))];
$net->poll();
self::assertTrue($net->send(41, str_repeat("\0", NetSession::MAX_PAYLOAD), 3));
self::assertSame(65536, strlen($fake->sent[0][0]));
self::assertSame(3, $fake->sent[0][1]);
self::assertFalse($net->send(41, str_repeat("\0", NetSession::MAX_PAYLOAD + 1)));
self::assertTrue($net->sendJson(40, ['t' => 'want', 'entry' => 'e1', 'offset' => 0]));
[$type, $payload] = MessageCodec::decode($fake->sent[1][0]);
self::assertSame([40, ['t' => 'want', 'entry' => 'e1', 'offset' => 0]], [$type, MessageCodec::unjson($payload)]);
}
public function testAStockRelayAnsweringAShortCodeIsAnError(): void
{
$net = new NetSession(new GameConfig(['id' => 'winzik']));
$fake = new FakeConnection();
$net->attach($fake);
$net->enter(NetSession::newRoomId());
$errors = [];
$net->on('error', function (string $code) use (&$errors): void { $errors[] = $code; });
$fake->events = [new Event(Event::ROOM, -1, json_encode(['room' => 'ABCD', 'peer' => 0, 'host' => 0, 'peers' => []]))];
$net->poll();
self::assertSame(['room-id'], $errors);
self::assertFalse($net->inRoom());
self::assertSame('leave', end($fake->controls)['t']);
}
public function testABadRoomIdIsRefused(): void
{
$this->expectException(\InvalidArgumentException::class);
(new NetSession(new GameConfig(['id' => 'winzik'])))->enter('ABCD');
}
/**
* Two sessions against the real relay (bin/jumphp relay up, with docker/relay's room-id.patch): skipped when none answers.
* JUMPHP_TEST_RELAY=ws://host:port/ws chooses it.
*/
public function testTwoDevicesMeetInALongRoomOnTheRelay(): void
{
$url = $this->relayUrl();
$room = NetSession::newRoomId();
$a = new NetSession(new GameConfig(['id' => 'winzik']));
$b = new NetSession(new GameConfig(['id' => 'winzik']));
$got = [];
$joined = [];
$errors = [];
$b->on('message', function (int $from, int $type, string $payload) use (&$got): void { $got[] = [$type, $payload]; });
$a->on('peerJoin', function (int $peer) use (&$joined): void { $joined[] = $peer; });
foreach ([$a, $b] as $s) {
$s->on('error', function (string $code, string $message) use (&$errors): void { $errors[] = "$code: $message"; });
}
$a->connect($url);
$a->enter($room, 4);
$this->pollUntil(function () use ($a, &$errors): bool { return $a->inRoom() || $errors !== []; }, [$a, $b]);
self::assertSame([], $errors);
self::assertSame($room, $a->roomCode());
$b->connect($url);
$b->enter($room, 4); // the same call: the room exists, b enters it
// (closures with references: an arrow fn would capture the arrays by value, once)
$this->pollUntil(function () use ($b, &$joined, &$errors): bool { return ($b->inRoom() && $joined !== []) || $errors !== []; }, [$a, $b]);
self::assertSame([], $errors);
self::assertSame($room, $b->roomCode());
self::assertSame([$b->peerId()], $joined);
$chunk = random_bytes(NetSession::MAX_PAYLOAD);
self::assertTrue($a->send(41, $chunk, $b->peerId()));
$closed = [];
$b->on('close', function (string $why) use (&$closed): void { $closed[] = $why; });
$this->pollUntil(function () use (&$got, &$errors, &$closed): bool { return $got !== [] || $errors !== [] || $closed !== []; }, [$a, $b]);
self::assertSame([[], []], [$errors, $closed]);
self::assertSame(41, $got[0][0]);
self::assertTrue($got[0][1] === $chunk, 'the 64 KB binary chunk arrived intact');
$left = [];
$a->on('peerLeave', function (int $peer) use (&$left): void { $left[] = $peer; });
$b->close();
$this->pollUntil(function () use (&$left): bool { return $left !== []; }, [$a]);
self::assertSame([$b->peerId()], $left);
$a->close();
}
private function relayUrl(): string
{
$candidates = array_filter([getenv('JUMPHP_TEST_RELAY') ?: null, 'ws://127.0.0.1:8090/ws', 'ws://172.17.0.1:8090/ws', 'ws://host.docker.internal:8090/ws']);
foreach ($candidates as $url) {
$parts = parse_url($url);
$socket = @stream_socket_client('tcp://' . $parts['host'] . ':' . $parts['port'], $errno, $error, 0.3);
if ($socket !== false) {
fclose($socket);
return $url;
}
}
self::markTestSkipped('no relay (bin/jumphp relay up)');
}
/** @param NetSession[] $sessions */
private function pollUntil(callable $done, array $sessions): void
{
for ($i = 0; $i < 1000 && !$done(); $i++) {
foreach ($sessions as $session) {
$session->poll();
}
usleep(5000);
}
self::assertTrue($done(), 'in time');
}
}