|
2 | 2 | from sentry_sdk.consts import OP, SPANDATA |
3 | 3 | from sentry_sdk.integrations import Integration, DidNotEnable |
4 | 4 | from sentry_sdk.tracing import BAGGAGE_HEADER_NAME |
5 | | -from sentry_sdk.tracing_utils import should_propagate_trace |
| 5 | +from sentry_sdk.tracing_utils import Baggage, should_propagate_trace |
6 | 6 | from sentry_sdk.utils import ( |
7 | 7 | SENSITIVE_DATA_SUBSTITUTE, |
8 | 8 | capture_internal_exceptions, |
|
14 | 14 | from typing import TYPE_CHECKING |
15 | 15 |
|
16 | 16 | if TYPE_CHECKING: |
| 17 | + from collections.abc import MutableMapping |
17 | 18 | from typing import Any |
18 | 19 |
|
19 | 20 |
|
@@ -82,11 +83,9 @@ def send(self, request, **kwargs): |
82 | 83 | key=key, value=value, url=request.url |
83 | 84 | ) |
84 | 85 | ) |
85 | | - if key == BAGGAGE_HEADER_NAME and request.headers.get( |
86 | | - BAGGAGE_HEADER_NAME |
87 | | - ): |
88 | | - # do not overwrite any existing baggage, just append to it |
89 | | - request.headers[key] += "," + value |
| 86 | + |
| 87 | + if key == BAGGAGE_HEADER_NAME: |
| 88 | + _add_sentry_baggage_to_headers(request.headers, value) |
90 | 89 | else: |
91 | 90 | request.headers[key] = value |
92 | 91 |
|
@@ -178,3 +177,21 @@ async def send(self, request, **kwargs): |
178 | 177 | return rv |
179 | 178 |
|
180 | 179 | AsyncClient.send = send |
| 180 | + |
| 181 | + |
| 182 | +def _add_sentry_baggage_to_headers(headers, sentry_baggage): |
| 183 | + # type: (MutableMapping[str, str], str) -> None |
| 184 | + """Add the Sentry baggage to the headers. |
| 185 | +
|
| 186 | + This function directly mutates the provided headers. The provided sentry_baggage |
| 187 | + is appended to the existing baggage. If the baggage already contains Sentry items, |
| 188 | + they are stripped out first. |
| 189 | + """ |
| 190 | + existing_baggage = headers.get(BAGGAGE_HEADER_NAME, "") |
| 191 | + stripped_existing_baggage = Baggage.strip_sentry_baggage(existing_baggage) |
| 192 | + |
| 193 | + separator = "," if len(stripped_existing_baggage) > 0 else "" |
| 194 | + |
| 195 | + headers[BAGGAGE_HEADER_NAME] = ( |
| 196 | + stripped_existing_baggage + separator + sentry_baggage |
| 197 | + ) |
0 commit comments