Пример #1
0
 protected function matchMapping($mode, $mappingMode, $method)
 {
     if (($mode & $mappingMode) == $mappingMode) {
         return \React\Promise\resolve([$this->filesystem, $method]);
     }
     return new RejectedPromise();
 }
 protected function resolveCoreAddresses($coreCount)
 {
     for ($i = 0; $i < $coreCount; $i++) {
         $this->availableAddresses[$i] = $i;
     }
     return \React\Promise\resolve($this->availableAddresses);
 }
 protected function __construct(Messenger $messenger, LoopInterface $loop)
 {
     $messenger->registerRpc('return', function (Payload $payload) {
         return \React\Promise\resolve($payload->getPayload());
     });
     $this->ran = true;
 }
Пример #4
0
 /**
  * @param array $node
  * @return \React\Promise\PromiseInterface
  */
 public function detect(array $node)
 {
     if (isset($this->mapping[$node['type']])) {
         return \React\Promise\resolve([$this->filesystem, $this->mapping[$node['type']]]);
     }
     return new RejectedPromise();
 }
 /**
  * @return PromiseInterface
  */
 public function execute()
 {
     return \WyriHaximus\React\childProcessPromise($this->loop, new Process('echo %NUMBER_OF_PROCESSORS%'))->then(function (ProcessOutcome $outcome) {
         if ($outcome->getExitCode() == 0) {
             return \React\Promise\resolve((int) trim($outcome->getStdout()));
         }
         return \React\Promise\reject();
     });
 }
 /**
  * @return PromiseInterface
  */
 protected function requeue()
 {
     if ($this->queue->count() === 0) {
         return new FulfilledPromise();
     }
     return \React\Promise\resolve($this->queue->dequeue())->then(function (Rpc $rpc) {
         return \React\Promise\resolve($this->memory->enqueue($rpc));
     });
 }
Пример #7
0
 /**
  * @param string $program
  * @return PromiseInterface
  */
 public function execute($program = '')
 {
     return \WyriHaximus\React\childProcessPromise($this->loop, new Process('hash ' . $program))->then(function (ProcessOutcome $outcome) {
         if ($outcome->getExitCode() == 0) {
             return \React\Promise\resolve();
         }
         return \React\Promise\reject();
     });
 }
Пример #8
0
 /** @test */
 public function shouldSwitchFromErrbacksToCallbacksWhenErrbackReturnsAResolution()
 {
     $adapter = $this->getPromiseTestAdapter();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(2));
     $adapter->reject(1);
     $adapter->promise()->then($this->expectCallableNever(), function ($val) {
         return \React\Promise\resolve($val + 1);
     })->then($mock, $this->expectCallableNever());
 }
 /** @test */
 public function thenShouldForwardPromisedCallbackResultValueToNextCallback()
 {
     $adapter = $this->getPromiseTestAdapter();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(2));
     $adapter->resolve(1);
     $adapter->promise()->then(function ($val) {
         return \React\Promise\resolve($val + 1);
     }, $this->expectCallableNever())->then($mock, $this->expectCallableNever());
 }
Пример #10
0
 public function testSubjectIsAllowedParamName()
 {
     $compiler = \Fbind\bindParam('subject')->toAsync(function () {
         return \React\Promise\resolve(['hello', 'world']);
     });
     $compiled = $compiler->compile(function (array $subject, array $bar) {
         $this->assertSame(['hello', 'world'], $subject);
         $this->assertSame(['foobar'], $bar);
     });
     $compiled(['foobar']);
 }
 /**
  * RPC Call - Set configuration
  *
  * @param \WyriHaximus\React\ChildProcess\Messenger\Messages\Payload $payload
  * @return \React\Promise\FulfilledPromise|\React\Promise\Promise
  */
 public function rpcConfig(Payload $payload)
 {
     try {
         $this->setAdapter(isset($payload['service']) ? $payload['service'] : self::DEFAULT_ADAPTER);
         if (!empty($payload['service_config'])) {
             $this->adapter->setConfig($payload['service_config']);
         }
     } catch (\Exception $ex) {
         return \React\Promise\reject(['success' => false, 'error' => $ex->getMessage()]);
     }
     return \React\Promise\resolve(['success' => true]);
 }
