266 lines
13 KiB
PHP
266 lines
13 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\Board\BoardCommands;
|
|
use JumPHP\Ide\Board\BoardLive;
|
|
use JumPHP\Ide\Board\LiveStream;
|
|
use JumPHP\Ide\Board\RemoteBoard;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/**
|
|
* Several people on a jumphp.net board, seen from the IDE: the live channel (a fake stream and a fake site, the clock moved by hand),
|
|
* what reaches the window, the reconnection with a growing delay and what was missed, the journal when there is no stream, presence,
|
|
* and the conflicts of RemoteBoard (a card changed meanwhile, a note merged by the site).
|
|
*/
|
|
final class BoardLiveTest extends TestCase
|
|
{
|
|
/** @var list<array{0: string, 1: string, 2: ?array, 3: array}> */
|
|
private array $calls = [];
|
|
/** @var list<array{0: string, 1: array}> */
|
|
private array $emitted = [];
|
|
private float $now = 1000.0;
|
|
/** @var list<FakeStream> */
|
|
private array $streams = [];
|
|
/** @var list<array> the journal of the fake site */
|
|
private array $journal = [];
|
|
private bool $hub = true;
|
|
private ?\Closure $answer = null;
|
|
|
|
private function client(): \Closure
|
|
{
|
|
return function (string $method, string $path, ?array $body = null, array $headers = []): Deferred {
|
|
$this->calls[] = [$method, $path, $body, $headers];
|
|
$rest = (string)preg_replace('#^/api/ide/projects/[^/]+#', '', $path);
|
|
if ($this->answer !== null && ($custom = ($this->answer)($method, $rest, $body)) !== null) {
|
|
return $custom instanceof \Throwable ? Deferred::rejected($custom) : Deferred::resolved($custom);
|
|
}
|
|
return Deferred::resolved(match (true) {
|
|
$rest === '/board/live' => ['seq' => 10, 'hub' => $this->hub ? 'https://jumphp.test/.well-known/mercure' : null, 'topic' => 'https://jumphp.test/board/7',
|
|
'token' => $this->hub ? 'jwt-' . count($this->calls) : null, 'presence' => [['login' => 'ada', 'name' => 'Ada', 'client' => 'web1', 'editing' => 'card:5', 'via' => 'web']], 'me' => 'me'],
|
|
str_starts_with($rest, '/board/events') => $this->events((int)substr($rest, strlen('/board/events?after='))),
|
|
$rest === '/board/presence' => ['presence' => [['login' => 'me', 'client' => $body['client'] ?? '', 'editing' => $body['editing'] ?? null, 'via' => 'ide']]],
|
|
default => [],
|
|
});
|
|
};
|
|
}
|
|
|
|
private function events(int $after): array
|
|
{
|
|
$out = array_values(array_filter($this->journal, fn ($m) => $m['seq'] > $after));
|
|
return ['events' => $out, 'last' => max([$after, ...array_column($this->journal, 'seq')]), 'reload' => false, 'presence' => []];
|
|
}
|
|
|
|
private function live(): BoardLive
|
|
{
|
|
return new BoardLive('my game', $this->client(), function (string $event, array $payload): void {
|
|
$this->emitted[] = [$event, $payload];
|
|
}, function (string $url, array $headers): ?LiveStream {
|
|
if (!$this->hub) {
|
|
return null;
|
|
}
|
|
$this->streams[] = $stream = new FakeStream($url, $headers);
|
|
return $stream;
|
|
}, fn () => $this->now);
|
|
}
|
|
|
|
/** @return list<array> the payloads of $event */
|
|
private function of(string $event): array
|
|
{
|
|
return array_values(array_map(fn ($e) => $e[1], array_filter($this->emitted, fn ($e) => $e[0] === $event)));
|
|
}
|
|
|
|
private static function message(int $seq, array $events, string $by = 'ada', ?string $client = 'web1'): array
|
|
{
|
|
return ['seq' => $seq, 'events' => $events, 'by' => $by, 'client' => $client, 'at' => '2026-11-16T10:00:00+00:00'];
|
|
}
|
|
|
|
public function testTheChangesOfTheOthersReachTheWindowOnceAndInTheIdesShapes(): void
|
|
{
|
|
$live = $this->live();
|
|
self::assertSame('live', $live->start()->result()['state']);
|
|
// the stream: the project's topic, the token as a header (never the IDE's own token)
|
|
self::assertCount(1, $this->streams);
|
|
self::assertSame('https://jumphp.test/.well-known/mercure?topic=https%3A%2F%2Fjumphp.test%2Fboard%2F7', $this->streams[0]->url);
|
|
self::assertSame(['Authorization: Bearer jwt-1'], $this->streams[0]->headers);
|
|
self::assertSame('card:5', $this->of('board.live.presence')[0]['people'][0]['editing']);
|
|
// the window's own id goes with its requests
|
|
self::assertSame($live->client, $this->calls[1][3]['X-Board-Client']);
|
|
|
|
// a message cut in two reads, then a heartbeat comment
|
|
$card = ['id' => 12, 'columnId' => 3, 'position' => 0, 'title' => 'Boss', 'priority' => 'normal', 'labels' => [], 'version' => 4];
|
|
$frame = 'id: urn:1' . "\n" . 'data: ' . json_encode(self::message(11, [['type' => 'card.saved', 'card' => $card], ['type' => 'card.deleted', 'id' => 9]])) . "\n\n";
|
|
$this->streams[0]->push(substr($frame, 0, 30));
|
|
$live->poll();
|
|
self::assertSame([], $this->of('board.live'));
|
|
$this->streams[0]->push(substr($frame, 30) . ":\n\n");
|
|
$live->poll();
|
|
$got = $this->of('board.live');
|
|
self::assertCount(1, $got);
|
|
self::assertSame(['12', '3', 'Boss', '', 4], [$got[0]['events'][0]['card']['id'], $got[0]['events'][0]['card']['columnId'], $got[0]['events'][0]['card']['title'],
|
|
$got[0]['events'][0]['card']['priority'], $got[0]['events'][0]['card']['version']]);
|
|
self::assertSame(['type' => 'card.deleted', 'id' => '9'], $got[0]['events'][1]);
|
|
self::assertSame(['ada', false], [$got[0]['by'], $got[0]['mine']]);
|
|
|
|
// the same message from the journal (the safety read every 15 s): not applied twice
|
|
$this->journal[] = self::message(11, [['type' => 'card.saved', 'card' => $card]]);
|
|
$this->now += BoardLive::SAFETY + 1;
|
|
$live->poll();
|
|
self::assertCount(1, $this->of('board.live'));
|
|
}
|
|
|
|
public function testACutStreamComesBackWithAGrowingDelayAndWhatWasMissed(): void
|
|
{
|
|
$live = $this->live();
|
|
$live->start();
|
|
$this->streams[0]->end('HTTP 401');
|
|
$live->poll();
|
|
self::assertSame('offline', $live->status()['state']);
|
|
self::assertSame('HTTP 401', $live->status()['error']);
|
|
|
|
// meanwhile someone moved a card
|
|
$this->journal[] = self::message(12, [['type' => 'column.saved', 'column' => ['id' => 4, 'name' => 'Review', 'position' => 2]]]);
|
|
$live->poll();
|
|
self::assertCount(1, $this->streams, 'not before a second');
|
|
$this->now += 1.1;
|
|
$live->poll();
|
|
self::assertCount(2, $this->streams, 'a new stream, with a new token');
|
|
self::assertNotSame($this->streams[0]->headers, $this->streams[1]->headers);
|
|
self::assertSame('Review', $this->of('board.live')[0]['events'][0]['column']['name'], 'what was missed, from the journal');
|
|
self::assertSame('live', $live->status()['state']);
|
|
|
|
// the hub refuses again and again: 1, 2, 4... seconds between the tries
|
|
$this->answer = fn (string $method, string $rest) => $rest === '/board/live' ? new \RuntimeException('jumphp.net cannot be reached') : null;
|
|
$this->streams[1]->end(null);
|
|
$live->poll();
|
|
$tries = fn () => count(array_filter($this->calls, fn ($c) => str_ends_with($c[1], '/board/live')));
|
|
$before = $tries();
|
|
foreach ([1.05, 2.05, 4.05] as $wait) {
|
|
$this->now += $wait - 0.1;
|
|
$live->poll();
|
|
self::assertSame($before, $tries(), "not before $wait s");
|
|
$this->now += 0.1;
|
|
$live->poll();
|
|
self::assertSame(++$before, $tries(), "after $wait s");
|
|
}
|
|
}
|
|
|
|
public function testWithoutAHubTheJournalIsReadEveryFewSeconds(): void
|
|
{
|
|
$this->hub = false;
|
|
$live = $this->live();
|
|
self::assertSame('polling', $live->start()->result()['state']);
|
|
self::assertSame([], $this->streams);
|
|
$this->journal[] = self::message(13, [['type' => 'note.saved', 'note' => ['id' => 3, 'title' => 'Plan', 'updatedAt' => '2026-11-16T10:00:00+00:00', 'version' => 2]]]);
|
|
$live->poll();
|
|
self::assertSame([], $this->of('board.live'));
|
|
$this->now += BoardLive::POLL + 0.1;
|
|
$live->poll();
|
|
self::assertSame(['3', 2], [$this->of('board.live')[0]['events'][0]['note']['id'], $this->of('board.live')[0]['events'][0]['note']['version']]);
|
|
self::assertSame(13, $live->status()['seq']);
|
|
}
|
|
|
|
public function testPresenceSaysWhatThisWindowEditsAndThatItLeft(): void
|
|
{
|
|
$live = $this->live();
|
|
$live->start();
|
|
$live->editing('card:12');
|
|
$last = end($this->calls);
|
|
self::assertSame(['POST', ['client' => $live->client, 'editing' => 'card:12']], [$last[0], $last[2]]);
|
|
$live->editing('rm -rf /');
|
|
self::assertNull(end($this->calls)[2]['editing']);
|
|
// every 20 seconds
|
|
$count = count($this->calls);
|
|
$this->now += BoardLive::HEARTBEAT + 0.1;
|
|
$live->poll();
|
|
self::assertTrue(count(array_filter(array_slice($this->calls, $count), fn ($c) => str_ends_with($c[1], '/board/presence'))) === 1);
|
|
$live->stop();
|
|
self::assertSame(['client' => $live->client, 'leave' => true], end($this->calls)[2]);
|
|
self::assertTrue($this->streams[0]->closed());
|
|
self::assertSame('off', end($this->emitted)[1]['state']);
|
|
}
|
|
|
|
public function testTheBoardWindowStartsTheChannelOnlyForJumphpNetsBoard(): void
|
|
{
|
|
$root = sys_get_temp_dir() . '/jumphp-live-' . bin2hex(random_bytes(4));
|
|
mkdir("$root/.git/info", 0777, true);
|
|
try {
|
|
$commands = new BoardCommands($root);
|
|
$commands->emit = function (string $event, array $payload): void { $this->emitted[] = [$event, $payload]; };
|
|
$commands->liveOpen = fn (string $url, array $headers) => $this->streams[] = new FakeStream($url, $headers);
|
|
self::assertSame('off', $commands->liveStart()->result()['state'], 'a local board has no channel');
|
|
$commands->connect(fn () => 'my-game', $this->client());
|
|
self::assertSame('live', $commands->liveStart()->result()['state']);
|
|
// the window's changes are named with its id
|
|
$commands->store()->deleteCard('5');
|
|
self::assertSame($commands->live()?->client, end($this->calls)[3]['X-Board-Client']);
|
|
$commands->setMode('local');
|
|
$commands->liveStop();
|
|
self::assertNull($commands->live());
|
|
} finally {
|
|
exec('rm -rf ' . escapeshellarg($root));
|
|
}
|
|
}
|
|
|
|
public function testACardChangedMeanwhileComesBackAsAConflictNeverOverwritten(): void
|
|
{
|
|
$theirs = ['id' => 12, 'columnId' => 1, 'position' => 0, 'title' => 'Main menu', 'priority' => 'normal', 'version' => 3];
|
|
$this->answer = function (string $method, string $rest, ?array $body) use ($theirs) {
|
|
if ($method === 'PATCH' && $rest === '/board/cards/12') {
|
|
return ($body['baseVersion'] ?? 0) === 3 ? array_merge($theirs, $body, ['version' => 4]) : new ConflictError('Someone else changed this card in the meantime.', 409, ['error' => '…', 'conflict' => ['card' => $theirs]]);
|
|
}
|
|
if ($method === 'PATCH' && $rest === '/notes/3') {
|
|
return ['id' => 3, 'title' => 'Plan', 'body' => 'merged text', 'version' => 5, 'merged' => ['conflicts' => 1]];
|
|
}
|
|
return null;
|
|
};
|
|
$remote = new RemoteBoard('g', $this->client());
|
|
$r = $remote->updateCard('12', ['priority' => 'high', 'baseVersion' => 2])->result();
|
|
self::assertSame(['Main menu', '', 3], [$r['conflict']['card']['title'], $r['conflict']['card']['priority'], $r['conflict']['card']['version']]);
|
|
self::assertSame(['priority' => 'high', 'baseVersion' => 2], end($this->calls)[2]);
|
|
$ok = $remote->updateCard('12', ['priority' => 'high', 'baseVersion' => 3])->result();
|
|
self::assertSame([4, 'high'], [$ok['version'], $ok['priority']]);
|
|
|
|
// a note: its version and the text it started from; the site merged it
|
|
$note = $remote->saveNote('3', 'Plan', 'mine', 4, 'base')->result();
|
|
self::assertSame(['title' => 'Plan', 'body' => 'mine', 'baseVersion' => 4, 'base' => 'base'], end($this->calls)[2]);
|
|
self::assertSame(['merged text', 5, ['conflicts' => 1]], [$note['body'], $note['version'], $note['merged']]);
|
|
// an error that is not a conflict stays an error
|
|
$this->answer = fn () => new \RuntimeException('down', 502);
|
|
self::assertSame('down', $remote->updateCard('12', ['title' => 'x', 'baseVersion' => 1])->error()?->getMessage());
|
|
}
|
|
}
|
|
|
|
/** the site's error with its decoded answer (games/ide's PlaygroundException) */
|
|
final class ConflictError extends \RuntimeException
|
|
{
|
|
public function __construct(string $message, int $code, private array $data)
|
|
{
|
|
parent::__construct($message, $code);
|
|
}
|
|
|
|
public function data(): array
|
|
{
|
|
return $this->data;
|
|
}
|
|
}
|
|
|
|
final class FakeStream implements LiveStream
|
|
{
|
|
private string $buffer = '';
|
|
private bool $ended = false;
|
|
private ?string $error = null;
|
|
|
|
/** @param list<string> $headers */
|
|
public function __construct(public string $url, public array $headers)
|
|
{
|
|
}
|
|
|
|
public function push(string $bytes): void { $this->buffer .= $bytes; }
|
|
public function end(?string $error): void { $this->ended = true; $this->error = $error; }
|
|
public function read(): string { $out = $this->buffer; $this->buffer = ''; return $out; }
|
|
public function closed(): bool { return $this->ended; }
|
|
public function error(): ?string { return $this->error; }
|
|
public function close(): void { $this->ended = true; }
|
|
}
|