"""Long running process that processes messages in SQS.""" from availability import config from availability.connectors import loggly from availability.connectors.sqs import JSONMessageExt from availability.constants import models from availability.logic import polling from availability.models import task logger = loggly.get_current_logger() def process_messages(queue): """Infinite loop that constantly checks for new messages. Args: queue (boto3.sqs.Queue): Instance of Amazon SQS. """ for message_number in range(config.SQS_NUM_MESSAGES_TO_PROCESS): message = queue.receive_messages( WaitTimeSeconds=config.SQS_WAIT_TIME_SECONDS, VisibilityTimeout=config.SQS_MESSAGE_VISIBILITY_TIMEOUT_SECONDS) if not message: continue single_message = JSONMessageExt(message[0]) message_dict = single_message.get_body() logger.info('Message received: {}'.format(message_dict)) single_message.delete() process_single_message(message_dict) def process_single_message(message): """Process message from SQS by invoking all required functions. Args: message (dict): Dict with attributes required to update product status. """ task.change_status( message['product_in_store_id'], models.TASK_STATUS_PROCESSING) logger.info('Task status set to processing') try: polling.update_product_status(**message) except Exception: logger.exception('Exception while updating product status') task_change_result = task.change_status( message['product_in_store_id'], models.TASK_STATUS_FAILED) logger.info('Task status set to failed') else: task_change_result = task.change_status( message['product_in_store_id'], models.TASK_STATUS_OK) logger.info('Task status set to ok') assert task_change_result, task_change_result.errors