mirror of
https://github.com/danog/parallel.git
synced 2024-11-27 12:54:55 +01:00
63 lines
1.9 KiB
PHP
63 lines
1.9 KiB
PHP
#!/usr/bin/env php
|
|
<?php declare(strict_types = 1);
|
|
|
|
use Amp\Parallel\{ ChannelException, SerializationException} ;
|
|
use Amp\Parallel\Sync\{ ChannelledSocket, Internal\ExitFailure, Internal\ExitSuccess };
|
|
use Amp\Parallel\Worker\{ BasicEnvironment, Internal\TaskRunner };
|
|
|
|
@cli_set_process_title("amp-worker");
|
|
error_reporting(E_ALL);
|
|
|
|
// Redirect all output written using echo, print, printf, etc. to STDERR.
|
|
ob_start(function ($data) {
|
|
fwrite(STDERR, $data);
|
|
return '';
|
|
}, 1, PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE);
|
|
|
|
(function () {
|
|
$paths = [
|
|
dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'autoload.php',
|
|
dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php',
|
|
];
|
|
|
|
$autoloadPath = null;
|
|
foreach ($paths as $path) {
|
|
if (file_exists($path)) {
|
|
$autoloadPath = $path;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if ($autoloadPath === null) {
|
|
fwrite(STDERR, 'Could not locate autoload.php.');
|
|
exit(1);
|
|
}
|
|
|
|
require $autoloadPath;
|
|
})();
|
|
|
|
AsyncInterop\Loop::execute(Amp\wrap(function () {
|
|
$channel = new ChannelledSocket(STDIN, STDOUT, false);
|
|
$environment = new BasicEnvironment;
|
|
$runner = new TaskRunner($channel, $environment);
|
|
|
|
try {
|
|
$result = new ExitSuccess(yield $runner->run());
|
|
} catch (Throwable $exception) {
|
|
$result = new ExitFailure($exception);
|
|
}
|
|
|
|
// Attempt to return the result.
|
|
try {
|
|
try {
|
|
return yield $channel->send($result);
|
|
} catch (SerializationException $exception) {
|
|
// Serializing the result failed. Send the reason why.
|
|
return yield $channel->send(new ExitFailure($exception));
|
|
}
|
|
} catch (ChannelException $exception) {
|
|
// The result was not sendable! The parent context must have died or killed the context.
|
|
return 0;
|
|
}
|
|
}));
|