winzik/docs/cryo.md

178 lines
10 KiB
Markdown

# Cryo in JumPHP
[ext-cryo](https://git.jumphp.net/jumphp/php-cryo) is linked statically into JumPHP's WebAssembly engine
(`docker/ext/cryo`, copied from PhpCryo by `tools/sync-jumphp.sh`). In a game or an application it gives: **snapshots**
of the PHP heap (memory leaks), their **reading** (`CryoReader`), **hot rewriting** of code (`Cryo\Engine`),
**metrics**, and **sandboxes**: PHP code isolated in another PHP instance, which can neither crash nor freeze the game.
To start, with short examples (a key to take a memory picture, finding a leak, a player's code in a sandbox, waiting
for several results, a flag read at every frame, changing a rule while the game runs): **https://jumphp.net/docs/cryo**.
The complete guide of the extension (freezing a script and resuming it elsewhere, fork, metrics, security…):
[php-cryo, `docs/guide/`](https://git.jumphp.net/jumphp/php-cryo/src/branch/main/docs/guide/README.md) (French), and
13 command-line examples: [`examples/`](https://git.jumphp.net/jumphp/php-cryo/src/branch/main/examples). This page
describes how it works in detail. Français : [cryo.fr.md](cryo.fr.md).
## Snapshots and CryoReader
```php
cryo_snapshot(sys_get_temp_dir() . '/a.cryo', ['redact' => ['password']]); // object graph, roots, orphans
$r = CryoReader::open(sys_get_temp_dir() . '/a.cryo');
$r->top('class', 10); // what takes the memory
$r->dominators(10); // what RETAINS the memory
$r->path($id); // root -> ... -> the object
cryo_roots_of($obj); // live, without a file: what keeps this object alive?
```
In the browser the file is written to emscripten's file system (`/tmp`), or to `var/` (IndexedDB) to keep it.
[Cryo Studio](https://jumphp.net/cryo-studio) opens `.cryo` files.
## Cryo\Engine
```php
$e = Cryo\Engine::current();
$e->redefineFunction('score_bonus', fn (int $n) => $n * 3); // the function body changes in place
$e->journal(); $e->revert($id); $e->exportJournal();
```
### Hot patch and console from the IDE (`JumPHP\Cryo\HotPatch`)
The JumPHP IDE's Cryo window, tab **Hot patch & console**, on a program run with *Run with memory metrics*
(`JUMPHP_CRYO_METRICS`; the requests are files in `var/cryo/hotpatch/`, answered between two frames):
- **Patch the method at the cursor**: the method (or function) under the editor's cursor, as it is in the editor now, replaces the
running one (`redefineMethod`): the level, the player, the connections stay. A constant can be set too. Every change is in the
journal and can be undone one by one or all (`revert`).
- **Console**: PHP typed into the running game (`$engine`, `$scene` = the scene on top; variables kept from one line to the next;
the last expression's value is shown), with Monaco's PHP colours and completions read from the program itself (`$scene->`, the real
object's methods and properties; `Class::`; `$`; functions and classes). Enter runs, Shift+Enter a new line, ↑ ↓ the history.
- Claude: `cryo_patch` (path + line), `cryo_patch_constant`, `cryo_patch_revert`, `cryo_console` (the IDE's MCP server).
Desktop only (the browser has no ext-cryo); the code of the file is not changed by a patch: save the fix as usual.
## Metrics
`cryo_metrics()` (memory, live objects, calls), `cryo_metrics_sample()` / `cryo_metrics_mark()` (`.cryom` series). The
browser has no HTTP server: the Prometheus text and the events reach the page as `cryo` events:
```js
addEventListener('cryo', (e) => console.log(e.detail.kind, e.detail.text)); // kind 1 = metrics JSON
```
## The sandbox in the browser (asynchronous)
In the browser a `Cryo\Sandbox\Sandbox` is a **Web Worker that starts its own PHP instance** (the same engine and the
same files as the game, `engine/web/jumphp-cryo-worker.js`): its memory is separate, and an `exit()`, a fatal error,
going over `memory_limit` or a WebAssembly *trap* never touch the game. On the desktop it is a child PHP process; the
same code works on both.
The browser calls PHP frame by frame (no JSPI, no Asyncify, no SharedArrayBuffer): **nothing can wait**. So only the
asynchronous API exists in the browser; `call()`, `eval()`, `get()`, `set()`, `include()`, `metrics()`, `proxy()`,
`Future::await()` on a future not ready yet, `awaitAll/awaitAny`, `Pool::call/map`, `recv()` throw a
`SandboxException`: "synchronous calls are not possible in the browser: use callAsync()->then() or Sandbox::wait()".
| Send (returns a `Cryo\Sandbox\Future`) | |
| --- | --- |
| `callAsync('fn', [args])`, `callAsync(['Class', 'method'], [args])` | a call |
| `evalAsync('return 1 + 1;')`, `includeAsync('src/x.php')` | code |
| `getAsync('name')`, `setAsync('name', $value)` | global variables of the sandbox |
| `metricsAsync()` | memory, calls, live objects of the sandbox |
| `send($message)` / `messages()` | messages (`Cryo\Sandbox\Channel::parent()->send()` on the sandbox side) |
| Read a `Future` (never blocking) | |
| --- | --- |
| `status()` | `'pending'`, `'ready'`, `'failed'`, `'cancelled'` |
| `isReady()`, `isFailed()`, `isCancelled()` | the same flags as booleans |
| `value()` | the value once ready, else `null` |
| `error()` | the exception once failed: `RemoteException` (exception in the sandbox, `getRemoteClass()`), `SandboxMemoryException`, `SandboxTimeoutException`, `SandboxCrashedException` (`getExitCode()`, `getStderr()`), `SandboxException` |
| `then(fn ($v) => ..., fn (\Throwable $e) => ...)` | a new future; the callbacks run between two frames |
| `cancel()` | a request not started yet is never run |
| `Sandbox::wait($future or [$futures], ?$timeout)` | a future settled once all are (values, same keys) |
| `Sandbox::pump()`, `Sandbox::pending()` | reads what arrived and runs the callbacks; number still waiting |
### The loop: `JumPHP\Cryo\SandboxLoop`
`SandboxLoop::spawn($options)` creates the sandbox and adds to the game's ReactPHP loop (`GameLoop`, the one that turns
once per frame in the browser) a periodic timer that calls `Sandbox::pump()`: answers arrive and `then()` callbacks run
between two frames, without ever waiting. `SandboxLoop::wait()` returns a `JumPHP\Async\Task` (same API as tasks:
`then()`, `isDone()`, `result()`).
```php
use JumPHP\Cryo\SandboxLoop;
final class PuzzleScene extends AbstractScene
{
private ?\Cryo\Sandbox\Sandbox $sb = null;
private string $text = '';
public function enter(array $params = []): void
{
// in enter(): the sandbox's PHP boots in its Worker (~0.5-1 s), requests wait for it over there
$this->sb = SandboxLoop::spawn([
'timeout' => 2, // per request: above it the Worker is terminated -> SandboxTimeoutException
'memory_limit' => '64M', // over it -> SandboxMemoryException
'disable_functions' => ['exec'],
'bootstrap' => 'src/Puzzle/rules.php',
'restart' => 'on_crash', // a new instance after a crash
]);
$this->sb->callAsync('solve', [$this->grid])
->then(fn ($moves) => $this->text = count($moves) . ' moves',
fn (\Throwable $e) => $this->text = $e->getMessage());
SandboxLoop::wait([$this->sb->evalAsync('return 6 * 7;'), $this->sb->getAsync('version')], 5.0)
->then(fn (array $v) => ..., fn (\Throwable $e) => ...);
}
public function exit(): void
{
$this->sb?->kill();
}
public function render(Renderer $r): void
{
// the flags, read at every frame without waiting: $future->status() === 'pending' ...
}
}
```
- A sandbox runs its requests **one at a time**: a slow request (or an endless loop, until its `timeout`) delays the
next ones of the same sandbox. Two sandboxes work in parallel.
- `timeout` (seconds, per request): the page terminates the Worker (`worker.terminate()`) and the future fails with
`SandboxTimeoutException`; the next requests of that sandbox fail (`SandboxCrashedException`, code 124) and, with
`restart => 'on_crash'`, the next request starts a new instance.
- Fatal error, `memory_limit`, `exit()`: the sandbox answers first (`SandboxMemoryException`, `SandboxException`), then
its instance ends.
- A *trap* (engine stack overflow...) or a Worker error: `SandboxCrashedException` (code 134, `getStderr()`: the
Worker's message).
- `start => 'fork'` does not exist in the browser (no copy of an instance): `spawn` (default) or `snapshot`.
- Values travel serialized (`serialize`): numbers, strings, arrays, plain objects; no closures nor resources. 32-bit
integers in the browser (§2 of AGENTS.md).
Demo: `games/cryo-sandbox-demo` (`bin/jumphp build cryo-sandbox-demo`, `bin/jumphp webshot cryo-sandbox-demo 8`),
played at https://jumphp.net/cryo-sandbox-demo/jouer.
### The JavaScript side
`engine/web/jumphp.js` installs `Module.cryoHost` (EM_JS functions of `ext-cryo/cryo_host.c`) with the host of
`engine/web/jumphp-cryo.js`:
| `Module.cryoHost.` | |
| --- | --- |
| `spawn(json)` → id | starts a `jumphp-cryo-worker.js` Worker (`{"timeout": s, "memory_limit": bytes}`) |
| `send(id, bytes)` | bytes to the sandbox; each complete frame (12-byte header + payload) goes in one `postMessage` |
| `recv(id, cap)` | at most `cap` bytes already arrived; `null`: nothing yet; `-2`: the sandbox has ended |
| `kill(id)`, `status(id)`, `error(id)` | `status`: -1 while it runs, else its exit code (124 timeout, 134 trap, 137 killed) |
In the Worker, each frame received is put into its PHP's `cryoHost.recv`, then `Module._cryo_sandbox_step()` (exported
by the engine) runs **one** request and sends its answers back through `cryoHost.send(0, ...)`. When a request starts,
`cryoHost.arm(ms, frame)` gives the page the prepared "timeout" answer: that is what PHP receives if the page has to
terminate the Worker. `window.JumPHP.cryoSandboxes` lists the instances (debugging).
In the JumPHP IDE, the **Cryo** window shows all this without code: live memory of a run, snapshots taken and compared,
freeze files, series, and a sandbox console ([ide.md](ide.md)).
**Whole-program save points** (desktop, the IDE's Cryo window): `JumPHP\Cryo\ProcessFreeze` freezes the running game with
`cryo_freeze($file, ['include' => ['globals', 'statics'], 'on_resource' => 'descriptor', 'key' => ...])` between two
frames, and a new process started with `JUMPHP_CRYO_THAW` thaws it before booting (`Application::boot()` returns the
thawed application): `cryo_register_resource('SDL Renderer' / 'SDL Texture')` and `cryo_on_thaw` +
`CryoThawContext::replaceClass()` make the native parts again (window, renderer, textures from `Sdl::$recipes`, fonts,
sounds, gamepads). Files are signed with a key of the project (`var/cryo/savepoints/.key`).