|
| 1 | +""" |
| 2 | +A script to receive messages in the waveform queue and write them to stdout, |
| 3 | +based on https://www.rabbitmq.com/tutorials/tutorial-one-python |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +from datetime import datetime, timezone |
| 8 | +import logging |
| 9 | +import pika |
| 10 | +import db as db # type:ignore |
| 11 | +import settings as settings # type:ignore |
| 12 | +import csv_writer as writer # type:ignore |
| 13 | + |
| 14 | +logging.basicConfig(format="%(levelname)s:%(asctime)s: %(message)s") |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +emap_db = db.starDB() |
| 19 | +emap_db.init_query() |
| 20 | +emap_db.connect() |
| 21 | + |
| 22 | + |
| 23 | +class waveform_message: |
| 24 | + def __init__(self, ch, delivery_tag, body): |
| 25 | + self.ch = ch |
| 26 | + self.delivery_tag = delivery_tag |
| 27 | + self.body = body |
| 28 | + |
| 29 | + |
| 30 | +def ack_message(ch, delivery_tag): |
| 31 | + """Note that `ch` must be the same pika channel instance via which the |
| 32 | + message being ACKed was retrieved (AMQP protocol constraint).""" |
| 33 | + if ch.is_open: |
| 34 | + ch.basic_ack(delivery_tag) |
| 35 | + else: |
| 36 | + logger.warning("Attempting to acknowledge a message on a closed channel.") |
| 37 | + |
| 38 | + |
| 39 | +def reject_message(ch, delivery_tag, requeue): |
| 40 | + if ch.is_open: |
| 41 | + ch.basic_reject(delivery_tag, requeue) |
| 42 | + else: |
| 43 | + logger.warning("Attempting to not acknowledge a message on a closed channel.") |
| 44 | + |
| 45 | + |
| 46 | +def waveform_callback(ch, method_frame, _header_frame, body): |
| 47 | + data = json.loads(body) |
| 48 | + try: |
| 49 | + location_string = data["mappedLocationString"] |
| 50 | + observation_timestamp = data["observationTime"] |
| 51 | + source_stream_id = data["sourceStreamId"] |
| 52 | + sampling_rate = data["samplingRate"] |
| 53 | + units = data["unit"] |
| 54 | + waveform_data = data["numericValues"] |
| 55 | + mapped_location_string = data["mappedLocationString"] |
| 56 | + except IndexError as e: |
| 57 | + reject_message(ch, method_frame.delivery_tag, False) |
| 58 | + logger.error( |
| 59 | + f"Waveform message {method_frame.delivery_tag} is missing required data {e}." |
| 60 | + ) |
| 61 | + return |
| 62 | + |
| 63 | + observation_time = datetime.fromtimestamp(observation_timestamp, tz=timezone.utc) |
| 64 | + lookup_success = True |
| 65 | + try: |
| 66 | + matched_mrn = emap_db.get_row(location_string, observation_time) |
| 67 | + except ValueError as e: |
| 68 | + lookup_success = False |
| 69 | + logger.error(f"Ambiguous or non existent match: {e}") |
| 70 | + matched_mrn = ("unmatched_mrn", "unmatched_nhs", "unmatched_csn") |
| 71 | + except ConnectionError as e: |
| 72 | + logger.error(f"Database error, will try again: {e}") |
| 73 | + reject_message(ch, method_frame.delivery_tag, True) |
| 74 | + return |
| 75 | + |
| 76 | + if writer.write_frame( |
| 77 | + waveform_data, |
| 78 | + source_stream_id, |
| 79 | + observation_timestamp, |
| 80 | + units, |
| 81 | + sampling_rate, |
| 82 | + mapped_location_string, |
| 83 | + matched_mrn[2], |
| 84 | + matched_mrn[0], |
| 85 | + ): |
| 86 | + if lookup_success: |
| 87 | + ack_message(ch, method_frame.delivery_tag) |
| 88 | + else: |
| 89 | + reject_message(ch, method_frame.delivery_tag, False) |
| 90 | + |
| 91 | + |
| 92 | +def receiver(): |
| 93 | + # set up database connection |
| 94 | + rabbitmq_credentials = pika.PlainCredentials( |
| 95 | + username=settings.RABBITMQ_USERNAME, password=settings.RABBITMQ_PASSWORD |
| 96 | + ) |
| 97 | + connection_parameters = pika.ConnectionParameters( |
| 98 | + credentials=rabbitmq_credentials, |
| 99 | + host=settings.RABBITMQ_HOST, |
| 100 | + port=settings.RABBITMQ_PORT, |
| 101 | + ) |
| 102 | + connection = pika.BlockingConnection(connection_parameters) |
| 103 | + channel = connection.channel() |
| 104 | + channel.basic_qos(prefetch_count=1) |
| 105 | + |
| 106 | + channel.basic_consume( |
| 107 | + queue=settings.RABBITMQ_QUEUE, |
| 108 | + auto_ack=False, |
| 109 | + on_message_callback=waveform_callback, |
| 110 | + ) |
| 111 | + try: |
| 112 | + channel.start_consuming() |
| 113 | + except KeyboardInterrupt: |
| 114 | + channel.stop_consuming() |
| 115 | + |
| 116 | + connection.close() |
0 commit comments