Exemple #1
0
 /**
  * Builds internal request handling objects.
  *
  * @return $this
  */
 public function build()
 {
     if ($this->cache) {
         $loader = new ClassLoader();
         if ($this->apc) {
             $apcLoader = new ApcClassLoader(sha1('ReactServer'), $loader);
             $loader->unregister();
             $apcLoader->register(true);
         }
     }
     require_once $this->root_dir . '/AppKernel.php';
     define('KERNEL_ROOT', $this->root_dir);
     $kernel = new ReactKernel($this->env, $this->env === 'dev' ? true : false);
     $this->loop = Factory::create();
     // TODO make config for this part
     if (class_exists('\\Doctrine\\DBAL\\Driver\\PingableConnection')) {
         $this->loop->addPeriodicTimer(15, function () use($kernel) {
             foreach ($kernel->getContainer()->get('doctrine')->getConnections() as $connection) {
                 if ($connection instanceof \Doctrine\DBAL\Driver\PingableConnection) {
                     $connection->ping();
                 }
             }
         });
     }
     $this->socket = new SocketServer($this->loop);
     $http = new HttpServer($this->socket, $this->loop);
     $http->on('request', $this->handleRequest($kernel));
     return $this;
 }
 public function __construct(AMQPQueue $queue, LoopInterface $loop, Serializer $serializer)
 {
     $this->queue = $queue;
     $this->loop = $loop;
     $this->timer = $this->loop->addPeriodicTimer(1, [$this, 'listen']);
     $this->serializer = $serializer;
 }
Exemple #3
0
 /**
  * Adds timer to Loop queue
  *
  * @param float $interval
  * @return TimerInterface
  */
 public function start($interval = self::DEFAULT_INTERVAL)
 {
     if ($this->timer) {
         $this->stop();
     }
     return $this->timer = $this->loop->addPeriodicTimer($interval, $this);
 }
 /**
  * @param TopicInterface $topic
  * @param string         $name
  * @param int|float      $timeout
  * @param mixed          $callback
  */
 public function addPeriodicTimer(TopicInterface $topic, $name, $timeout, $callback)
 {
     $namespace = spl_object_hash($topic);
     if (!isset($this->registry[$namespace])) {
         $this->registry[$namespace] = [];
     }
     $this->registry[$namespace][$name] = $this->loop->addPeriodicTimer($timeout, $callback);
 }
Exemple #5
0
 /**
  * ShortUUID constructor.
  *
  * @param LoopInterface $loop
  * @param int           $generator_id
  */
 public function __construct(LoopInterface $loop, $generator_id = 1)
 {
     $this->loop = $loop;
     $this->generator_id = (int) $generator_id;
     $this->resetCounter();
     // reset the counter every 1 milliseconds
     $this->loop->addPeriodicTimer(0.001, array($this, 'resetCounter'));
 }
 /**
  * Constructor. Stores the message queue and the event loop for use.
  *
  * @param AMQPQueue                     $queue    Message queue
  * @param React\EventLoop\LoopInterface $loop     Event loop
  * @param float                         $interval Interval to check for new messages
  * @param int                           $max      Max number of messages to consume in one go
  */
 public function __construct(AMQPQueue $queue, LoopInterface $loop, $interval, $max = null)
 {
     $this->queue = $queue;
     $this->loop = $loop;
     $this->max = $max;
     $this->timer = $this->loop->addPeriodicTimer($interval, $this);
     $this->on('close_amqp_consumer', [$this, 'close']);
 }
 /**
  * Start the keep alive timer when the first client subscribes
  *
  * @param CakeEvent $event
  */
 public function onSubscribeNewTopic(CakeEvent $event)
 {
     if (Configure::read('Ratchet.Connection.keepaliveInterval') > 0) {
         $this->__timer = $this->__loop->addPeriodicTimer(Configure::read('Ratchet.Connection.keepaliveInterval'), function () use($event) {
             $event->subject()->broadcast('Rachet.connection.keepAlive', ['ping']);
         });
         $event->subject()->broadcast('Rachet.connection.keepAlive', ['ping']);
     }
 }
