Listen to the given queue in a loop.

@param  string                          $connectionName
@param  string                          $queue
@param  \Illuminate\Queue\WorkerOptions $options
@return void
482959
public function daemon($workCommand, $connectionName, $queue, WorkerOptions $options)
    {
        if ($this->supportsAsyncSignals()) {
            $this->listenForSignals();
        }

        $lastRestart = $this->getTimestampOfLastQueueRestart();

        while (true) {
            // Before reserving any jobs, we will make sure this queue is not paused and
            // if it is we will just pause this worker for a given amount of time and
            // make sure we do not need to kill this worker process off completely.
            if (!$this->daemonShouldRun($options, $connectionName, $queue)) {
                $this->pauseWorker($options, $lastRestart);

                continue;
            }

            // First, we will attempt to get the next job off of the queue. We will also
            // register the timeout handler and reset the alarm for this job so it is
            // not stuck in a frozen state forever. Then, we can fire off this job.
            $job = $this->getNextJob(
                $this->manager->connection($connectionName), $queue
            );

            if ($this->supportsAsyncSignals()) {
                $this->registerTimeoutHandler($job, $options);
            }

            // If the daemon should run (not in maintenance mode, etc.), then we can run
            // fire off this job for processing. Otherwise, we will need to sleep the
            // worker so no more jobs are processed until they should be processed.
            if ($job) {
                $this->runJob($workCommand, $job, $connectionName, $options);
            } else {
                $this->sleep($options->sleep);
            }

            // Finally, we will check to see if we have exceeded our memory limits or if
            // the queue should restart based on other indications. If so, we'll stop
            // this worker and let whatever is "monitoring" it restart the process.
            $this->stopIfNecessary($options, $lastRestart, $job);
        }
    }
486652
public function listen(): void
    {
        $this->socket = stream_socket_server(
            $this->getUri(),
            $errno,
            $errstr,
            STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
            $this->getStreamContext()
        );

        if (!$this->socket) {
            throw new ConnectionException(sprintf(
                'Could not listen on socket: %s (%d)',
                $errstr,
                $errno
            ));
        }

        $this->listening = true;
    }
1161027
private function persistentConnect(\stdClass $connectionOptions)
    {
        if (!$this->connection->pconnect(
            $connectionOptions->host,
            $connectionOptions->port,
            $connectionOptions->timeout
        )) {
            throw new MemcacheConnectionException(
                "Can't connect to memcache server with config: "
                . var_export($connectionOptions, true)
            );
        };
    }
877649
protected function runWorker($connection, $queue)
    {
        foreach (explode(',', $queue) as $tube) {
            $this->worker->eyeQueues[] = Queue::firstOrCreate(['connection' => $connection,
                                                               'tube' => $tube,
                                                               'driver' => $this->getDriverName($connection),
                                                               'healthy' => 1]);
        }

        return parent::runWorker($connection, $queue);
    }
768638
public function process($connectionName, $job, WorkerOptions $options)
    {
        $startTime = microtime(true);

        try {
            parent::process($connectionName, $job, $options);
        } catch (Exception $e) {
            $this->recordJobException($e);
        } catch (Throwable $e) {
            $this->recordJobException($e);
        } finally {
            $this->recordJobEnd($startTime, $job->resolveName());
        }
    }
786112
public function listenToQueue(array $handlers , $routingKey = null, $options =[] )
    {
        /* Look for handlers */
        $handlersMap = array();
        foreach ($handlers as $handlerClassPath) {
            if (!class_exists($handlerClassPath)) {
                $handlerClassPath = "Kontoulis\\RabbitMQLaravel\\Handlers\\DefaultHandler";
                if (!class_exists($handlerClassPath)) {
                    throw new BrokerException(
                        "Class $handlerClassPath was not found!"
                    );
                }
            }
            $handlerOb = new $handlerClassPath();
            $classPathParts = explode("\\", $handlerClassPath);
            $handlersMap[$classPathParts[count($classPathParts) - 1]] = $handlerOb;
        }

        $this->queueDeclareBind($routingKey);
        /* Start consuming */
        $this->basic_qos(
            (isset($options["prefetch_size"]) ? $options["prefetch_size"] : null),
            (isset($options["prefetch_count"]) ? $options["prefetch_count"] : 1),
            (isset($options["a_global"]) ? $options["a_global"] : null)
        );
        $this->basic_consume(
            $routingKey,
            (isset($options["consumer_tag"]) ? $options["consumer_tag"] : ''),
            (isset($options["no_local"]) ? (bool)$options["no_local"] : false),
            (isset($options["no_ack"]) ? (bool)$options["no_ack"] : false),
            (isset($options["exclusive"]) ? (bool)$options["exclusive"] : false),
            (isset($options["no_wait"]) ? (bool)$options["no_wait"] : false),
            function (AMQPMessage $amqpMsg) use($handlersMap) {
                $msg = Message::fromAMQPMessage($amqpMsg);
                $this->handleMessage($msg, $handlersMap);
            }
        );
        return $this->waitConsume($options);
    }
