rob-revisited/ide/tests/WorkerPoolTest.php

137 lines
5.9 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\WorkerError;
use JumPHP\Ide\Async\WorkerPool;
use PHPUnit\Framework\TestCase;
/** The IDE's helper processes: answers, errors as values, a worker killed or hung in the middle of a job, a pool that cannot start. */
final class WorkerPoolTest extends TestCase
{
private function pool(int $size = 2, ?array $command = null, float $start = 15.0): WorkerPool
{
$how = WorkerPool::command();
self::assertNotNull($how, 'this PHP can start workers');
return new WorkerPool($command ?? $how[0], $how[1] + ['JUMPHP_IDE_WORKER_TEST' => '1'], $size, $start);
}
/** Polls until the Deferreds are settled (a test may wait; the IDE never does). */
private function settle(WorkerPool $pool, array $deferreds, float $timeout = 20.0): void
{
$end = microtime(true) + $timeout;
while (array_filter($deferreds, fn ($d) => !$d->isDone()) && microtime(true) < $end) {
$pool->poll(0.01);
usleep(2000);
}
}
public function testJobsAreAnsweredAndAnErrorIsAValue(): void
{
$pool = $this->pool();
$file = sys_get_temp_dir() . '/jph-worker-' . getmypid() . '.php';
file_put_contents($file, "<?php\nnamespace App;\nfinal class Score { public function add(int \$n): void {} }\n");
$jobs = [$pool->submit('ping'), $pool->submit('analyze', ['path' => $file]), $pool->submit('fail'), $pool->submit('analyze', ['path' => '/nowhere.php'])];
$this->settle($pool, $jobs);
@unlink($file);
self::assertSame('pong', $jobs[0]->result());
self::assertArrayHasKey('app\\score', $jobs[1]->result()['classes']);
self::assertInstanceOf(WorkerError::class, $jobs[2]->error());
self::assertStringContainsString('failed on purpose', $jobs[2]->error()->getMessage());
self::assertSame(\DomainException::class, $jobs[2]->error()->class);
self::assertInstanceOf(WorkerError::class, $jobs[3]->error());
// the worker went on after the errors
$more = $pool->submit('ping');
$this->settle($pool, [$more]);
self::assertSame('pong', $more->result());
$pool->close();
}
public function testAWorkerThatDiesInTheMiddleOfAJobIsReplacedAndTheJobTriedAgain(): void
{
$pool = $this->pool(1);
$first = $pool->submit('ping');
$this->settle($pool, [$first]);
// killed from outside while it works on a long job
$slow = $pool->submit('sleep', ['ms' => 3000]);
$pool->poll(0.01);
usleep(200000);
foreach ($pool->pids() as $pid) {
posix_kill($pid, 9);
}
$this->settle($pool, [$slow]);
self::assertSame('slept', $slow->result(), 'tried again on a new worker');
self::assertGreaterThanOrEqual(1, $pool->status()['retried']);
// a job that kills its worker every time: rejected after the second try, the pool still works
$crash = $pool->submit('crash');
$after = $pool->submit('ping');
$this->settle($pool, [$crash, $after]);
self::assertInstanceOf(WorkerError::class, $crash->error());
self::assertSame('pong', $after->result());
$pool->close();
}
public function testAHungJobIsStoppedAtItsTimeout(): void
{
$pool = $this->pool(1);
$hung = $pool->submit('sleep', ['ms' => 60000], 0.5);
$this->settle($pool, [$hung], 10);
self::assertInstanceOf(WorkerError::class, $hung->error());
$pool->close();
}
public function testAPoolThatCannotStartClosesItselfAndRejects(): void
{
$pool = $this->pool(2, [PHP_BINARY, '-r', 'sleep(30);'], 0.5);
$job = $pool->submit('ping');
$this->settle($pool, [$job], 10);
self::assertInstanceOf(WorkerError::class, $job->error());
self::assertFalse($pool->available());
self::assertInstanceOf(WorkerError::class, $pool->submit('ping')->error(), 'rejected at once from then on');
$pool->close();
}
public function testAnIndexMadeByTheWorkersIsTheSameAsOneMadeHere(): void
{
$dir = sys_get_temp_dir() . '/jph-pool-index-' . getmypid();
@mkdir("$dir/src", 0777, true);
for ($i = 0; $i < 60; $i++) {
file_put_contents("$dir/src/C$i.php", "<?php\nnamespace App;\n\nfinal class C$i extends Base\n{\n public function run(): int\n {\n return \$this->step($i) + strlen('x');\n }\n}\n");
}
try {
$here = new \JumPHP\Ide\Php\Index(new \JumPHP\Ide\Workspace\LocalWorkspace($dir));
self::assertTrue($here->refresh());
$pool = $this->pool(3);
$there = new \JumPHP\Ide\Php\Index(new \JumPHP\Ide\Workspace\LocalWorkspace($dir));
$there->setPool($pool);
$end = microtime(true) + 30;
while (!$pool->ready() && microtime(true) < $end) { // started in the background: the index works alone meanwhile
$pool->poll(0.01);
usleep(2000);
}
while (!$there->refresh(0.005) && microtime(true) < $end) {
usleep(1000);
}
self::assertGreaterThan(0, $pool->status()['done'], 'the workers did the work');
self::assertEquals($here->files(), $there->files());
self::assertSame(['done' => 60, 'total' => 60], $there->progress());
$pool->close();
} finally {
array_map('unlink', glob("$dir/src/*.php") ?: []);
@rmdir("$dir/src");
@rmdir($dir);
}
}
public function testManyJobsOnEveryCore(): void
{
$pool = $this->pool(max(2, min(8, WorkerPool::cores())));
$jobs = [];
for ($i = 0; $i < 300; $i++) {
$jobs[] = $pool->submit('ping');
}
$this->settle($pool, $jobs, 60);
self::assertSame(300, count(array_filter($jobs, fn ($d) => $d->isDone() && $d->result() === 'pong')));
$pool->close();
}
}