2016-09-22 17:18:05 +01:00
|
|
|
import json
|
2016-02-17 12:57:51 +00:00
|
|
|
import logging
|
2016-06-01 15:24:19 +01:00
|
|
|
|
2018-05-04 10:55:58 +01:00
|
|
|
from time import monotonic
|
2016-09-22 17:18:05 +01:00
|
|
|
from requests import request, RequestException
|
2016-06-01 15:24:19 +01:00
|
|
|
|
2016-09-22 17:18:05 +01:00
|
|
|
from app.clients.sms import (SmsClient, SmsClientResponseException)
|
2016-02-17 12:57:51 +00:00
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2016-04-05 14:39:59 +01:00
|
|
|
|
2016-05-27 12:28:58 +01:00
|
|
|
# Firetext will send a delivery receipt with three different status codes.
|
|
|
|
|
# The `firetext_response` maps these codes to the notification statistics status and notification status.
|
|
|
|
|
# If we get a pending (status = 2) delivery receipt followed by a declined (status = 1) delivery receipt we will set
|
|
|
|
|
# the notification status to temporary-failure rather than permanent failure.
|
|
|
|
|
# See the code in the notification_dao.update_notifications_status_by_id
|
2016-04-06 14:31:33 +01:00
|
|
|
firetext_responses = {
|
2018-02-07 17:49:15 +00:00
|
|
|
'0': 'delivered',
|
|
|
|
|
'1': 'permanent-failure',
|
|
|
|
|
'2': 'pending'
|
2016-04-06 14:31:33 +01:00
|
|
|
}
|
2016-04-05 14:39:59 +01:00
|
|
|
|
2020-04-09 17:50:05 +01:00
|
|
|
firetext_codes = {
|
2020-04-21 13:30:42 +01:00
|
|
|
# code '000' means 'No errors reported'
|
2020-04-20 18:20:01 +01:00
|
|
|
'101': {'status': 'permanent-failure', 'reason': 'Unknown Subscriber'},
|
|
|
|
|
'102': {'status': 'temporary-failure', 'reason': 'Absent Subscriber'},
|
|
|
|
|
'103': {'status': 'temporary-failure', 'reason': 'Subscriber Busy'},
|
|
|
|
|
'104': {'status': 'temporary-failure', 'reason': 'No Subscriber Memory'},
|
|
|
|
|
'201': {'status': 'permanent-failure', 'reason': 'Invalid Number'},
|
|
|
|
|
'301': {'status': 'permanent-failure', 'reason': 'SMS Not Supported'},
|
|
|
|
|
'302': {'status': 'temporary-failure', 'reason': 'SMS Not Supported'},
|
|
|
|
|
'401': {'status': 'permanent-failure', 'reason': 'Message Rejected'},
|
|
|
|
|
'900': {'status': 'temporary-failure', 'reason': 'Routing Error'},
|
2020-04-09 17:50:05 +01:00
|
|
|
}
|
|
|
|
|
|
2016-04-06 14:31:33 +01:00
|
|
|
|
2020-06-01 11:45:35 +01:00
|
|
|
def get_firetext_responses(status, detailed_status_code=None):
|
|
|
|
|
detailed_status = firetext_codes[detailed_status_code]['reason'] if firetext_codes.get(
|
|
|
|
|
detailed_status_code, None
|
|
|
|
|
) else None
|
|
|
|
|
return (firetext_responses[status], detailed_status)
|
2016-03-15 14:40:42 +00:00
|
|
|
|
|
|
|
|
|
2020-06-01 11:45:35 +01:00
|
|
|
def get_message_status_and_reason_from_firetext_code(detailed_status_code):
|
|
|
|
|
return firetext_codes[detailed_status_code]['status'], firetext_codes[detailed_status_code]['reason']
|
2020-04-09 17:50:05 +01:00
|
|
|
|
|
|
|
|
|
2016-09-22 17:18:05 +01:00
|
|
|
class FiretextClientResponseException(SmsClientResponseException):
|
|
|
|
|
def __init__(self, response, exception):
|
2017-04-05 15:31:37 +01:00
|
|
|
status_code = response.status_code if response is not None else 504
|
|
|
|
|
text = response.text if response is not None else "Gateway Time-out"
|
|
|
|
|
self.status_code = status_code
|
|
|
|
|
self.text = text
|
2016-09-22 17:18:05 +01:00
|
|
|
self.exception = exception
|
2016-03-10 13:22:45 +00:00
|
|
|
|
|
|
|
|
def __str__(self):
|
2016-09-22 17:18:05 +01:00
|
|
|
return "Code {} text {} exception {}".format(self.status_code, self.text, str(self.exception))
|
2016-02-17 12:57:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class FiretextClient(SmsClient):
|
|
|
|
|
'''
|
|
|
|
|
FireText sms client.
|
|
|
|
|
'''
|
|
|
|
|
|
2016-06-01 15:24:19 +01:00
|
|
|
def init_app(self, current_app, statsd_client, *args, **kwargs):
|
2016-02-17 12:57:51 +00:00
|
|
|
super(SmsClient, self).__init__(*args, **kwargs)
|
2016-06-01 15:24:19 +01:00
|
|
|
self.current_app = current_app
|
|
|
|
|
self.api_key = current_app.config.get('FIRETEXT_API_KEY')
|
2016-06-06 09:49:51 +01:00
|
|
|
self.from_number = current_app.config.get('FROM_NUMBER')
|
2016-02-25 11:23:04 +00:00
|
|
|
self.name = 'firetext'
|
2019-04-12 12:03:58 +01:00
|
|
|
self.url = current_app.config.get('FIRETEXT_URL')
|
2016-05-13 17:15:39 +01:00
|
|
|
self.statsd_client = statsd_client
|
2016-02-25 11:23:04 +00:00
|
|
|
|
|
|
|
|
def get_name(self):
|
|
|
|
|
return self.name
|
2016-02-17 12:57:51 +00:00
|
|
|
|
2016-09-22 17:18:05 +01:00
|
|
|
def record_outcome(self, success, response):
|
2017-04-05 15:31:37 +01:00
|
|
|
status_code = response.status_code if response else 503
|
|
|
|
|
|
2016-09-23 10:24:12 +01:00
|
|
|
log_message = "API {} request {} on {} response status_code {}".format(
|
2016-09-22 17:18:05 +01:00
|
|
|
"POST",
|
|
|
|
|
"succeeded" if success else "failed",
|
|
|
|
|
self.url,
|
2017-04-05 15:31:37 +01:00
|
|
|
status_code
|
2016-09-22 17:18:05 +01:00
|
|
|
)
|
|
|
|
|
|
2016-09-23 15:59:23 +01:00
|
|
|
if success:
|
2016-09-22 17:18:05 +01:00
|
|
|
self.current_app.logger.info(log_message)
|
|
|
|
|
self.statsd_client.incr("clients.firetext.success")
|
2016-09-23 15:59:23 +01:00
|
|
|
else:
|
|
|
|
|
self.statsd_client.incr("clients.firetext.error")
|
2021-01-18 15:43:50 +00:00
|
|
|
self.current_app.logger.warning(log_message)
|
2016-09-22 17:18:05 +01:00
|
|
|
|
2016-07-01 14:06:32 +01:00
|
|
|
def send_sms(self, to, content, reference, sender=None):
|
2016-02-17 12:57:51 +00:00
|
|
|
|
|
|
|
|
data = {
|
|
|
|
|
"apiKey": self.api_key,
|
2016-07-01 14:06:32 +01:00
|
|
|
"from": self.from_number if sender is None else sender,
|
2016-02-17 12:57:51 +00:00
|
|
|
"to": to.replace('+', ''),
|
2016-03-10 15:51:11 +00:00
|
|
|
"message": content,
|
|
|
|
|
"reference": reference
|
2016-02-17 12:57:51 +00:00
|
|
|
}
|
|
|
|
|
|
add raw request timings to provider send functions
we're using statsd to monitor how long provider requests are taking.
However, there's lots of busy work that happens inside our statsd
metrics timing window. Things like json dumping and loading, building
headers, exception handling, etc.
for firetext/mmg, the response object from requests has an elapsed
property [1], which captures from sending raw data to parsing the
response headers. for ses, it's a bit trickier, but boto3 exposes a few
event hooks [2]. it's hard to find them without stepping through the
code, but the interesting ones are before-call, after-call,
after-call-error, request-created, and response-received. The
before-call and after-call involve some marshalling, built-in retrying,
etc, while request-created and response-received are much lower level.
They might be called more than once per ses request, if boto3 itself
retries the request on 5xx, 429 and low level socket errors [3].
Add these as new `raw-request-time` metrics rather than overwriting to
avoid changing the meaning of an existing metric, and to let us compare
the metrics to see if there's a noticeable difference at all
[1] https://requests.readthedocs.io/en/master/api/#requests.Response.elapsed
[2] https://boto3.amazonaws.com/v1/documentation/api/latest/guide/events.html
[3] https://boto3.amazonaws.com/v1/documentation/api/latest/guide/retries.html#legacy-retry-mode
2020-05-29 13:56:29 +01:00
|
|
|
response = None
|
2016-03-10 13:22:45 +00:00
|
|
|
start_time = monotonic()
|
2016-02-17 12:57:51 +00:00
|
|
|
try:
|
|
|
|
|
response = request(
|
|
|
|
|
"POST",
|
2016-09-22 17:18:05 +01:00
|
|
|
self.url,
|
2017-04-04 16:05:25 +01:00
|
|
|
data=data,
|
|
|
|
|
timeout=60
|
2016-02-17 12:57:51 +00:00
|
|
|
)
|
|
|
|
|
response.raise_for_status()
|
2016-09-22 17:18:05 +01:00
|
|
|
try:
|
|
|
|
|
json.loads(response.text)
|
|
|
|
|
if response.json()['code'] != 0:
|
|
|
|
|
raise ValueError()
|
|
|
|
|
except (ValueError, AttributeError) as e:
|
|
|
|
|
self.record_outcome(False, response)
|
|
|
|
|
raise FiretextClientResponseException(response=response, exception=e)
|
|
|
|
|
self.record_outcome(True, response)
|
2016-02-17 12:57:51 +00:00
|
|
|
except RequestException as e:
|
2016-09-22 17:18:05 +01:00
|
|
|
self.record_outcome(False, e.response)
|
|
|
|
|
raise FiretextClientResponseException(response=e.response, exception=e)
|
2016-03-02 09:33:20 +00:00
|
|
|
finally:
|
|
|
|
|
elapsed_time = monotonic() - start_time
|
2016-12-20 13:24:08 +00:00
|
|
|
self.current_app.logger.info("Firetext request for {} finished in {}".format(reference, elapsed_time))
|
2016-08-08 11:23:58 +01:00
|
|
|
self.statsd_client.timing("clients.firetext.request-time", elapsed_time)
|
add raw request timings to provider send functions
we're using statsd to monitor how long provider requests are taking.
However, there's lots of busy work that happens inside our statsd
metrics timing window. Things like json dumping and loading, building
headers, exception handling, etc.
for firetext/mmg, the response object from requests has an elapsed
property [1], which captures from sending raw data to parsing the
response headers. for ses, it's a bit trickier, but boto3 exposes a few
event hooks [2]. it's hard to find them without stepping through the
code, but the interesting ones are before-call, after-call,
after-call-error, request-created, and response-received. The
before-call and after-call involve some marshalling, built-in retrying,
etc, while request-created and response-received are much lower level.
They might be called more than once per ses request, if boto3 itself
retries the request on 5xx, 429 and low level socket errors [3].
Add these as new `raw-request-time` metrics rather than overwriting to
avoid changing the meaning of an existing metric, and to let us compare
the metrics to see if there's a noticeable difference at all
[1] https://requests.readthedocs.io/en/master/api/#requests.Response.elapsed
[2] https://boto3.amazonaws.com/v1/documentation/api/latest/guide/events.html
[3] https://boto3.amazonaws.com/v1/documentation/api/latest/guide/retries.html#legacy-retry-mode
2020-05-29 13:56:29 +01:00
|
|
|
if response and hasattr(response, 'elapsed'):
|
|
|
|
|
self.statsd_client.timing("clients.firetext.raw-request-time", response.elapsed.total_seconds())
|
2016-02-17 12:57:51 +00:00
|
|
|
return response
|