Exemple #8
0
 public function init(LoopInterface $loop = null)
 {
     $this->loop = is_null($loop) ? \React\EventLoop\Factory::create() : $loop;
     $this->loop->addPeriodicTimer(0.1, array($this, 'checkSchedule'));
     $this->bindSignals();
     $this->loop->addPeriodicTimer(1, function () {
         pcntl_signal_dispatch();
     });
 }
Exemple #9
0
 public function __construct(LoopInterface $loop, FrameBuffer $frameBuffer, ContainerInterface $container)
 {
     $this->loop = $loop;
     $this->frameBuffer = $frameBuffer;
     $this->container = $container;
     $this->connections = new \SplObjectStorage();
     $fps = (double) $container->get('server.fps');
     $this->update_timer = $this->loop->addPeriodicTimer(1.0 / $fps, [$this, 'onFrameUpdate']);
     $this->switchToGameLoop($container->get(TestImageScreen::class));
 }
Exemple #10
0
 protected function addLookupTimer()
 {
     $this->loop->addPeriodicTimer(30, function () {
         $addresses = $this->lookup->lookup();
         foreach ($addresses as $address) {
             $key = $address['ip'] . ':' . $address['port'];
         }
         // ... refresh connection
     });
 }
Exemple #11
0
 public function start()
 {
     $this->bindSignals();
     //master process shutdown request handler
     $this->loop->addPeriodicTimer(1, function () {
         pcntl_signal_dispatch();
     });
     foreach ($this->daemons as $daemon) {
         $this->daemons[$daemon] = $this->newInstance($daemon);
     }
 }
Exemple #12
0
 public function handle($id)
 {
     $this->id = $id;
     printf("Will connect on %s\n", $this->ip);
     $this->dealer->connect($this->ip, sprintf('dealer-%s', $this->id));
     $this->dealer->filter(function (Event $event) {
         return $event->is("/response/foo");
     })->subscribeCallback([$this, 'onFooResponse']);
     $this->dealer->filter(function (Event $event) {
         return $event->is("/response/bar");
     })->subscribeCallback([$this, 'onBarResponse']);
     echo "Will ask router every 5 seconds\n";
     $this->loop->addPeriodicTimer(5, [$this, 'askRouter']);
 }
