Example #1
1
 /**
  * Starts pending tasks end move them from the pendingQueue to the runningQueue
  */
 private function startPendingTasks()
 {
     while (count($this->runningTasks) < $this->concurrencyLimit && !$this->pendingTasks->isEmpty()) {
         /** @var TaskInterface $task */
         $task = $this->pendingTasks->dequeue();
         $task->start()->progress(function (Event $notification) {
             $this->deferred->notify($notification);
         })->always(function () use($task) {
             $this->finishedTasks[] = $task;
             $this->deferred->notify(new TaskFinishedEvent($this, $task));
         });
         $this->deferred->notify(new TaskStartedEvent($this, $task));
         $this->runningTasks->enqueue($task);
     }
 }
Example #2
0
 /**
  * @coroutine
  *
  * @return \Generator
  *
  * @resolve \Icicle\Postgres\Connection
  */
 private function pop() : \Generator
 {
     while (null !== $this->awaitable) {
         try {
             (yield $this->awaitable);
             // Prevent simultaneous connection creation.
         } catch (\Throwable $exception) {
             // Ignore failure or cancellation of other operations.
         }
     }
     if ($this->idle->isEmpty()) {
         try {
             if ($this->connections->count() >= $this->getMaxConnections()) {
                 // All possible connections busy, so wait until one becomes available.
                 $this->awaitable = new Delayed();
                 (yield $this->awaitable);
             } else {
                 // Max connection count has not been reached, so open another connection.
                 $this->awaitable = new Coroutine($this->createConnection());
                 $this->addConnection((yield $this->awaitable));
             }
         } finally {
             $this->awaitable = null;
         }
     }
     // Shift a connection off the idle queue.
     return $this->idle->shift();
 }
 public function close()
 {
     if (!$this->promises->isEmpty()) {
         $this->promises->dequeue()->resolve();
     } else {
         $this->current--;
     }
 }
Example #4
0
 public function __invoke($id, $service)
 {
     if ($this->middlewares->isEmpty()) {
         return $service;
     }
     $method = $this->middlewares->dequeue();
     return call_user_func($method, $this->container, new Next($this->container, $this->middlewares), $id, $service);
 }
 public function uncork()
 {
     if (!$this->corked) {
         return;
     }
     while (!$this->corked && !$this->writeBuffer->isEmpty()) {
         $this->doWrite(...$this->writeBuffer->dequeue());
     }
 }
Example #6
0
 private function tick()
 {
     while (!$this->tick->isEmpty() && !$this->main->isFinished()) {
         $task = $this->nextTask();
         $task->run();
         if ($task->isBlocked()) {
             $this->addFutureTask($task);
         }
     }
 }
 /**
  * @inheritDoc
  */
 public function getQuery(Driver $driver, $link)
 {
     if (!$this->pool->contains($link)) {
         throw new \OutOfBoundsException(sprintf('Undefined %s in the pooling controller.', $driver->info($link)));
     }
     if (!$this->waiting->isEmpty()) {
         return $this->waiting->dequeue();
     }
     $this->idle->enqueue($link);
 }
 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);
     });
 }
Example #9
0
 /**
  * @param Message $chapterCommand
  * @param mixed $data
  * @param ChapterLogger $chapterLogger
  */
 public function __invoke(Message $chapterCommand, $data, ChapterLogger $chapterLogger)
 {
     $done = $this->done;
     // No middleware remains; done
     if ($this->queue->isEmpty()) {
         return $done($chapterCommand, $data, $chapterLogger);
     }
     $stage = $this->queue->dequeue();
     $executeStage = $this->executeStage;
     return $executeStage($stage, $chapterCommand, $data, $chapterLogger, $this);
 }
Example #10
0
 protected function processQueue()
 {
     $this->loop->futureTick(function () {
         if ($this->callQueue->isEmpty()) {
             return;
         }
         $this->runningOperations++;
         $message = $this->callQueue->dequeue();
         $data = ['function' => $message->getFunction(), 'args' => $message->getArgs(), 'errorResultCode' => $message->getErrorResultCode()];
         $message->getDeferred()->resolve($data);
     });
 }