918162
protected function runJob($workCommand, $job, $connectionName, WorkerOptions $options)
    {
        try {
            return $this->process($workCommand, $connectionName, $job, $options);
        } catch (Exception $e) {
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        } catch (Throwable $e) {
            $e = new FatalThrowableError($e);
            $this->report($e);

            $this->stopWorkerIfLostConnection($e);
        }
    }
234736
protected function runJob($job, $connectionName, WorkerOptions $options)
    {
        try {
            $this->process($connectionName, $job, $options);
        } catch (Exception $e) {

            $this->stopWorkerIfLostConnection($e);
        } catch (Throwable $e) {

            $this->stopWorkerIfLostConnection($e);
        }
    }
19733
public function synchronize($connectionName)
    {
        $configuration = $this->getConfiguration($connectionName);
        $database = $this->getDatabase($connectionName);

        foreach ($configuration->getVertexes() as $vertex) {
            try {
                $database->query(sprintf('CREATE CLASS %s EXTENDS V',
                    $vertex->getName()
                ));
                $database->query(sprintf('DISPLAY RECORD 0',
                    $vertex->getName()
                ));
                dump($res); die;
            } catch (\Exception $e) {
                if (preg_match(sprintf('/Class %s already exists in current database$/', $vertex->getName()), $e->getMessage())) {
                    continue;
                }

                throw $e;
            }
        }
    }
449549
protected function flushQueueItem(string $connectionName, MessageEnvelopeQueue $queue)
    {
        if ($queue->isEmpty()) {
            return;
        }

        $connection = $this->getConnectionHandler()->getConnection($connectionName);
        /* @var AppleConnection $connection */
        foreach ($queue->getQueue() as $item) {
            /* @var AppleMessageEnvelope $item */
            $connection->send($item->getMessage());
        }

        $response = $this->getResponseData($connection);
        if ($response->isSuccess()) {
            $queue->traverseWith(function (MessageEnvelope $messageEnvelope) {
                $messageEnvelope->setState(MessageEnvelope::SUCCESS);
            });
            $queue->clear();
        } else {
            $this->handleErrorResponse($connectionName, $queue, $response);
        }
    }
1066446
protected function raiseBeforeJobEvent($connectionName, $job)
    {
        $this->events->dispatch(new Events\JobProcessing(
            $connectionName, $job
        ));
    }
363150
public function process($connectionName, $job, WorkerOptions $options)
    {
        try {
            // First we will raise the before job event and determine if the job has already ran
            // over its maximum attempt limits, which could primarily happen when this job is
            // continually timing out and not actually throwing any exceptions from itself.
            $this->raiseBeforeJobEvent($connectionName, $job);

            $this->markJobAsFailedIfAlreadyExceedsMaxAttempts(
                $connectionName, $job, (int) $options->maxTries
            );

            // Here we will fire off the job and let it process. We will catch any exceptions so
            // they can be reported to the developers logs, etc. Once the job is finished the
            // proper events will be fired to let any listeners know this job has finished.
            $job->fire();

            $this->raiseAfterJobEvent($connectionName, $job);
        } catch (Exception $e) {
            $this->handleJobException($connectionName, $job, $options, $e);
        } catch (Throwable $e) {
            $this->handleJobException(
                $connectionName, $job, $options, new FatalThrowableError($e)
            );
        }
    }