Пример #12
0
/**
 * @param Promise[] $promises
 *
 * @return Promise
 */
function serial($promises)
{
    if (!count($promises)) {
        return \React\Promise\resolve([]);
    }
    $promise = array_shift($promises);
    return $promise->then(function ($result) use($promises) {
        return serial($promises)->then(function ($childResults) use($result) {
            return \React\Promise\resolve(array_merge([$result], $childResults));
        });
    });
}
 /**
  * Process constructor.
  * @param LoopInterface $loop
  * @param Messenger $messenger
  */
 protected function __construct(LoopInterface $loop, Messenger $messenger)
 {
     $this->loop = $loop;
     $this->messenger = $messenger;
     $this->messenger->registerRpc(MessengerFactory::PROCESS_REGISTER, function (Payload $payload) {
         if (!is_subclass_of($payload['className'], 'WyriHaximus\\React\\ChildProcess\\Messenger\\ChildInterface')) {
             throw new \Exception('Given class doesn\'t implement ChildInterface');
         }
         $this->registerClass($payload['className']);
         $this->deregisterRpc();
         return \React\Promise\resolve([]);
     });
 }
Пример #14
0
 public static function detectAsync(LoopInterface $loop, Collections $collections = null)
 {
     if ($collections === null) {
         $collections = getDefaultCollections($loop);
     }
     return $collections->getDetectors()->execute($collections->getCounters())->then(function (CountInterface $counter) {
         return $counter->execute();
     })->then(function ($count) use($collections) {
         return $collections->getDetectors()->execute($collections->getAffinities())->then(function (AffinityInterface $affinity) use($count) {
             Resolver::setAffinity($affinity);
             return \React\Promise\resolve($count);
         });
     });
 }
 /**
  * @param string $class
  * @param LoopInterface $loop
  * @param array $options
  * @return PromiseInterface
  */
 public static function createFromClass($class, LoopInterface $loop, array $options = [])
 {
     $options = array_merge(self::$defaultOptions, $options);
     return \WyriHaximus\React\ChildProcess\Pool\detectCoreCount($loop, $options)->then(function ($coreCount) use($class, $loop, $options) {
         $options[Options::SIZE] = $coreCount;
         $processes = [];
         for ($i = 0; $i < $coreCount; $i++) {
             $processes[] = Resolver::resolve($i, '%s')->then(function ($command) use($class) {
                 return \React\Promise\resolve(new ClassName($class, ['cmdTemplate' => $command]));
             });
         }
         return \React\Promise\all($processes)->then(function ($processes) use($loop, $options) {
             return \React\Promise\resolve(new Fixed(new ArrayList($processes), $loop, $options));
         });
     });
 }
 /**
  * @param string $className
  * @param LoopInterface $loop
  * @param array $options
  * @param float $interval
  * @return \React\Promise\PromiseInterface
  * @throws \Exception
  */
 public static function parentFromClass($className, LoopInterface $loop, array $options = [], $interval = self::INTERVAL)
 {
     if (!is_subclass_of($className, 'WyriHaximus\\React\\ChildProcess\\Messenger\\ChildInterface')) {
         throw new \Exception('Given class doesn\'t implement ChildInterface');
     }
     $template = '%s';
     if (isset($options['cmdTemplate'])) {
         $template = $options['cmdTemplate'];
         unset($options['cmdTemplate']);
     }
     $process = new Process(sprintf($template, self::getProcessForCurrentOS() . ' ' . ArgvEncoder::encode($options)));
     return static::parent($process, $loop, $options, $interval)->then(function (Messenger $messenger) use($className) {
         return $messenger->rpc(MessengesFactory::rpc(Factory::PROCESS_REGISTER, ['className' => $className]))->then(function () use($messenger) {
             return \React\Promise\resolve($messenger);
         });
     });
 }
