|
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 |
|
@@ -76,11 +77,9 @@ def send(self, request, **kwargs):
|
76 | 77 | key=key, value=value, url=request.url
|
77 | 78 | )
|
78 | 79 | )
|
79 |
| - if key == BAGGAGE_HEADER_NAME and request.headers.get( |
80 |
| - BAGGAGE_HEADER_NAME |
81 |
| - ): |
82 |
| - # do not overwrite any existing baggage, just append to it |
83 |
| - request.headers[key] += "," + value |
| 80 | + |
| 81 | + if key == BAGGAGE_HEADER_NAME: |
| 82 | + _add_sentry_baggage_to_headers(request.headers, value) |
84 | 83 | else:
|
85 | 84 | request.headers[key] = value
|
86 | 85 |
|
@@ -148,3 +147,21 @@ async def send(self, request, **kwargs):
|
148 | 147 | return rv
|
149 | 148 |
|
150 | 149 | AsyncClient.send = send
|
| 150 | + |
| 151 | + |
| 152 | +def _add_sentry_baggage_to_headers(headers, sentry_baggage): |
| 153 | + # type: (MutableMapping[str, str], str) -> None |
| 154 | + """Add the Sentry baggage to the headers. |
| 155 | +
|
| 156 | + This function directly mutates the provided headers. The provided sentry_baggage |
| 157 | + is appended to the existing baggage. If the baggage already contains Sentry items, |
| 158 | + they are stripped out first. |
| 159 | + """ |
| 160 | + existing_baggage = headers.get(BAGGAGE_HEADER_NAME, "") |
| 161 | + stripped_existing_baggage = Baggage.strip_sentry_baggage(existing_baggage) |
| 162 | + |
| 163 | + separator = "," if len(stripped_existing_baggage) > 0 else "" |
| 164 | + |
| 165 | + headers[BAGGAGE_HEADER_NAME] = ( |
| 166 | + stripped_existing_baggage + separator + sentry_baggage |
| 167 | + ) |
0 commit comments