Example #11
0
 private function run()
 {
     /** @var HttpServer $server */
     $server = $this->container->get('http_server');
     // Run async dispatcher
     $server->getLoop()->addPeriodicTimer(Timer::MIN_INTERVAL, function (Timer $timer) {
         if ($this->queue->isEmpty()) {
             $timer->cancel();
             return;
         }
         $event = $this->queue->dequeue();
         $this->dispatch($event);
     });
 }
Example #12
0
 /**
  * @param Request $request
  * @param Response $response
  * @param callable[] ...$callables unshift callables (top priority)
  * @return Response
  */
 public function __invoke(Request $request, Response $response, ...$callables)
 {
     while ($callable = array_pop($callables)) {
         $this->queue->unshift($callable);
     }
     if ($this->queue->isEmpty()) {
         return $response;
     }
     $callable = $this->resolve($this->queue->dequeue());
     if (is_callable($callable)) {
         return call_user_func($callable, $request, $response, $this);
     } else {
         throw new \UnexpectedValueException();
     }
 }
 private function endRead()
 {
     $this->readEnded = true;
     if ($this->readBuffer->isEmpty()) {
         $this->ensureEndEmitted();
     }
 }
Example #14
0
 /**
  * @param null $lastPublicationId
  */
 private function processStateQueue($lastPublicationId = null)
 {
     if ($lastPublicationId !== null) {
         // create an array of pub ids
         // if we can't find the lastPublicationId in the queue
         // then we are going to assume it was before our time
         $pubIds = [];
         /** @var EventMessage $msg */
         foreach ($this->pauseQueue as $msg) {
             $pubIds[] = $msg->getPublicationId();
         }
         if (!in_array($lastPublicationId, $pubIds)) {
             $lastPublicationId = null;
         }
     }
     while (!$this->pauseQueue->isEmpty()) {
         $msg = $this->pauseQueue->dequeue();
         if ($lastPublicationId === null) {
             $this->sendEventMessage($msg);
         }
         if ($lastPublicationId == $msg->getPublicationId()) {
             $lastPublicationId = null;
         }
     }
 }
Example #15
0
 /**
  * Process the given queue of template files and
  * returns the generated output.
  *
  * @param string $file
  *
  * @return string
  * @throws RendererException
  */
 public function render(string $file) : string
 {
     if ($this->rendering) {
         throw new RendererException("Cannot call render() inside templates.");
     }
     $this->rendering = true;
     $this->queue->enqueue($file);
     $this->sections()->declare('content');
     ob_start();
     while (!$this->queue->isEmpty()) {
         $file = $this->engine->path($this->queue->dequeue());
         if (!file_exists($file)) {
             throw new \RuntimeException("Cannot find file: {$file}");
         }
         require $file;
         $this->sections()->populate('content', ob_get_contents(), 'replace');
         ob_clean();
         if ($this->extended) {
             $this->extended = false;
         }
     }
     ob_end_clean();
     $this->rendering = false;
     return $this->sections()->fetch('content');
 }
Example #16
0
 private function startUpdates()
 {
     if (!$this->updateQueue->isEmpty()) {
         $this->updating = true;
         $this->loop->futureTick([$this, 'update']);
     }
 }
 /**
  * Close the writer
  *
  * @return void
  */
 public function shutdown()
 {
     while (!$this->buffer->isEmpty()) {
         $this->buffer->dequeue();
     }
     $this->writer->shutdown();
 }
Example #18
0
 /**
  * @return string[] names of any dependencies involved in dependency cycle[s] (or that depend
  *     upon those in the cycle)
  */
 public function list_dependency_cycles()
 {
     $dep_counts = $this->dependency_counts();
     $depends_on = $this->reverse_graph();
     $deps_met_queue = new \SplQueue();
     foreach ($dep_counts as $dependency => $count) {
         if ($count === 0) {
             $deps_met_queue->enqueue($dependency);
         }
     }
     // Iteratively resolve dependencies
     $num_removed = 0;
     while (!$deps_met_queue->isEmpty()) {
         $name = $deps_met_queue->dequeue();
         $num_removed++;
         if (!array_key_exists($name, $depends_on)) {
             continue;
         }
         foreach ($depends_on[$name] as $dependant) {
             $dep_counts[$dependant]--;
             if ($dep_counts[$dependant] === 0) {
                 $deps_met_queue->enqueue($dependant);
             }
         }
     }
     // Find the dependencies that couldn't be resolved
     $depends_on_cycle = [];
     foreach ($dep_counts as $dependency => $count) {
         if ($count > 0) {
             $depends_on_cycle[] = $dependency;
         }
     }
     return $depends_on_cycle;
 }
