public function promiseAction(Request $request)
 {
     $secs = intval($request->attributes->get("secs"));
     $deferred = new Deferred();
     $this->loop->addTimer($secs, function () use($secs, $deferred) {
         $deferred->resolve(Response::create("{$secs} seconds later...\n"));
     });
     return $deferred->promise();
 }
Esempio n. 2
0
 /**
  * {@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;
         }
     }
 }
Esempio n. 3
0
 public function __construct(LoopInterface $loop, EventEmitter $emit, \SplObjectStorage $clients, RoundProcessor $roundProcessor, EngineHelper $helper, $time = 60, $debug = false)
 {
     $this->debug = $debug;
     $this->helper = $helper;
     $this->emit = $emit;
     $this->loop = $loop;
     $this->roundTimer = new RoundTimer($loop, $emit);
     $this->roundNumber = 0;
     $this->clients = $clients;
     $this->disconnected = new \SplObjectStorage();
     $this->time = $time;
     $that = $this;
     $this->say = new Say($this->clients);
     $this->roundProcessor = $roundProcessor;
     $players = new Say($this->clients);
     // Setup listeners on the roundTimer object.
     $emit->on('GAME.COUNTDOWN', function () use($that) {
         if ($this->playerCount !== $this->clients->count()) {
             $this->playerCount = $this->clients->count();
             $this->say->to($this->clients)->that(Say::TICK, ["players" => $this->playerCount]);
         }
     });
     // Setup listeners on the roundTimer object.
     $emit->on('GAME.COUNTDOWN_END', function () use($that, $loop, $emit) {
         $this->say->to($this->clients)->that(Say::GAME_STARTING, ["players" => $this->clients->count()]);
         $this->setGameStarted(true);
         $loop->addTimer(3, function () use($loop, $emit) {
             $this->startRound($loop, $emit);
         });
     });
     $this->roundTimer->startCountDown($this->time);
 }
Esempio n. 4
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;
 }
 /**
  * @param Player                 $player
  * @param ServerMessageInterface $message
  * @param int                    $timeout
  *
  * @return Promise
  */
 public function enqueueMessage(Player $player, ServerMessageInterface $message, $timeout = 0)
 {
     $deferred = new Deferred();
     $sendMessage = function () use($player, $message, $deferred) {
         $connection = $this->getPlayerConnection($player);
         if (!$connection) {
             $deferred->reject(new \RuntimeException('Connection for player ' . $player->getName() . ' does not exist'));
             return;
         }
         try {
             $serializedMessage = $this->serializer->serialize($message);
             // Newline is the message separator
             $connection->getSocket()->write($serializedMessage . "\n");
             $connection->setLastMessageSentAt(new \DateTime());
             $deferred->resolve();
         } catch (\Exception $e) {
             try {
                 $connection->getSocket()->close();
             } catch (\Exception $e) {
             }
             $deferred->reject($e);
         }
     };
     if ($timeout > 0) {
         /** @noinspection PhpParamsInspection */
         $this->loop->addTimer($timeout, $sendMessage);
     } else {
         $sendMessage();
     }
     return $deferred->promise();
 }
 /**
  * Sets up a callback to poll a specified feed.
  *
  * @param string $url Feed URL
  */
 protected function queuePoll($url)
 {
     $self = $this;
     $this->loop->addTimer($this->interval, function () use($url, $self) {
         $self->pollFeed($url);
     });
 }
Esempio n. 7
0
 public function handleConnectedSocks(Stream $stream, $host, $port, $timeout, $protocolVersion, $auth = null)
 {
     $deferred = new Deferred();
     $resolver = $deferred->resolver();
     $timerTimeout = $this->loop->addTimer($timeout, function () use($resolver) {
         $resolver->reject(new Exception('Timeout while establishing socks session'));
     });
     if ($protocolVersion === '5' || $auth !== null) {
         $promise = $this->handleSocks5($stream, $host, $port, $auth);
     } else {
         $promise = $this->handleSocks4($stream, $host, $port);
     }
     $promise->then(function () use($resolver, $stream) {
         $resolver->resolve($stream);
     }, function ($error) use($resolver) {
         $resolver->reject(new Exception('Unable to communicate...', 0, $error));
     });
     $loop = $this->loop;
     $deferred->then(function (Stream $stream) use($timerTimeout, $loop) {
         $loop->cancelTimer($timerTimeout);
         $stream->removeAllListeners('end');
         return $stream;
     }, function ($error) use($stream, $timerTimeout, $loop) {
         $loop->cancelTimer($timerTimeout);
         $stream->close();
         return $error;
     });
     $stream->on('end', function (Stream $stream) use($resolver) {
         $resolver->reject(new Exception('Premature end while establishing socks session'));
     });
     return $deferred->promise();
 }
