|
| 1 | +from io import BytesIO |
| 2 | +from logging import getLogger |
| 3 | +from time import sleep |
| 4 | + |
| 5 | +import boto3 |
| 6 | +import ujson |
| 7 | + |
| 8 | +class Importer: |
| 9 | + def __init__(self, queue_name: str, region: str = "us-east-1"): |
| 10 | + self.queue_name = queue_name |
| 11 | + self.session = boto3.Session(region_name=region) |
| 12 | + self.sqs_client = self.session.client("sqs") |
| 13 | + self.s3_client = self.session.client("s3") |
| 14 | + self.sqs_queue_url = self.sqs_client.get_queue_url(QueueName=self.queue_name) |
| 15 | + self.logger = getLogger(self.__class__.__name__) |
| 16 | + |
| 17 | + def run(self): |
| 18 | + while True: |
| 19 | + resp = self.sqs_client.receive_message( |
| 20 | + QueueUrl=self.sqs_queue_url, |
| 21 | + MaxNumberOfMessages=1, # retrieve one message at a time - we could up this and parallelize but no point until way more files. |
| 22 | + VisibilityTimeout=600, # 10 minutes to process message before it becomes visible for another consumer. |
| 23 | + ) |
| 24 | + # if no messages found, wait 5m for next poll |
| 25 | + if len(resp["Messages"]) == 0: |
| 26 | + sleep(600) |
| 27 | + continue |
| 28 | + |
| 29 | + for message in resp["Messages"]: |
| 30 | + sqs_body = ujson.loads(message["Body"]) |
| 31 | + for record in sqs_body["Records"]: # this comes through as a list, but we expect one object |
| 32 | + bucket_name = record["s3"]["bucket"]["name"] |
| 33 | + key = record["s3"]["object"]["key"] |
| 34 | + with BytesIO() as fileobj: |
| 35 | + self.s3_client.download_fileobj(bucket_name, key, fileobj) |
| 36 | + fileobj.seek(0) |
| 37 | + content = fileobj.read() |
| 38 | + |
| 39 | + # TODO: we now have an in-memory copy of the s3 file content. This is where we would run the import. |
| 40 | + # we want a standardized importer class; we would call something like below: |
| 41 | + # loader = Loader(content).load() |
| 42 | + |
| 43 | + self.logger.info(f"Imported s3://{bucket_name}/{key}") |
| 44 | + |
| 45 | +class Loader: |
| 46 | + def __init__(self, content: bytes): |
| 47 | + self.content = content |
| 48 | + |
| 49 | + def load(self): |
| 50 | + raise Exception("unimplemented; extend this class to write a load migration.") |
0 commit comments