DE
apps/cryo-studio / src / Cryo / MetricSeries.php · commit 76aa68d
<?phpdeclare(strict_types=1);namespace App\Cryo;/** * Pure-PHP reader of the .cryom metric series written by * cryo_metrics_sample() (same result as cryo_metrics_read() of ext-cryo). * Layout: see ext-cryo/cryo_format.h. * * Works on 32-bit PHP: only unpack('v'/'V'/'e') is used, every u64 is read as * two u32 and combined (float above PHP_INT_MAX). */final class MetricSeries{    public const SAMPLE = 1;    public const MARK = 2;    public const SNAPSHOT = 3;    public const START = 4;    private const HEADER_SIZE = 32;    private const SAMPLE_LEN = 144;    private const TWO32 = 4294967296.0;    private const FIELDS = [        'memory', 'memory_real', 'memory_peak', 'memory_peak_real', 'rss', 'objects_alive',        'objects_store_size', 'gc_runs', 'gc_collected', 'gc_time', 'freezes', 'thaws',        'restarts', 'last_freeze_ms', 'last_freeze_bytes', 'bytes_reclaimed',    ];    public int $version = 0;    public int $phpVersion = 0;    public int|float $pid = 0;    public float $start = 0.0;    public int|float $intervalMs = 0;    public bool $truncated = false;    /** @var list<array<string, int|float|null>> */    private array $samples = [];    /** @var list<array{time: float, seq: int|float, label: string}> */    private array $marks = [];    /** @var list<array{time: float, seq: int|float, file: string}> */    private array $snapshots = [];    /** @var list<array{time: float, pid: int|float, interval_ms: int|float}> */    private array $sessions = [];    private function __construct() {}    public static function open(string $file): self    {        $data = @file_get_contents($file);        if ($data === false) {            throw new \RuntimeException("Cannot open $file");        }        return self::fromString($data, $file);    }    public static function fromString(string $data, string $name = 'data'): self    {        if (strlen($data) < self::HEADER_SIZE || substr($data, 0, 4) !== 'CRYM') {            throw new \RuntimeException("$name is not a .cryom file");        }        $s = new self();        $h = unpack('vversion/vflags/Vphp/Vpid/estart/Vinterval', $data, 4);        $s->version = $h['version'];        if ($s->version !== 1) {            throw new \RuntimeException("Unsupported .cryom version {$s->version}");        }        $s->phpVersion = self::u32($h['php']);        $s->pid = self::u32($h['pid']);        $s->start = (float) $h['start'];        $s->intervalMs = self::u32($h['interval']);        $len = strlen($data);        $p = self::HEADER_SIZE;        while ($p < $len) {            if ($len - $p < 4) {                $s->truncated = true;                break;            }            $kind = ord($data[$p]);            $rlen = ord($data[$p + 2]) | (ord($data[$p + 3]) << 8);            $pl = $p + 4;            if ($len - $pl < $rlen) {                $s->truncated = true;                break;            }            if ($kind === self::SAMPLE && $rlen >= self::SAMPLE_LEN) {                $s->samples[] = self::sample($data, $pl);            } elseif (($kind === self::MARK || $kind === self::SNAPSHOT) && $rlen >= 12) {                $r = unpack('etime/Vseq', $data, $pl);                $row = ['time' => (float) $r['time'], 'seq' => self::u32($r['seq'])];                if ($kind === self::MARK) {                    $row['label'] = substr($data, $pl + 12, $rlen - 12);                    $s->marks[] = $row;                } else {                    $row['file'] = substr($data, $pl + 12, $rlen - 12);                    $s->snapshots[] = $row;                }            } elseif ($kind === self::START && $rlen >= 16) {                $r = unpack('etime/Vpid/Vinterval', $data, $pl);                $s->sessions[] = ['time' => (float) $r['time'], 'pid' => self::u32($r['pid']), 'interval_ms' => self::u32($r['interval'])];            }            $p = $pl + $rlen;        }        return $s;    }    /** @return list<array<string, int|float|null>> */    public function samples(): array    {        return $this->samples;    }    /** @return list<array{time: float, seq: int|float, label: string}> */    public function marks(): array    {        return $this->marks;    }    /** @return list<array{time: float, seq: int|float, file: string}> */    public function snapshots(): array    {        return $this->snapshots;    }    /** @return list<array{time: float, pid: int|float, interval_ms: int|float}> */    public function sessions(): array    {        return $this->sessions;    }    /** Same shape as cryo_metrics_read(). */    public function toArray(): array    {        return [            'version' => $this->version,            'php_version' => $this->phpVersion,            'pid' => $this->pid,            'start' => $this->start,            'interval_ms' => $this->intervalMs,            'samples' => $this->samples,            'marks' => $this->marks,            'snapshots' => $this->snapshots,            'sessions' => $this->sessions,            'truncated' => $this->truncated,        ];    }    /**     * Values of one field over time: list of [time, value].     * @return list<array{0: float, 1: int|float|null}>     */    public function column(string $field): array    {        $out = [];        foreach ($this->samples as $s) {            $out[] = [$s['time'], $s[$field] ?? null];        }        return $out;    }    /**     * Summary used by `cryo-inspect metrics` and the Series screen: duration,     * min / max / last of `memory`, slope in MB per hour (least squares),     * marks.     */    public function summary(string $field = 'memory'): array    {        return self::summarize($this->toArray(), $field);    }    /** Summary of an array returned by cryo_metrics_read() or toArray(). */    public static function summarize(array $series, string $field = 'memory'): array    {        $samples = $series['samples'];        $n = count($samples);        $out = [            'samples' => $n,            'sessions' => count($series['sessions']),            'duration' => 0.0,            'field' => $field,            'min' => null,            'max' => null,            'last' => null,            'slope_mb_per_hour' => null,            'peak' => null,            'rss_last' => null,            'objects_last' => null,            'marks' => $series['marks'],            'snapshots' => array_column($series['snapshots'], 'file'),        ];        if ($n === 0) {            return $out;        }        $t0 = $samples[0]['time'];        $out['duration'] = round($samples[$n - 1]['time'] - $t0, 3);        $vals = array_map(static fn($s) => $s[$field], $samples);        $out['min'] = min($vals);        $out['max'] = max($vals);        $out['last'] = $vals[$n - 1];        $out['peak'] = $samples[$n - 1]['memory_peak'];        $out['rss_last'] = $samples[$n - 1]['rss'];        $out['objects_last'] = $samples[$n - 1]['objects_alive'];        if ($n >= 2) {            $sx = $sy = $sxx = $sxy = 0.0;            foreach ($samples as $i => $s) {                $x = $s['time'] - $t0;                $y = (float) $vals[$i];                $sx += $x;                $sy += $y;                $sxx += $x * $x;                $sxy += $x * $y;            }            $den = $n * $sxx - $sx * $sx;            if ($den > 0) {                $bytesPerSecond = ($n * $sxy - $sx * $sy) / $den;                $out['slope_mb_per_hour'] = round($bytesPerSecond * 3600 / 1048576, 3);            }        }        return $out;    }    private static function sample(string $data, int $p): array    {        $h = unpack('etime/Vseq/Vflags', $data, $p);        $row = ['time' => (float) $h['time'], 'seq' => self::u32($h['seq'])];        $flags = self::u32($h['flags']);        $w = unpack('V32', $data, $p + 16);        foreach (self::FIELDS as $i => $name) {            $v = self::u64($w[2 * $i + 1], $w[2 * $i + 2]);            if ($name === 'rss' && !($flags & 1)) {                $row[$name] = null;            } elseif ($name === 'gc_time') {                $row[$name] = $v / 1e9;            } elseif ($name === 'last_freeze_ms') {                $row[$name] = $v / 1000.0;            } else {                $row[$name] = $v;            }        }        return $row;    }    /** unpack('V') is signed on 32-bit PHP. */    private static function u32(int $v): int|float    {        return $v < 0 ? $v + self::TWO32 : $v;    }    private static function u64(int $lo, int $hi): int|float    {        $lo = self::u32($lo);        $hi = self::u32($hi);        if ($hi == 0) {            return $lo;        }        if (PHP_INT_SIZE >= 8 && $hi < 2147483648) {            return ((int) $hi << 32) | (int) $lo; // exact on 64-bit        }        return $hi * self::TWO32 + $lo;    }}