Esempio n. 8
0
 protected function queueProcess()
 {
     if (!$this->benchmarks->valid()) {
         return;
     }
     $b = $this->benchmarks->current();
     $this->benchmarks->next();
     $key = serialize([$b->benchmark, $b->subbenchmark, $b->count]);
     if (!isset($this->stdout[$key])) {
         $this->stdout[$key] = '';
     }
     if (!isset($this->runtimes[$key])) {
         $this->runtimes[$key] = [];
     }
     $current_process_id = $this->process_id;
     $this->process_id++;
     $this->processes[$current_process_id] = $process = new Process($b->command);
     $start = null;
     $process->on('exit', function ($code, $signal) use($b, $key, &$current_process_id, &$start) {
         $this->runtimes[$key][] = microtime(true) - $start;
         $this->output->writeln('<comment>End ' . $b->benchmark . '-' . $b->subbenchmark . ' ' . $b->count . ' #' . $b->execution . '</comment>');
         unset($this->processes[$current_process_id]);
         $this->queueProcess();
     });
     $this->loop->addTimer(0.001, function ($timer) use($process, $key, $b, &$start) {
         $this->output->writeln('<comment>Start ' . $b->benchmark . '-' . $b->subbenchmark . ' ' . $b->count . ' #' . $b->execution . '</comment>');
         $start = microtime(true);
         $process->start($timer->getLoop());
         $process->stdout->on('data', function ($data) use(&$stdout, $key) {
             $this->stdout[$key] .= $data;
         });
     });
 }
 /**
  * @param HttpRequest $request
  */
 public function setRequestTimeout(HttpRequest $request)
 {
     if ($this->options['timeout'] > 0) {
         $this->requestTimer = $this->loop->addTimer($this->options['timeout'], function () use($request) {
             $request->closeError(new \Exception('Transaction time out'));
         });
     }
 }
Esempio n. 10
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();
 }
Esempio n. 11
0
 public function __construct(LoopInterface $loop)
 {
     $bspcProcess = proc_open('pactl subscribe', [['pipe', 'r'], ['pipe', 'w']], $pipes);
     $bspcStdout = new Stream($pipes[1], $loop);
     $bspcStdout->on('data', [$this, 'onUpdate']);
     $loop->addTimer(0, function () {
         $this->queryData();
     });
 }
Esempio n. 12
0
 public function testFutureTickEventGeneratedByTimer()
 {
     $this->loop->addTimer(0.001, function () {
         $this->loop->futureTick(function () {
             echo 'future-tick' . PHP_EOL;
         });
     });
     $this->expectOutputString('future-tick' . PHP_EOL);
     $this->loop->run();
 }
Esempio n. 13
0
 protected function registerCancelTimer()
 {
     $this->cancel_timer = $this->loop->addTimer(0.5, function () {
         if (false == $this->isAllNeedsProvided()) {
             $this->deferred->reject();
         }
         echo "resolving by timer\n";
         $this->deferred->resolve($this->response);
     });
 }
Esempio n. 14
0
 /**
  * NewEventLoopScheduler constructor.
  * @param callable|LoopInterface $timerCallableOrLoop
  */
 public function __construct($timerCallableOrLoop)
 {
     // passing a loop directly into the scheduler will be deprecated in the next major release
     $this->timerCallable = $timerCallableOrLoop instanceof LoopInterface ? function ($ms, $callable) use($timerCallableOrLoop) {
         $timerCallableOrLoop->addTimer($ms / 1000, $callable);
     } : $timerCallableOrLoop;
     parent::__construct($this->now(), function ($a, $b) {
         return $a - $b;
     });
 }
 protected function processQueue()
 {
     $this->loop->addTimer($this->interval, function () {
         if ($this->callQueue->isEmpty()) {
             return;
         }
         $message = $this->callQueue->dequeue();
         $data = ['function' => $message->getFunction(), 'args' => $message->getArgs(), 'errorResultCode' => $message->getErrorResultCode()];
         $message->getDeferred()->resolve($data);
     });
 }
 /**
  * Enqueue a callback to be invoked once 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 addTimer($interval, callable $callback)
 {
     $loopTimer = null;
     $wrapper = function () use(&$loopTimer, $callback, $interval) {
         $this->emit('timerTick', [$interval, $callback, $loopTimer]);
         $callback($loopTimer);
     };
     $loopTimer = new TimerDecorator($this, $this->loop->addTimer($interval, $wrapper));
     $this->emit('addTimer', [$interval, $callback, $loopTimer]);
     return $loopTimer;
 }
Esempio n. 17
0
/**
 * wait/sleep for $time seconds
 *
 * @param float $time
 * @param LoopInterface $loop
 */
