public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->get('routing_key');
     $method = 'read' . Inflector::camelize($routingKey);
     $interpreter = isset($this->interpreters[$this->exchange]) ? $this->interpreters[$this->exchange] : (isset($this->interpreters['*']) ? $this->interpreters['*'] : null);
     if ($interpreter === null) {
         $interpreter = $this;
     } else {
         if (class_exists($interpreter)) {
             $interpreter = new $interpreter();
             if (!$interpreter instanceof AmqpInterpreter) {
                 throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $interpreter));
             }
         } else {
             throw new Exception(sprintf("Interpreter class '%s' was not found.", $interpreter));
         }
     }
     if (method_exists($interpreter, $method) || is_callable([$interpreter, $method])) {
         $info = ['exchange' => $this->exchange, 'routing_key' => $routingKey, 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null, 'delivery_tag' => $msg->get('delivery_tag')];
         try {
             $body = Json::decode($msg->body, true);
         } catch (\Exception $e) {
             $body = $msg->body;
         }
         $interpreter->{$method}($body, $info, $this->amqp->channel);
     } else {
         if (!$interpreter instanceof AmqpInterpreter) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->exchange])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->exchange])) {
         $interpreter = new $this->interpreters[$this->exchange]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->exchange]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->exchange]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         $interpreter->{$method}(Json::decode($msg->body, true), $info);
     } else {
         if (!isset($this->interpreters[$this->exchange])) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
 public function execute(AMQPMessage $msg)
 {
     //$msg will be an instance of `PhpAmqpLib\Message\AMQPMessage` with the $msg->body being the data sent over RabbitMQ.
     echo "Event: " . $msg->get('routing_key') . PHP_EOL;
     $routingKey = $msg->get('routing_key');
     if ($this->dispatcher->hasListeners($routingKey) && $routingKey != '') {
         $data = $this->serializer->deserialize($msg->body, 'array', 'json');
         var_dump($data);
         $this->dispatcher->dispatch($routingKey, new GenericEvent($routingKey, $data));
         return true;
     }
     return false;
 }
Exemple #4
0
 public function callback(AMQPMessage $Message)
 {
     try {
         $result = $Message->delivery_info['delivery_tag'];
         // отправляем ответ, если он вообще нужен
         if ($Message->has('reply_to')) {
             $Message->delivery_info['channel']->basic_publish(new AMQPMessage($this->_encode($result), ['correlation_id' => $Message->get('correlation_id')]), '', $Message->get('reply_to'));
         }
         // подтверждаем
         $Message->delivery_info['channel']->basic_ack($Message->delivery_info['delivery_tag']);
     } catch (\Exception $e) {
         $Message->delivery_info['channel']->basic_nack($Message->delivery_info['delivery_tag']);
     }
 }
Exemple #5
0
 /**
  * @param AMQPMessage $amqpMessage The message to convert
  *
  * @return MessageInterface
  */
 public static function toMessage(AMQPMessage $amqpMessage)
 {
     $properties = array('content_type', 'content_encoding', 'app_id', 'correlation_id', 'delivery_tag', 'message_id', 'priority', 'reply_to', 'routing_key', 'exchange_name', 'timestamp', 'type', 'user_id');
     $propertyValues = array_map(function ($propertyName) use($amqpMessage) {
         if ($amqpMessage->has($propertyName)) {
             return $amqpMessage->get($propertyName);
         }
         return false;
     }, $properties);
     $headers = $amqpMessage->has('application_headers') ? $amqpMessage->get('application_headers')->getNativeData() : array();
     $message = new \Amqp\Message();
     $message->setPayload($amqpMessage->body)->setDeliveryMode($amqpMessage->get('delivery_mode'))->setHeaders($headers)->setProperties(array_combine($properties, $propertyValues));
     return $message;
 }
 /**
  * @param AMQPMessage $message
  *
  * @return AMQPTable
  */
 private function getHeaders(AMQPMessage $message)
 {
     if ($message->has('application_headers')) {
         return $message->get('application_headers');
     }
     return new AMQPTable();
 }
Exemple #7
0
 /**
  * @param string $name
  * @return string
  */
 private function getFromEnvelope(string $name) : string
 {
     if ($this->envelope->has($name)) {
         return $this->envelope->get($name);
     }
     return '';
 }
 public function execute(AMQPMessage $msg)
 {
     $infoHeader = $msg->get("application_headers")->getNativeData();
     $response = json_decode($msg->body, true);
     echo "Message: " . $response["response"] . "  Reason (" . $infoHeader['x-death'][0]['reason'] . ")" . PHP_EOL;
     return self::MSG_ACK;
 }
 /**
  * When a message appears, it checks the correlation_id property. If it
  * matches the value from the request it returns the response to the
  * application.
  *
  * @param AMQPMessage $rep
  */
 public function onResponse(AMQPMessage $rep)
 {
     $this->log->addInfo('Received response');
     if ($rep->get('correlation_id') == $this->corr_id) {
         $this->log->addInfo('Correlation id matches, setting response: ' . $rep->body);
         $this->response = $rep->body;
     }
 }
 public function execute(AMQPMessage $msg)
 {
     $body = json_decode($msg->body, true);
     if ($msg->has("application_headers")) {
         $nativeData = $msg->get("application_headers")->getNativeData();
     }
     return $this->readMessage($body, isset($nativeData['attempts']) ? $nativeData['attempts'] : 0);
 }
Exemple #11
0
 public function processMessage(AMQPMessage $msg)
 {
     $messageBody = $msg->body;
     if ($this->expectSerializedResponse) {
         $messageBody = call_user_func($this->unserializer, $messageBody);
     }
     $this->replies[$msg->get('correlation_id')] = $messageBody;
 }
Exemple #12
0
 /**
  * Decodes a message
  *
  * @param \PhpAmqpLib\Message\AMQPMessage $message the message to decode
  *
  * @return bool|array the decoded message, or false if the message content type
  * is unsupported or the message is malformed.
  */
 public function decode($message)
 {
     $contentType = $message->get('content_type');
     if (!stristr($contentType, 'json')) {
         return false;
     }
     $decoded = json_decode($message->body, true);
     return $decoded === null ? false : $decoded;
 }
 /**
  * @param AmqpLibMessage $message
  *
  * @return AmqpMessage
  */
 public static function createMessage(AmqpLibMessage $message)
 {
     $properties = ['body' => $message->body];
     foreach (self::$PROPERTY_MAP as $name => $amqpLibName) {
         if ($message->has($amqpLibName)) {
             $properties[$name] = $message->get($amqpLibName);
         }
     }
     return CustomAmqpMessage::fromProperties($properties);
 }
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\User\\UserRegistered' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         $this->commandBus->handle(new SignupCommand($eventBody->user_id->id));
         return true;
     }
     return false;
 }
 /**
  * @param AMQPMessage $message
  *
  * @return Request
  *
  * @throws \Exception
  */
 private function createRequest(AMQPMessage $message)
 {
     $topic = $message->delivery_info['routing_key'];
     $headers = $message->has('application_headers') ? $message->get('application_headers')->getNativeData() : [];
     $version = isset($headers['version']) ? $headers['version'] : null;
     $arguments = json_decode($message->getBody(), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         throw new EncodingException('Unable to decode request: ' . json_last_error_msg());
     }
     return new Request($topic, $version, $arguments, $headers);
 }
 /**
  * Executes when a message is received.
  *
  * @param AMQPMessage $req
  */
 public function callback(AMQPMessage $req)
 {
     $this->log->addInfo('Received message: ' . $req->body);
     $credentials = json_decode($req->body);
     $authResult = $this->auth($credentials);
     /*
      * Creating a reply message with the same correlation id than the incoming message
      */
     $msg = new AMQPMessage(json_encode(array('status' => $authResult)), array('correlation_id' => $req->get('correlation_id')));
     $this->log->addInfo('Created response: ' . $msg->body . ' for correlation id: ' . $req->get('correlation_id'));
     /*
      * Publishing to the same channel from the incoming message
      */
     $req->delivery_info['channel']->basic_publish($msg, '', $req->get('reply_to'));
     $this->log->addInfo('Published response, replying to: ' . $req->get('reply_to'));
     /*
      * Acknowledging the message
      */
     $req->delivery_info['channel']->basic_ack($req->delivery_info['delivery_tag']);
     $this->log->addInfo('Acknowledged message to delivery tag: ' . $req->delivery_info['delivery_tag']);
 }
 /**
  * Verify if message reached max attemps.
  * @param AMQPMessage $msg
  * @return bool
  */
 protected function hasMaxAttempts(AMQPMessage $msg)
 {
     $AMQPTable = $msg->get("application_headers");
     $properties = $AMQPTable->getNativeData();
     if (isset($properties['attempts'])) {
         $attemps = $properties['attempts'];
         if ($attemps > self::MAX_ATTEMPTS) {
             return true;
         }
     }
     return false;
 }
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->queue])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->queue])) {
         $interpreter = new $this->interpreters[$this->queue]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->queue]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->queue]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'queue' => $this->queue, 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         try {
             $interpreter->{$method}(Json::decode($msg->body, true), $info);
         } catch (\Exception $exc) {
             $error_info = "consumer fail:" . $exc->getMessage() . PHP_EOL . "info:" . print_r($info, true) . PHP_EOL . "body:" . PHP_EOL . print_r($msg->body, true) . PHP_EOL . $exc->getTraceAsString();
             \Yii::warning($error_info, __METHOD__);
             $format = [Console::FG_RED];
             Console::stdout(Console::ansiFormat($error_info . PHP_EOL, $format));
             Console::stdout(Console::ansiFormat($exc->getTraceAsString() . PHP_EOL, $format));
         }
     } else {
         if (!isset($this->interpreters[$this->queue])) {
             $interpreter = new AmqpInterpreter();
         }
         $error_info = "Unknown routing key '{$routingKey}' for exchange '{$this->queue}'.";
         $error_info .= PHP_EOL . $msg->body;
         \Yii::warning($error_info, __METHOD__);
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->queue), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
Exemple #19
0
 /**
  * Process message.
  *
  * @param AMQPMessage $message
  * @throws \OutOfBoundsException
  * @throws \PhpAmqpLib\Exception\AMQPInvalidArgumentException
  */
 public function processMessage(AMQPMessage $message)
 {
     try {
         $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
         $result = call_user_func($this->callback, $message->body);
         $this->sendReply($result, $message->get('reply_to'), $message->get('correlation_id'));
     } catch (AMQPRuntimeException $exception) {
         $this->sendReply('error: ' . $exception->getMessage(), $message->get('reply_to'), $message->get('correlation_id'));
     } catch (AMQPInvalidArgumentException $exception) {
         $this->sendReply('error: ' . $exception->getMessage(), $message->get('reply_to'), $message->get('correlation_id'));
     }
 }
 public function execute(AMQPMessage $msg)
 {
     if (!$msg->has('application_headers') || !isset($msg->get('application_headers')['x-death'])) {
         sleep(2);
         return false;
     }
     $message = json_decode($msg->body, true);
     /* Отправка задачи на исполнение */
     $producer = $this->container->get('old_sound_rabbit_mq.' . $message['producer'] . '_producer');
     if (isset($message['route'])) {
         $producer->publish($message['payload'], $message['route']);
     } else {
         $producer->publish($message['payload']);
     }
     /* Установка задачи с задержкой */
     if ($message['recurring']) {
         $this->sheduleJob($message);
     }
     return true;
 }
 /**
  * Handles a task.
  *
  * @param mixed $message
  */
 private function taskHandler(AMQPMessage $message)
 {
     /** @var AMQPChannel $channel */
     $channel = $message->delivery_info['channel'];
     // Listen to the "reply_to" queue
     $replyExchange = null;
     $replyQueue = null;
     if ($message->has('reply_to')) {
         list($replyExchange, $replyQueue) = explode(';', $message->get('reply_to'));
     }
     /** @var Task $task */
     $task = unserialize($message->body);
     try {
         $this->triggerEvent(self::EVENT_AFTER_TASK_UNSERIALIZATION, [$task]);
         $this->triggerEvent(self::EVENT_BEFORE_TASK_EXECUTION, [$task]);
         // Execute the task
         $this->getExecutor($task)->execute($task);
         $this->triggerEvent(self::EVENT_BEFORE_TASK_FINISHED, [$task]);
         $success = true;
         $e = null;
     } catch (Exception $e) {
         $success = false;
     }
     // Signal the job status to RabbitMQ
     if ($success) {
         $channel->basic_ack($message->delivery_info['delivery_tag']);
     } else {
         $channel->basic_reject($message->delivery_info['delivery_tag'], false);
     }
     $dispatcherNotified = false;
     // Signal the job status to the dispatcher
     if ($replyExchange) {
         $message = $success ? 'finished' : 'errored';
         $dispatcherNotified = $this->notifyDispatcher($replyExchange, $replyQueue, $message);
     }
     if ($success) {
         $this->triggerEvent(self::EVENT_ON_TASK_SUCCESS, [$task, $dispatcherNotified]);
     } else {
         $this->triggerEvent(self::EVENT_ON_TASK_ERROR, [$task, $e, $dispatcherNotified]);
     }
 }
