2016-08-22 06:40:48 +02:00
|
|
|
<?php declare(strict_types = 1);
|
2015-08-27 16:10:08 +02:00
|
|
|
|
2016-08-23 23:47:40 +02:00
|
|
|
namespace Amp\Parallel\Worker\Internal;
|
2015-08-27 16:10:08 +02:00
|
|
|
|
2016-08-21 17:33:39 +02:00
|
|
|
use Amp\{ Coroutine, Failure, Success };
|
2016-08-23 23:47:40 +02:00
|
|
|
use Amp\Parallel\{ Sync\Channel, Worker\Environment };
|
2016-08-18 18:04:48 +02:00
|
|
|
use Interop\Async\Awaitable;
|
|
|
|
|
|
|
|
class TaskRunner {
|
2015-08-27 16:10:08 +02:00
|
|
|
/**
|
2016-08-23 23:47:40 +02:00
|
|
|
* @var \Amp\Parallel\Sync\Channel
|
2015-08-27 16:10:08 +02:00
|
|
|
*/
|
|
|
|
private $channel;
|
|
|
|
|
2015-09-10 06:29:41 +02:00
|
|
|
/**
|
2016-08-23 23:47:40 +02:00
|
|
|
* @var \Amp\Parallel\Worker\Environment
|
2015-09-10 06:29:41 +02:00
|
|
|
*/
|
|
|
|
private $environment;
|
|
|
|
|
2016-08-18 18:04:48 +02:00
|
|
|
public function __construct(Channel $channel, Environment $environment) {
|
2015-08-27 16:10:08 +02:00
|
|
|
$this->channel = $channel;
|
2015-09-10 06:29:41 +02:00
|
|
|
$this->environment = $environment;
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
2016-08-18 18:04:48 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Runs the task runner, receiving tasks from the parent and sending the result of those tasks.
|
|
|
|
*
|
|
|
|
* @return \Interop\Async\Awaitable
|
|
|
|
*/
|
|
|
|
public function run(): Awaitable {
|
|
|
|
return new Coroutine($this->execute());
|
|
|
|
}
|
|
|
|
|
2015-08-27 16:10:08 +02:00
|
|
|
/**
|
|
|
|
* @coroutine
|
|
|
|
*
|
|
|
|
* @return \Generator
|
|
|
|
*/
|
2016-08-18 18:04:48 +02:00
|
|
|
private function execute(): \Generator {
|
2016-08-21 17:33:39 +02:00
|
|
|
$job = yield $this->channel->receive();
|
2015-08-27 16:10:08 +02:00
|
|
|
|
2016-08-21 17:33:39 +02:00
|
|
|
while ($job instanceof Job) {
|
|
|
|
$task = $job->getTask();
|
|
|
|
|
2015-08-27 16:10:08 +02:00
|
|
|
try {
|
2016-08-18 18:04:48 +02:00
|
|
|
$result = $task->run($this->environment);
|
|
|
|
|
|
|
|
if ($result instanceof \Generator) {
|
|
|
|
$result = new Coroutine($result);
|
|
|
|
}
|
|
|
|
|
2016-08-21 17:33:39 +02:00
|
|
|
if (!$result instanceof Awaitable) {
|
|
|
|
$result = new Success($result);
|
2016-08-18 18:04:48 +02:00
|
|
|
}
|
2016-01-23 07:00:56 +01:00
|
|
|
} catch (\Throwable $exception) {
|
2016-08-21 17:33:39 +02:00
|
|
|
$result = new Failure($exception);
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
2016-08-21 17:33:39 +02:00
|
|
|
|
|
|
|
$result->when(function ($exception, $value) use ($job) {
|
|
|
|
if ($exception) {
|
|
|
|
$result = new TaskFailure($job->getId(), $exception);
|
|
|
|
} else {
|
|
|
|
$result = new TaskSuccess($job->getId(), $value);
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->channel->send($result);
|
|
|
|
});
|
2015-08-27 16:10:08 +02:00
|
|
|
|
2016-08-21 17:33:39 +02:00
|
|
|
$job = yield $this->channel->receive();
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
|
|
|
|
2016-08-21 17:33:39 +02:00
|
|
|
return $job;
|
2015-08-27 16:10:08 +02:00
|
|
|
}
|
|
|
|
}
|