501 lines
28 KiB
PHP
501 lines
28 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Public API of ext-cryo. Everything listed here is implemented (milestones 1 to 7).
|
|
*
|
|
* @generate-function-entries (arginfo is hand-written in v0.1)
|
|
*/
|
|
|
|
namespace {
|
|
|
|
const CRYO_FROZEN = 1;
|
|
const CRYO_THAWED = 2;
|
|
|
|
class CryoException extends Exception {}
|
|
class CryoFreezeException extends CryoException {}
|
|
class CryoThawException extends CryoException {}
|
|
class CryoSignatureException extends CryoThawException {}
|
|
|
|
/* ---- Freeze / thaw / restart (cryo_freeze.c) ---------------------------- */
|
|
|
|
/**
|
|
* Freezes the running script (globals, statics, function statics, constants,
|
|
* handlers, hooks, Engine journal, every user frame with its variables,
|
|
* temporaries and position). Returns CRYO_FROZEN, or CRYO_THAWED when the
|
|
* execution resumes from the file.
|
|
* Options: mode exit (default) | continue | fork | memory_image (WASM);
|
|
* fork child|parent|template (+ workers, max_jobs, max_memory, max_runs);
|
|
* include ['globals','statics','stack'] (without 'stack': values only, cryo_thaw() then returns);
|
|
* exclude [class or variable names]; compress none|zlib (zstd/lz4: zlib);
|
|
* key (HMAC-SHA256 signature, default ini cryo.key), encrypt (libsodium);
|
|
* on_resource null|descriptor|fail; strict; watch [extra files whose change invalidates it]; data.
|
|
*/
|
|
function cryo_freeze(string $file, array $options = []): int {}
|
|
/** Restores and resumes after the original cryo_freeze(); needs a fresh process. */
|
|
function cryo_thaw(string $file, array $options = []): never {}
|
|
/** Freeze + start PHP again on the same command line + thaw. Usable from a cryo_memory_watch() callback. */
|
|
function cryo_restart(string $file, array $options = []): never {}
|
|
function cryo_freeze_vars(string $file, array $vars, array $options = []): void {}
|
|
function cryo_thaw_vars(string $file): array {}
|
|
function cryo_can_freeze(): true|string {}
|
|
function cryo_is_thawed(): bool {}
|
|
function cryo_thaw_count(): int {}
|
|
/** @return array{file?: string, time?: float, pid?: int, host?: string, script?: string} */
|
|
function cryo_origin(): array {}
|
|
/** Header of a freeze file: php, script, time, pid, host, thaw_count, resume, frames, sources, signed, compressed, encrypted, size. */
|
|
function cryo_info(string $file): array {}
|
|
/** Signature and compatibility (same PHP, unchanged sources). */
|
|
function cryo_verify(string $file, array $options = []): bool {}
|
|
function cryo_info_runtime(): array {}
|
|
|
|
/* ---- Hooks and resources (cryo_freeze.c, cryo_walk.c) ------------------- */
|
|
function cryo_on_freeze(callable $callback, int $priority = 0): void {}
|
|
/** The callback receives a CryoThawContext. */
|
|
function cryo_on_thaw(callable $callback, int $priority = 0): void {}
|
|
/** $describe($resourceOrObject): array; $reopen(array $description): mixed. $type: resource type or internal class. */
|
|
function cryo_register_resource(string $type, callable $describe, callable $reopen): void {}
|
|
|
|
interface CryoAware
|
|
{
|
|
public function __cryoFreeze(): array;
|
|
public function __cryoThaw(array $data): void;
|
|
}
|
|
|
|
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
|
|
final class CryoTransient {}
|
|
|
|
/** A value nobody reopened after a thaw (resolve it in cryo_on_thaw). */
|
|
final class CryoPending
|
|
{
|
|
public string $path = '';
|
|
public string $type = '';
|
|
public mixed $desc = null;
|
|
}
|
|
|
|
final class CryoThawContext
|
|
{
|
|
/** @return array<string, array{type: string, desc: mixed}> path => description */
|
|
public function pending(): array {}
|
|
/** Paths: "GLOBALS.a.b", "Class::$prop.x", "frame.N.$var". */
|
|
public function resolve(string $path, mixed $value): bool {}
|
|
public function unset(string $path): bool {}
|
|
/** Replaces every instance of $class by $factory($old); returns the number replaced. */
|
|
public function replaceClass(string $class, callable $factory): int {}
|
|
}
|
|
|
|
/* ---- Fork (cryo_fork.c) ------------------------------------------------- */
|
|
|
|
/**
|
|
* Master + worker processes; every worker is a fork of the master (same state).
|
|
*
|
|
* Options:
|
|
* - workers (int, default: number of CPUs; with jobs: at most count(jobs))
|
|
* - jobs (array): argument lists (list => positional, string keys => named),
|
|
* keys kept. The master hands them out, the results come back:
|
|
* returns [key => result]; on_result(mixed $result, $key, int $worker),
|
|
* on_error(string $message, $key, int $worker) (default: warning).
|
|
* - without jobs: each worker calls $job(int $worker) again as long as it
|
|
* returns true (the job pulls its own work: return false/null/anything
|
|
* else when there is nothing left). That last value is the result
|
|
* ([worker => value]). A worker that ends normally (last call returned,
|
|
* or exit(0)) is not replaced; the pool returns when every worker is done.
|
|
* - max_jobs (int): a worker exits after N jobs (calls returning true) and
|
|
* is replaced by a new fork of the master.
|
|
* - max_memory (int, bytes): a worker whose memory_get_usage() is above it
|
|
* after a job exits and is replaced by a new fork of the master.
|
|
* - respawn (bool, default true): replace workers that die abnormally
|
|
* (crash, exit status != 0, uncaught exception without jobs);
|
|
* respawn_limit (int, default 16): stop replacing after that many abnormal
|
|
* deaths in a row (no successful job in between), with a warning.
|
|
* - on_message(mixed $data, int $worker, int $pid): messages sent by workers
|
|
* with cryo_fork_send(); without it they are queued for cryo_fork_recv().
|
|
* SIGTERM / SIGINT / SIGHUP received by the master are forwarded to the
|
|
* workers. The cryo_on_thaw hooks run in every worker before its first job.
|
|
* WebAssembly: the jobs run one after the other in the same instance.
|
|
*/
|
|
function cryo_fork_pool(callable $job, array $options = []): array {}
|
|
|
|
/**
|
|
* Fork checkpoint; same as cryo_freeze('', ['mode' => 'fork', 'fork' => $variant] + $options)
|
|
* without a file. Returns CRYO_FROZEN in the process that goes on, CRYO_THAWED
|
|
* in a process that resumes from the checkpoint. The cryo_on_thaw hooks run
|
|
* in every new child. Output buffers are flushed before each fork.
|
|
* - "child": the child goes on (CRYO_FROZEN); the parent waits for its end
|
|
* and forks again from the checkpoint (CRYO_THAWED in the new child).
|
|
* Without max_runs: forked again after abnormal ends only (respawn,
|
|
* respawn_limit), the parent exits with the child's status once it is 0.
|
|
* max_runs (int): forked again after every end until max_runs children
|
|
* ran, then the parent exits with the last status.
|
|
* - "parent": the parent goes on (CRYO_FROZEN); a forked copy stops at once
|
|
* (SIGSTOP) as an in-memory resume point (pid in cryo_fork_info()['suspended']).
|
|
* cryo_thaw_fork($pid) resumes it. Suspended copies are killed when the
|
|
* process that owns them ends normally.
|
|
* - "template": this process becomes a frozen master that forks `workers`
|
|
* children (default: CPUs) running the rest of the script (CRYO_THAWED).
|
|
* A child that exits with 0 is not replaced; abnormal ends are respawned
|
|
* (respawn, respawn_limit); max_jobs / max_memory recycle a child at
|
|
* cryo_fork_job_done(); max_runs caps the number of forks. The master
|
|
* exits when every child is done (0, or the status of a failed one).
|
|
* child and template also take on_message(mixed $data, int $worker, int $pid).
|
|
* WebAssembly: cryo_host_clone(); the JS host carries out the variant.
|
|
*/
|
|
function cryo_fork(string $variant = "child", array $options = []): int {}
|
|
|
|
/**
|
|
* Resumes a suspended checkpoint (variant "parent"). The calling process runs
|
|
* no more PHP code: checkpoints taken after $pid are killed, $pid is woken
|
|
* (SIGCONT) and returns CRYO_THAWED; when it is a child of the caller, the
|
|
* caller only waits for it and exits with its status (no orphan).
|
|
*/
|
|
function cryo_thaw_fork(int $pid): never {}
|
|
|
|
/**
|
|
* In a worker / child: sends $data (serialized) to the master ($worker ignored).
|
|
* In the master (inside a pool callback): sends to worker $worker, or to every
|
|
* worker when $worker is null.
|
|
*/
|
|
function cryo_fork_send(mixed $data, ?int $worker = null): void {}
|
|
|
|
/**
|
|
* In a worker / child: next message from the master, null on timeout
|
|
* (null = wait). In the master (pool callbacks, or after the pool for the
|
|
* queued messages): ['worker' => int, 'pid' => int, 'data' => mixed] or null.
|
|
*/
|
|
function cryo_fork_recv(?float $timeout = null): mixed {}
|
|
|
|
/** End of one job in a template child: counts it against max_jobs, checks
|
|
* max_memory; past a limit the child exits (exit(0)) and the master forks a
|
|
* fresh replacement from the checkpoint. false outside a template child. */
|
|
function cryo_fork_job_done(): bool {}
|
|
|
|
/** ['role' => main|master|worker|child|template|thawed, 'worker' => ?int,
|
|
* 'pid' => int, 'channel' => bool, 'jobs' => int, 'suspended' => int[]] */
|
|
function cryo_fork_info(): array {}
|
|
|
|
/* ---- Analysis ----------------------------------------------------------- */
|
|
/** Options: "gc" (bool, collect cycles first, default true);
|
|
* "redact" (list<string>: key / property / variable name patterns, `*` wildcard, case-insensitive:
|
|
* matching strings keep only their length, keys below them become "[redacted N]"). */
|
|
function cryo_snapshot(string $file, array $options = []): void {} // M1 (+redact: M2)
|
|
function cryo_track(bool $enable): void {} // M1
|
|
|
|
/** Up to $max shortest paths from the roots to $object in the running process (no file; the
|
|
* variable passed is not counted as a root). Same shape as CryoReader::path(). */
|
|
function cryo_roots_of(object $object, int $max = 5): array {} // M2
|
|
/** Objects of the running process kept alive only by uncollected cycles (no gc first).
|
|
* @return list<node record> */
|
|
function cryo_orphans(): array {} // M2
|
|
/** Objects per class in two snapshots, by bytes_delta desc then count_delta desc.
|
|
* @return list<array{class:string,count_a:int,count_b:int,count_delta:int,bytes_a:int,bytes_b:int,bytes_delta:int}> */
|
|
function cryo_diff(string $a, string $b): array {} // M2
|
|
|
|
final class CryoReader
|
|
{
|
|
private function __construct() {}
|
|
public static function open(string $file): static {} // M1
|
|
public function info(): array {} // M1
|
|
|
|
/** Objects grouped by $by: "retained" (per class, with the retained size of the class: instances
|
|
* not dominated by another instance of the same class), "class", "site", "stack"
|
|
* (cryo.track_alloc=stack, frames joined by " <- ") or "write" (last write site).
|
|
* @return list<array{<key>:string,count:int,bytes:int,retained?:int}> key = "class" for "retained";
|
|
* sorted by retained (if any), bytes, count desc, then first seen; unknown keys are "(unknown)". */
|
|
public function top(string $by = "retained", int $limit = 20): array {} // M1 (+retained/stack/write: M2)
|
|
|
|
/** @return list<array{kind:string,name:string,node:int}>
|
|
* kind: global | static_prop | frame | orphan | static_var ("f::$v", "C::m::$v") */
|
|
public function roots(): array {} // M1
|
|
|
|
/** Compares N snapshots of the same process. $opts: ["by" => "site"|"class"|"stack"] = view used by
|
|
* ArrayAccess / Countable / foreach on the result (a string is taken as "by"). */
|
|
public static function delta(array $files, array|string $opts = []): CryoDelta {} // M1 (CryoDelta: M2)
|
|
|
|
/*
|
|
* M2 graph queries. Node ids are positions in the snapshot (0..nodes-1).
|
|
* type: "array" | "object" | "string" | "ref"; class: string for objects, null otherwise.
|
|
* A "node record" is:
|
|
* array{node:int, type:string, class:?string, size:int, site:?string, write:?string, epoch:?int, handle:?int}
|
|
* (site / write / epoch / handle are null when unknown; sizes are floats only above PHP_INT_MAX).
|
|
* site = allocation site "file:line function" (where `new` ran);
|
|
* write = last write site of an object (the ASSIGN / ASSIGN_DIM / ASSIGN_OBJ / ASSIGN_STATIC_PROP
|
|
* line, or _OP / _REF variant, that stored it: e.g. `self::$log[] = $q`), needs cryo.track_alloc;
|
|
* stack = allocation call stack (cryo.track_alloc=stack): up to 8 frames, innermost first.
|
|
* A "path" is a list of steps array{kind:string,name:string,node:int,type:string,class:?string,write:?string}:
|
|
* first step kind = root kind and name = root name; next steps kind = "edge" and name = edge name
|
|
* (property, "[index]", array key or "&" for a reference).
|
|
*/
|
|
|
|
/** Up to $max shortest paths from a root to $node (all of minimal length: BFS layers walked back,
|
|
* predecessors in file order). [] if $node does not exist or is unreachable.
|
|
* @return list<path> */
|
|
public function path(int $node, int $max = 5): array {} // M2
|
|
|
|
/** Dominator tree from a super-root linked to every root (Cooper-Harvey-Kennedy);
|
|
* the $limit nodes that retain the most, by retained desc then node asc.
|
|
* @return list<array{node:int,type:string,class:?string,self:int,retained:int,idom:?int}>
|
|
* retained = self + size of every node it dominates; idom = immediate dominator, null = a root. */
|
|
public function dominators(int $limit = 20): array {} // M2
|
|
|
|
/** Objects reachable only from "orphan" roots (uncollected cycles), by node id.
|
|
* @return list<node record> */
|
|
public function orphans(): array {} // M2
|
|
|
|
/** Strings and flat arrays (scalar / string values only) present in several copies with
|
|
* the same content (section HASH; [] for files written without it), by wasted desc.
|
|
* @return list<array{type:string,hash:string,length:int,count:int,bytes:int,wasted:int,node:int}>
|
|
* hash: 8 hex digits (FNV-1a 32); length: bytes of a string / elements of an array;
|
|
* bytes: all copies; wasted: bytes - smallest copy; node: one copy (lowest id). */
|
|
public function dupes(int $limit = 20): array {} // M2
|
|
|
|
/** Node records matching $expr, by node id (at most "limit", default 100).
|
|
* string: query language — `class=App\* and retained>1M or type=string and size>=10K`:
|
|
* fields class, type, site, write (strings: = and !=, `*` wildcard), size, retained, epoch
|
|
* (numbers: = != > < >= <=, units K M G = 1024^n); `and` binds tighter than `or`;
|
|
* values may be "quoted"; unknown values (no site...) only match !=.
|
|
* array: filters type, class (exact), site (substring; known sites only), min_size, epoch_min,
|
|
* epoch_max (known epochs only), expr (query language), limit.
|
|
* Syntax error, unknown key or type: ValueError.
|
|
* @return list<node record> */
|
|
public function query(string|array $expr): array {} // M2
|
|
|
|
/** Node record + allocation stack + edges, or null if there is no such node.
|
|
* @return null|array{node:int, type:string, class:?string, size:int, site:?string, write:?string,
|
|
* epoch:?int, handle:?int, stack:?list<string>, out:list<array{name:string,node:int,type:string,class:?string}>,
|
|
* in:list<array{name:string,node:int,type:string,class:?string}>,
|
|
* roots:list<array{kind:string,name:string}>} */
|
|
public function node(int $id): ?array {} // M2
|
|
|
|
/** Suspicious patterns, by score desc: "orphans" (objects kept by uncollected cycles),
|
|
* "static_cache" (static property / variable retaining > 10 % of the reachable heap),
|
|
* "listeners" (arrays of 10+ elements, 80 % callables: Closure or [object, "method"]),
|
|
* "memory_log" (arrays of 100+ elements, 90 % strings), "growth" (with 2+ $files: growing
|
|
* allocation sites of their delta).
|
|
* @return list<array{kind:string,score:int,message:string,node:?int,site:?string,bytes:int,path:?path}> */
|
|
public function heuristics(array $files = []): array {} // M2
|
|
}
|
|
|
|
/** Result of CryoReader::delta(). Rows of every view:
|
|
* array{<key>:string, new_per_interval:list<int>, cohort_alive_at_last:list<int>, survivors:int,
|
|
* survival:float, bytes_last:int, growing:bool, hooked_by:?string}
|
|
* key = site | class | stack; hooked_by = most frequent write site of the survivors.
|
|
* Growing rows first, then survivors desc. */
|
|
final class CryoDelta implements IteratorAggregate, Countable, ArrayAccess
|
|
{
|
|
private function __construct() {}
|
|
public function bySite(): array {} // M2
|
|
public function byClass(): array {} // M2
|
|
public function byStack(): array {} // M2
|
|
/** @return array{snapshots:list<array{file:string,epoch:int,objects:int,bytes:int}>,
|
|
* by_class:array<string,list<int>>, by_site:array<string,list<int>>} live objects per snapshot */
|
|
public function timeline(): array {} // M2
|
|
/** A bySite() row (index or site string): code around the allocation site and the main write
|
|
* site, typical paths of its survivors in the last snapshot (top 3 by count). null if unknown.
|
|
* @return null|array{site:string,row:array,file:?string,line:?int,code:?array<int,string>,
|
|
* hooked_by:?string,hook_code:?array<int,string>,paths:list<array{count:int,path:path}>} */
|
|
public function explain(int|string $site): ?array {} // M2
|
|
public function getIterator(): Iterator {}
|
|
public function count(): int {}
|
|
public function offsetExists(mixed $offset): bool {}
|
|
public function offsetGet(mixed $offset): mixed {}
|
|
public function offsetSet(mixed $offset, mixed $value): void {} // throws Error (read-only)
|
|
public function offsetUnset(mixed $offset): void {} // throws Error (read-only)
|
|
}
|
|
|
|
/* ---- Metrics (cryo_metrics.c) ------------------------------------------- */
|
|
/**
|
|
* memory, memory_real, memory_peak, memory_peak_real (Zend MM), memory_rss and
|
|
* memory_overhead = rss - memory_real (null when unknown, e.g. WASM),
|
|
* objects_alive, objects_store_size, gc_runs, gc_collected, gc_roots,
|
|
* gc_time (s), freezes, thaws, restarts, last_freeze_ms, last_freeze_bytes,
|
|
* bytes_reclaimed, snapshot_epoch, tracking, class_counting, sampling,
|
|
* samples, otlp_sent, otlp_errors, serve_pid, serve_port.
|
|
*/
|
|
function cryo_metrics(): array {} // M1
|
|
/** class => live objects, by count desc. Kept up to date with cryo.metrics=1. */
|
|
function cryo_metrics_class_counts(int $top = 20): array {} // M1
|
|
/** Background sampling into an append-only .cryom file; $ms <= 0 stops. */
|
|
function cryo_metrics_sample(int $ms, string $file): void {} // M1
|
|
/** Named mark in the active series. */
|
|
function cryo_metrics_mark(string $label): void {} // M1
|
|
/** version, php_version, pid, start, interval_ms, samples, marks, snapshots, sessions, truncated */
|
|
function cryo_metrics_read(string $file): array {} // M1
|
|
/**
|
|
* HTTP exporter in a child process; returns its pid. $port 0 = any (see serve_port), < 0 stops.
|
|
* GET /metrics (Prometheus), GET /metrics.json (cryo_metrics() + time + pid + class_counts with
|
|
* cryo.metrics=1), GET /series.json?since=SEQ (samples of the active cryo_metrics_sample() series),
|
|
* POST /snapshot (GET too when a token is set): cryo_snapshot() taken by this process at its next
|
|
* safe point, returned as application/octet-stream (504 after snapshot_timeout).
|
|
* $options: cors (allowed origin, "*" or "https://..."; default none), token (required as ?token=
|
|
* or Authorization: Bearer, else 401; OPTIONS preflights are always answered), snapshot (true,
|
|
* false, or an array of cryo_snapshot() options such as redact), snapshot_timeout (s, default 10).
|
|
* WebAssembly: no process, the Prometheus text goes to cryo_host_emit(); options throw.
|
|
*/
|
|
function cryo_metrics_serve(int $port, string $host = "127.0.0.1", array $options = []): int {} // M1
|
|
/** All metrics as StatsD gauges, one UDP send to udp://host:8125. */
|
|
function cryo_metrics_push(string $url, string $prefix = "php"): bool {} // M1
|
|
function cryo_memory_watch(int $bytes, callable $callback): void {} // M4
|
|
|
|
}
|
|
|
|
namespace Cryo\Sandbox {
|
|
|
|
/**
|
|
* Isolated PHP (M6). Options:
|
|
* start "spawn" (default: exec of a fresh PHP) | "fork" (copy of this process)
|
|
* | "snapshot" (spawn + cryo_thaw($options["snapshot"])) | "thread" (needs ZTS)
|
|
* bootstrap file included at start (include_once semantics)
|
|
* memory_limit bytes or "64M": PHP memory_limit + RLIMIT_AS (mapped size + 2 x limit + 256M)
|
|
* cpu_time seconds of CPU (RLIMIT_CPU) -> SandboxTimeoutException
|
|
* timeout seconds per request (timer in the child) -> SandboxTimeoutException
|
|
* ini ["name" => "value"]
|
|
* disable_functions list or "a,b": handlers replaced (fork) / disable_functions (spawn)
|
|
* network false: seccomp-bpf denies socket() but AF_UNIX (Linux), else PHP network functions disabled
|
|
* restart "never" (default) | "on_crash" | "always" (fresh child after every request)
|
|
* output "capture" (default: see output()) | "pass" (echoed by the parent)
|
|
*/
|
|
final class Sandbox
|
|
{
|
|
public function __construct(array $options = []) {}
|
|
public static function spawn(array $options = []): static {}
|
|
public static function fromSnapshot(string $file, array $options = []): static {}
|
|
|
|
public function call(string|array $function, array $args = []): mixed {} // [class, method] for static methods
|
|
public function callAsync(string|array $function, array $args = []): Future {}
|
|
public function eval(string $code): mixed {} // eval() semantics, global scope
|
|
public function evalAsync(string $code): Future {}
|
|
public function include(string $file): mixed {}
|
|
public function get(string $name): mixed {} // global variable of the child
|
|
public function set(string $name, mixed $value): void {}
|
|
public function snapshot(string $file): void {} // cryo_snapshot() in the child
|
|
public function freeze(string $file): mixed {} // cryo_freeze() in the child
|
|
public function metrics(): array {}
|
|
public function proxy(string $expression): RemoteObject {}
|
|
|
|
public function send(mixed $message): void {} // to Channel::parent()->recv() in the child
|
|
public function recv(?float $timeout = null): mixed {} // from Channel::parent()->send()
|
|
/** @return resource readable socket (dup) for event loops */
|
|
public function stream() {}
|
|
public function engine(): EngineProxy {}
|
|
|
|
public function kill(): void {}
|
|
public function restart(): void {}
|
|
public function status(): array {} // pid, alive, start, backend, calls, pending, memory, last_error, signal, exit_code, network, restart
|
|
public function output(): string {} // output of the last request
|
|
|
|
public static function awaitAll(array $futures, ?float $timeout = null): array {}
|
|
public static function awaitAny(array $futures, ?float $timeout = null): mixed {}
|
|
public static function select(array $futures, ?float $timeout = 0.0): array {} // keys of the ready futures
|
|
|
|
// non-blocking API (the only one in the browser: synchronous calls throw a SandboxException there)
|
|
public function getAsync(string $name): Future {}
|
|
public function setAsync(string $name, mixed $value): Future {}
|
|
public function includeAsync(string $file): Future {}
|
|
public function metricsAsync(): Future {}
|
|
public function messages(): array {} // what the child sent so far, never waits
|
|
/** A future settled once every given future is (wait(Future): its value; array: values, same keys). Never blocks. */
|
|
public static function wait(Future|array $futures, ?float $timeout = null): Future {}
|
|
/** Reads what every sandbox sent, runs the then() callbacks, settles wait(); returns how many futures settled. */
|
|
public static function pump(): int {}
|
|
/** Requests waiting for an answer + then() / wait() futures not settled yet. */
|
|
public static function pending(): int {}
|
|
}
|
|
|
|
final class Future
|
|
{
|
|
private function __construct() {}
|
|
public function await(?float $timeout = null): mixed {}
|
|
public function isReady(): bool {}
|
|
public function status(): string {} // 'pending', 'ready', 'failed', 'cancelled' (never waits)
|
|
public function isFailed(): bool {}
|
|
public function isCancelled(): bool {}
|
|
public function value(): mixed {} // the value once ready, else null (never throws)
|
|
public function error(): ?\Throwable {} // the exception once failed / cancelled, else null
|
|
public function cancel(): bool {}
|
|
/** $callback($value), or $onError($exception): run once, by Sandbox::pump() or when the new future is read. */
|
|
public function then(callable $callback, ?callable $onError = null): Future {}
|
|
}
|
|
|
|
final class RemoteObject
|
|
{
|
|
private function __construct() {}
|
|
public function __call(string $name, array $arguments): mixed {}
|
|
public function __get(string $name): mixed {}
|
|
public function __set(string $name, mixed $value): void {}
|
|
public function __isset(string $name): bool {}
|
|
public function __unset(string $name): void {}
|
|
public function remoteClass(): string {}
|
|
}
|
|
|
|
/** Cryo\Engine of the child: same methods as Cryo\Engine (closures are recompiled from their source). */
|
|
final class EngineProxy
|
|
{
|
|
private function __construct() {}
|
|
public function __call(string $name, array $arguments): mixed {}
|
|
}
|
|
|
|
/** Child side of the channel. */
|
|
final class Channel
|
|
{
|
|
private function __construct() {}
|
|
public static function parent(): Channel {}
|
|
public function send(mixed $message): void {}
|
|
public function recv(?float $timeout = null): mixed {}
|
|
/** @internal entry point of a spawned child */
|
|
public static function serve(int $fd): never {}
|
|
}
|
|
|
|
/** Options: those of Sandbox + max_jobs (requests before a worker is replaced), max_memory (bytes). */
|
|
final class Pool
|
|
{
|
|
public function __construct(int $size, array $options = []) {}
|
|
public function call(string|array $function, array $args = []): mixed {}
|
|
public function callAsync(string|array $function, array $args = []): Future {}
|
|
public function map(string|array $function, array $argsList): array {}
|
|
public function status(): array {}
|
|
public function close(): void {}
|
|
}
|
|
|
|
class SandboxException extends \CryoException {}
|
|
class SandboxCrashedException extends SandboxException
|
|
{
|
|
public function getSignal(): ?int {}
|
|
public function getExitCode(): ?int {}
|
|
public function getStderr(): string {} // last 2 KiB of the child's stderr/stdout
|
|
}
|
|
class SandboxTimeoutException extends SandboxException {}
|
|
class SandboxMemoryException extends SandboxException {}
|
|
class RemoteException extends SandboxException // file/line/code/message of the original exception
|
|
{
|
|
public function getRemoteClass(): string {}
|
|
public function getRemoteTrace(): string {}
|
|
}
|
|
|
|
}
|
|
|
|
namespace Cryo {
|
|
|
|
/**
|
|
* Hot code changes in the running process (M6). Every method returns the id of
|
|
* the change; everything is undone by revert() and at the end of the request.
|
|
* Internal functions need cryo.engine_internal_override=1; cryo.engine=0 disables the class.
|
|
*/
|
|
final class Engine
|
|
{
|
|
private function __construct() {}
|
|
public static function current(): static {}
|
|
public function redefineFunction(string $name, \Closure $body): int {}
|
|
public function addFunction(string $name, \Closure $body): int {}
|
|
public function removeFunction(string $name): int {}
|
|
public function renameFunction(string $name, string $newName): int {}
|
|
public function redefineMethod(string $class, string $method, \Closure $body): int {}
|
|
public function addMethod(string $class, string $method, \Closure $body, int $flags = \ReflectionMethod::IS_PUBLIC): int {}
|
|
public function removeMethod(string $class, string $method): int {}
|
|
public function redefineConstant(string $name, mixed $value): int {} // "NAME" or "Class::NAME"
|
|
public function registerSuperglobal(string $name): int {}
|
|
public function journal(): array {} // [id, kind, target, time, file, line, replayable]
|
|
public function revert(?int $id = null): int {}
|
|
public function exportJournal(): array {} // closures as file + lines + scope + bound variables
|
|
public function replayJournal(array $journal): int {}
|
|
}
|
|
|
|
}
|