Пример #17
0
 /**
  * @param ProcessCollectionInterface $processCollection
  * @param LoopInterface $loop
  * @param array $options
  */
 public function __construct(ProcessCollectionInterface $processCollection, LoopInterface $loop, array $options = [])
 {
     $this->loop = $loop;
     $this->options = $options;
     $this->queue = \WyriHaximus\React\ChildProcess\Pool\getQueue($this->options, 'WyriHaximus\\React\\ChildProcess\\Pool\\Queue\\Memory', $loop);
     $this->manager = \WyriHaximus\React\ChildProcess\Pool\getManager($this->options, $processCollection, 'WyriHaximus\\React\\ChildProcess\\Pool\\Manager\\Fixed', $loop);
     $this->manager->on('ready', function (WorkerInterface $worker) {
         $this->emit('worker', [$worker]);
         if ($this->queue->count() === 0) {
             return;
         }
         \React\Promise\resolve($this->queue->dequeue())->then(function (Rpc $message) use($worker) {
             $hash = spl_object_hash($message);
             $this->deferreds[$hash]->resolve($worker->rpc($message));
             unset($this->deferreds[$hash]);
         });
     });
 }
Пример #18
0
 function getConnection()
 {
     if (!empty($this->pool)) {
         $key = key($this->pool);
         $conn = $this->pool[$key];
         unset($this->pool[$key]);
         return \React\Promise\resolve($conn);
     }
     if ($this->pool_i >= $this->maxConnections) {
         $deferred = new Deferred();
         $this->waiting[] = $deferred;
         return $deferred->promise();
     }
     $conn = call_user_func($this->makeConnection);
     if ($conn !== false) {
         $this->pool_i++;
     }
     return $conn === false ? \React\Promise\reject(new \Exception(mysqli_connect_error())) : \React\Promise\resolve($conn);
 }
Пример #19
0
 /**
  * @param HandBetPair $hand
  * @param DealerHand  $dealerHand
  *
  * @return Promise
  */
 public function requestAction(HandBetPair $hand, DealerHand $dealerHand)
 {
     return \Blackjack\Promise\timedResolve(self::RESPONSE_SPEED)->then(function () use($hand, $dealerHand) {
         if ($this->getSeat() === null) {
             return \React\Promise\reject(new \RuntimeException('Player kicked'));
         }
         if ($hand->getHand()->canSplitPair()) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_SPLIT));
         }
         if ($hand->getHand()->getValue() === 10) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_DOUBLE_DOWN));
         }
         if ($hand->getHand()->getValue() < 17) {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_HIT));
         } else {
             return \React\Promise\resolve(new HandAction(HandAction::ACTION_STAND));
         }
     });
 }
Пример #20
0
 /**
  * Attempt to find a job from the top of one of the queues for this worker.
  *
  * @return PromiseInterface
  */
 public function reserve()
 {
     $queues = $this->queues();
     if ($queues instanceof PromiseInterface) {
         if ($this->paused) {
             return $queues->then(function () {
                 sleep($this->options['interval']);
             });
         } else {
             return $queues->then(function ($response) {
                 if (empty($response)) {
                     sleep($this->options['interval']);
                     return \React\Promise\resolve();
                 }
                 return Resque::bpop($response, $this->options['interval']);
             });
         }
     } else {
         if ($this->processing <= $this->options['concurrency']) {
             return Resque::bpop($queues, $this->options['interval']);
         } else {
             return \React\Promise\resolve();
         }
     }
 }
Пример #21
0
 /** @test */
 public function alwaysShouldNotSuppressRejectionWhenHandlerReturnsAPromise()
 {
     $adapter = $this->getPromiseTestAdapter();
     $exception = new \Exception();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo($exception));
     $adapter->promise()->always(function () {
         return \React\Promise\resolve(1);
     })->then(null, $mock);
     $adapter->reject($exception);
 }
 /**
  * RPC Call - Fetch karma value for specified term
  *
  * @param string $term
  * @return \React\Promise\FulfilledPromise|\React\Promise\Promise
  */
 public function fetchKarma($term)
 {
     return \React\Promise\resolve(['success' => true, 'karma' => rand(-10, 10)]);
 }
 protected function openWrite($path)
 {
     $stream = new ThroughStream();
     BufferedSink::createPromise($stream)->then(function ($contents) use($path) {
         $this->invoker->invokeCall('write', ['flysystem' => serialize($this->flysystem), 'path' => $path, 'contents' => base64_encode($contents)]);
     });
     return \React\Promise\resolve($stream);
 }
