|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +""" |
| 4 | +Batch SQS utilities |
| 5 | +""" |
| 6 | +from typing import List, Optional, Tuple |
| 7 | + |
| 8 | +import boto3 |
| 9 | +from botocore.config import Config |
| 10 | + |
| 11 | +from .base import BasePartialProcessor |
| 12 | + |
| 13 | + |
| 14 | +class PartialSQSProcessor(BasePartialProcessor): |
| 15 | + """ |
| 16 | + Amazon SQS batch processor to delete successes from the Queue. |
| 17 | +
|
| 18 | + Only the **special** case of partial failure is handled, thus a batch in |
| 19 | + which all records failed is **not** going to be removed from the queue, and |
| 20 | + the same is valid for a full success. |
| 21 | +
|
| 22 | + Parameters |
| 23 | + ---------- |
| 24 | + config: Config |
| 25 | + botocore config object |
| 26 | +
|
| 27 | + Example |
| 28 | + ------- |
| 29 | + **Process batch triggered by SQS** |
| 30 | +
|
| 31 | + >>> from aws_lambda_powertools.utilities.batch import PartialSQSProcessor |
| 32 | + >>> |
| 33 | + >>> def record_handler(record): |
| 34 | + >>> return record["body"] |
| 35 | + >>> |
| 36 | + >>> def handler(event, context): |
| 37 | + >>> records = event["Records"] |
| 38 | + >>> processor = PartialSQSProcessor() |
| 39 | + >>> |
| 40 | + >>> with processor(records=records, handler=record_handler): |
| 41 | + >>> result = processor.process() |
| 42 | + >>> |
| 43 | + >>> # Case a partial failure occurred, all successful executions |
| 44 | + >>> # have been deleted from the queue after context's exit. |
| 45 | + >>> |
| 46 | + >>> return result |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, config: Optional[Config] = None): |
| 50 | + """ |
| 51 | + Initializes sqs client. |
| 52 | + """ |
| 53 | + config = config or Config() |
| 54 | + self.client = boto3.client("sqs", config=config) |
| 55 | + |
| 56 | + super().__init__() |
| 57 | + |
| 58 | + def _get_queue_url(self) -> str: |
| 59 | + """ |
| 60 | + Format QueueUrl from first records entry |
| 61 | + """ |
| 62 | + if not getattr(self, "records", None): |
| 63 | + return |
| 64 | + |
| 65 | + *_, account_id, queue_name = self.records[0]["eventSourceARN"].split(":") |
| 66 | + return f"{self.client._endpoint.host}/{account_id}/{queue_name}" |
| 67 | + |
| 68 | + def _get_entries_to_clean(self) -> List: |
| 69 | + """ |
| 70 | + Format messages to use in batch deletion |
| 71 | + """ |
| 72 | + return [{"Id": msg["messageId"], "ReceiptHandle": msg["receiptHandle"]} for msg in self.success_messages] |
| 73 | + |
| 74 | + def _process_record(self, record) -> Tuple: |
| 75 | + """ |
| 76 | + Process a record with instance's handler |
| 77 | +
|
| 78 | + Parameters |
| 79 | + ---------- |
| 80 | + record: Any |
| 81 | + An object to be processed. |
| 82 | + """ |
| 83 | + try: |
| 84 | + result = self.handler(record) |
| 85 | + return self.success_handler(record, result) |
| 86 | + except Exception as exc: |
| 87 | + return self.failure_handler(record, exc) |
| 88 | + |
| 89 | + def _prepare(self): |
| 90 | + """ |
| 91 | + Remove results from previous execution. |
| 92 | + """ |
| 93 | + self.success_messages.clear() |
| 94 | + self.fail_messages.clear() |
| 95 | + |
| 96 | + def _clean(self): |
| 97 | + """ |
| 98 | + Delete messages from Queue in case of partial failure. |
| 99 | + """ |
| 100 | + if not (self.fail_messages and self.success_messages): |
| 101 | + return |
| 102 | + |
| 103 | + queue_url = self._get_queue_url() |
| 104 | + entries_to_remove = self._get_entries_to_clean() |
| 105 | + |
| 106 | + return self.client.delete_message_batch(QueueUrl=queue_url, Entries=entries_to_remove) |
0 commit comments