function sleep($time, LoopInterface $loop)
{
    $wait = true;
    $loop->addTimer($time, function () use($loop, &$wait) {
        $loop->stop();
        $wait = false;
    });
    do {
        $loop->run();
    } while ($wait);
}
 protected function checkQueue()
 {
     if ($this->callQueue->count() > 0 && $this->readyPool->count() > 0) {
         $this->callQueue->dequeue()->resolve();
     }
     if ($this->callQueue->count() > 0) {
         $this->timer = $this->loop->addTimer(static::INTERVAL, function () {
             $this->checkQueue();
         });
     }
 }
 /**
  * @param LoopInterface $loop
  * @param Messenger $messenger
  * @return Process
  */
 public static function create(LoopInterface $loop, Messenger $messenger)
 {
     try {
         return new Process($loop, $messenger);
     } catch (\Exception $exeption) {
         $messenger->error(MessagesFactory::error(['message' => $exeption->getMessage(), 'code' => $exeption->getCode(), 'line' => $exeption->getLine(), 'file' => $exeption->getFile()]));
         $loop->addTimer(1, function () use($loop) {
             $loop->stop();
         });
     }
 }
Esempio n. 20
0
function resolve($time, LoopInterface $loop)
{
    return new Promise(function ($resolve) use($loop, $time, &$timer) {
        // resolve the promise when the timer fires in $time seconds
        $timer = $loop->addTimer($time, function () use($time, $resolve) {
            $resolve($time);
        });
    }, function ($resolveUnused, $reject) use(&$timer, $loop) {
        // cancelling this promise will cancel the timer and reject
        $loop->cancelTimer($timer);
        $reject(new \RuntimeException('Timer cancelled'));
    });
}
Esempio n. 21
0
 /**
  * Schedule a callback to execute once
  *
  * Time intervals are measured in milliseconds.
  *
  * @param callable $callback Any valid PHP callable
  * @param float $delay The delay in seconds before the callback will be invoked (zero is allowed)
  * @return int
  */
 public function once(callable $callback, $delay)
 {
     $watcherId = null;
     $timer = $this->reactor->addTimer($delay / $this->timeScaleFactor, function () use(&$watcherId, $callback) {
         $this->deregisterWatcher($watcherId);
         if (isset($this->disabledWatchers[$watcherId])) {
             return null;
         }
         return call_user_func($callback, $watcherId, $this);
     });
     $watcherId = $this->registerWatcher(self::WATCHER_TYPE_TIMER, $timer);
     return $watcherId;
 }
Esempio n. 22
0
 /**
  * Callback when heartbeat timer timed out.
  */
 public function onHeartbeat()
 {
     $now = microtime(true);
     $nextHeartbeat = ($this->lastWrite ?: $now) + $this->options["heartbeat"];
     if ($now >= $nextHeartbeat) {
         $this->writer->appendFrame(new HeartbeatFrame(), $this->writeBuffer);
         $this->flushWriteBuffer()->then(function () {
             $this->heartbeatTimer = $this->eventLoop->addTimer($this->options["heartbeat"], [$this, "onHeartbeat"]);
         });
     } else {
         $this->heartbeatTimer = $this->eventLoop->addTimer($nextHeartbeat - $now, [$this, "onHeartbeat"]);
     }
 }
 /**
  * @param LoopInterface $loop
  * @param array $options
  * @param null $termiteCallable
  * @return Messenger
  */
 public static function child(LoopInterface $loop, array $options = [], $termiteCallable = null)
 {
     $messenger = new Messenger(new Stream(STDIN, $loop), new Stream(STDOUT, $loop), new Stream(STDERR, $loop), ['read' => 'stdin', 'write_err' => 'stderr', 'write' => 'stdout'] + $options);
     if ($termiteCallable === null) {
         $termiteCallable = function () use($loop) {
             $loop->addTimer(self::TERMINATE_TIMEOUT, [$loop, 'stop']);
         };
     }
     $messenger->registerRpc(Messenger::TERMINATE_RPC, function (Payload $payload, Messenger $messenger) use($loop, $termiteCallable) {
         $messenger->emit('terminate', [$messenger]);
         $termiteCallable($payload, $messenger);
         return new FulfilledPromise();
     });
     return $messenger;
 }
Esempio n. 24
0
 /**
  * start crontab every minute
  */
 public function crontabCallback(Crontab $crontab, LoopInterface $loop)
 {
     $loop->addTimer(60 - time() % 60, function () use($crontab) {
         $pid = pcntl_fork();
         if ($pid > 0) {
             return;
         } elseif ($pid == 0) {
             $crontab->start(time());
             exit;
         } else {
             $this->logger->error("could not fork");
             exit;
         }
     });
 }