/**
 * @param $address
 * @param Process $childProcess
 * @return Process
 */
function rebuildProcess($address, Process $childProcess)
{
    return Resolver::resolve($address, getProcessPropertyValue('cmd', $childProcess))->then(function ($cmd) use($childProcess) {
        return \React\Promise\resolve(new Process($cmd, getProcessPropertyValue('cwd', $childProcess), getProcessPropertyValue('env', $childProcess), getProcessPropertyValue('options', $childProcess)));
    });
}
Пример #25
0
 /**
  * @it nulls out error subtrees
  */
 public function testNullsOutErrorSubtrees()
 {
     $doc = '{
   sync
   syncError
   syncRawError
   syncReturnError
   syncReturnErrorList
   async
   asyncReject
   asyncRawReject
   asyncEmptyReject
   asyncError
   asyncRawError
   asyncReturnError
     }';
     $data = ['sync' => function () {
         return 'sync';
     }, 'syncError' => function () {
         throw new \Exception('Error getting syncError');
     }, 'syncRawError' => function () {
         throw new \Exception('Error getting syncRawError');
     }, 'syncReturnError' => function () {
         return new \Exception('Error getting syncReturnError');
     }, 'syncReturnErrorList' => function () {
         return ['sync0', new \Exception('Error getting syncReturnErrorList1'), 'sync2', new \Exception('Error getting syncReturnErrorList3')];
     }, 'async' => function () {
         return new Promise(function (callable $resolve) {
             return $resolve('async');
         });
     }, 'asyncReject' => function () {
         return new Promise(function ($_, callable $reject) {
             return $reject('Error getting asyncReject');
         });
     }, 'asyncRawReject' => function () {
         return \React\Promise\reject('Error getting asyncRawReject');
     }, 'asyncEmptyReject' => function () {
         return \React\Promise\reject();
     }, 'asyncError' => function () {
         return new Promise(function () {
             throw new \Exception('Error getting asyncError');
         });
     }, 'asyncRawError' => function () {
         return new Promise(function () {
             throw new \Exception('Error getting asyncRawError');
         });
     }, 'asyncReturnError' => function () {
         return \React\Promise\resolve(new \Exception('Error getting asyncReturnError'));
     }];
     $docAst = Parser::parse($doc);
     $schema = new Schema(['query' => new ObjectType(['name' => 'Type', 'fields' => ['sync' => ['type' => Type::string()], 'syncError' => ['type' => Type::string()], 'syncRawError' => ['type' => Type::string()], 'syncReturnError' => ['type' => Type::string()], 'syncReturnErrorList' => ['type' => Type::listOf(Type::string())], 'async' => ['type' => Type::string()], 'asyncReject' => ['type' => Type::string()], 'asyncRawReject' => ['type' => Type::string()], 'asyncEmptyReject' => ['type' => Type::string()], 'asyncError' => ['type' => Type::string()], 'asyncRawError' => ['type' => Type::string()], 'asyncReturnError' => ['type' => Type::string()]]])]);
     $expected = ['data' => ['sync' => 'sync', 'syncError' => null, 'syncRawError' => null, 'syncReturnError' => null, 'syncReturnErrorList' => ['sync0', null, 'sync2', null], 'async' => 'async', 'asyncReject' => null, 'asyncRawReject' => null, 'asyncEmptyReject' => null, 'asyncError' => null, 'asyncRawError' => null, 'asyncReturnError' => null], 'errors' => [['message' => 'Error getting syncError', 'locations' => [['line' => 3, 'column' => 7]], 'path' => ['syncError']], ['message' => 'Error getting syncRawError', 'locations' => [['line' => 4, 'column' => 7]], 'path' => ['syncRawError']], ['message' => 'Error getting syncReturnError', 'locations' => [['line' => 5, 'column' => 7]], 'path' => ['syncReturnError']], ['message' => 'Error getting syncReturnErrorList1', 'locations' => [['line' => 6, 'column' => 7]], 'path' => ['syncReturnErrorList', 1]], ['message' => 'Error getting syncReturnErrorList3', 'locations' => [['line' => 6, 'column' => 7]], 'path' => ['syncReturnErrorList', 3]], ['message' => 'Error getting asyncReject', 'locations' => [['line' => 8, 'column' => 7]], 'path' => ['asyncReject']], ['message' => 'Error getting asyncRawReject', 'locations' => [['line' => 9, 'column' => 7]], 'path' => ['asyncRawReject']], ['message' => 'An unknown error occurred.', 'locations' => [['line' => 10, 'column' => 7]], 'path' => ['asyncEmptyReject']], ['message' => 'Error getting asyncError', 'locations' => [['line' => 11, 'column' => 7]], 'path' => ['asyncError']], ['message' => 'Error getting asyncRawError', 'locations' => [['line' => 12, 'column' => 7]], 'path' => ['asyncRawError']], ['message' => 'Error getting asyncReturnError', 'locations' => [['line' => 13, 'column' => 7]], 'path' => ['asyncReturnError']]]];
     Executor::setPromiseAdapter(new ReactPromiseAdapter());
     $result = Executor::execute($schema, $docAst, $data);
     $this->assertEquals($expected, self::awaitPromise($result));
 }
 /**
  * @param Rpc $message
  * @return PromiseInterface
  */
 protected function sendRpc(Rpc $message)
 {
     $messenger = $this->readyPool->dequeue();
     return $messenger->rpc($message)->then(function ($data) use($messenger) {
         $this->readyPool->enqueue($messenger);
         $this->checkQueue();
         return \React\Promise\resolve($data);
     }, function ($error) use($messenger) {
         $this->readyPool->enqueue($messenger);
         $this->checkQueue();
         return \React\Promise\reject($error);
     });
 }
