RU
apps/cryo-studio / src / Cryo / Studio.php · commit 76aa68d
<?phpnamespace App\Cryo;use JumPHP\Util\Lang;/** * The analysis behind the window: a set of .cryo snapshots, read by ext-cryo's CryoReader / CryoDelta when the * extension is loaded (native PHP, or an engine that links it) or by the pure-PHP PhpCryoReader / PhpCryoDelta (same * API, same results: the browser), and turned into rows for the screens. A row is ['text' => line shown, ...] with * what a click on it needs (a node, a site, a class). */final class Studio{    public const DEMO = ['shop-0.cryo', 'shop-1.cryo', 'shop-2.cryo', 'shop-3.cryo', 'shop-4.cryo'];    public const DEMO_SERIES = 'shop.cryom';    public const DEMO_FREEZE = 'worker.cryf';    /** @var array<string, \CryoReader|PhpCryoReader> path => reader, oldest epoch first */    private array $readers = [];    /** @var array<string, string> path => name shown */    private array $names = [];    private \CryoDelta|PhpCryoDelta|null $delta = null;    /** @var array<string, array<int, int|float>> path => node => retained (the inspector) */    private array $retained = [];    /** @param string $demoDir folder of the demo snapshots and of their source (assets/demo) */    public function __construct(private string $demoDir) {}    public static function native(): bool    {        return extension_loaded('cryo') && class_exists(\CryoReader::class, false);    }    public static function backend(): string    {        return self::native() ? 'ext-cryo' : 'PHP reader';    }    public function clear(): void    {        $this->readers = [];        $this->names = [];        $this->delta = null;        $this->retained = [];    }    public function loadDemo(): void    {        $this->clear();        foreach (self::DEMO as $file) {            $this->add($this->demoDir . '/' . $file);        }    }    /** Adds a snapshot; throws when the file is not a readable .cryo. */    public function add(string $path, ?string $name = null): void    {        $reader = self::native() ? \CryoReader::open($path) : PhpCryoReader::open($path);        $this->readers[$path] = $reader;        $this->names[$path] = $name ?? basename($path);        uasort($this->readers, fn ($a, $b) => $a->info()['epoch'] <=> $b->info()['epoch']);        $this->delta = null;    }    /** @return list<string> */    public function paths(): array    {        return array_keys($this->readers);    }    public function count(): int    {        return count($this->readers);    }    public function reader(int $index): \CryoReader|PhpCryoReader|null    {        $path = $this->paths()[$index] ?? null;        return $path === null ? null : $this->readers[$path];    }    /** @return list<string> one line per snapshot */    public function snapshotLines(): array    {        $out = [];        foreach ($this->readers as $path => $r) {            $i = $r->info();            $out[] = Lang::t('{name} · {objects} objects', ['name' => $this->names[$path], 'objects' => $i['objects']]);        }        return $out;    }    public function info(int $index): ?array    {        return $this->reader($index)?->info();    }    // overview ---------------------------------------------------------------------------------------------------    /** @return list<array{text: string, node: ?int}> */    public function overviewRows(int $index): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        $rows = [['text' => Lang::t('Top classes (objects, bytes, retained)'), 'node' => null]];        foreach ($r->top('retained', 8) as $t) {            $rows[] = ['text' => sprintf('      %s   %d · %s · %s', $t['class'], $t['count'], self::bytes($t['bytes']), self::bytes($t['retained'] ?? 0)), 'node' => null];        }        $rows[] = ['text' => Lang::t('Top allocation sites'), 'node' => null];        foreach ($r->top('site', 8) as $t) {            $rows[] = ['text' => sprintf('      %s   %d · %s', self::shortSite($t['site']), $t['count'], self::bytes($t['bytes'])), 'node' => null];        }        $rows[] = ['text' => Lang::t('Roots of the graph'), 'node' => null];        foreach ($r->roots() as $rt) {            $rows[] = ['text' => sprintf('      %s %s   #%d', $rt['kind'], $rt['name'], $rt['node']), 'node' => $rt['node']];        }        return $rows;    }    /**     * Alerts of the heuristics on a snapshot (with 2+ snapshots open: growth too), by score.     * @return list<array{text: string, alert: array<string, mixed>}>     */    public function alertRows(int $index): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        if ($r instanceof PhpCryoReader) {            // the readers themselves (delta() takes them too): the files are not read again            $alerts = $r->heuristics($this->count() >= 2 ? array_values($this->readers) : []); // @phpstan-ignore argument.type        } else {            $alerts = $r->heuristics($this->count() >= 2 ? $this->paths() : []);        }        return array_map(fn (array $a) => [            'text' => sprintf('%d  %s  —  %s', $a['score'], $a['kind'], self::shortMessage((string)$a['message'])),            'alert' => $a,        ], $alerts);    }    /** The message of an alert with its sites shortened ("dir/file.php:17" => "file.php:17"). */    public static function shortMessage(string $message): string    {        return (string)preg_replace('~\S*/([^/\s]+\.php:\d+)~', '$1', $message);    }    // leaks (delta) ----------------------------------------------------------------------------------------------    public function delta(): \CryoDelta|PhpCryoDelta|null    {        if ($this->count() < 2) {            return null;        }        return $this->delta ??= self::native() ? \CryoReader::delta($this->paths()) : PhpCryoReader::delta(array_values($this->readers));    }    /**     * Delta rows by 'site', 'class' or 'stack': growing keys (leaks) first.     * @return list<array{text: string, key: string, row: array<string, mixed>}>     */    public function deltaRows(string $by = 'site'): array    {        $delta = $this->delta();        if ($delta === null) {            return [];        }        $rows = match ($by) {            'class' => $delta->byClass(),            'stack' => $delta->byStack(),            default => $delta->bySite(),        };        return array_map(function (array $d) use ($by) {            $key = (string)$d[$by];            $shown = match ($by) {                'site' => self::shortSite($key),                'stack' => self::shortStack($key),                default => $key,            };            $hook = $d['hooked_by'] === null ? '' : Lang::t('hooked by {site}', ['site' => self::hookShort((string)$d['hooked_by'], self::rowSite($by, $key))]) . '   ';            return [                'text' => ($d['growing'] ? '[LEAK] ' : '         ') . $shown . '   ' . $hook . Lang::t('new {new} · kept {kept} ({pct}%) · {bytes}', [                    'new' => implode('/', $d['new_per_interval']), 'kept' => $d['survivors'],                    'pct' => (int)round($d['survival'] * 100), 'bytes' => self::bytes($d['bytes_last'])]),                'key' => $key,                'row' => $d,            ];        }, $rows);    }    /** The write site of a delta row, short: "line 18" when it is in the file and function of the allocation site. */    public static function hookShort(string $hook, ?string $site): string    {        $h = self::parseSite($hook);        $s = $site === null ? null : self::parseSite($site);        if ($s !== null && $h['line'] > 0 && $h['file'] === $s['file'] && $h['function'] === $s['function']) {            return Lang::t('line {line}', ['line' => $h['line']]);        }        return self::shortSite($hook);    }    /** The allocation site of a row of the site or stack view (no lookup for a class). */    private static function rowSite(string $by, string $key): ?string    {        return match ($by) {            'site' => $key,            'stack' => explode(' <- ', $key)[0],            default => null,        };    }    /** "a.php:17 f <- a.php:73 g" => "a.php:17 f ← a.php:73 g" (directories cut) */    public static function shortStack(string $stack): string    {        return implode(' ← ', array_map(self::shortSite(...), explode(' <- ', $stack)));    }    /** explain() of an allocation site: its row, its write site and the typical paths of its survivors. */    public function explain(string $site): ?array    {        return $this->delta()?->explain($site);    }    /**     * The allocation site behind a delta row: the site itself, the first frame of a stack, or for a class the site     * where most of its objects of the last snapshot were created.     */    public function siteOf(string $by, string $key): ?string    {        if ($by !== 'class') {            return self::rowSite($by, $key);        }        $last = $this->reader($this->count() - 1);        if ($last === null) {            return null;        }        $sites = array_filter(array_column($last->query(['class' => $key, 'limit' => 100000]), 'site'), 'is_string');        $counts = array_count_values($sites);        arsort($counts);        $site = array_key_first($counts);        return $site === null ? null : (string)$site;    }    /** A path (list of steps) in one line: "SqlLogger::$log (static_prop) → [399] Query #498". */    public static function pathLine(array $path): string    {        $parts = [];        foreach ($path as $i => $step) {            $parts[] = $i === 0 ? $step['name'] . ' (' . $step['kind'] . ')' : $step['name'] . ' ' . ($step['class'] ?? $step['type']) . ' #' . $step['node'];        }        return implode('  →  ', $parts);    }    // classes, nodes, dominators, orphans, duplicates, query -----------------------------------------------------    /** @return list<array{text: string, class: string}> objects per class, by retained size */    public function classRows(int $index): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        return array_map(fn (array $t) => [            'text' => Lang::t('{class}   {count} objects · {bytes} · retained {retained}', ['class' => $t['class'], 'count' => $t['count'],                'bytes' => self::bytes($t['bytes']), 'retained' => self::bytes($t['retained'] ?? 0)]),            'class' => (string)$t['class'],        ], $r->top('retained', 500));    }    /**     * @param list<array<string, mixed>> $records node records     * @return list<array{text: string, node: int}>     */    public function nodeRows(array $records): array    {        return array_map(fn (array $n) => ['text' => self::nodeLine($n), 'node' => (int)$n['node']], $records);    }    /** "#498  Query  56 B  epoch 4  shop_worker.php:17 SqlLogger::log" */    public static function nodeLine(array $n): string    {        $site = isset($n['site']) && is_string($n['site']) ? '   ' . self::shortSite($n['site']) : '';        $epoch = isset($n['epoch']) ? '   epoch ' . $n['epoch'] : '';        return sprintf('#%-5d %s   %s', $n['node'], $n['class'] ?? $n['type'], self::bytes($n['size'] ?? 0)) . $epoch . $site;    }    /** @return list<array{text: string, node: int}> instances of a class (at most $limit) */    public function instanceRows(int $index, string $class, int $limit = 300): array    {        $r = $this->reader($index);        return $r === null ? [] : $this->nodeRows($r->query(['class' => $class, 'limit' => $limit]));    }    /** @return list<array{text: string, node: int}> */    public function dominatorRows(int $index, int $limit = 50): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        return array_map(fn (array $d) => [            'text' => sprintf('%10s   #%-5d %s   ', self::bytes($d['retained']), $d['node'], $d['class'] ?? $d['type'])                . Lang::t('(self {bytes})', ['bytes' => self::bytes($d['self'])]),            'node' => (int)$d['node'],        ], $r->dominators($limit));    }    /** Orphans grouped by class: a line per class, then its objects. @return list<array{text: string, node: ?int}> */    public function orphanRows(int $index): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        $groups = [];        foreach ($r->orphans() as $n) {            $groups[(string)($n['class'] ?? $n['type'])][] = $n;        }        uasort($groups, fn ($a, $b) => count($b) <=> count($a));        $rows = [];        foreach ($groups as $class => $nodes) {            $bytes = array_sum(array_column($nodes, 'size'));            $rows[] = ['text' => Lang::t('{class}: {n} objects, {bytes}', ['class' => $class, 'n' => count($nodes), 'bytes' => self::bytes($bytes)]), 'node' => null];            foreach ($nodes as $n) {                $rows[] = ['text' => '      ' . self::nodeLine($n), 'node' => (int)$n['node']];            }        }        return $rows;    }    /** @return list<array{text: string, node: int}> */    public function dupeRows(int $index): array    {        $r = $this->reader($index);        if ($r === null) {            return [];        }        return array_map(fn (array $d) => [            'text' => Lang::t('{count} × {type} of {length}   {bytes} · {wasted} wasted   #{node}', [                'count' => $d['count'], 'type' => $d['type'], 'length' => $d['length'], 'bytes' => self::bytes($d['bytes']),                'wasted' => self::bytes($d['wasted']), 'node' => $d['node']]),            'node' => (int)$d['node'],        ], $r->dupes(100));    }    /** @return list<array{text: string, node: int}> nodes matching a query (ValueError on a syntax error) */    public function queryRows(int $index, string $expr, int $limit = 200): array    {        $r = $this->reader($index);        return $r === null ? [] : $this->nodeRows($r->query(['expr' => $expr, 'limit' => $limit]));    }    public function node(int $index, int $node): ?array    {        return $this->reader($index)?->node($node);    }    /** @return list<list<array<string, mixed>>> shortest paths from a root to a node */    public function pathsToRoot(int $index, int $node, int $max = 3): array    {        return $this->reader($index)?->path($node, $max) ?? [];    }    /** Retained size of a node (from the dominator tree), null when no root reaches it. */    public function retained(int $index, int $node): int|float|null    {        $path = $this->paths()[$index] ?? null;        $r = $this->reader($index);        if ($path === null || $r === null) {            return null;        }        $this->retained[$path] ??= array_column($r->dominators(1000000), 'retained', 'node');        return $this->retained[$path][$node] ?? null;    }    // source -----------------------------------------------------------------------------------------------------    /** "dir/file.php:17 Class::method" => "file.php:17 Class::method" */    public static function shortSite(string $site): string    {        $s = self::parseSite($site);        return $s['line'] > 0 ? basename($s['file']) . ':' . $s['line'] . ' ' . $s['function'] : $site;    }    /** "file:line function" => [file, line, function] */    public static function parseSite(string $site): array    {        if (preg_match('/^(.*?):(\d+) (.*)$/s', $site, $m)) {            return ['file' => $m[1], 'line' => (int)$m[2], 'function' => $m[3]];        }        return ['file' => $site, 'line' => 0, 'function' => ''];    }    /** Source lines around a site, the line itself marked with ">". Looks for the file as is, then in the demo folder. */    public function sourceExcerpt(?string $site, int $around = 3): string    {        if ($site === null) {            return '';        }        $s = self::parseSite($site);        $file = is_readable($s['file']) ? $s['file'] : $this->demoDir . '/' . basename($s['file']);        if ($s['line'] < 1 || !is_readable($file)) {            return '';        }        $lines = file($file, FILE_IGNORE_NEW_LINES) ?: [];        $code = [];        for ($i = max(1, $s['line'] - $around); $i <= min(count($lines), $s['line'] + $around); $i++) {            // without the comment at the end of a line of code: the boxes are narrow            $code[$i] = rtrim((string)preg_replace('~([;{}),])\s+//.*$~', '$1', rtrim($lines[$i - 1])));        }        $indent = PHP_INT_MAX;        foreach ($code as $line) {            if (trim($line) !== '') {                $indent = min($indent, strlen($line) - strlen(ltrim($line)));            }        }        $out = [];        foreach ($code as $i => $line) {            $out[] = sprintf('%s%3d  %s', $i === $s['line'] ? '>' : ' ', $i, substr($line, $indent === PHP_INT_MAX ? 0 : $indent));        }        return implode("\n", $out);    }    // metric series (.cryom) -------------------------------------------------------------------------------------    /** A .cryom file as cryo_metrics_read() gives it (ext-cryo) or MetricSeries::toArray() (same shape). */    public static function readSeries(string $path): array    {        if (self::native() && function_exists('cryo_metrics_read')) {            return cryo_metrics_read($path);        }        return MetricSeries::open($path)->toArray();    }    // freeze files (.cryf) --------------------------------------------------------------------------------------------    /** The header of a freeze file: cryo_info() of ext-cryo when it is loaded, else read in PHP (same keys). */    public static function freezeInfo(string $path, FreezeFile $file): array    {        if (self::native() && function_exists('cryo_info')) {            try {                return cryo_info($path);            } catch (\Throwable) {                // the extension refuses it (another format version...): the PHP reader still shows it            }        }        return $file->info();    }    /** "JobQueue::process()" / "runWorker()" / "{main}" */    public static function frameName(array $frame): string    {        if (!isset($frame['func'])) {            return '{main}';        }        return (isset($frame['class']) ? $frame['class'] . '::' : '') . $frame['func'] . '()';    }    /** "JobQueue::process()   freeze_worker.php:29   2 args" */    public static function frameLine(array $frame): string    {        $args = isset($frame['func']) ? '   ' . Lang::t('{n} args', ['n' => (int)($frame['num_args'] ?? 0)]) : '';        return self::frameName($frame) . '   ' . basename((string)($frame['file'] ?? '?')) . ':' . (int)($frame['line'] ?? 0) . $args;    }    public static function bytes(int|float $b): string    {        return match (true) {            $b >= 1048576 => sprintf('%.1f MB', $b / 1048576),            $b >= 1024 => sprintf('%.1f KB', $b / 1024),            default => sprintf('%d B', $b),        };    }}