|
| 1 | +import json |
1 | 2 | import re |
2 | 3 | from typing import TYPE_CHECKING |
3 | 4 | from urllib.parse import unquote, urlsplit |
|
7 | 8 | from sentry_sdk.integrations.boto3._utils import ( |
8 | 9 | _get_aws_arn_attributes, |
9 | 10 | _get_batch_error_type, |
| 11 | + _inject_message_attributes, |
10 | 12 | ) |
11 | | -from sentry_sdk.traces import SpanStatus |
| 13 | +from sentry_sdk.traces import ( |
| 14 | + BAGGAGE_HEADER_NAME, |
| 15 | + SENTRY_TRACE_HEADER_NAME, |
| 16 | + NoOpSpan, |
| 17 | + SpanStatus, |
| 18 | +) |
| 19 | +from sentry_sdk.tracing_utils import extract_sentrytrace_data |
12 | 20 | from sentry_sdk.utils import capture_internal_exceptions |
13 | 21 |
|
14 | 22 | if TYPE_CHECKING: |
15 | | - from typing import Any, Optional |
| 23 | + from typing import Any, Dict, Optional, Tuple |
16 | 24 |
|
17 | | - from sentry_sdk._types import Attributes |
| 25 | + from sentry_sdk._types import Attributes, SpanLink |
18 | 26 | from sentry_sdk.integrations.boto3._context import AwsCallContext |
19 | 27 | from sentry_sdk.traces import Span |
20 | 28 |
|
|
28 | 36 | } |
29 | 37 |
|
30 | 38 |
|
| 39 | +def _message_link(message: "Dict[str, Any]") -> "Optional[SpanLink]": |
| 40 | + # message was sent straight to SQS, or through SNS with raw message delivery on. |
| 41 | + sentry_trace = ( |
| 42 | + message.get("MessageAttributes", {}) |
| 43 | + .get(SENTRY_TRACE_HEADER_NAME, {}) |
| 44 | + .get("StringValue") |
| 45 | + ) |
| 46 | + |
| 47 | + # SNS wraps the message and its attributes in a JSON envelope when raw message delivery is off. |
| 48 | + # https://docs.aws.amazon.com/sns/latest/dg/sns-large-payload-raw-message-delivery.html |
| 49 | + body = message.get("Body", "") |
| 50 | + if sentry_trace is None and f'"{SENTRY_TRACE_HEADER_NAME}"' in body: |
| 51 | + try: |
| 52 | + envelope = json.loads(body) |
| 53 | + except ValueError: |
| 54 | + envelope = None |
| 55 | + if isinstance(envelope, dict) and envelope.get("Type") == "Notification": |
| 56 | + sentry_trace = ( |
| 57 | + envelope.get("MessageAttributes", {}) |
| 58 | + .get(SENTRY_TRACE_HEADER_NAME, {}) |
| 59 | + .get("Value") |
| 60 | + ) |
| 61 | + |
| 62 | + data = extract_sentrytrace_data(sentry_trace) |
| 63 | + if data is None or not data["trace_id"] or not data["parent_span_id"]: |
| 64 | + return None |
| 65 | + |
| 66 | + link: "SpanLink" = { |
| 67 | + "trace_id": str(data["trace_id"]), |
| 68 | + "span_id": str(data["parent_span_id"]), |
| 69 | + # Sentry drops other link attributes for now; add `messaging.message.id` in the future. |
| 70 | + "attributes": {SPANDATA.SENTRY_LINK_TYPE: "message_origin"}, |
| 71 | + } |
| 72 | + if data["parent_sampled"] is not None: |
| 73 | + link["sampled"] = bool(data["parent_sampled"]) |
| 74 | + return link |
| 75 | + |
| 76 | + |
31 | 77 | class _SQSExtension(_ServiceExtension): |
32 | 78 | def get_span_op(self, ctx: "AwsCallContext") -> "Optional[str]": |
33 | 79 | if ctx.operation_name in _MESSAGING_OPERATIONS: |
@@ -124,5 +170,45 @@ def on_success_response( |
124 | 170 | span.status = SpanStatus.ERROR |
125 | 171 | attributes[SPANDATA.ERROR_TYPE] = error_type |
126 | 172 |
|
| 173 | + if ctx.operation_name == "ReceiveMessage": |
| 174 | + with capture_internal_exceptions(): |
| 175 | + # one link per producer context; batch entries of one send share it. |
| 176 | + links: "Dict[Tuple[str, str], SpanLink]" = {} |
| 177 | + for message in response.get("Messages", ()): |
| 178 | + # returns a link to the producer context a received message carries, if valid. |
| 179 | + link = _message_link(message) |
| 180 | + if link is not None: |
| 181 | + links.setdefault((link["trace_id"], link["span_id"]), link) |
| 182 | + span.add_links(list(links.values())) |
| 183 | + |
127 | 184 | span.set_attributes(attributes) |
128 | 185 | span.end() |
| 186 | + |
| 187 | + def get_request_params( |
| 188 | + self, ctx: "AwsCallContext", span: "Optional[Span]" |
| 189 | + ) -> "Optional[Dict[str, Any]]": |
| 190 | + if ctx.operation_name in ("SendMessage", "SendMessageBatch"): |
| 191 | + return _inject_message_attributes(ctx, span, "MessageBody", "Entries") |
| 192 | + |
| 193 | + # only request the carrier when the receive span can record links. |
| 194 | + if ( |
| 195 | + ctx.operation_name != "ReceiveMessage" |
| 196 | + or span is None |
| 197 | + or isinstance(span, NoOpSpan) |
| 198 | + ): |
| 199 | + return None |
| 200 | + |
| 201 | + # SQS only returns the message attributes named in `MessageAttributeNames`. |
| 202 | + # https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html |
| 203 | + names = ctx.params.get("MessageAttributeNames", []) |
| 204 | + missing = [ |
| 205 | + name |
| 206 | + for name in (SENTRY_TRACE_HEADER_NAME, BAGGAGE_HEADER_NAME) |
| 207 | + if name not in names |
| 208 | + ] |
| 209 | + # `All` and `.*` already return every attribute, including ours. |
| 210 | + if not missing or "All" in names or ".*" in names: |
| 211 | + return None |
| 212 | + |
| 213 | + # append ours to the caller's names, in a copy of their params. |
| 214 | + return {**ctx.params, "MessageAttributeNames": [*names, *missing]} |
0 commit comments