Exemple #13
0
 /**
  * @param int    $port
  * @param string $host
  */
 public function listen($port, $host)
 {
     $this->http->on('request', function (ReactRequest $request, ReactResponse $response) {
         return $this->onRequest($request, $response);
     });
     $this->logger->info("Phiremock http server listening on {$host}:{$port}");
     $this->socket->listen($port, $host);
     // Dispatch pending signals periodically
     if (function_exists('pcntl_signal_dispatch')) {
         $this->loop->addPeriodicTimer(0.5, function () {
             pcntl_signal_dispatch();
         });
     }
     $this->loop->run();
 }
 /**
  * Start server
  *
  * @throws RuntimeException
  */
 public function run()
 {
     try {
         $this->loop->addPeriodicTimer($this->timePeriod, $this->getPeriodicTimerCallback());
         //listening of the ports
         foreach ($this->listen as $port) {
             $socket = new Server($this->loop);
             //initialize socket
             $socket->on('connection', function (Connection $conn) {
                 $this->conns->attach($conn);
                 $conn->on('data', function ($data, $conn) {
                     //$request insteadof React\Http\Request
                     list($request, $body) = (new RequestHeaderParser())->parseRequest($data);
                     $this->conns->attach($conn, new LongPooling\ConnectionInfo($request, $body));
                 });
                 $conn->on('end', function ($conn) {
                     $this->conns->detach($conn);
                 });
             });
             $socket->listen($port);
         }
         $this->loop->run();
     } catch (Exception $e) {
         throw new RuntimeException("Server Run Exception", 301, $e);
     }
 }
 /**
  * @param bool $profile
  *
  * @throws \React\Socket\ConnectionException
  */
 public function launch($host, $port, $profile)
 {
     $this->logger->info('Starting web socket');
     $stack = new Builder();
     $server = new Server($this->loop);
     $server->listen($port, $host);
     if (true === $profile) {
         $memoryUsagePeriodicTimer = new PeriodicMemoryUsage($this->logger);
         $this->periodicRegistry->addPeriodic($memoryUsagePeriodicTimer);
     }
     /** @var PeriodicInterface $periodic */
     foreach ($this->periodicRegistry->getPeriodics() as $periodic) {
         $this->loop->addPeriodicTimer($periodic->getTimeout(), [$periodic, 'tick']);
         $this->logger->info(sprintf('Register periodic callback %s, executed each %s seconds', $periodic instanceof ProxyInterface ? get_parent_class($periodic) : get_class($periodic), $periodic->getTimeout()));
     }
     $allowedOrigins = array_merge(array('localhost', '127.0.0.1'), $this->originRegistry->getOrigins());
     $stack->push('Ratchet\\Server\\IoServer', $server, $this->loop)->push('Ratchet\\Http\\HttpServer');
     if ($this->originCheck) {
         $stack->push('Gos\\Bundle\\WebSocketBundle\\Server\\App\\Stack\\OriginCheck', $allowedOrigins, $this->eventDispatcher);
     }
     $stack->push('Ratchet\\WebSocket\\WsServer')->push('Gos\\Bundle\\WebSocketBundle\\Server\\App\\Stack\\WampConnectionPeriodicTimer', $this->loop)->push('Ratchet\\Session\\SessionProvider', $this->sessionHandler)->push('Ratchet\\Wamp\\WampServer');
     $app = $stack->resolve($this->wampApplication);
     /* Server Event Loop to add other services in the same loop. */
     $event = new ServerEvent($this->loop, $server);
     $this->eventDispatcher->dispatch(Events::SERVER_LAUNCHED, $event);
     $this->logger->info(sprintf('Launching %s on %s PID: %s', $this->getName(), $host . ':' . $port, getmypid()));
     $app->run();
 }
 /**
  * Create a new file driven handler instance.
  *
  * @param \Illuminate\Filesystem\Filesystem $files
  * @param React\EventLoop\LoopInterface $loop
  * @param string $path
  * 
  * @return void
  */
 public function __construct(Factory $factory, LoopInterface $loop, Server $server, $lifetime)
 {
     $this->factory = $factory;
     $this->lifetime = $lifetime;
     $this->server = $server;
     $this->loop = $loop;
     // PING redis connection every 5 minutes
     // and try to reconnect on connection error
     $this->timer = $loop->addPeriodicTimer(60 * 1, function () use($server) {
         $this->promise->then(function ($client) use($server) {
             $client->PING()->then(function ($pong) use($server) {
                 $server->log('Redis server responded ping with: %s', [$pong]);
                 return $pong == 'PONG';
             }, function ($e) {
                 return $this->reconnectByError($e);
             });
         });
     });
     // server statistics for redis connection
     $this->loop->addPeriodicTimer(60 * 30, function () {
         $this->server->log('Server statistics to the last 30 minutes.');
         $this->server->log('Best time of %fs, poor time of %fs and a average of %f seconds for total %d requests.', array_values($this->statistics));
         $this->statistics = array('best' => 0, 'poor' => 0, 'avg' => 0, 'total' => 0);
     });
 }