Exemple #22
0
 /**
  * Handles a message.
  *
  * @param mixed $message
  */
 public function handle(AMQPMessage $message)
 {
     /** @var AMQPChannel $channel */
     $channel = $message->delivery_info['channel'];
     // Listen to the "reply_to" queue
     $replyExchange = null;
     $replyQueue = null;
     if ($message->has('reply_to')) {
         list($replyExchange, $replyQueue) = explode(';', $message->get('reply_to'));
     }
     $this->trigger(IWorker::BEFORE_UNSERIALIZATION, [$message]);
     $envelope = unserialize($message->body);
     try {
         // Execute the handler; consume the message
         $this->trigger(IWorker::BEFORE_CONSUMING, [$envelope]);
         $this->consume($envelope);
         $this->trigger(IWorker::AFTER_CONSUMING, [$envelope]);
         $success = true;
         $e = null;
     } catch (\Exception $e) {
         $success = false;
     }
     // Signal the job status to RabbitMQ
     if ($success) {
         $channel->basic_ack($message->delivery_info['delivery_tag']);
     } else {
         $channel->basic_reject($message->delivery_info['delivery_tag'], false);
     }
     $dispatcherNotified = false;
     // Signal the job status to the dispatcher
     if ($replyExchange) {
         $message = $success ? 'finished' : 'errored';
         $dispatcherNotified = $this->notifyDispatcher($replyExchange, $replyQueue, $message);
     }
     if ($success) {
         $this->trigger(IWorker::ON_HANDLER_SUCCESS, [$envelope, $dispatcherNotified]);
     } else {
         $this->trigger(IWorker::ON_HANDLER_ERROR, [$envelope, $e, $dispatcherNotified]);
     }
 }