Пример #27
0
 /**
  * @param string $class
  * @param LoopInterface $loop
  * @param array $options
  * @return PromiseInterface
  */
 public static function createFromClass($class, LoopInterface $loop, array $options = [])
 {
     return \React\Promise\resolve(new DummyPool(new Single(new ClassName($class)), $loop, $options));
 }
Пример #28
0
 /**
  * @return \React\Promise\Promise
  */
 public function perform()
 {
     $instance = $this->getInstance();
     $deferred = new \React\Promise\Deferred();
     $promise = $deferred->promise();
     $promise->then(function () {
         $this->worker->processing++;
     });
     if (method_exists($instance, 'setUp')) {
         $promise = $promise->then(function () use($instance) {
             return \React\Promise\resolve($instance->setUp());
         });
     }
     $promise = $promise->then(function () use($instance) {
         return $instance->perform();
     });
     if (method_exists($instance, 'tearDown')) {
         $promise = $promise->then(function ($response = null) use($instance) {
             return \React\Promise\resolve($instance->tearDown());
         });
     }
     $promise->then(function ($responses = null) {
         $this->worker->processing--;
         $this->worker->processed++;
     }, function ($e) {
         $this->worker->processing--;
         $this->worker->processed++;
         if ($e instanceof \Exception) {
             error_log(sprintf('%s:%s in %s at %d', get_class($e), $e->getMessage(), __FILE__, __LINE__));
         }
         error_log($e);
     });
     $deferred->resolve();
     return $promise;
 }
Пример #29
0
 /** @test */
 public function alwaysShouldNotSuppressValueWhenHandlerReturnsAPromise()
 {
     $adapter = $this->getPromiseTestAdapter();
     $value = new \stdClass();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo($value));
     $adapter->promise()->always(function () {
         return \React\Promise\resolve(1);
     })->then($mock);
     $adapter->resolve($value);
 }
Пример #30
0
 /**
  * @param string $class
  * @param LoopInterface $loop
  * @param array $options
  * @return PromiseInterface
  */
 public static function createFromClass($class, LoopInterface $loop, array $options = [])
 {
     $options = array_merge(self::$defaultOptions, $options);
     return \React\Promise\resolve(new FixedPool(new Single(new ClassName($class)), $loop, $options));
 }