FR
games/cryo-sandbox-demo / src / Scene / SandboxScene.php · commit b70c9cd
<?phpnamespace App\Scene;use JumPHP\Cryo\SandboxLoop;use JumPHP\Renderer\Renderer;use JumPHP\Scene\AbstractScene;/** * Cryo\Sandbox in a game: PHP code runs in sandboxes (in the browser: Web Workers, each with its own PHP engine), * the game only sends requests and reads the flags of their futures (pending, ready, failed, cancelled) at each * frame. Nothing waits: the bar at the bottom keeps spinning while a sandbox computes, crashes or times out. * SPACE runs everything again. */final class SandboxScene extends AbstractScene{    private const COLOURS = ['pending' => [255, 200, 60], 'ready' => [90, 230, 120], 'failed' => [255, 90, 90], 'cancelled' => [150, 150, 150]];    private float $time = 0.0;    private int $frames = 0;    private ?\Cryo\Sandbox\Sandbox $main = null;    private ?\Cryo\Sandbox\Sandbox $strict = null;    /** @var list<array{label: string, future: ?object, start: float, end: ?float, text: string, status: string, next: ?\Closure}> */    private array $rows = [];    private string $waitText = '';    private string $problem = '';    private int $round = 0;    public function enter(array $params = []): void    {        $this->time = 0.0;        $this->frames = 0;        $this->rows = [];        $this->problem = '';        $this->round = 0;        if (!SandboxLoop::available()) {            $this->problem = 'ext-cryo is not in this PHP: build for the browser (bin/jumphp build cryo-sandbox-demo)';            return;        }        try {            // two sandboxes: requests of one sandbox run one after the other            $this->main = SandboxLoop::spawn(['timeout' => 5, 'memory_limit' => '32M', 'restart' => 'on_crash']);            $this->strict = SandboxLoop::spawn(['timeout' => 1, 'restart' => 'on_crash']);        } catch (\Throwable $e) {            $this->problem = get_class($e) . ': ' . $e->getMessage();            return;        }        $this->run();    }    public function exit(): void    {        $this->main?->kill();        $this->strict?->kill();        $this->main = $this->strict = null;    }    private function run(): void    {        $this->round++;        $this->rows = [];        $main = $this->main;        $strict = $this->strict;        if ($main === null || $strict === null) {            return;        }        $repeat = $this->add("callAsync('str_repeat', ['ab', 3])", fn () => $main->callAsync('str_repeat', ['ab', 3]));        $heavy = $this->add('heavy loop (4 million turns)', fn () => $main->evalAsync('$s = 0; for ($i = 0; $i < 4000000; $i++) { $s += $i % 7; } return $s;'));        $this->add('then(): evalAsync(21) * 2', fn () => $main->evalAsync('return 21;')->then(fn ($v) => $v * 2));        $this->add('throw new RuntimeException', fn () => $main->evalAsync('throw new RuntimeException("broken on purpose");'));        // a fatal error ends that instance: what is sent after it starts a new one (restart => on_crash)        $this->add('fatal: 100 MB string, limit 32M', fn () => $main->evalAsync('return strlen(str_repeat("x", 100 * 1024 * 1024));'),            fn () => $this->add('after the fatal: a new instance', fn () => $main->evalAsync('return "restarted, pid " . getmypid();')));        $this->add('endless loop, timeout 1 s', fn () => $strict->evalAsync('while (true) {}'),            fn () => $this->add('after the timeout: a new instance', fn () => $strict->evalAsync('return "alive again";')));        $this->waitText = 'SandboxLoop::wait(): pending';        $round = $this->round;        $repeat !== null && $heavy !== null && SandboxLoop::wait(['repeat' => $repeat, 'heavy' => $heavy], 30.0)->then(            function (array $values) use ($round): void {                if ($round === $this->round) {                    $this->waitText = 'SandboxLoop::wait(): ready, repeat=' . $values['repeat'] . ' heavy=' . $values['heavy'];                }            },            function (\Throwable $e) use ($round): void {                if ($round === $this->round) {                    $this->waitText = 'SandboxLoop::wait(): failed ' . $e->getMessage();                }            },        );    }    /**     * @param \Closure(): object $send     * @param \Closure|null $next sent once this one is settled     */    private function add(string $label, \Closure $send, ?\Closure $next = null): ?object    {        try {            $future = $send();            $this->rows[] = ['label' => $label, 'future' => $future, 'start' => $this->time, 'end' => null, 'text' => '', 'status' => 'pending', 'next' => $next];            return $future;        } catch (\Throwable $e) {            $this->rows[] = ['label' => $label, 'future' => null, 'start' => $this->time, 'end' => $this->time, 'text' => get_class($e) . ': ' . $e->getMessage(), 'status' => 'failed', 'next' => null];            return null;        }    }    public function update(float $dt): void    {        $this->time += $dt;        $this->frames++;        if ($this->actions()->isPressed('jump') || $this->actions()->isPressed('confirm')) {            $this->run();        }        $next = [];        foreach ($this->rows as &$row) {            if ($row['future'] === null || $row['end'] !== null) {                continue;            }            // the flags: never blocks (Cryo\Sandbox\Future::status() reads what already arrived)            $row['status'] = $row['future']->status();            if ($row['status'] === 'pending') {                continue;            }            $row['end'] = $this->time;            if ($row['status'] === 'ready') {                $value = $row['future']->value();                $row['text'] = is_scalar($value) ? var_export($value, true) : json_encode($value);            } else {                $e = $row['future']->error();                $row['text'] = $e ? (new \ReflectionClass($e))->getShortName() . ': ' . $e->getMessage() : $row['status'];            }            if ($row['next'] !== null) {                $next[] = $row['next'];                $row['next'] = null;            }        }        unset($row);        foreach ($next as $send) {            $send();        }    }    public function render(Renderer $r): void    {        $r->clear([14, 16, 30]);        $font = $this->font();        $font->draw($r, 'CRYO SANDBOX IN THE BROWSER', 8, 6, 2, [150, 200, 255]);        $backend = $this->main !== null ? ($this->main->status()['backend'] ?? '?') : '-';        $font->draw($r, sprintf('BACKEND %s   FRAME %d   T %.1fS   ROUND %d   SPACE: AGAIN', strtoupper($backend), $this->frames, $this->time, $this->round), 8, 26, 1, [150, 150, 190]);        if ($this->problem !== '') {            $this->wrap($r, strtoupper($this->problem), 8, 50, [255, 120, 120]);        }        $y = 42;        foreach ($this->rows as $row) {            $colour = self::COLOURS[$row['status']] ?? [200, 200, 200];            $r->fillRect(8, $y + 1, 6, 6, $colour);            $secs = ($row['end'] ?? $this->time) - $row['start'];            $font->draw($r, strtoupper(sprintf('%-9s %4.1fS  %s', $row['status'], $secs, $row['label'])), 18, $y, 1, $colour);            if ($row['text'] !== '') {                $font->draw($r, strtoupper(mb_strimwidth($row['text'], 0, 74, '...')), 30, $y + 9, 1, [200, 200, 220]);            }            $y += 21;        }        $font->draw($r, strtoupper(mb_strimwidth($this->waitText, 0, 78, '...')), 8, $this->height() - 30, 1, [150, 200, 255]);        foreach (['main' => $this->main, 'strict' => $this->strict] as $name => $sb) {            if ($sb !== null) {                $st = $sb->status();                $font->draw($r, strtoupper(sprintf('%s: %s%s CALLS %d PENDING %d', $name, $st['alive'] ? 'ALIVE' : 'DOWN', !empty($st['starting']) ? ' (BOOTING)' : '', $st['calls'], $st['pending'])),                    $name === 'main' ? 8 : 250, $this->height() - 20, 1, [130, 130, 170]);            }        }        // the animation that proves the frame never waits        $w = $this->width() - 16;        $x = 8 + (int)((sin($this->time * 3) * 0.5 + 0.5) * ($w - 40));        $r->fillRect(8, $this->height() - 9, $w, 4, [40, 40, 70]);        $r->fillRect($x, $this->height() - 10, 40, 6, [120, 200, 255]);    }    private function wrap(Renderer $r, string $text, int $x, int $y, array $colour): void    {        foreach (str_split($text, 76) as $i => $line) {            $this->font()->draw($r, $line, $x, $y + $i * 10, 1, $colour);        }    }}