public function terminate()
 {
     $promises = [];
     foreach ($this->workers as $worker) {
         $promises[] = $worker->terminate();
     }
     return \React\Promise\all($promises);
 }
 public function createMultipleAsync($n, $host = '127.0.0.1', $docroot = null, $router = null)
 {
     $promises = [];
     for ($i = 0; $i < $n; ++$i) {
         $promises[] = $this->createAsync($host, $docroot, $router);
     }
     return \React\Promise\all($promises);
 }
Example #3
0
 public function __construct()
 {
     parent::__construct(function () {
         $loop = LoopFactory::create();
         $context = new ZmqContext($loop);
         $socket = $context->getSocket(\ZMQ::SOCKET_REP);
         $socket->bind("tcp://127.0.0.1:5591");
         $workers = $context->getSocket(\ZMQ::SOCKET_PUSH);
         $workers->bind('tcp://127.0.0.1:5592');
         $sub = $context->getSocket(\ZMQ::SOCKET_SUB);
         $sub->connect('tcp://127.0.0.1:5594');
         $sub->subscribe('control');
         $sub->on('messages', function ($msg) use($loop) {
             if ($msg[1] == 'shutdown') {
                 $loop->stop();
             }
         });
         /**
          * @var \React\Promise\Deferred[]
          */
         $deferredSet = [];
         $results = [];
         $socket->on('message', function ($message) use($socket, $workers, &$results, &$deferredSet) {
             // Incoming work. Distribute.
             $payload = json_decode($message, true);
             $batch = [];
             $work = ["txid" => $payload['txid'], "tx" => $payload['tx'], "flags" => $payload['flags'], "vin" => null, "scriptPubKey" => null];
             // Send to workers, and create a Promise for each result.
             foreach ($payload['scripts'] as $vin => $scriptPubKey) {
                 $work['vin'] = $vin;
                 $work['scriptPubKey'] = $scriptPubKey;
                 $deferred = new \React\Promise\Deferred();
                 $deferredSet[$payload['txid'] . $vin] = $deferred;
                 $batch[] = $deferred->promise();
                 $workers->send(json_encode($work));
             }
             // Once all promises have resolved, return outcome to socket.
             \React\Promise\all($batch)->then(function ($results) use($socket) {
                 $final = true;
                 foreach ($results as $result) {
                     $final &= $result['result'];
                 }
                 $socket->send($final);
             });
         });
         $results = $context->getSocket(\ZMQ::SOCKET_PULL);
         $results->bind("tcp://127.0.0.1:5593");
         $results->on('message', function ($message) use(&$deferredSet) {
             $payload = json_decode($message, true);
             $deferredSet[$payload['txid'] . $payload['vin']]->resolve($payload);
         });
         $loop->run();
         exit(0);
     });
 }
