{"repo_name": "pokio", "file_name": "/pokio/src/Environment.php", "inference_info": {"prefix_code": "\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future\n */\n public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n\n // Adding a little sleep to prevent busy-waiting and CPU\n // starvation, allowing other processes to run in the\n // meantime. -------------------------------------\n\n usleep(1000);\n }\n\n $ipc = IPC::create();\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n\n // @codeCoverageIgnoreStart\n try {\n $result = $callback();\n\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n\n $data = serialize($result);\n\n $ipc->put($data);\n\n exit(0);\n // @codeCoverageIgnoreEnd\n }\n\n self::$processes[$pid] = true;\n\n /** @var Future $future */\n // @phpstan-ignore-next-line\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n\n return $future;\n }\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Kernel.php", "asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Promise.php", "|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", ",\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/types/Async.php", " 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Functions.php", "\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array>|Promise $promises\n * @return ($promises is array ? array : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/src/Pokio.php", "useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Contracts/Runtime.php", "\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Exceptions/PromiseAlreadyStarted.php", "\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future\n */\n public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n\n // Adding a little sleep to prevent busy-waiting and CPU\n // starvation, allowing other processes to run in the\n // meantime. -------------------------------------\n\n usleep(1000);\n }\n\n $ipc = IPC::create();\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n\n // @codeCoverageIgnoreStart\n try {\n $result = $callback();\n\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n\n $data = serialize($result);\n\n $ipc->put($data);\n\n exit(0);\n // @codeCoverageIgnoreEnd\n }\n\n self::$processes[$pid] = true;\n\n /** @var Future $future */\n // @phpstan-ignore-next-line\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n\n return $future;\n }\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Kernel.php", "asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", ",\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Promise.php", "|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/types/Async.php", " 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Functions.php", "\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array>|Promise $promises\n * @return ($promises is array ? array : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/src/Pokio.php", "useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Contracts/Runtime.php", "\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Exceptions/PromiseAlreadyStarted.php", "\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future\n */\n ", "suffix_code": "\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n", "middle_code": "public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n usleep(1000);\n }\n $ipc = IPC::create();\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n try {\n $result = $callback();\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n $data = serialize($result);\n $ipc->put($data);\n exit(0);\n }\n self::$processes[$pid] = true;\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n return $future;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/pokio/src/Promise.php", "|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Environment.php", "asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/Functions.php", "\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array>|Promise $promises\n * @return ($promises is array ? array : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", ",\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/types/Async.php", " 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Contracts/Runtime.php", "\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Pokio.php", "useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Exceptions/FutureAlreadyAwaited.php", "isOrchestrator()) {\n try {\n $result = $callback();\n $promise->resolve($result);\n } catch (Throwable $e) {\n $promise->reject($e);\n }\n return $promise;\n }\n\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n }\n\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Unable to fork process.');\n }\n\n if ($pid === 0) {\n try {\n $result = $callback();\n exit(serialize(['result' => $result]));\n } catch (Throwable $e) {\n exit(serialize(['exception' => $e]));\n }\n }\n\n self::$processes[$pid] = true;\n UnwaitedFutureManager::register($pid, $promise);\n\n return $promise;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-30-09"}, "editdistance_info": {"edit_distance": 26.5487, "calculate_time": "2025-08-20 21:30:09", "true_code_clean": "public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n usleep(1000);\n }\n $ipc = IPC::create();\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n try {\n $result = $callback();\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n $data = serialize($result);\n $ipc->put($data);\n exit(0);\n }\n self::$processes[$pid] = true;\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n return $future;\n }", "predict_code_clean": "public function defer(Closure $callback): Future\n {\n $promise = new Promise();\n if (!Kernel::instance()->isOrchestrator()) {\n try {\n $result = $callback();\n $promise->resolve($result);\n } catch (Throwable $e) {\n $promise->reject($e);\n }\n return $promise;\n }\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n }\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Unable to fork process.');\n }\n if ($pid === 0) {\n try {\n $result = $callback();\n exit(serialize(['result' => $result]));\n } catch (Throwable $e) {\n exit(serialize(['exception' => $e]));\n }\n }\n self::$processes[$pid] = true;\n UnwaitedFutureManager::register($pid, $promise);\n return $promise;\n }"}}