def listenAuth(): EXCHANGE = "auth" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='fanout') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json.body_to_dic(body.decode('utf-8')) if (len(validator.validateSchema(EVENT, event)) > 0): return if (event["type"] == "logout"): security.invalidateSession(event["message"]) print("RabbitMQ Auth conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception: print("RabbitMQ Auth desconectado, intentando reconectar en 10'") threading.Timer(10.0, initAuth).start()
def send_is_article_valid(exchange, queue, type, price): connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url()) ) channel = connection.channel() channel.exchange_declare(exchange=exchange, exchange_type='fanout') channel.queue_declare(queue = queue) article = {} article["articleId"] = price["article_id"] article["referenceId"] = price["_id"] message = { "exchange": exchange, "queue": queue, "type": type, "message": article } channel.basic_publish( exchange=exchange, routing_key=queue, body=json_serializer.dic_to_json(message) ) print("RabbitMQ Catalog GET article-exist catalogId: {}, articleId: {}".format(article["referenceId"], article["articleId"])) connection.close()
def sendArticleData(exchange, queue, referenceId, articleId, valid, stock, price): """ Envía eventos al Cart article-data : Es una validación solicitada por Cart para validar si el articulo puede incluirse en el cart @api {direct} cart/article-data Validación de Articulos @apiGroup RabbitMQ POST @apiDescription Enviá de mensajes article-exist desde cart. Valida articulos @apiSuccessExample {json} Mensaje { "type": "article-exist", "message" : { "referenceId": "{referenceId}", "articleId": "{articleId}", "valid": True|False, "stock": {stock}, "price": {price} } } """ connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=exchange, exchange_type='direct') channel.queue_declare(queue=queue) message = { "type": "article-data", "message": { "referenceId": referenceId, "articleId": articleId, "valid": valid, "stock": stock, "price": price, } } channel.basic_publish(exchange=exchange, routing_key=queue, body=json.dic_to_json(message)) connection.close() print( "RabbitMQ Cart POST article-data catalogId:%r , articleId:%r , valid:%r", referenceId, articleId, valid)
def listen_article(): EXCHANGE = "article" QUEUE = "article" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url()) ) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='fanout') result = channel.queue_declare(QUEUE, durable=True) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json_serializer.body_to_dic(body.decode('utf-8')) if(len(validator.validateSchema(EVENT, event)) > 0): return if (event["type"] == "article-change"): message = event["message"] if(len(validator.validateSchema(MSG_ARTICLE_CHANGE, message)) > 0): return article_id = message['_id'] print("RabbitMQ Pricing POST article-change article_id: {}".format(article_id)) try: price = {} price['max_price'] = message['price'] price['min_price'] = message['price'] price['price'] = message['price'] price['price_currency'] = 'ARS' price['article_id'] = article_id price['state'] = ACTIVE crud._addOrUpdatePrice(price) except Exception: print('Cannot handle article-change') print("RabbitMQ Article conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception as inst: print(inst) print("RabbitMQ Article desconectado, intentando reconectar en 10'") Timer(10.0, initArticle).start()
def listenTransactions(): import app.domain.transactions.transactions_crud as transactions_crud import app.domain.transactions.transactions_service as transactions_service """ Escucha a transacciones a procesar emitidas por adaptadores de pago. @api {direct} payments/transaction_task_queue Process Transaction @apiGroup RabbitMQ GET @apiDescription Escucha a transacciones a procesar emitidas por adaptadores de pago. @apiExample {json} Mensaje { "type": "transaction_task_queue", "message" : { "amount":{Float}, "status":{String}, "id_payment":{String}, "external_reference":{String} } } """ QUEUE = "transaction_task_queue" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.queue_declare(queue=QUEUE, durable=False) def callback(ch, method, properties, body): params = json.body_to_dic(body.decode('utf-8')) transactions_service.process_transaction(params) ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1) print("RabbitMQ PaymentTransactions conectado") channel.basic_consume(queue=QUEUE, on_message_callback=callback) channel.start_consuming() except Exception as err: print(err) print("RabbitMQ PaymentTransactions, intentando reconectar en 10'") threading.Timer(10.0, initTransactions).start()
def listenPaymentsFailed(): """ Escucha a eventos de payments-failed enviados por Payments. @api {fanout} payments/payments-failed Payment Complete @apiGroup RabbitMQ GET MOCK @apiDescription Escucha a eventos de payments-failed enviados por Payments. @apiExample {json} Mensaje { "type": "payment-failed", "exchange" : "{payments-failed}" "message" : { "paymentId": "{paymentId}", } } """ EXCHANGE = "payments-failed" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='fanout') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json.body_to_dic(body.decode('utf-8')) print("Payment Failed!") print(event) print("RabbitMQ Payments GET conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception: print( "RabbitMQ Payments Failed GET desconectado, intentando reconectar en 10'" ) threading.Timer(10.0, initPaymentsFailed).start()
def listen_auth(): """ Básicamente eventos de logout enviados por auth. @api {fanout} auth/logout Logout @apiGroup RabbitMQ GET @apiDescription Escucha de mensajes logout desde auth. Invalida sesiones en cache. @apiExample {json} Mensaje { "type": "article-exist", "message" : "tokenId" } """ EXCHANGE = "auth" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url()) ) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='fanout') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json_serializer.body_to_dic(body.decode('utf-8')) if(len(json_serializer.validateSchema(EVENT, event)) > 0): return if (event["type"] == "logout"): security.invalidateSession(event["message"]) print("RabbitMQ Auth conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception: print("RabbitMQ Auth desconectado, intentando reconectar en 10'") Timer(10.0, initAuth).start()
def listen_auth(): """ Escucha eventos de logout provenientes de Auth para borrar tokens del cache. @api {fanout} auth/logout Logout @apiGroup RabbitMQ GET @apiDescription Escucha eventos de logout provenientes de Auth para borrar tokens del cache. @apiExample {json} Mensaje { "type": "article-exist", "message" : "tokenId" } """ exchange = "auth" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=exchange, exchange_type='fanout') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange=exchange, queue=queue_name) def callback(ch, method, properties, body): event = json.body_to_dic(body.decode('utf-8')) if len(validator.validateSchema(EVENT, event)) > 0: return if event["type"] == "logout": security.invalidate_session(event["message"]) print("RabbitMQ Auth conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception: print("RabbitMQ Auth desconectado, intentando reconectar en 10'") threading.Timer(10.0, init).start()
def sendLevelNotice(userId, levelId): print("entra a rabbit_service") """ Envía notificacion a Auth (User si existise) para informar que hay un cambio en el nivel level-data : Es una notificación al perfil del usuario informando el estado de su puntaje y su estado actual @api {direct} rewards/level-data Informar Cambio de Nivel @apiGroup RabbitMQ POST @apiDescription Enviá de mensajes level-updated. Informa el Nivel del Usuario @apiSuccessExample {json} Mensaje { "type": "level-updated", "message" : { "userId": "{userId}", "levelId": "{levelId}" } } """ connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() exchange = "rewards" channel.exchange_declare(exchange="rewards", exchange_type='direct') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue queue = queue_name message = { "type": "level-updated", "message": { "userId": userId, "levelId": levelId } } channel.basic_publish(exchange=exchange, routing_key="level-update", body=json.dic_to_json(message)) connection.close() print("RabbitMQ Cart POST level-updated uderId:%r , levelId:%r ")
def listen_catalog(): EXCHANGE = "catalog" QUEUE = "catalog" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url()) ) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='fanout') result = channel.queue_declare(QUEUE, durable=False) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json_serializer.body_to_dic(body.decode('utf-8')) if(len(validator.validateSchema(EVENT, event)) > 0): return if (event["type"] == "article-exist"): message = event.get('message') if(len(validator.validateSchema(MSG_ARTICLE_EXIST, message)) > 0): return article_id = message.get('articleId') print("RabbitMQ Catalog POST article-exist article_id: {}".format(article_id)) try: if not message['valid']: crud.del_price(article_id) except Exception: print('Cannot handle article-exist') print("RabbitMQ Catalog conectado") channel.basic_consume(queue_name, callback, auto_ack=True) channel.start_consuming() except Exception as inst: print(inst) print("RabbitMQ Catalog desconectado, intentando reconectar en 10'") Timer(10.0, initCatalog).start()
def send_new_score(id_article, score): """ Envía eventos cuando hay un nuevo score para un artículo @api {fanout} score/new_score Nuevo Score @apiGroup RabbitMQ POST @apiDescription Enviá mensajes de nuevo score @apiSuccessExample {json} Mensaje { "type": "new_score", "message" : { "id_article": "{id del articulo}", "score": {score promedio del articulo} } } """ exchange = "score" connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=exchange, exchange_type='fanout') message = { "type": "new_score", "message": { "id_article": id_article, "score": score, } } validator.validateSchema(MSG_NEW_SCORE, message) channel.basic_publish(exchange=exchange, routing_key='', body=json.dic_to_json(message)) connection.close() print("RabbitMQ Cart POST new_score id_article:%r", id_article)
def postTransactions(message): """ Postea eventos de notificacion acerca de transacciones de pagos @api {fanout} transactions/transaction_task_queue Post New Transaction @apiGroup RabbitMQ POST @apiDescription Postea transacciones recibidas a procesar @apiExample {json} Mensaje { "type": "transaction", "exchange" : "{''}" "queue" : "" "message" : { "amount":{Float}, "id_payment":{String}, "status":{String}, "external_reference":{String} } """ QUEUE = "transaction_task_queue" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.queue_declare(queue=QUEUE, durable=False) channel.basic_publish(exchange='', routing_key=QUEUE, body=json.dic_to_json(message), properties=pika.BasicProperties(delivery_mode=2)) connection.close() except Exception as err: print(err) print("Error enviando mensaje a " + QUEUE)
def send_new_discount(exchange, queue, type, discounts): connection = pika.BlockingConnection(pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=exchange, exchange_type='fanout') channel.queue_declare(queue = queue) message = { "type": type, "message": discounts } channel.basic_publish( exchange=exchange, routing_key=queue, body=json_serializer.dic_to_json(message) ) connection.close()
def sendStats(): EXCHANGE = "stats" QUEUE = "stats" connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='topic') channel.queue_declare(queue=QUEUE) channel.queue_bind(exchange=EXCHANGE, queue=QUEUE) message = service.sendRabbit() channel.basic_publish(exchange=EXCHANGE, routing_key=QUEUE, body=json.dic_to_json(message)) print("MENSAJE ENVIADO a la cola de stats") connection.close()
def listenOrder(): EXCHANGE = "stats" QUEUE = "order_placed" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url()) ) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='topic') result = channel.queue_declare(QUEUE) queue_name = result.method.queue channel.queue_bind(exchange=EXCHANGE, queue=queue_name) def callback(ch, method, properties, body): event = json.body_to_dic(body.decode('utf-8')) resp = service.saveOrders(event) ## Se recibe una orden y se calcula la estadistica y se guarda los articulos en la base de datos. statsService.sendStats()## Se envia a la cola de rabbit , luego de que se haya calculado la estadistica al recibir una orden. print("RabbitMQ Order conectado") channel.basic_consume(queue_name, callback ,auto_ack=True) channel.start_consuming() except Exception as e: print("RabbitMQ Order desconectado, intentando reconectar en 10") print(format(e)) threading.Timer(10.0, initOrder).start()
def send_msg_delete_article(articleId): """ Envía eventos a category """ """ Delete_article : Es un mensaje que avisa a category de la eliminación de un artículo. @api {direct} category/mensaje de eliminación de artículos @apiGroup RabbitMQ POST @apiDescription Enviá de mensajes Delete_article @apiSuccessExample {json} Mensaje { "type": "article-exist", "message" : { "articleId": "{articleId}", } """ connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange='category', exchange_type='direct') channel.queue_declare(queue='category') message = { "type": "Delete_article", "message": { "articleId": articleId, } } channel.basic_publish(exchange='category', routing_key='category', body=json.dic_to_json(message)) print("RabbitMQ Category DELETE article , articleId:%r", articleId) connection.close()
def listenOrder(): """ order-payed : Es una validación solicitada por Rewards para validar si hay una nueva orden pagada para acreditar los puntos @api {direct} order/order-payed Acreditar Puntos @apiGroup RabbitMQ GET @apiDescription Escucha de mensajes order-payed desde order. Acredita Puntos @apiExample {json} Mensaje { “type” : “order-payed", “exchange” : “{Exchange name to reply}” “queue” : “{Queue name to reply}” “message” : { “orderId” : "{orderId}”, "userId" : "{userId}", "amount" : {amount} } } """ try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange="sell_flow", exchange_type='topic') EXCHANGE = "sell_flow" result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue queue = queue_name binding_key = "order_payed" channel.queue_bind(exchange=EXCHANGE, queue=queue_name, routing_key=binding_key) def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) event = json.body_to_dic(body.decode('utf-8')) """if(len(validator.validateSchema(EVENT_CALLBACK, event)) > 0): return """ if (event["type"] == "order-payed"): message = event["message"] exchange = event["exchange"] queue = event["queue"] orderId = message["orderId"] userId = message["userId"] amount = message["amount"] print("RabbitMQ order-placed orderId:", orderId, "userId: ", userId, " amount= $", amount) crud.updateScore(userId, amount) print("Score Updated Succesfully") print("RabbitMQ Order Conectado") channel.basic_consume(queue, callback, consumer_tag=queue, auto_ack=True) channel.start_consuming() except Exception: traceback.print_exc() print("RabbitMQ Order desconectado")
def listenCatalog(): """ article-exist : Es una validación solicitada por Cart para validar si el articulo puede incluirse en el cart @api {direct} catalog/article-exist Validación de Articulos @apiGroup RabbitMQ GET @apiDescription Escucha de mensajes article-exist desde cart. Valida articulos @apiExample {json} Mensaje { "type": "article-exist", "exchange" : "{Exchange name to reply}" "queue" : "{Queue name to reply}" "message" : { "referenceId": "{referenceId}", "articleId": "{articleId}", } """ """ article-data : Es una validación solicitada por Cart para validar si el articulo puede incluirse en el cart @api {direct} catalog/article-exist Validación de Articulos @apiGroup RabbitMQ GET @apiDescription Escucha de mensajes article-data desde cart. Valida articulos @apiExample {json} Mensaje { "type": "article-exist", "exchange" : "{Exchange name to reply}" "queue" : "{Queue name to reply}" "message" : { "referenceId": "{referenceId}", "articleId": "{articleId}", } """ EXCHANGE = "catalog" QUEUE = "catalog" try: connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange=EXCHANGE, exchange_type='direct') channel.queue_declare(queue=QUEUE) channel.queue_bind(queue=QUEUE, exchange=EXCHANGE, routing_key=QUEUE) def callback(ch, method, properties, body): event = json.body_to_dic(body.decode('utf-8')) if (len(validator.validateSchema(EVENT_CALLBACK, event)) > 0): return if (event["type"] == "article-exist"): message = event["message"] if (len(validator.validateSchema(MSG_ARTICLE_EXIST, message)) > 0): return exchange = event["exchange"] queue = event["queue"] referenceId = message["referenceId"] articleId = message["articleId"] print( "RabbitMQ Catalog GET article-exist catalogId:%r , articleId:%r", referenceId, articleId) try: articleValidation.validateArticleExist(articleId) sendArticleValid(exchange, queue, referenceId, articleId, True) except Exception: sendArticleValid(exchange, queue, referenceId, articleId, False) if (event["type"] == "article-data"): message = event["message"] if (len(validator.validateSchema(MSG_ARTICLE_EXIST, message)) > 0): return exchange = event["exchange"] queue = event["queue"] referenceId = message["referenceId"] articleId = message["articleId"] print( "RabbitMQ Catalog GET article-data catalogId:%r , articleId:%r", referenceId, articleId) try: article = crud.getArticle(articleId) valid = ("enabled" in article and article["enabled"]) stock = article["stock"] price = article["price"] articleValidation.validateArticleExist(articleId) sendArticleData(exchange, queue, referenceId, articleId, valid, stock, price) except Exception: sendArticleData(exchange, queue, referenceId, articleId, False, 0, 0) print("RabbitMQ Catalog conectado") channel.basic_consume(QUEUE, callback, consumer_tag=QUEUE, auto_ack=True) channel.start_consuming() except Exception: traceback.print_exc() print("RabbitMQ Catalog desconectado, intentando reconectar en 10'") threading.Timer(10.0, initCatalog).start()
def send_msg_update_article(article): """ Envía eventos a category """ """ update_article : Es un mensaje que avisa a category de la modificación de un artículo. @api {direct} category/mensaje de modificación de artículos @apiGroup RabbitMQ POST @apiDescription Enviá mensajes Update_article @apiSuccessExample {json} Mensaje { "type": "Update_article", "message": { "articleId": article["_id"], "name": article["name"], "description": article["description"], "image": article["image"], "price": article["price"], "stock": article["stock"], "updated":article["updated"] } } """ connection = pika.BlockingConnection( pika.ConnectionParameters(host=config.get_rabbit_server_url())) channel = connection.channel() channel.exchange_declare(exchange='category', exchange_type='direct') channel.queue_declare(queue='category') articleId = article["_id"] name = article["name"] description = article["description"] image = article["image"] price = article["price"] stock = article["stock"] updated = article["updated"] created = article["created"] enabled = article["enabled"] message = { "type": "Updated_article", "message": { "articleId": articleId, "name": name, "description": description, "image": image, "price": price, "stock": stock, "updated": updated, "created": created, "enabled": enabled } } channel.basic_publish(exchange='category', routing_key='category', body=json.dic_to_json(message)) print("RabbitMQ Category UPDATE article , articleId:%r", article["_id"]) connection.close()