Exemple #23
0
 /**
  * @param AMQPMessage $message
  * @param string      $header
  *
  * @return string|null
  */
 private function getMessageHeader(AMQPMessage $message, $header)
 {
     $headers = $message->has('application_headers') ? $message->get('application_headers') : [];
     return array_key_exists($header, $headers) ? $headers[$header] : null;
 }
 /**
  * @param AMQPMessage $message
  *
  * @return Response
  *
  * @throws ReplyException
  */
 private function createResponse(AMQPMessage $message)
 {
     $headers = $message->has('application_headers') ? $message->get('application_headers')->getNativeData() : [];
     if (!empty($headers['x-error'])) {
         throw new ReplyException($headers['x-error'], isset($headers['x-error-code']) ? $headers['x-error-code'] : 0);
     }
     $type = $message->has('content_type') ? $message->get('content_type') : null;
     $value = $this->encoder->decode(new Encoded($type, $message->getBody()));
     return new Response($value, $headers);
 }
Exemple #25
0
 /**
  * Get the job identifier.
  *
  * @return string
  */
 public function getJobId()
 {
     return $this->amqpMessage->get('message_id');
 }
 function let(Container $container, RabbitMQQueue $queue, AMQPMessage $job, AMQPChannel $channel)
 {
     $job->get('body')->willReturn(json_encode(['job' => 'foo', 'data' => ['someData'], 'attempts' => 1]));
     $job->get('delivery_tag')->willReturn('fooTagId');
     $this->beConstructedWith($container, $queue, $job, 'default', $channel);
 }
 /**
  * Get the appropriate payload type for the AMQP message and deserialize
  * the message body with the payload.
  * @param AMQPMessage $message
  * @throws Exception\UnexpectedResponse
  * @return IPayload
  */
 protected function processMessage(AMQPMessage $message)
 {
     try {
         $type = $message->get('type');
     } catch (OutOfBoundsException $e) {
         throw new Exception\UnexpectedResponse('No "type" set for message.');
     }
     $payload = $this->messageFactory->messagePayload($type);
     $payload->deserialize($message->body);
     return $payload;
 }
 public function processMessage(AMQPMessage $msg)
 {
     $this->replies[$msg->get('correlation_id')] = unserialize($msg->body);
 }
 /**
  * @param AMQPMessage $message
  */
 public function consume(AMQPMessage $message)
 {
     $context = [];
     if ($message->has('correlation_id')) {
         $context['correlation_id'] = $message->get('correlation_id');
     }
     if ($this->logger) {
         $this->logger->info('received message with content-type ' . $message->get('content_type'), $context);
     }
     $contentType = new StringLiteral($message->get('content_type'));
     try {
         $deserializer = $this->deserializerLocator->getDeserializerForContentType($contentType);
         $domainMessage = $deserializer->deserialize(new StringLiteral($message->body));
         // If the deserializer did not return a DomainMessage yet, then
         // consider the returned value as the payload, and wrap it in a
         // DomainMessage.
         if (!$domainMessage instanceof DomainMessage) {
             $domainMessage = new DomainMessage(UUID::generateAsString(), 0, new Metadata($context), $domainMessage, DateTime::now());
         }
         $this->delayIfNecessary();
         if ($this->logger) {
             $this->logger->info('passing on message to event bus', $context);
         }
         $this->eventBus->publish(new DomainEventStream([$domainMessage]));
     } catch (\Exception $e) {
         if ($this->logger) {
             $this->logger->error($e->getMessage(), $context + ['exception' => $e]);
         }
         $message->delivery_info['channel']->basic_reject($message->delivery_info['delivery_tag'], false);
         if ($this->logger) {
             $this->logger->info('message rejected', $context);
         }
         return;
     }
     $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
     if ($this->logger) {
         $this->logger->info('message acknowledged', $context);
     }
 }
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\Wish\\WishWasMade' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         try {
             $this->commandBus->handle(new RewardUserCommand($eventBody->user_id->id, 5));
         } catch (AggregateDoesNotExist $e) {
             // Noop
         }
         return true;
     }
     return false;
 }