|
| 1 | +from itertools import chain |
| 2 | +from ddtrace._trace.utils_botocore.span_pointers import _aws_s3_object_span_pointer_description |
| 3 | +from ddtrace._trace._span_pointer import _SpanPointerDirection |
| 4 | +from ddtrace._trace._span_pointer import _SpanPointerDescription |
| 5 | +from datadog_lambda.trigger import EventTypes |
| 6 | +import logging |
| 7 | + |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def calculate_span_pointers( |
| 13 | + event_source, |
| 14 | + event, |
| 15 | +) -> list[_SpanPointerDescription]: |
| 16 | + if event_source.equals(EventTypes.S3): |
| 17 | + return _calculate_s3_span_pointers_for_event(event) |
| 18 | + |
| 19 | + return [] |
| 20 | + |
| 21 | + |
| 22 | +def _calculate_s3_span_pointers_for_event(event) -> list[_SpanPointerDescription]: |
| 23 | + # Example event: |
| 24 | + # https://docs.aws.amazon.com/lambda/latest/dg/with-s3.html |
| 25 | + |
| 26 | + return list( |
| 27 | + chain.from_iterable( |
| 28 | + _calculate_s3_span_pointers_for_event_record(record) |
| 29 | + for record in event.get("Records", []) |
| 30 | + ) |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +def _calculate_s3_span_pointers_for_event_record(record) -> list[_SpanPointerDescription]: |
| 35 | + # Event types: |
| 36 | + # https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html |
| 37 | + |
| 38 | + if record.get("eventName").startswith("ObjectCreated:"): |
| 39 | + s3_information = record.get("s3", None) |
| 40 | + if s3_information is not None: |
| 41 | + return _calculate_s3_span_pointers_for_object_created_s3_information(s3_information) |
| 42 | + |
| 43 | + return [] |
| 44 | + |
| 45 | + |
| 46 | +def _calculate_s3_span_pointers_for_object_created_s3_information(s3_information) -> list[_SpanPointerDescription]: |
| 47 | + try: |
| 48 | + bucket = s3_information["bucket"]["name"] |
| 49 | + key = s3_information["object"]["key"] |
| 50 | + etag = s3_information["object"]["eTag"] |
| 51 | + |
| 52 | + except KeyError as e: |
| 53 | + logger.warning( |
| 54 | + "missing s3 information required to make a span pointer: %s", |
| 55 | + str(e), |
| 56 | + ) |
| 57 | + return [] |
| 58 | + |
| 59 | + try: |
| 60 | + return [ |
| 61 | + _aws_s3_object_span_pointer_description( |
| 62 | + pointer_direction=_SpanPointerDirection.UPSTREAM, |
| 63 | + bucket=bucket, |
| 64 | + key=key, |
| 65 | + etag=etag, |
| 66 | + ) |
| 67 | + ] |
| 68 | + |
| 69 | + except Exception as e: |
| 70 | + logger.warning( |
| 71 | + "failed to generate S3 span pointer: %s", |
| 72 | + str(e), |
| 73 | + ) |
| 74 | + return [] |
0 commit comments