Exemple #17
0
 /**
  * Starts downloader in daemon mode, awaiting for future tasks
  * @todo Locks and signal processing
  *
  * @param EventLoop\LoopInterface $loop A loop, worker is run on
  */
 public function runDaemon(EventLoop\LoopInterface $loop)
 {
     $loop->addPeriodicTimer($this->tick, function ($timer) use($loop) {
         $this->run($loop, $this->limit);
     });
     $loop->run();
 }
 /**
  * @param string $captchaId
  * @return Promise\Promise
  */
 public function wait($captchaId)
 {
     $deferred = new Promise\Deferred();
     $this->loop->addPeriodicTimer($this->requestInterval, function ($timer) use($deferred, $captchaId) {
         $request = $this->client->request($this->getResultMethod(), $this->getResultPath(), ['Content-Length' => strlen($this->getResultQuery($captchaId)), 'Content-Type' => 'application/x-www-form-urlencoded']);
         $request->on('response', function ($response) use($request, $deferred, $timer) {
             /** @var \React\HttpClient\Response $response */
             $response->on('data', function ($data, $response) use($request, $deferred, $timer) {
                 /** @var \GuzzleHttp\Psr7\Stream $data */
                 /** @var \React\HttpClient\Response $response */
                 $response->handleEnd();
                 $answer = $data->getContents();
                 // stream read
                 if (!$answer) {
                     $this->loop->cancelTimer($timer);
                     $deferred->reject(new ServiceException('ERROR_CONNECTION'));
                 } elseif (substr($answer, 0, 2) === 'OK') {
                     $this->loop->cancelTimer($timer);
                     $deferred->resolve(substr($answer, 3));
                 } elseif ($answer !== 'CAPCHA_NOT_READY') {
                     $this->loop->cancelTimer($timer);
                     $deferred->reject(new ServiceException($answer));
                 }
             });
         });
         $request->end($this->getResultQuery($captchaId));
     });
     return $deferred->promise();
 }
 /**
  * {@inheritdoc}
  */
 public function run($tasks, $servers, $environments, $input, $output)
 {
     $this->tasks = $tasks;
     $this->servers = $servers;
     $this->input = $input;
     $this->output = new OutputWatcher($output);
     $this->informer = new Informer($this->output);
     $this->port = self::START_PORT;
     connect:
     $this->pure = new Server($this->port);
     $this->loop = $this->pure->getLoop();
     // Start workers for each server.
     $this->loop->addTimer(0, [$this, 'startWorkers']);
     // Wait for output
     $this->outputStorage = $this->pure['output'] = new QueueStorage();
     $this->loop->addPeriodicTimer(0, [$this, 'catchOutput']);
     // Lookup for exception
     $this->exceptionStorage = $this->pure['exception'] = new QueueStorage();
     $this->loop->addPeriodicTimer(0, [$this, 'catchExceptions']);
     // Send workers tasks to do.
     $this->loop->addPeriodicTimer(0, [$this, 'sendTasks']);
     // Wait all workers finish they tasks.
     $this->loop->addPeriodicTimer(0, [$this, 'idle']);
     // Start loop
     try {
         $this->pure->run();
     } catch (ConnectionException $exception) {
         // If port is already used, try with another one.
         $output->writeln("<error>" . $exception->getMessage() . "</error>");
         if (++$this->port <= self::STOP_PORT) {
             goto connect;
         }
     }
 }
Exemple #20
0
 /**
  * Add event listener to event loop.
  *
  * @param $fd
  * @param $flag
  * @param $func
  * @param array $args
  * @return bool
  */
 public function add($fd, $flag, $func, $args = array())
 {
     switch ($flag) {
         case EventInterface::EV_READ:
             return $this->_loop->addReadStream($fd, $func);
         case EventInterface::EV_WRITE:
             return $this->_loop->addWriteStream($fd, $func);
         case EventInterface::EV_SIGNAL:
             return $this->_loop->addSignal($fd, $func);
         case EventInterface::EV_TIMER:
             return $this->_loop->addPeriodicTimer($fd, $func);
         case EventInterface::EV_TIMER_ONCE:
             return $this->_loop->addTimer($fd, $func);
     }
     return false;
 }
Exemple #21
0
 /**
  * Start manager loop
  */
 private function startLoop()
 {
     $this->client = $this->stompFactory->createClient();
     $this->client->connect()->then(function (Client $client) {
         $this->loop->addPeriodicTimer(self::PROVISION_TIME, function () {
             $this->provision();
         });
         $client->subscribe($this->channel, function (Frame $frame) use($client) {
             try {
                 $request = $this->messageTransformer->decodeRequest($frame->body);
                 $closure = $request->getClosure();
                 if (!is_callable($closure)) {
                     throw new ManagerException('Запрос не содерджит callable');
                 }
                 $result = $closure($this);
                 $response = new Response($result);
             } catch (\Exception $e) {
                 $this->logger->error('Exception при обработке запроса ' . $e->getMessage());
                 $response = new Response($e->getMessage(), Response::STATUS_ERROR);
             }
             if ($replayTo = $frame->getHeader('reply-to')) {
                 $body = $this->messageTransformer->encodeResponse($response);
                 $client->send($replayTo, $body);
             }
         });
     }, function (\Exception $e) {
         $this->logger->critical($e->getMessage());
     });
     $this->loop->run();
 }
