'*', 'token' => '...'])`. * * - every POLL seconds GET /metrics.json (cryo_metrics() + time + pid + class_counts): the memory curve and the * counters; one request at a time, never more; * - snapshot(): POST /snapshot, the script writes a cryo_snapshot() at its next safe point and the exporter sends * the .cryo back (binary body). * * The requests go through a transport, fn (string $method, string $url, array $headers, float $timeout): Task that * settles with a JumPHP\Http\HttpResponse (or an error when there is no answer): $engine->http() in the app (fetch() * in the browser, never blocks the frame), a fake server in the tests. Answers of an older connection are dropped. */ final class LiveClient { public const POLL = 2.0; /** Memory points kept for the curve (10 minutes at one point every 2 s). */ public const KEEP = 300; public const METRICS_TIMEOUT = 5.0; /** The exporter waits 10 s at most for a safe point, then the file has to come. */ public const SNAPSHOT_TIMEOUT = 30.0; /** @var callable(string, string, array, float): Task */ private $transport; private string $base = ''; private string $token = ''; private bool $active = false; private int $generation = 0; private bool $polling = false; private bool $snapshotting = false; private float $wait = 0.0; private int $snapshots = 0; /** Last /metrics.json, null before the first answer. @var array|null */ public ?array $metrics = null; /** @var list [unix time, memory bytes] */ public array $points = []; /** @var list [unix time, label]: the snapshots taken */ public array $marks = []; /** What the screen says about the link (connected, error...). */ public string $status = ''; public bool $error = false; /** Grows at each change of what the screen shows (the form redraws only then). */ public int $version = 0; /** @param callable(string, string, array, float): Task $transport */ public function __construct(callable $transport) { $this->transport = $transport; } /** @param callable(string, string, array, float): Task $transport */ public function setTransport(callable $transport): void { $this->transport = $transport; } /** "127.0.0.1:9600", "http://host:9600/metrics" ... => "http://host:9600"; '' when it is no http(s) address. */ public static function normalizeUrl(string $url): string { $url = trim($url); if ($url === '') { return ''; } if (!preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) { $url = 'http://' . $url; } if (!preg_match('~^https?://[^/\s?#]+~i', $url, $m)) { return ''; } $path = rtrim((string)substr($url, strlen($m[0])), '/'); $path = (string)preg_replace('#/(metrics(\.json)?|series\.json|snapshot)?(\?.*)?$#', '', $path); return $m[0] . $path; } public function connect(string $url, string $token): bool { $this->disconnect(); $this->base = self::normalizeUrl($url); $this->token = trim($token); if ($this->base === '') { $this->fail(Lang::t('Give the address of the exporter, e.g. http://127.0.0.1:9600')); return false; } $this->active = true; $this->status = Lang::t('Connecting to {url}...', ['url' => $this->base]); $this->version++; $this->poll(); return true; } public function disconnect(): void { $this->generation++; $this->active = $this->polling = $this->snapshotting = false; $this->metrics = null; $this->points = []; $this->marks = []; $this->wait = 0.0; $this->status = ''; $this->error = false; $this->version++; } public function isActive(): bool { return $this->active; } /** Connected: the exporter answered at least once. */ public function isConnected(): bool { return $this->active && $this->metrics !== null; } public function isSnapshotting(): bool { return $this->snapshotting; } public function base(): string { return $this->base; } /** Each frame (Form::tick): polls every POLL seconds while connected. */ public function tick(float $dt): void { if (!$this->active || $this->polling) { return; } $this->wait += $dt; if ($this->wait >= self::POLL) { $this->poll(); } } /** GET /metrics.json now (if no request of the poll is running). */ public function poll(): void { if (!$this->active || $this->polling) { return; } $this->polling = true; $this->wait = 0.0; $gen = $this->generation; $this->send('GET', '/metrics.json', self::METRICS_TIMEOUT)->then( function (mixed $r) use ($gen) { if ($gen === $this->generation) { $this->polling = false; $this->onMetrics($r); } }, function (\Throwable $e) use ($gen) { if ($gen === $this->generation) { $this->polling = false; $this->fail(Lang::t('No answer from {url}: is the script running, with cryo_metrics_serve() and cors? ({error})', ['url' => $this->base, 'error' => $e->getMessage()])); } }, ); } /** * POST /snapshot. $onFile receives the bytes of the .cryo and a file name, $onError a message. * @param callable(string, string): void $onFile * @param callable(string): void $onError */ public function snapshot(callable $onFile, callable $onError): bool { if (!$this->active || $this->snapshotting) { return false; } $this->snapshotting = true; $this->version++; $gen = $this->generation; $this->send('POST', '/snapshot', self::SNAPSHOT_TIMEOUT)->then( function (mixed $r) use ($gen, $onFile, $onError) { if ($gen !== $this->generation) { return; } $this->snapshotting = false; $this->version++; if (!$r instanceof HttpResponse) { $onError(Lang::t('Bad answer')); } elseif ($r->ok()) { $this->snapshots++; $name = self::fileName($r->header('content-disposition') ?? '') ?? sprintf('live-%s-%d.cryo', $this->metrics['pid'] ?? 'x', $this->snapshots); $this->marks[] = [$this->lastTime(), Lang::t('snapshot {n}', ['n' => $this->snapshots])]; $onFile($r->body, $name); } else { $onError($this->httpError($r)); } }, function (\Throwable $e) use ($gen, $onError) { if ($gen === $this->generation) { $this->snapshotting = false; $this->version++; $onError(Lang::t('No answer from {url}: {error}', ['url' => $this->base, 'error' => $e->getMessage()])); } }, ); return true; } /** The counters shown under the curve. @return list */ public function counterLines(): array { $m = $this->metrics; if ($m === null) { return []; } $lines = [ Lang::t('Memory {mem} (peak {peak}) · allocated {real} · RSS {rss}', [ 'mem' => Studio::bytes($m['memory'] ?? 0), 'peak' => Studio::bytes($m['memory_peak'] ?? 0), 'real' => Studio::bytes($m['memory_real'] ?? 0), 'rss' => isset($m['memory_rss']) ? Studio::bytes($m['memory_rss']) : '?']), Lang::t('{objects} live objects · GC: {runs} runs, {collected} collected, {roots} roots', [ 'objects' => $m['objects_alive'] ?? 0, 'runs' => $m['gc_runs'] ?? 0, 'collected' => $m['gc_collected'] ?? 0, 'roots' => $m['gc_roots'] ?? 0]), Lang::t('Allocation tracking: {tracking} · series: {sampling} · snapshots taken: {n}', [ 'tracking' => !empty($m['tracking']) ? Lang::t('on') : Lang::t('off'), 'sampling' => !empty($m['sampling']) ? Lang::t('{n} samples', ['n' => $m['samples'] ?? 0]) : Lang::t('off'), 'n' => $this->snapshots]), ]; return $lines; } /** Live objects per class (with cryo.metrics=1), by count. @return list */ public function classLines(int $max = 50): array { $counts = $this->metrics['class_counts'] ?? null; if (!is_array($counts)) { return []; } $out = []; foreach (array_slice($counts, 0, $max, true) as $class => $n) { $out[] = sprintf('%8d %s', (int)$n, $class); } return $out; } /** @return list the curve, in seconds from its first point */ public function chartPoints(): array { $t0 = $this->points[0][0] ?? 0.0; return array_map(fn (array $p) => [$p[0] - $t0, $p[1]], $this->points); } /** @return list */ public function chartMarks(): array { $t0 = $this->points[0][0] ?? 0.0; return array_map(fn (array $m) => [$m[0] - $t0, $m[1]], $this->marks); } // ------------------------------------------------------------------------------------------------------------ private function send(string $method, string $path, float $timeout): Task { $headers = $this->token === '' ? [] : ['Authorization' => 'Bearer ' . $this->token]; try { return ($this->transport)($method, $this->base . $path, $headers, $timeout); } catch (\Throwable $e) { $task = new Task(); $task->settle(null, $e); return $task; } } private function onMetrics(mixed $r): void { if (!$r instanceof HttpResponse) { $this->fail(Lang::t('Bad answer')); return; } if (!$r->ok()) { $this->fail($this->httpError($r)); return; } try { $m = $r->json(); } catch (\JsonException) { $m = null; } if (!is_array($m) || !isset($m['memory'])) { $this->fail(Lang::t('{url} answers, but it is not cryo_metrics_serve() (ext-cryo with Live: /metrics.json)', ['url' => $this->base])); return; } $this->metrics = $m; $time = is_numeric($m['time'] ?? null) ? (float)$m['time'] : $this->lastTime() + self::POLL; $this->points[] = [$time, (float)$m['memory']]; if (count($this->points) > self::KEEP) { $this->points = array_slice($this->points, -self::KEEP); $first = $this->points[0][0]; $this->marks = array_values(array_filter($this->marks, fn (array $mk) => $mk[0] >= $first)); } $this->error = false; $this->version++; $this->status = Lang::t('Connected to {url} · pid {pid} · {n} points', ['url' => $this->base, 'pid' => $m['pid'] ?? '?', 'n' => count($this->points)]); } private function httpError(HttpResponse $r): string { $message = ''; try { $j = $r->json(); $message = is_array($j) && is_string($j['error'] ?? null) ? $j['error'] : ''; } catch (\JsonException) { } return match ($r->status) { 401 => Lang::t('The exporter wants a token (cryo_metrics_serve option token): wrong or missing'), 403 => Lang::t('Remote snapshots are disabled in this script (option snapshot => false)'), 404 => Lang::t('{url} answers, but it is not cryo_metrics_serve() (ext-cryo with Live: /metrics.json)', ['url' => $this->base]), 409 => Lang::t('A snapshot is already being taken'), 504 => Lang::t('The script did not reach a safe point in time (stuck in sleep() or I/O?)'), default => Lang::t('HTTP {status}: {message}', ['status' => $r->status, 'message' => $message]), }; } private function fail(string $message): void { $this->status = $message; $this->error = true; $this->version++; } private function lastTime(): float { return $this->points === [] ? 0.0 : $this->points[count($this->points) - 1][0]; } /** filename="cryo-live-123-1.cryo" of a Content-Disposition, kept to safe characters. */ public static function fileName(string $disposition): ?string { if (!preg_match('/filename="?([^";]+)"?/i', $disposition, $m)) { return null; } $name = (string)preg_replace('/[^A-Za-z0-9._-]/', '_', basename($m[1])); return $name === '' || $name[0] === '.' ? null : $name; } }