1207005
public function query($collectionName, $options = [])
    {
        $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;

        $token = $this->log(
            'find',
            array_merge(
                [
                    'ns' => $databaseName . '.' . $collectionName,
                    'filter' => $this->document,
                ],
                $options
            ),
            __METHOD__
        );

        $readConcern = $this->getReadConcern();
        if ($readConcern !== null) {
            $options['readConcern'] = $readConcern;
        }

        try {
            $this->beginProfile($token, __METHOD__);

            $query = new \MongoDB\Driver\Query($this->document, $options);
            $this->db->open();
            $cursor = $this->db->manager->executeQuery($databaseName . '.' . $collectionName, $query, $this->getReadPreference());
            $cursor->setTypeMap($this->db->typeMap);

            $this->endProfile($token, __METHOD__);
        } catch (RuntimeException $e) {
            $this->endProfile($token, __METHOD__);
            throw new Exception($e->getMessage(), $e->getCode(), $e);
        }

        return $cursor;
    }
813729
public static function handle($connectionName, $job, $e = null)
    {
        $job->markAsFailed();

        if ($job->isDeleted()) {
            return;
        }

        try {
            // If the job has failed, we will delete it, call the "failed" method and then call
            // an event indicating the job has failed so it can be logged if needed. This is
            // to allow every developer to better keep monitor of their failed queue jobs.
            $job->delete();

            $job->failed($e);

        } finally {
        }
    }
81352
public static function handle($connectionName, $job, $e = null)
    {
        $job->markAsFailed();

        if ($job->isDeleted()) {
            return;
        }

        try {
            // If the job has failed, we will delete it, call the "failed" method and then call
            // an event indicating the job has failed so it can be logged if needed. This is
            // to allow every developer to better keep monitor of their failed queue jobs.
            $job->delete();

            $job->failed($e);
        } finally {
            static::events()->dispatch(new JobFailed(
                $connectionName, $job, $e ?: new ManuallyFailedException()
            ));
        }
    }
221790
private function configureSearchServices(ContainerBuilder $container, $connectionName, $connectionParams)
    {
        $alias = $this->getAlias();

        // Http client
        $httpClientId = static::HTTP_CLIENT_ID . ".$connectionName";
        $httpClientDef = new DefinitionDecorator(self::HTTP_CLIENT_ID);
        $httpClientDef->replaceArgument(0, $connectionParams['server']);
        $container->setDefinition($httpClientId, $httpClientDef);

        // Content search gateway
        $contentSearchGatewayDef = new DefinitionDecorator(self::CONTENT_SEARCH_GATEWAY_ID);
        $contentSearchGatewayDef->replaceArgument(0, new Reference($httpClientId));
        $contentSearchGatewayDef->replaceArgument(5, $connectionParams['index_name']);
        $contentSearchGatewayId = self::CONTENT_SEARCH_GATEWAY_ID . ".$connectionName";
        $container->setDefinition($contentSearchGatewayId, $contentSearchGatewayDef);

        // Location search gateway
        $locationSearchGatewayDef = new DefinitionDecorator(self::LOCATION_SEARCH_GATEWAY_ID);
        $locationSearchGatewayDef->replaceArgument(0, new Reference($httpClientId));
        $locationSearchGatewayDef->replaceArgument(5, $connectionParams['index_name']);
        $locationSearchGatewayId = self::LOCATION_SEARCH_GATEWAY_ID . ".$connectionName";
        $container->setDefinition($locationSearchGatewayId, $locationSearchGatewayDef);

        $container->setParameter(
            "$alias.connection.$connectionName.content_document_type_identifier",
            $connectionParams['document_type_name']['content']
        );
        $container->setParameter(
            "$alias.connection.$connectionName.location_document_type_identifier",
            $connectionParams['document_type_name']['location']
        );
    }
1028627
public function flushQueue(string $connectionName = null)
    {
        if (empty($this->queues)) {
            return;
        }

        if ($connectionName === null) {
            foreach ($this->queues as $queueConnectionName => $queue) {
                $this->flushQueueItem($queueConnectionName, $queue);
            }
        } elseif (array_key_exists($connectionName, $this->queues)) {
            $this->flushQueueItem($connectionName, $this->queues[$connectionName]);
        }
    }