Example #4
0
 /**
  * Handles session started
  *
  * @param \Thruway\ClientSession $session
  * @param \Thruway\Transport\TransportProviderInterface $transport
  */
 public function onSessionStart($session, $transport)
 {
     $promises = [];
     $promises[] = $session->register('add_state_handler', [$this, "addStateHandler"]);
     $promises[] = $session->register('remove_state_handler', [$this, "removeStateHandler"]);
     $pAll = \React\Promise\all($promises);
     $pAll->then(function () {
         $this->setReady(true);
     }, function () {
         $this->setReady(false);
     });
 }
 /**
  * Create a queue with fanout exchange.
  *
  * @param string $exchange
  * @param string $queue
  *
  * @return PromiseInterface
  */
 public function fanout($exchange, $queue)
 {
     if (!isset($this->queues[$queue])) {
         $this->queues[$queue] = $this->connect()->then(function (Channel $channel) use($exchange, $queue) {
             return \React\Promise\all([$channel, $channel->queueDeclare($queue), $channel->exchangeDeclare($exchange, 'fanout'), $channel->queueBind($queue, $exchange)]);
         }, function (Exception $exception) {
             $this->loop->stop();
             throw new AsyncMessagingException(sprintf('Could not create channel and exchange: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
         });
     }
     return $this->queues[$queue];
 }
Example #6
0
 /**
  * Bootstrap plugin
  */
 public function enable()
 {
     $callback = function ($method) {
         return function (Message $message) use($method) {
             \React\Promise\all([$message->getChannel(), $message->getUser()])->then(function ($data) use($message, $method) {
                 $this->lastMessageChannel = $data[0];
                 $this->lastMessageUser = $data[1];
                 call_user_func([$this, $method], $message, $data[0], $data[1]);
             });
         };
     };
     $this->bot->on('message', $callback('onMessage'));
     $this->bot->on('mention', $callback('onMention'));
 }
 /**
  * @param $list
  * @param $method
  * @param $args
  * @return \React\Promise\PromiseInterface
  */
 protected function iterateNode($list, $method, $args)
 {
     $promises = [];
     foreach ($list as $node) {
         if ($node instanceof Directory) {
             $promises[] = call_user_func_array([$node, $method . 'Recursive'], $args);
         } else {
             $promises[] = call_user_func_array([$node, $method], $args);
         }
     }
     return \React\Promise\all($promises)->then(function () use($method, $args) {
         return call_user_func_array([$this->node, $method], $args);
     });
 }
 /**
  * @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));
         });
     });
 }
 public function testNotAuthorized()
 {
     $this->_conn = new \Thruway\Connection(["realm" => 'authorizing_realm', "url" => 'ws://127.0.0.1:8090', "max_retries" => 0]);
     $this->_testResult = "";
     $this->_error = null;
     $this->_conn->on('open', function (\Thruway\ClientSession $session) {
         $promises = [];
         $promises[] = $session->register('something', function () {
         })->then(function () {
             $this->_error = "registration should have failed";
         }, function ($res) {
             $this->assertTrue($res instanceof \Thruway\Message\ErrorMessage);
             $this->assertEquals("wamp.error.not_authorized", $res->getErrorUri());
             $this->_testResult .= "ok";
         });
         $promises[] = $session->call('some_rpc', [])->then(function () {
             $this->_error = "call should have failed";
         }, function ($res) {
             $this->assertTrue($res instanceof \Thruway\Message\ErrorMessage);
             $this->assertEquals("wamp.error.not_authorized", $res->getErrorUri());
             $this->_testResult .= "ok";
         });
         $promises[] = $session->subscribe('some_topic', function () {
         })->then(function () {
             $this->_error = "subscribe should have failed";
         }, function ($res) {
             $this->assertInstanceOf('\\Thruway\\Message\\ErrorMessage', $res);
             $this->assertEquals("wamp.error.not_authorized", $res->getErrorUri());
             $this->_testResult .= "ok";
         });
         $promises[] = $session->publish('some_topic', ["Hello"], null, ["acknowledge" => true])->then(function () {
             $this->_error = "publish should have failed";
         }, function ($res) {
             $this->assertInstanceOf('\\Thruway\\Message\\ErrorMessage', $res);
             $this->assertEquals("wamp.error.not_authorized", $res->getErrorUri());
             $this->_testResult .= "ok";
         });
         React\Promise\all($promises)->then(function () {
             $this->_conn->close();
         }, function () {
             $this->_conn->close();
         });
     });
     $this->_conn->open();
     $this->assertNull($this->_error, "Error: " . $this->_error);
     $this->assertEquals("okokokok", $this->_testResult);
 }
 /**
  * @param QueueMessage $message
  *
  * @return void
  */
 protected function publishMessage(QueueMessage $message)
 {
     $this->channelFactory->fanout($this->exchange, $this->channel)->then(function ($r) use($message) {
         /** @var Channel $channel */
         $channel = $r[0];
         return \React\Promise\all([$channel->publish(json_encode($this->serializer->serialize($message)), [], $this->exchange)]);
     }, function (Exception $exception) {
         $this->loop->stop();
         throw new AsyncMessagingException(sprintf('Could not publish message: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
     })->then(function () {
         $this->loop->stop();
     }, function (Exception $exception) {
         $this->loop->stop();
         var_dump(sprintf('Could not publish message: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()));
     });
     $this->loop->run();
 }
Example #11
0
 * @var \React\Promise\Deferred[]
 */
$socket->on('message', function ($message) use($socket, $workers, &$results, &$deferredSet) {
    // Incoming work. Distribute.
    $payload = json_decode($message, true);
    $reqid = $payload['id'];
    $batch = [];
    $work = ["txid" => null, "tx" => null, "flags" => $payload['flags'], "vin" => null, "scriptPubKey" => null];
    // Send to workers, and create a Promise for each result.
    foreach ($payload['txs'] as $t) {
        $work['txid'] = $t['txid'];
        $work['tx'] = $t['tx'];
        foreach ($t['scripts'] as $vin => $scriptPubKey) {
            $work['vin'] = $vin;
            $work['scriptPubKey'] = $scriptPubKey;
            $deferred = new \React\Promise\Deferred();
            $deferredSet[$t['txid'] . $vin] = $deferred;
            $batch[] = $deferred->promise();
            $workers->send(json_encode($work));
        }
    }
    // Once all promises have resolved, return outcome to socket.
    \React\Promise\all($batch)->then(function ($results) use($socket, $reqid) {
        $final = true;
        foreach ($results as $result) {
            $final &= $result;
        }
        $socket->send(json_encode(['txid' => $reqid, 'result' => $final]));
    });
});
$loop->run();
Example #12
0
 public function pruneDeadWorkers()
 {
     $worker_pids = $this->workerPids();
     return Resque::redis()->smembers('workers')->then(function ($response) use($worker_pids) {
         $promises = \React\Promise\map($response, function ($workerId) use($worker_pids) {
             list($hostname, $pid, $queues) = explode(':', $workerId, 3);
             if ($hostname != $this->hostname || in_array($pid, $worker_pids) || $pid == getmypid()) {
                 return null;
             }
             $queues = explode(',', $queues);
             $worker = new self($queues, \Iwai\React\Resque::getEventLoop());
             $worker->setId($workerId);
             return $worker->unregisterWorker();
         });
         return \React\Promise\all($promises);
     });
 }
Example #13
0
File: Co.php Project: mpyw/co
 /**
  * Promise all changes in yieldables are prepared.
  * @param  array $yieldables
  * @param  bool  $throw_acceptable
  * @return PromiseInterface
  */
 private function promiseAll(array $yieldables, $throw_acceptable)
 {
     $promises = [];
     foreach ($yieldables as $yieldable) {
         // Add or enqueue cURL handles
         if (TypeUtils::isCurl($yieldable['value'])) {
             $promises[(string) $yieldable['value']] = $this->pool->addCurl($yieldable['value']);
             continue;
         }
         // Process generators
         if (TypeUtils::isGeneratorContainer($yieldable['value'])) {
             $promises[(string) $yieldable['value']] = $this->processGeneratorContainer($yieldable['value']);
             continue;
         }
     }
     // If caller cannot accept exception,
     // we handle rejected value as resolved.
     if (!$throw_acceptable) {
         $promises = array_map(['\\mpyw\\Co\\Internal\\YieldableUtils', 'safePromise'], $promises);
     }
     return \React\Promise\all($promises);
 }
Example #14
0
<?php

require 'vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$dir = \React\Filesystem\Filesystem::create($loop)->dir(dirname(__DIR__));
$dir->lsRecursive()->then(function (\SplObjectStorage $list) {
    $phpFiles = new RegexIterator($list, '/.*?.php$/');
    $promises = [];
    foreach ($phpFiles as $node) {
        if (strpos($node->getPath(), 'vendor') !== false) {
            continue;
        }
        $file = $node;
        $promises[] = $file->size()->then(function ($size) use($file) {
            echo $file->getPath(), ': ', number_format($size / 1024, 2), 'KB', PHP_EOL;
            return $size;
        });
    }
    \React\Promise\all($promises)->then(function ($sizes) {
        $total = 0;
        foreach ($sizes as $size) {
            $total += $size;
        }
        echo 'Total: ', number_format($total / 1024, 2), 'KB', PHP_EOL;
    });
});
$loop->run();
 public function broadcastMessageIgnoringPlayer(Table $table, Player $ignoredPlayer, ServerMessageInterface $message)
 {
     $promises = [];
     foreach ($table->getSeats() as $seat) {
         $player = $seat->getPlayer();
         if ($player === null || $player === $ignoredPlayer) {
             continue;
         }
         if (!$seat->isServerBot()) {
             $promises[] = $this->enqueueMessage($player, $message, 0);
         }
     }
     return \React\Promise\all($promises);
 }
 protected function processLsContents($result, ObjectStream $stream)
 {
     $promises = [];
     foreach ($result as $entry) {
         $node = ['path' => $entry['path'], 'type' => $entry['type']];
         $promises[] = \React\Filesystem\detectType($this->typeDetectors, $node)->then(function (NodeInterface $node) use($stream) {
             $stream->write($node);
             return new FulfilledPromise();
         });
     }
     \React\Promise\all($promises)->then(function () use($stream) {
         $stream->close();
     });
 }
Example #17
0
<?php

require '../bootstrap.php';
require __DIR__ . '/LastClient.php';
require_once 'RelayClient.php';
require __DIR__ . '/CallingClient.php';
$loop = \React\EventLoop\Factory::create();
$theClients = array();
$promises = array();
$url = "ws://demo.thruway.ws:9090/";
$url = "ws://127.0.0.1:9090/";
for ($i = 0; $i < 100; $i++) {
    $client = new RelayClient('theRealm', $loop, $i);
    $client->addTransportProvider(new \Thruway\Transport\PawlTransportProvider($url));
    $client->start(false);
    array_push($promises, $client->getRegisteredPromise());
    array_push($theClients, $client);
}
$lastClient = new LastClient('theRealm', $loop, $i);
$lastClient->addTransportProvider(new \Thruway\Transport\PawlTransportProvider($url));
$lastClient->start(false);
array_push($promises, $lastClient->getRegisteredPromise());
$allDeferred = new \React\Promise\Deferred();
$thePromise = \React\Promise\all($promises);
$callingClient = new CallingClient('theRealm', $loop, $thePromise);
$callingClient->addTransportProvider(new \Thruway\Transport\PawlTransportProvider($url));
$callingClient->start();
Example #18
0
 /**
  * @param DirectoryInterface $targetNode
  * @return ObjectStream
  */
 protected function copyToDirectory(DirectoryInterface $targetNode)
 {
     $promises = [];
     $objectStream = new ObjectStream();
     $stream = $this->lsStreaming();
     $stream->on('data', function (NodeInterface $node) use($targetNode, &$promises, $objectStream) {
         $deferred = new Deferred();
         $promises[] = $deferred->promise();
         $stream = $this->handleStreamingCopyNode($node, $targetNode);
         $stream->on('end', function () use($deferred) {
             $deferred->resolve();
         });
         $stream->pipe($objectStream, ['end' => false]);
     });
     $stream->on('end', function () use($objectStream, &$promises, $targetNode) {
         \React\Promise\all($promises)->then(function () use($objectStream, $targetNode) {
             $objectStream->end();
         });
     });
     return $objectStream;
 }
Example #19
0
<?php

require '../bootstrap.php';
require '../includes.php';
$mesh = getSDK(false, true);
$start = microtime(true);
$skus = array('193965', '121017', '185469', '178114', '185458', '193962', '193961', '185463', '185464', '190977', '192717', '006875', '193965', '121017', '185469', '178114', '185458', '193962', '193961', '185463', '185464', '190977', '192717', '006875');
$promises = array();
foreach ($skus as $sku) {
    $promises[] = $mesh->products->createProductAsync($sku);
}
$promise = React\Promise\all($promises)->done(function ($products) use($start) {
    $content = theme('all-names', array('products' => $products));
    $time = getTime($start);
    echo theme('all', array('time' => $time, 'names' => $content));
}, function ($error) use($start) {
    $time = getTime($start);
    echo theme('failture', array('time' => $time, 'error' => $error->getMessage()));
});
Example #20
0
 /**
  * Stops all processes for this command
  */
 public function stopProcess()
 {
     $promises = [];
     if (count($this->processes) < 1) {
         return \React\Promise\reject("No Process to stop");
     }
     foreach ($this->processes as $process) {
         $deffer = new Deferred();
         if ($process->isRunning()) {
             $process->terminate();
         }
         $process->on('exit', function () use($deffer) {
             $deffer->resolve();
         });
         $promises[] = $deffer->promise();
     }
     return \React\Promise\all($promises);
 }
Example #21
0
<?php

require 'vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$dns = (new React\Dns\Resolver\Factory())->create('8.8.8.8', $loop);
$promises = [];
foreach (['example.com', 'blog.wyrihaximus.net', 'wyrihaximus.net'] as $host) {
    $hostname = $host;
    $promises[] = $dns->resolve($hostname)->then(function ($ip) use($hostname) {
        echo 'The IP address for ' . $hostname . ' is: ' . $ip, PHP_EOL;
        return $hostname;
    });
}
\React\Promise\all($promises)->then(function ($hostnames) {
    echo 'Done: ' . implode(', ', $hostnames) . '!', PHP_EOL;
});
$loop->run();
 /**
  * Compares the karma between two terms. Optionally increases/decreases
  * the karma of either term.
  *
  * @param string $term0  First term
  * @param string $term1  Second term
  * @param string $method Comparison method (< or >)
  * @param \Phergie\Irc\Event\UserEvent $event
  * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
  */
 protected function compareKarma($term0, $term1, $method, UserEvent $event, Queue $queue)
 {
     $nick = $event->getNick();
     $canonicalTerm0 = $this->getCanonicalTerm($term0, $nick);
     $canonicalTerm1 = $this->getCanonicalTerm($term1, $nick);
     $fixedKarma0 = $this->fetchFixedKarma($term0);
     $fixedKarma1 = $this->fetchFixedKarma($term1);
     if ($fixedKarma0 || $fixedKarma1) {
         return;
     }
     if ($canonicalTerm0 == 'everything') {
         $change = $method == '<' ? '++' : '--';
         $karma0 = ['karma' => 0];
         $karma1 = $this->modifyKarma($term1, $change, $event, $queue);
     } elseif ($canonicalTerm1 == 'everything') {
         $change = $method == '<' ? '--' : '++';
         $karma0 = $this->modifyKarma($term0, $change, $event, $queue);
         $karma1 = ['karma' => 0];
     } else {
         $karma0 = $this->messenger->rpc(MessageFactory::rpc('fetchKarma', ['term' => $this->getCanonicalTerm($term0, $nick)]));
         $karma1 = $this->messenger->rpc(MessageFactory::rpc('fetchKarma', ['term' => $this->getCanonicalTerm($term1, $nick)]));
     }
     \React\Promise\all([$karma0, $karma1])->then(function ($payload) use($event, $queue, $method, $term0, $term1) {
         $this->logDebug('payload karma0: ' . var_export($payload[0], true));
         $this->logDebug('payload karma1: ' . var_export($payload[1], true));
         // Combining the first and second branches here causes an odd
         // single-line lapse in code coverage, but the lapse disappears if
         // they're separated
         if ($method == '<' && $payload[0]['karma'] < $payload[1]['karma']) {
             $replyType = 'compare-true';
         } elseif ($method == '>' && $payload[0]['karma'] > $payload[1]['karma']) {
             $replyType = 'compare-true';
         } else {
             $replyType = 'compare-false';
         }
         $message = max($payload[0]['karma'], $payload[1]['karma']) == $payload[0]['karma'] ? $this->getUserMessage($replyType, $term0, $term1) : $this->getUserMessage($replyType, $term1, $term0);
         $queue->ircPrivmsg($event->getSource(), $message);
     });
 }
 public function testMultiRegistration()
 {
     $this->_error = null;
     $this->_result = null;
     $this->_conn->on('open', function (\Thruway\ClientSession $session) {
         $session->register('partitioned_rpc', [$this, "thePartitionedRPC1"], ["thruway_multiregister" => true])->then(function ($ret) use($session) {
             // this should fail because we are registering an identical rpc from the same connection
             $session->register('partitioned_rpc', [$this, "thePartitionedRPC1"])->then(function () use($session) {
                 $this->_error = "Second registration from same connection should have failed";
                 $session->close();
             }, function () use($session) {
                 $this->_conn2->on('open', function (\Thruway\ClientSession $s2) use($session) {
                     // this should fail without thruway_multiregister
                     $s2->register('partitioned_rpc', [$this, "thePartitionedRPC2"])->then(function () use($s2, $session) {
                         $this->_error = "Second registration without multiregister option should have failed";
                         $s2->close();
                         $session->close();
                     }, function () use($s2, $session) {
                         // this should be the 2nd RPC
                         $s2->register('partitioned_rpc', [$this, "thePartitionedRPC2"], ["thruway_multiregister" => true])->then(function () use($s2, $session) {
                             // good - we have 2 registrations - lets make some calls
                             $this->_result = "";
                             $session->subscribe('thruway.metaevent.procedure.congestion', function ($args) {
                                 if (isset($args[0]) && isset($args[0]['name'])) {
                                     $procName = $args[0]['name'];
                                 } else {
                                     $procName = "";
                                 }
                                 $this->_result = $this->_result . "[congestion(" . $procName . ")]";
                             })->then(function () use($s2, $session) {
                                 $promises = [];
                                 $promises[] = $session->call('partitioned_rpc', [0])->then(function ($res) use($s2, $session) {
                                     $this->_result = $this->_result . $res;
                                 }, function ($err) use($s2, $session) {
                                     $this->_error = "Error calling RPC attempt 1";
                                     $s2->close();
                                     $session->close();
                                 });
                                 $promises[] = $session->call('partitioned_rpc', [1])->then(function ($res) use($s2, $session) {
                                     $this->_result = $this->_result . $res;
                                 }, function ($err) use($s2, $session) {
                                     $this->_error = "Error calling RPC(2)";
                                     $s2->close();
                                     $session->close();
                                 });
                                 $promises[] = $session->call('partitioned_rpc', [2])->then(function ($res) use($s2, $session) {
                                     $this->_result = $this->_result . $res;
                                 }, function ($err) use($s2, $session) {
                                     $this->_error = "Error calling RPC";
                                     $s2->close();
                                     $session->close();
                                 });
                                 $pAll = \React\Promise\all($promises);
                                 $pAll->then(function () use($s2, $session) {
                                     $s2->close();
                                     $session->close();
                                 }, function ($err) {
                                     $this->_error = "Could not subscribe to metaevent";
                                 });
                             });
                         }, function () use($s2, $session) {
                             $this->_error = "Second registration failed with multiregister";
                             $s2->close();
                             $session->close();
                         });
                     });
                 });
                 $this->_conn2->open();
             });
         }, function ($err) use($session) {
             $this->_error = "First registration failed";
             var_dump($err);
             $session->close();
         });
     });
     $this->_conn->open();
     $this->assertNull($this->_error, "Error occurred: " . $this->_error);
     $this->assertEquals("211", $this->_result);
 }
Example #24
0
 public function testWhiteList()
 {
     $conns = [];
     $sessionIds = [];
     $results = [];
     $loop = $this->_loop;
     $subscribePromises = [];
     for ($i = 0; $i < 5; $i++) {
         $results[$i] = "";
         $conns[$i] = $conn = new \Thruway\Connection($this->_connOptions, $loop);
         $conn->on('open', function (\Thruway\ClientSession $session) use($i, &$sessionIds, &$subscribePromises, &$results) {
             $sessionIds[$i] = $session->getSessionId();
             $subscribePromises[] = $session->subscribe('test.whitelist', function ($args) use($i, $session, &$results) {
                 $results[$i] .= "-" . $args[0] . "." . $i . "-";
                 if ($args[0] == "X") {
                     $session->close();
                 }
             });
         });
         $conn->open(false);
     }
     $this->_conn->on('open', function (\Thruway\ClientSession $session) use($subscribePromises, &$sessionIds) {
         \React\Promise\all($subscribePromises)->then(function () use($session, &$sessionIds) {
             $session->publish('test.whitelist', ["A"], null, ['acknowledge' => true])->then(function () use($session, &$sessionIds) {
                 $session->publish('test.whitelist', ["B"], null, ['acknowledge' => true, 'eligible' => $sessionIds])->then(function () use($session, &$sessionIds) {
                     $session->publish('test.whitelist', ["C"], null, ['acknowledge' => true, 'exclude' => [$sessionIds[1]], 'eligible' => $sessionIds])->then(function () use($session, &$sessionIds) {
                         $session->publish('test.whitelist', ["D"], null, ['acknowledge' => true, 'exclude' => [$sessionIds[1]], 'eligible' => [$sessionIds[2]]])->then(function () use($session, &$sessionIds) {
                             $session->publish('test.whitelist', ["E"], null, ['acknowledge' => true, 'exclude' => [$sessionIds[1]], 'eligible' => []])->then(function () use($session, &$sessionIds) {
                                 $session->publish('test.whitelist', ["F"], null, ['acknowledge' => true, 'exclude' => [], 'eligible' => [$sessionIds[0]]])->then(function () use($session, &$sessionIds) {
                                     // shutdown the sessions
                                     $session->publish('test.whitelist', ["X"], null, ['acknowledge' => true])->then(function () use($session) {
                                         $session->close();
                                     });
                                 });
                             });
                         });
                     });
                 });
             });
         });
     });
     $this->_conn->open();
     $this->assertEquals("-A.0--B.0--C.0--F.0--X.0-", $results[0]);
     $this->assertEquals("-A.1--B.1--X.1-", $results[1]);
     $this->assertEquals("-A.2--B.2--C.2--D.2--X.2-", $results[2]);
     $this->assertEquals("-A.3--B.3--C.3--X.3-", $results[3]);
     $this->assertEquals("-A.4--B.4--C.4--X.4-", $results[4]);
 }
Example #25
0
 /**
  * @param $basePath
  * @param $result
  * @param ObjectStream $stream
  */
 protected function processLsContents($basePath, $result, ObjectStream $stream)
 {
     if (!isset($result['dents'])) {
         $stream->close();
         return;
     }
     $promises = [];
     foreach ($result['dents'] as $entry) {
         $path = $basePath . DIRECTORY_SEPARATOR . $entry['name'];
         $node = ['path' => $path, 'type' => $entry['type']];
         $promises[] = $this->processLsDent($node, $stream);
     }
     \React\Promise\all($promises)->then(function () use($stream) {
         $stream->close();
     });
 }
Example #26
0
 /**
  * Create $n connections to clients available in the PeerLocator
  * @param int $n
  *
  * @param Locator $locator
  * @param $n
  * @return null|\React\Promise\FulfilledPromise|\React\Promise\Promise|\React\Promise\PromiseInterface|\React\Promise\RejectedPromise|static
  */
 public function connectToPeers(Locator $locator, $n)
 {
     $peers = [];
     for ($i = 0; $i < $n; $i++) {
         $peers[$i] = $this->connectNextPeer($locator);
     }
     return \React\Promise\all($peers);
 }
 /**
  * Given an array of promises, return a promise that is fulfilled when all the
  * items in the array are fulfilled.
  *
  * @param mixed $promisesOrValues Promises or values.
  *
  * @return mixed a Promise
  */
 public function createPromiseAll($promisesOrValues)
 {
     return \React\Promise\all($promisesOrValues);
 }
Example #28
0
 /**
  * @param \Thruway\ClientSession $session
  * @param \Thruway\Transport\TransportInterface $transport
  */
 public function onSessionStart($session, $transport)
 {
     $promises = [];
     $promises[] = $this->getCallee()->register($session, 'add_authorization_rule', [$this, "addAuthorizationRule"]);
     $promises[] = $this->getCallee()->register($session, 'remove_authorization_rule', [$this, "removeAuthorizationRule"]);
     $promises[] = $this->getCallee()->register($session, 'flush_authorization_rules', [$this, 'flushAuthorizationRules']);
     $promises[] = $this->getCallee()->register($session, 'get_authorization_rules', [$this, 'getAuthorizationRules']);
     $promises[] = $this->getCallee()->register($session, 'test_authorization', [$this, 'testAuthorization']);
     $pAll = \React\Promise\all($promises);
     $pAll->then(function () {
         $this->setReady(true);
     }, function () {
         $this->setReady(false);
     });
 }
Example #29
0
 /**
  * Request player bets in parallel.
  * Players which do not respond in time are not allowed to play this hand.
  *
  * @return Promise
  */
 private function requestBets()
 {
     $promises = [];
     foreach ($this->table->getSeats() as $seat) {
         if ($seat->isFree()) {
             continue;
         }
         $player = $seat->getPlayer();
         if ($player->getChips()->getAmount() < $this->table->getMinimumBet()) {
             $this->connectionManager->kickPlayer($player, KickedMessage::REASON_INSUFFICIENT_FUNDS);
             continue;
         }
         $promises[] = $this->table->requestPlayerBet($player)->then(function ($amount) use($seat) {
             $this->table->acceptPlayerBet($seat->getPlayer(), $seat->getHands()[0], $amount);
             $seat->setInPlay(true);
             $this->logger->info('Player bet', ['player' => $seat->getPlayer()->getName(), 'amount' => $amount, 'stack' => $seat->getPlayer()->getChips()->getAmount()]);
             return null;
         })->otherwise(function (\Exception $reason) use($seat) {
             $seat->setInPlay(false);
             $this->logger->info('Player unable to bet', ['player' => $seat->getPlayer()->getName(), 'stack' => $seat->getPlayer()->getChips()->getAmount(), 'reason' => $reason->getMessage()]);
             return null;
         });
     }
     return \React\Promise\all($promises)->then(function () {
         return \Blackjack\Promise\timedResolve(self::PAUSE_SPEED);
     });
 }