Exemple #22
0
 /**
  * Runs the application
  *
  * @return void
  */
 public function run()
 {
     if (!self::$defaultApplication) {
         self::$defaultApplication = $this;
     }
     $application = $this;
     if (OsDetector::isMacOS()) {
         $processName = './phpgui-i386-darwin';
         $processPath = __DIR__ . '/../lazarus/phpgui-i386-darwin.app/Contents/MacOS/';
     } elseif (OsDetector::isFreeBSD()) {
         $processName = './phpgui-x86_64-freebsd';
         $processPath = __DIR__ . '/../lazarus/';
     } elseif (OsDetector::isUnix()) {
         $processName = './phpgui-x86_64-linux';
         $processPath = __DIR__ . '/../lazarus/';
     } elseif (OsDetector::isWindows()) {
         $processName = '.\\phpgui-x86_64-win64';
         $processPath = __DIR__ . '\\..\\lazarus\\';
     } else {
         throw new RuntimeException('Operational System not identified by PHP-GUI.');
     }
     $this->process = $process = new Process($processName, $processPath);
     $this->process->on('exit', function () use($application) {
         $application->loop->stop();
     });
     $this->receiver = $receiver = new Receiver($this);
     $this->sender = $sender = new Sender($this, $receiver);
     $this->loop->addTimer(0.001, function ($timer) use($process, $application, $receiver) {
         $process->start($timer->getLoop());
         // We need to pause all default streams
         // The react/loop uses fread to read data from streams
         // On Windows, fread always is blocking
         // Stdin is paused, we use our own way to write on it
         $process->stdin->pause();
         // Stdout is paused, we use our own way to read it
         $process->stdout->pause();
         // Stderr is paused for avoiding fread
         $process->stderr->pause();
         $process->stdout->on('data', function ($data) use($receiver) {
             $receiver->onData($data);
         });
         $process->stderr->on('data', function ($data) {
             if (!empty($data)) {
                 Output::err($data);
             }
         });
         $application->running = true;
         // Bootstrap the application
         $application->fire('start');
     });
     $this->loop->addPeriodicTimer(0.001, function () use($application) {
         $application->sender->tick();
         if (@is_resource($application->process->stdout->stream)) {
             $application->receiver->tick();
         }
     });
     $this->loop->run();
 }
Exemple #23
0
 /**
  * Create a new event pusher handler
  */
 public function __construct(LoopInterface $loop, OutputInterface $output = null)
 {
     $this->loop = $loop;
     $this->output = $output;
     $this->clients = new \SplObjectStorage();
     $this->subscriber = \Service::getContainer()->get('kernel.subscriber.bzion_subscriber');
     // Ping timer
     $loop->addPeriodicTimer(self::KEEP_ALIVE, array($this, 'ping'));
 }
 /**
  * Enqueue a callback to be invoked repeatedly after the given interval.
  *
  * The execution order of timers scheduled to execute at the same time is
  * not guaranteed.
  *
  * @param numeric $interval The number of seconds to wait before execution.
  * @param callable $callback The callback to invoke.
  *
  * @return TimerInterface
  */
 public function addPeriodicTimer($interval, callable $callback)
 {
     $loopTimer = new TimerDecorator($this, $this->loop->addPeriodicTimer($interval, function () use(&$loopTimer, $callback, $interval) {
         $this->emit('periodicTimerTick', [$interval, $callback, $loopTimer]);
         $callback($loopTimer);
     }));
     $this->emit('addPeriodicTimer', [$interval, $callback, $loopTimer]);
     return $loopTimer;
 }
