"""Connector for ows-manual-adjustment microservice.""" import functools import time from owsrequest import request as requests from accounting.flows.reserve_payouts import connectors from accounting.flows.reserve_payouts import setting from accounting.flows.reserve_payouts.constants import ows_manual_adjustment def health_check(): """Do the health check for ows-manual-adjustment micro-service. Returns: namedtuple: with bool and message attributes, (True, '') if connection is ok, (False, 'Error message') otherwise. """ response = requests.process( application=setting.APP_NAME, environment=setting.ENVIRONMENT, method='GET', service_name=setting.OWS_MANUAL_ADJUSTMENT, path='/health') if response.status_code == 200: result = connectors.HealthCheckResult(True, '') else: text = response.text or '{}: {}'.format( response.status_code, response.reason) result = connectors.HealthCheckResult(False, text) return result def request_with_retry(req, num_retries=1): """Execute the request and retry if response status code in 502, 503, 504. Args: req (func): partial request.process function with all the arguments num_retries (int): number of retries Returns: Response: the Requests response from ows-manual-adjustment """ for i in range(num_retries): response = req() if response.status_code in setting.HTTP_CODES_TO_RETRY: time.sleep(setting.OWS_MANUAL_ADJUSTMENT_TIME_TO_SLEEP * i) continue break return response def post_manual_adjustment(request_data): """Do a POST request to /manual-adjustment endpoint. Args: request_data (dict): request payload Returns: Response: the Requests response from ows-manual-adjustment """ category_id = request_data['category_id'] request_data.update({ 'parent_type': ows_manual_adjustment.PARENT_TYPE, 'comment': ows_manual_adjustment.COMMENT_MAP[category_id], 'created_by': ows_manual_adjustment.CREATED_BY_USER_ID, }) post_request = functools.partial( requests.process, application=setting.APP_NAME, environment=setting.ENVIRONMENT, method='POST', service_name=setting.OWS_MANUAL_ADJUSTMENT, path=ows_manual_adjustment.MANUAL_ADJUSTMENT_ENDPOINT, json=request_data) response = request_with_retry( post_request, setting.OWS_MANUAL_ADJUSTMENT_NUM_RETRIES) return response