"""Connector for work with aws simple queue service.""" import base64 import json import boto3 from botocore.exceptions import ClientError from flask import g from oto import response from project_manager.constant import error_const def put_message_to_sqs( queue_name, payload, region='us-east-1', orchard_user_id=None): """Put message to SQS queue. Args: queue_name (str): name of sqs queue which should receive message. payload (dict): body of sqs message. region (str): (optional) aws region which should be used. orchard_user_id (str): (optional) orchard user id. Returns: oto.Response: response with error or job id. """ try: client = boto3.client('sqs', region_name=region) sqs_queue_url = client.get_queue_url( QueueName=queue_name).get('QueueUrl') payload_value = json.dumps(payload) payload_value = base64.b64encode( payload_value.encode('utf-8')).decode('utf-8') message_attributes = { 'Correlation-Id': { 'StringValue': g.ows.correlation_id, 'DataType': 'String'}} # add user context which will be used by daemons to check # the feature flags if orchard_user_id: message_attributes.update( { 'feature_flag_user_context': { 'StringValue': orchard_user_id, 'DataType': 'String'} }) client.send_message( QueueUrl=sqs_queue_url, MessageBody=payload_value, MessageAttributes=message_attributes) return response.Response() except ClientError as e: status = e.response['ResponseMetadata']['HTTPStatusCode'] return response.create_error_response( code=error_const.SQS_ERROR, status=status, message=str(e) )