Exemple #25
0
 /**
  * @param string
  * @return \React\Promise\PromiseInterface
  */
 function query($query)
 {
     return $this->pool->getConnection()->then(function (mysqli $conn) use($query) {
         $status = $conn->query($query, MYSQLI_ASYNC);
         if ($status === false) {
             $this->pool->free($conn);
             throw new Exception($conn->error);
         }
         $id = spl_object_hash($conn);
         $this->conn[$id] = $conn;
         $this->query[$id] = $query;
         $this->deferred[$id] = $deferred = new Deferred();
         if (!isset($this->timer)) {
             $this->timer = $this->loop->addPeriodicTimer(0.01, function () {
                 $links = $errors = $reject = $this->conn;
                 mysqli_poll($links, $errors, $reject, 0);
                 // don't wait, just check
                 $each = array('links' => $links, 'errors' => $errors, 'reject' => $reject);
                 foreach ($each as $type => $connects) {
                     /**
                      * @var $conn mysqli
                      */
                     foreach ($connects as $conn) {
                         $id = spl_object_hash($conn);
                         if (isset($this->conn[$id])) {
                             $deferred = $this->deferred[$id];
                             if ($type == 'links') {
                                 /**
                                  * @var $result mysqli_result
                                  */
                                 $result = $conn->reap_async_query();
                                 if ($result === false) {
                                     $deferred->reject(new Exception($conn->error . '; sql: ' . $this->query[$id]));
                                 } else {
                                     $deferred->resolve(new Result($result, $conn->insert_id, $conn->affected_rows));
                                 }
                             }
                             if ($type == 'errors') {
                                 $deferred->reject(new Exception($conn->error . '; sql: ' . $this->query[$id]));
                             }
                             if ($type == 'reject') {
                                 $deferred->reject(new Exception('Query was rejected; sql: ' . $this->query[$id]));
                             }
                             unset($this->deferred[$id], $this->conn[$id], $this->query[$id]);
                             $this->pool->free($conn);
                         }
                     }
                 }
                 if (empty($this->conn)) {
                     $this->timer->cancel();
                     $this->timer = null;
                 }
             });
         }
         return $deferred->promise();
     });
 }
Exemple #26
0
 /**
  * Prepare periodic commands
  */
 protected function preparePeriodicCommands()
 {
     $commands = $this->invoker->getPeriodicCommands();
     foreach ($commands as $command) {
         $this->loop->addPeriodicTimer($command->getInterval(), function () use($command) {
             $cmdResult = $command->execute();
             $this->sendMessageByDestName($cmdResult->getText(), $cmdResult->getDestination());
         });
     }
 }
Exemple #27
0
 /**
  * @param int $timeout
  * @return $this
  */
 public function timeoutWithoutVersion($timeout = 20)
 {
     $this->once('data', function () use($timeout) {
         $this->loop->addPeriodicTimer($timeout, function (Timer $timer) {
             if (false === $this->exchangedVersion) {
                 $this->intentionalClose();
             }
             $timer->cancel();
         });
     });
     return $this;
 }
 public function __construct(LoopInterface $loop, $queueKey, array $options = array())
 {
     $this->loop = $loop;
     $this->queueKey = $queueKey;
     $this->parseOptions($options);
     $this->initQueue();
     // add our queue polling loop
     $self = $this;
     $this->loop->addPeriodicTimer($this->loopInterval, function () use($self) {
         $self->checkMessages();
     });
 }
Exemple #29
0
 public function handle()
 {
     printf("Will connect on %s\n", $this->sock);
     $this->pusher->connect($this->sock);
     echo "Will push keepalive every 5 seconds\n";
     $this->loop->addPeriodicTimer(5, [$this, 'keepAlive']);
     $this->httpd->route('POST', '/{type}', function (HttpdRequest $request, HttpdResponse $response) {
         try {
             $data = $request->getJson();
         } catch (\Exception $e) {
             $response->sendError($e->getMessage());
             return;
         }
         $type = $request->getRouteParam('type');
         $name = sprintf("/request/%s", $type);
         printf("Sending %s with data : %s\n", $name, json_encode($data));
         $this->pusher->send(new \Rxnet\Event\Event($name, $data));
         $response->text("It worked\n");
     });
     printf("You can send to puller from curl -XPOST http://127.0.0.1:23002/whatever -d'{'json':'encoded'}'\n");
     $this->httpd->listen(23002);
 }
Exemple #30
0
 /**
  * Starts the processor server.
  *
  * @param OutputInterface $output
  * @param bool $verbose
  * @throws \React\Socket\ConnectionException
  */
 public function start(OutputInterface &$output, $verbose = false)
 {
     $this->output = $output;
     $this->verbose = $verbose;
     $this->loop = Factory::create();
     $this->socket = new Server($this->loop);
     $http = new \React\Http\Server($this->socket);
     $http->on('request', [$this, 'manageRequest']);
     $this->socket->listen($this->port, $this->host);
     $this->registerListeners();
     $this->loop->addPeriodicTimer($this->interval, [$this, 'manageQueue']);
     $this->loop->run();
 }