Esempio n. 25
0
 public function initialize(Messenger $server, Messenger $client, LoopInterface $loop)
 {
     foreach ($this->messages as $message) {
         $client->on($message->event, function ($arg) use($message, $loop) {
             $this->assertEquals($arg, $message->arguments);
             $message->called = true;
             $this->totalCalled++;
             if ($this->totalCalled === count($this->messages)) {
                 $loop->stop();
             }
         });
         $loop->addTimer(0.001, function () use($server, $message) {
             $server->send($message->event, $message->arguments);
         });
     }
     $loop->addTimer(3, function () use($loop) {
         $loop->stop();
         throw new \RuntimeException('Timeout reached, server has not accomplished all messages.');
     });
     $loop->run();
     foreach ($this->messages as $message) {
         $this->assertTrue($message->called);
     }
 }
 /**
  * @return array
  */
 protected function preparePromises()
 {
     $userFacingDeferred = new Deferred();
     $privateDeferred = new Deferred();
     $userFacingPromise = $userFacingDeferred->promise();
     $privateDeferred->promise()->then(function ($shortUrl) use($userFacingDeferred) {
         $userFacingDeferred->resolve($shortUrl);
     }, function () use($userFacingDeferred) {
         $userFacingDeferred->reject();
     });
     $this->loop->addTimer($this->shortenTimeout, function () use($privateDeferred) {
         $privateDeferred->reject();
     });
     return [$privateDeferred, $userFacingPromise];
 }
Esempio n. 27
0
 public function testEmptyReadablePipe()
 {
     $ended = false;
     $buffer = buffer(['highWaterMark' => 1])->pause();
     $buffer->on('end', function () use(&$ended) {
         $ended = true;
     });
     $this->eventLoop->addTimer(0, function () use($buffer) {
         $stream = readable(new \ArrayIterator([]));
         $stream->pipe($buffer);
         $stream->resume();
     });
     $items = iterator_to_array(iterator($buffer, $this->waitFn(0.5)));
     $this->assertSame([], $items);
     $this->assertTrue($ended);
 }
Esempio n. 28
0
 /**
  * @param LoopInterface $loop
  * @param callable      $task
  * @param int|float     $interval
  * @param bool          $periodic
  * @param int           $count
  *
  * @throws \InvalidArgumentException
  */
 public function __construct(LoopInterface $loop, callable $task, $interval, $periodic = false, $count = null)
 {
     $this->maxIterations = $count !== null ? (int) $count : ($periodic ? null : 1);
     if ($this->maxIterations !== null && $this->maxIterations <= 0) {
         throw new \InvalidArgumentException('The count argument must be a positive integer value');
     }
     $this->task = new Delegate($task);
     $this->iterations = 0;
     $onTick = function () {
         $this->onTick();
     };
     if ($periodic) {
         $this->timer = $loop->addPeriodicTimer($interval, $onTick);
     } else {
         $this->timer = $loop->addTimer($interval, $onTick);
     }
 }
Esempio n. 29
0
 /**
  * @param RemoteEventMessage $message
  * @param null $timeout
  * @return \React\Promise\Promise|\React\Promise\PromiseInterface
  */
 public function whenResponseTo(RemoteEventMessage $message, $timeout = null)
 {
     $deferred = new Deferred();
     $tag = $message->getTag();
     $this->deferred[$tag] = $deferred;
     $this->carrierProtocol->sendString($message->toJson());
     $this->logger->debug(sprintf("Awaiting response to '%s'%s with %s", $message->getData(), $message->getRoom() ? " in room " . $message->getRoom() : '', $timeout ? "timeout {$timeout}" : 'no timeout'));
     if ($timeout) {
         $list =& $this->deferred;
         $logger = $this->logger;
         $this->timers[$tag] = $this->loop->addTimer($timeout, function () use($deferred, &$list, $tag, $logger) {
             unset($list[$tag]);
             $logger->debug("Request with tag {$tag} has timed out");
             $deferred->reject("Timeout occurred");
         });
     }
     return $deferred->promise();
 }
Esempio n. 30
-1
 public function ping($timeout = 10)
 {
     $payload = $this->pingSeq;
     $this->conn->send(new Frame($payload, true, Frame::OP_PING));
     $seq = $this->pingSeq;
     $this->pingSeq++;
     if ($timeout > 0) {
         $timer = $this->loop->addTimer($timeout, function () use($seq) {
             if (isset($this->pingRequests[$seq])) {
                 $this->pingRequests[$seq]['deferred']->reject('timeout');
                 unset($this->pingRequests[$seq]);
             }
         });
         $deferred = new Deferred();
         $this->pingRequests[$seq] = array('seq' => $seq, 'deferred' => $deferred, 'timer' => $timer);
         return $deferred->promise();
     }
 }