Example #19
0
 /**
  * Receive a value from the channel.
  * 
  * Be careful when you may receive null values: you need to change the EOF param accordingly!
  * 
  * @param mixed $eof The EOF value, a channel will return this value if it has been closed without an error.
  * @return mixed The received value.
  * 
  * @throws \Throwable Fails if the channel has been closed with an error.
  */
 public function receive($eof = null) : Awaitable
 {
     if (!$this->buffer) {
         while ($this->senders && !$this->senders->isEmpty()) {
             $subscription = $this->senders->dequeue();
             if ($subscription->active) {
                 $subscription->resolve($subscription->data);
                 return new Success($subscription->data);
             }
         }
     } elseif (!$this->buffer->isEmpty()) {
         while ($this->senders && !$this->senders->isEmpty()) {
             $subscription = $this->senders->dequeue();
             if ($subscription->active) {
                 $subscription->resolve($subscription->data);
                 $this->buffer->push($subscription->data);
             }
         }
         return new Success($this->buffer->dequeue());
     }
     if ($this->closed instanceof \Throwable) {
         return new Failure($this->closed);
     } elseif ($this->closed) {
         return new Success($eof);
     }
     if (!$this->receivers) {
         $this->receivers = new \SplQueue();
     }
     $this->receivers->enqueue($subscription = new ChannelSubscription($eof));
     return $subscription;
 }
 /**
  * Solve missionaries and cannibals problem.
  *
  * @return bool
  */
 public function solve()
 {
     $initialState = new State(3, 3, 0, 0, 'left');
     $initialNode = new Node($initialState, null, null);
     if ($initialNode->state->isGoalState()) {
         $this->displayNodeInfo($initialNode);
         return true;
     }
     $queue = new SplQueue();
     $queue->push($initialNode);
     $explored = [];
     while (true) {
         if ($queue->isEmpty()) {
             return false;
             //nothing found
         }
         $node = $queue->pop();
         $this->displayNodeInfo($node);
         array_push($explored, $node->state);
         if ($node->state->isGoalState()) {
             return true;
         }
         //get all action and states available
         $states = $node->state->getNextStates();
         foreach ($states as $stateNode) {
             if (!$stateNode->state->isValidState()) {
                 continue;
             }
             if (!in_array($stateNode->state, $explored)) {
                 $queue->push($stateNode);
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
 {
     while (!$commands->isEmpty()) {
         $connection->writeRequest($commands->dequeue());
     }
     $connection->disconnect();
     return array();
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function tick()
 {
     if (!$this->process->isRunning() && $this->outputBuffer->isEmpty()) {
         usleep(1000);
         if ($this->outputBuffer->isEmpty()) {
             if ($this->process->isSuccessful()) {
                 $this->deferred->resolve(new MessageEvent($this, $this->process->getOutput()));
             } else {
                 $this->deferred->reject(new MessageEvent($this, $this->process->getOutput()));
             }
             return;
         }
     }
     if (!$this->outputBuffer->isEmpty()) {
         $this->deferred->notify(new MessageEvent($this, $this->outputBuffer->dequeue()[1]));
     }
 }
Example #23
0
 /**
  * Cancels all pending tasks.
  */
 private function cancelPending()
 {
     if (!$this->busyQueue->isEmpty()) {
         $exception = new WorkerException('Worker was shut down.');
         do {
             $this->busyQueue->dequeue()->cancel($exception);
         } while (!$this->busyQueue->isEmpty());
     }
 }
 public function execute()
 {
     /** @var Transaction[] */
     $failed = [];
     while (!$this->transactionsToRetry->isEmpty()) {
         //Some failed transactions are waiting from the previous execution to be retried
         $this->transactionQueue->enqueue($this->transactionsToRetry->dequeue());
     }
     if (!$this->transactionQueue->isEmpty()) {
         $this->player->getServer()->getPluginManager()->callEvent($ev = new InventoryTransactionEvent($this));
     } else {
         return;
     }
     while (!$this->transactionQueue->isEmpty()) {
         $transaction = $this->transactionQueue->dequeue();
         if ($ev->isCancelled()) {
             $this->transactionCount -= 1;
             $transaction->sendSlotUpdate($this->player);
             //Send update back to client for cancelled transaction
             unset($this->inventories[spl_object_hash($transaction)]);
             continue;
         } elseif (!$transaction->execute($this->player)) {
             $transaction->addFailure();
             if ($transaction->getFailures() >= self::DEFAULT_ALLOWED_RETRIES) {
                 /* Transaction failed completely after several retries, hold onto it to send a slot update */
                 $this->transactionCount -= 1;
                 $failed[] = $transaction;
             } else {
                 /* Add the transaction to the back of the queue to be retried on the next tick */
                 $this->transactionsToRetry->enqueue($transaction);
             }
             continue;
         }
         $this->transactionCount -= 1;
         $transaction->setSuccess();
         $transaction->sendSlotUpdate($this->player);
         unset($this->inventories[spl_object_hash($transaction)]);
     }
     foreach ($failed as $f) {
         $f->sendSlotUpdate($this->player);
         unset($this->inventories[spl_object_hash($f)]);
     }
 }
Example #25
0
 /**
  * 
  * @throws Exception
  * @return int
  */
 protected function _getNewStreamId()
 {
     if ($this->_lastStreamId < 32767) {
         return ++$this->_lastStreamId;
     }
     while ($this->_recycledStreams->isEmpty()) {
         $this->_getResponse();
     }
     return $this->_recycledStreams->dequeue();
 }
Example #26
0
 /**
  * @inheritDoc
  */
 public function __invoke(ObservableInterface $observable, ObserverInterface $observer, SchedulerInterface $scheduler = null)
 {
     if ($this->scheduler !== null) {
         $scheduler = $this->scheduler;
     }
     if ($scheduler === null) {
         throw new \Exception("You must use a scheduler that support non-zero delay.");
     }
     /** @var AnonymousObservable $observable */
     $disp = $observable->materialize()->timestamp()->map(function (Timestamped $x) {
         return new Timestamped($x->getTimestampMillis() + $this->delayTime, $x->getValue());
     })->subscribe(new CallbackObserver(function (Timestamped $x) use($scheduler, $observer) {
         if ($x->getValue() instanceof Notification\OnErrorNotification) {
             $x->getValue()->accept($observer);
             return;
         }
         $this->queue->enqueue($x);
         if ($this->schedulerDisposable === null) {
             $doScheduledStuff = function () use($observer, $scheduler, &$doScheduledStuff) {
                 while (!$this->queue->isEmpty() && $scheduler->now() >= $this->queue->bottom()->getTimestampMillis()) {
                     /** @var Timestamped $item */
                     $item = $this->queue->dequeue();
                     /** @var Notification $materializedValue */
                     $materializedValue = $item->getValue();
                     $materializedValue->accept($observer);
                 }
                 if ($this->queue->isEmpty()) {
                     $this->schedulerDisposable = null;
                     return;
                 }
                 $this->schedulerDisposable = $scheduler->schedule($doScheduledStuff, $this->queue->bottom()->getTimestampMillis() - $scheduler->now());
             };
             $doScheduledStuff();
         }
     }, [$observer, 'onError']), $scheduler);
     return new CallbackDisposable(function () use($disp) {
         if ($this->schedulerDisposable) {
             $this->schedulerDisposable->dispose();
         }
         $disp->dispose();
     });
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function tick()
 {
     if (!$this->queue->isEmpty()) {
         $immediate = $this->queue->shift();
         $this->immediates->detach($immediate);
         // Execute the immediate.
         $immediate->call();
         return true;
     }
     return false;
 }
 /**
  * Called when the Visitor is passed to an Item.
  * It calls TraversingItemVisitor.entering(ItemInterface, int) followed by
  * TraversingItemVisitor.leaving(ItemInterface, int). Implement these
  * abstract methods to specify behavior on 'arrival at' and 'after leaving'
  * the $item.
  *
  * If this method throws, the visiting process is aborted.
  *
  * @param PHPCR_ItemInterface $item the Node or Property that is accepting this visitor.
  * @return void
  * @throws PHPCR_RepositoryException if an error occurs.
  * @author Karsten Dambekalns <*****@*****.**>
  * @author Day Management AG, Switzerland
  * @api
  */
 public function visit(PHPCR_ItemInterface $item)
 {
     if ($item instanceof PHPCR_PropertyInterface) {
         $this->entering($item);
         $this->leaving($item);
     } else {
         try {
             if ($this->breadthFirst === FALSE) {
                 // depth-first traversal
                 $this->entering($item, $this->currentLevel);
                 if ($this->maxLevel == -1 || $this->currentLevel < $this->maxLevel) {
                     $this->currentLevel++;
                     $propertyIterator = $item->getProperties();
                     while ($propertyIterator->hasNext()) {
                         $propertyIterator->nextProperty()->accept($this);
                     }
                     $nodeIterator = $item->getNodes();
                     while ($nodeIterator->hasNext()) {
                         $nodeIterator->nextNode()->accept($this);
                     }
                     $this->currentLevel--;
                 }
                 $this->leaving($item, $this->currentLevel);
             } else {
                 // breadth-first traversal
                 $this->entering($item, $this->currentLevel);
                 $this->leaving($item, $this->currentLevel);
                 if ($this->maxLevel == -1 || $this->currentLevel < $this->maxLevel) {
                     $propertyIterator = $item->getProperties();
                     while ($propertyIterator->hasNext()) {
                         $this->nextQueue->enqueue($propertyIterator->nextProperty());
                     }
                     $nodeIterator = $item->getNodes();
                     while ($nodeIterator->hasNext()) {
                         $this->nextQueue->enqueue($nodeIterator->nextNode());
                     }
                 }
                 while (!$this->currentQueue->isEmpty() || !$this->nextQueue->isEmpty()) {
                     if ($this->currentQueue->isEmpty()) {
                         $this->currentLevel++;
                         $this->currentQueue = $this->nextQueue;
                         $this->nextQueue = new SplQueue();
                     }
                     $item = $this->currentQueue->dequeue();
                     $item->accept($this);
                 }
                 $this->currentLevel = 0;
             }
         } catch (PHPCR_RepositoryException $exception) {
             $this->currentLevel = 0;
             throw $exception;
         }
     }
 }
Example #29
0
 /**
  * Shifts the given data back to the front of the stream and will be the first bytes returned from any pending or
  * subsequent read.
  *
  * @param string $data
  */
 public function unshift(string $data)
 {
     $data = (string) $data;
     if (!strlen($data)) {
         return;
     }
     $this->buffer = $data . $this->buffer;
     if (!$this->queue->isEmpty()) {
         /** @var \Icicle\Awaitable\Delayed $delayed */
         $delayed = $this->queue->shift();
         $delayed->resolve();
         $this->poll->cancel();
     }
 }
Example #30
0
 protected function addRulesForPackage(PackageInterface $package)
 {
     $workQueue = new \SplQueue();
     $workQueue->enqueue($package);
     while (!$workQueue->isEmpty()) {
         $package = $workQueue->dequeue();
         if (isset($this->addedMap[$package->getId()])) {
             continue;
         }
         $this->addedMap[$package->getId()] = true;
         foreach ($package->getRequires() as $link) {
             $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
             foreach ($possibleRequires as $require) {
                 $workQueue->enqueue($require);
             }
         }
         foreach ($package->getConflicts() as $link) {
             $possibleConflicts = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             foreach ($possibleConflicts as $conflict) {
                 $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
             }
         }
         $isInstalled = isset($this->installedMap[$package->getId()]);
         foreach ($package->getReplaces() as $link) {
             $obsoleteProviders = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
             foreach ($obsoleteProviders as $provider) {
                 if ($provider === $package) {
                     continue;
                 }
                 if (!$this->obsoleteImpossibleForAlias($package, $provider)) {
                     $reason = $isInstalled ? Rule::RULE_INSTALLED_PACKAGE_OBSOLETES : Rule::RULE_PACKAGE_OBSOLETES;
                     $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $provider, $reason, $link));
                 }
             }
         }
         $obsoleteProviders = $this->pool->whatProvides($package->getName(), null);
         foreach ($obsoleteProviders as $provider) {
             if ($provider === $package) {
                 continue;
             }
             if ($package instanceof AliasPackage && $package->getAliasOf() === $provider) {
                 $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package));
             } elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) {
                 $reason = $package->getName() == $provider->getName() ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES;
                 $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createConflictRule($package, $provider, $reason, $package));
             }
         }
     }
 }