sentry-sdk 0.7.5__py2.py3-none-any.whl → 2.46.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sentry_sdk/__init__.py +48 -30
- sentry_sdk/_compat.py +74 -61
- sentry_sdk/_init_implementation.py +84 -0
- sentry_sdk/_log_batcher.py +172 -0
- sentry_sdk/_lru_cache.py +47 -0
- sentry_sdk/_metrics_batcher.py +167 -0
- sentry_sdk/_queue.py +289 -0
- sentry_sdk/_types.py +338 -0
- sentry_sdk/_werkzeug.py +98 -0
- sentry_sdk/ai/__init__.py +7 -0
- sentry_sdk/ai/monitoring.py +137 -0
- sentry_sdk/ai/utils.py +144 -0
- sentry_sdk/api.py +496 -80
- sentry_sdk/attachments.py +75 -0
- sentry_sdk/client.py +1023 -103
- sentry_sdk/consts.py +1438 -66
- sentry_sdk/crons/__init__.py +10 -0
- sentry_sdk/crons/api.py +62 -0
- sentry_sdk/crons/consts.py +4 -0
- sentry_sdk/crons/decorator.py +135 -0
- sentry_sdk/debug.py +15 -14
- sentry_sdk/envelope.py +369 -0
- sentry_sdk/feature_flags.py +71 -0
- sentry_sdk/hub.py +611 -280
- sentry_sdk/integrations/__init__.py +276 -49
- sentry_sdk/integrations/_asgi_common.py +108 -0
- sentry_sdk/integrations/_wsgi_common.py +180 -44
- sentry_sdk/integrations/aiohttp.py +291 -42
- sentry_sdk/integrations/anthropic.py +439 -0
- sentry_sdk/integrations/argv.py +9 -8
- sentry_sdk/integrations/ariadne.py +161 -0
- sentry_sdk/integrations/arq.py +247 -0
- sentry_sdk/integrations/asgi.py +341 -0
- sentry_sdk/integrations/asyncio.py +144 -0
- sentry_sdk/integrations/asyncpg.py +208 -0
- sentry_sdk/integrations/atexit.py +17 -10
- sentry_sdk/integrations/aws_lambda.py +377 -62
- sentry_sdk/integrations/beam.py +176 -0
- sentry_sdk/integrations/boto3.py +137 -0
- sentry_sdk/integrations/bottle.py +221 -0
- sentry_sdk/integrations/celery/__init__.py +529 -0
- sentry_sdk/integrations/celery/beat.py +293 -0
- sentry_sdk/integrations/celery/utils.py +43 -0
- sentry_sdk/integrations/chalice.py +134 -0
- sentry_sdk/integrations/clickhouse_driver.py +177 -0
- sentry_sdk/integrations/cloud_resource_context.py +280 -0
- sentry_sdk/integrations/cohere.py +274 -0
- sentry_sdk/integrations/dedupe.py +48 -14
- sentry_sdk/integrations/django/__init__.py +584 -191
- sentry_sdk/integrations/django/asgi.py +245 -0
- sentry_sdk/integrations/django/caching.py +204 -0
- sentry_sdk/integrations/django/middleware.py +187 -0
- sentry_sdk/integrations/django/signals_handlers.py +91 -0
- sentry_sdk/integrations/django/templates.py +79 -5
- sentry_sdk/integrations/django/transactions.py +49 -22
- sentry_sdk/integrations/django/views.py +96 -0
- sentry_sdk/integrations/dramatiq.py +226 -0
- sentry_sdk/integrations/excepthook.py +50 -13
- sentry_sdk/integrations/executing.py +67 -0
- sentry_sdk/integrations/falcon.py +272 -0
- sentry_sdk/integrations/fastapi.py +141 -0
- sentry_sdk/integrations/flask.py +142 -88
- sentry_sdk/integrations/gcp.py +239 -0
- sentry_sdk/integrations/gnu_backtrace.py +99 -0
- sentry_sdk/integrations/google_genai/__init__.py +301 -0
- sentry_sdk/integrations/google_genai/consts.py +16 -0
- sentry_sdk/integrations/google_genai/streaming.py +155 -0
- sentry_sdk/integrations/google_genai/utils.py +576 -0
- sentry_sdk/integrations/gql.py +162 -0
- sentry_sdk/integrations/graphene.py +151 -0
- sentry_sdk/integrations/grpc/__init__.py +168 -0
- sentry_sdk/integrations/grpc/aio/__init__.py +7 -0
- sentry_sdk/integrations/grpc/aio/client.py +95 -0
- sentry_sdk/integrations/grpc/aio/server.py +100 -0
- sentry_sdk/integrations/grpc/client.py +91 -0
- sentry_sdk/integrations/grpc/consts.py +1 -0
- sentry_sdk/integrations/grpc/server.py +66 -0
- sentry_sdk/integrations/httpx.py +178 -0
- sentry_sdk/integrations/huey.py +174 -0
- sentry_sdk/integrations/huggingface_hub.py +378 -0
- sentry_sdk/integrations/langchain.py +1132 -0
- sentry_sdk/integrations/langgraph.py +337 -0
- sentry_sdk/integrations/launchdarkly.py +61 -0
- sentry_sdk/integrations/litellm.py +287 -0
- sentry_sdk/integrations/litestar.py +315 -0
- sentry_sdk/integrations/logging.py +307 -96
- sentry_sdk/integrations/loguru.py +213 -0
- sentry_sdk/integrations/mcp.py +566 -0
- sentry_sdk/integrations/modules.py +14 -31
- sentry_sdk/integrations/openai.py +725 -0
- sentry_sdk/integrations/openai_agents/__init__.py +61 -0
- sentry_sdk/integrations/openai_agents/consts.py +1 -0
- sentry_sdk/integrations/openai_agents/patches/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/patches/agent_run.py +140 -0
- sentry_sdk/integrations/openai_agents/patches/error_tracing.py +77 -0
- sentry_sdk/integrations/openai_agents/patches/models.py +50 -0
- sentry_sdk/integrations/openai_agents/patches/runner.py +45 -0
- sentry_sdk/integrations/openai_agents/patches/tools.py +77 -0
- sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +21 -0
- sentry_sdk/integrations/openai_agents/spans/ai_client.py +42 -0
- sentry_sdk/integrations/openai_agents/spans/execute_tool.py +48 -0
- sentry_sdk/integrations/openai_agents/spans/handoff.py +19 -0
- sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +86 -0
- sentry_sdk/integrations/openai_agents/utils.py +199 -0
- sentry_sdk/integrations/openfeature.py +35 -0
- sentry_sdk/integrations/opentelemetry/__init__.py +7 -0
- sentry_sdk/integrations/opentelemetry/consts.py +5 -0
- sentry_sdk/integrations/opentelemetry/integration.py +58 -0
- sentry_sdk/integrations/opentelemetry/propagator.py +117 -0
- sentry_sdk/integrations/opentelemetry/span_processor.py +391 -0
- sentry_sdk/integrations/otlp.py +82 -0
- sentry_sdk/integrations/pure_eval.py +141 -0
- sentry_sdk/integrations/pydantic_ai/__init__.py +47 -0
- sentry_sdk/integrations/pydantic_ai/consts.py +1 -0
- sentry_sdk/integrations/pydantic_ai/patches/__init__.py +4 -0
- sentry_sdk/integrations/pydantic_ai/patches/agent_run.py +215 -0
- sentry_sdk/integrations/pydantic_ai/patches/graph_nodes.py +110 -0
- sentry_sdk/integrations/pydantic_ai/patches/model_request.py +40 -0
- sentry_sdk/integrations/pydantic_ai/patches/tools.py +98 -0
- sentry_sdk/integrations/pydantic_ai/spans/__init__.py +3 -0
- sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +246 -0
- sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +49 -0
- sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +112 -0
- sentry_sdk/integrations/pydantic_ai/utils.py +223 -0
- sentry_sdk/integrations/pymongo.py +214 -0
- sentry_sdk/integrations/pyramid.py +112 -68
- sentry_sdk/integrations/quart.py +237 -0
- sentry_sdk/integrations/ray.py +165 -0
- sentry_sdk/integrations/redis/__init__.py +48 -0
- sentry_sdk/integrations/redis/_async_common.py +116 -0
- sentry_sdk/integrations/redis/_sync_common.py +119 -0
- sentry_sdk/integrations/redis/consts.py +19 -0
- sentry_sdk/integrations/redis/modules/__init__.py +0 -0
- sentry_sdk/integrations/redis/modules/caches.py +118 -0
- sentry_sdk/integrations/redis/modules/queries.py +65 -0
- sentry_sdk/integrations/redis/rb.py +32 -0
- sentry_sdk/integrations/redis/redis.py +69 -0
- sentry_sdk/integrations/redis/redis_cluster.py +107 -0
- sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +50 -0
- sentry_sdk/integrations/redis/utils.py +148 -0
- sentry_sdk/integrations/rq.py +95 -37
- sentry_sdk/integrations/rust_tracing.py +284 -0
- sentry_sdk/integrations/sanic.py +294 -123
- sentry_sdk/integrations/serverless.py +48 -19
- sentry_sdk/integrations/socket.py +96 -0
- sentry_sdk/integrations/spark/__init__.py +4 -0
- sentry_sdk/integrations/spark/spark_driver.py +316 -0
- sentry_sdk/integrations/spark/spark_worker.py +116 -0
- sentry_sdk/integrations/sqlalchemy.py +142 -0
- sentry_sdk/integrations/starlette.py +737 -0
- sentry_sdk/integrations/starlite.py +292 -0
- sentry_sdk/integrations/statsig.py +37 -0
- sentry_sdk/integrations/stdlib.py +235 -29
- sentry_sdk/integrations/strawberry.py +394 -0
- sentry_sdk/integrations/sys_exit.py +70 -0
- sentry_sdk/integrations/threading.py +158 -28
- sentry_sdk/integrations/tornado.py +84 -52
- sentry_sdk/integrations/trytond.py +50 -0
- sentry_sdk/integrations/typer.py +60 -0
- sentry_sdk/integrations/unleash.py +33 -0
- sentry_sdk/integrations/unraisablehook.py +53 -0
- sentry_sdk/integrations/wsgi.py +201 -119
- sentry_sdk/logger.py +96 -0
- sentry_sdk/metrics.py +81 -0
- sentry_sdk/monitor.py +120 -0
- sentry_sdk/profiler/__init__.py +49 -0
- sentry_sdk/profiler/continuous_profiler.py +730 -0
- sentry_sdk/profiler/transaction_profiler.py +839 -0
- sentry_sdk/profiler/utils.py +195 -0
- sentry_sdk/py.typed +0 -0
- sentry_sdk/scope.py +1713 -85
- sentry_sdk/scrubber.py +177 -0
- sentry_sdk/serializer.py +405 -0
- sentry_sdk/session.py +177 -0
- sentry_sdk/sessions.py +275 -0
- sentry_sdk/spotlight.py +242 -0
- sentry_sdk/tracing.py +1486 -0
- sentry_sdk/tracing_utils.py +1236 -0
- sentry_sdk/transport.py +806 -134
- sentry_sdk/types.py +52 -0
- sentry_sdk/utils.py +1625 -465
- sentry_sdk/worker.py +54 -25
- sentry_sdk-2.46.0.dist-info/METADATA +268 -0
- sentry_sdk-2.46.0.dist-info/RECORD +189 -0
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/WHEEL +1 -1
- sentry_sdk-2.46.0.dist-info/entry_points.txt +2 -0
- sentry_sdk-2.46.0.dist-info/licenses/LICENSE +21 -0
- sentry_sdk/integrations/celery.py +0 -119
- sentry_sdk-0.7.5.dist-info/LICENSE +0 -9
- sentry_sdk-0.7.5.dist-info/METADATA +0 -36
- sentry_sdk-0.7.5.dist-info/RECORD +0 -39
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1236 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import functools
|
|
3
|
+
import inspect
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from random import Random
|
|
10
|
+
from urllib.parse import quote, unquote
|
|
11
|
+
import uuid
|
|
12
|
+
|
|
13
|
+
import sentry_sdk
|
|
14
|
+
from sentry_sdk.consts import OP, SPANDATA, SPANSTATUS, SPANTEMPLATE
|
|
15
|
+
from sentry_sdk.utils import (
|
|
16
|
+
capture_internal_exceptions,
|
|
17
|
+
filename_for_module,
|
|
18
|
+
Dsn,
|
|
19
|
+
logger,
|
|
20
|
+
match_regex_list,
|
|
21
|
+
qualname_from_function,
|
|
22
|
+
safe_repr,
|
|
23
|
+
to_string,
|
|
24
|
+
try_convert,
|
|
25
|
+
is_sentry_url,
|
|
26
|
+
_is_external_source,
|
|
27
|
+
_is_in_project_root,
|
|
28
|
+
_module_in_list,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from typing import TYPE_CHECKING
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from typing import Any
|
|
35
|
+
from typing import Dict
|
|
36
|
+
from typing import Generator
|
|
37
|
+
from typing import Optional
|
|
38
|
+
from typing import Union
|
|
39
|
+
|
|
40
|
+
from types import FrameType
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
SENTRY_TRACE_REGEX = re.compile(
|
|
44
|
+
"^[ \t]*" # whitespace
|
|
45
|
+
"([0-9a-f]{32})?" # trace_id
|
|
46
|
+
"-?([0-9a-f]{16})?" # span_id
|
|
47
|
+
"-?([01])?" # sampled
|
|
48
|
+
"[ \t]*$" # whitespace
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# This is a normal base64 regex, modified to reflect that fact that we strip the
|
|
53
|
+
# trailing = or == off
|
|
54
|
+
base64_stripped = (
|
|
55
|
+
# any of the characters in the base64 "alphabet", in multiples of 4
|
|
56
|
+
"([a-zA-Z0-9+/]{4})*"
|
|
57
|
+
# either nothing or 2 or 3 base64-alphabet characters (see
|
|
58
|
+
# https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding for
|
|
59
|
+
# why there's never only 1 extra character)
|
|
60
|
+
"([a-zA-Z0-9+/]{2,3})?"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class EnvironHeaders(Mapping): # type: ignore
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
environ, # type: Mapping[str, str]
|
|
68
|
+
prefix="HTTP_", # type: str
|
|
69
|
+
):
|
|
70
|
+
# type: (...) -> None
|
|
71
|
+
self.environ = environ
|
|
72
|
+
self.prefix = prefix
|
|
73
|
+
|
|
74
|
+
def __getitem__(self, key):
|
|
75
|
+
# type: (str) -> Optional[Any]
|
|
76
|
+
return self.environ[self.prefix + key.replace("-", "_").upper()]
|
|
77
|
+
|
|
78
|
+
def __len__(self):
|
|
79
|
+
# type: () -> int
|
|
80
|
+
return sum(1 for _ in iter(self))
|
|
81
|
+
|
|
82
|
+
def __iter__(self):
|
|
83
|
+
# type: () -> Generator[str, None, None]
|
|
84
|
+
for k in self.environ:
|
|
85
|
+
if not isinstance(k, str):
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
k = k.replace("-", "_").upper()
|
|
89
|
+
if not k.startswith(self.prefix):
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
yield k[len(self.prefix) :]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def has_tracing_enabled(options):
|
|
96
|
+
# type: (Optional[Dict[str, Any]]) -> bool
|
|
97
|
+
"""
|
|
98
|
+
Returns True if either traces_sample_rate or traces_sampler is
|
|
99
|
+
defined and enable_tracing is set and not false.
|
|
100
|
+
"""
|
|
101
|
+
if options is None:
|
|
102
|
+
return False
|
|
103
|
+
|
|
104
|
+
return bool(
|
|
105
|
+
options.get("enable_tracing") is not False
|
|
106
|
+
and (
|
|
107
|
+
options.get("traces_sample_rate") is not None
|
|
108
|
+
or options.get("traces_sampler") is not None
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@contextlib.contextmanager
|
|
114
|
+
def record_sql_queries(
|
|
115
|
+
cursor, # type: Any
|
|
116
|
+
query, # type: Any
|
|
117
|
+
params_list, # type: Any
|
|
118
|
+
paramstyle, # type: Optional[str]
|
|
119
|
+
executemany, # type: bool
|
|
120
|
+
record_cursor_repr=False, # type: bool
|
|
121
|
+
span_origin="manual", # type: str
|
|
122
|
+
):
|
|
123
|
+
# type: (...) -> Generator[sentry_sdk.tracing.Span, None, None]
|
|
124
|
+
|
|
125
|
+
# TODO: Bring back capturing of params by default
|
|
126
|
+
if sentry_sdk.get_client().options["_experiments"].get("record_sql_params", False):
|
|
127
|
+
if not params_list or params_list == [None]:
|
|
128
|
+
params_list = None
|
|
129
|
+
|
|
130
|
+
if paramstyle == "pyformat":
|
|
131
|
+
paramstyle = "format"
|
|
132
|
+
else:
|
|
133
|
+
params_list = None
|
|
134
|
+
paramstyle = None
|
|
135
|
+
|
|
136
|
+
query = _format_sql(cursor, query)
|
|
137
|
+
|
|
138
|
+
data = {}
|
|
139
|
+
if params_list is not None:
|
|
140
|
+
data["db.params"] = params_list
|
|
141
|
+
if paramstyle is not None:
|
|
142
|
+
data["db.paramstyle"] = paramstyle
|
|
143
|
+
if executemany:
|
|
144
|
+
data["db.executemany"] = True
|
|
145
|
+
if record_cursor_repr and cursor is not None:
|
|
146
|
+
data["db.cursor"] = cursor
|
|
147
|
+
|
|
148
|
+
with capture_internal_exceptions():
|
|
149
|
+
sentry_sdk.add_breadcrumb(message=query, category="query", data=data)
|
|
150
|
+
|
|
151
|
+
with sentry_sdk.start_span(
|
|
152
|
+
op=OP.DB,
|
|
153
|
+
name=query,
|
|
154
|
+
origin=span_origin,
|
|
155
|
+
) as span:
|
|
156
|
+
for k, v in data.items():
|
|
157
|
+
span.set_data(k, v)
|
|
158
|
+
yield span
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def maybe_create_breadcrumbs_from_span(scope, span):
|
|
162
|
+
# type: (sentry_sdk.Scope, sentry_sdk.tracing.Span) -> None
|
|
163
|
+
if span.op == OP.DB_REDIS:
|
|
164
|
+
scope.add_breadcrumb(
|
|
165
|
+
message=span.description, type="redis", category="redis", data=span._tags
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
elif span.op == OP.HTTP_CLIENT:
|
|
169
|
+
level = None
|
|
170
|
+
status_code = span._data.get(SPANDATA.HTTP_STATUS_CODE)
|
|
171
|
+
if status_code:
|
|
172
|
+
if 500 <= status_code <= 599:
|
|
173
|
+
level = "error"
|
|
174
|
+
elif 400 <= status_code <= 499:
|
|
175
|
+
level = "warning"
|
|
176
|
+
|
|
177
|
+
if level:
|
|
178
|
+
scope.add_breadcrumb(
|
|
179
|
+
type="http", category="httplib", data=span._data, level=level
|
|
180
|
+
)
|
|
181
|
+
else:
|
|
182
|
+
scope.add_breadcrumb(type="http", category="httplib", data=span._data)
|
|
183
|
+
|
|
184
|
+
elif span.op == "subprocess":
|
|
185
|
+
scope.add_breadcrumb(
|
|
186
|
+
type="subprocess",
|
|
187
|
+
category="subprocess",
|
|
188
|
+
message=span.description,
|
|
189
|
+
data=span._data,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _get_frame_module_abs_path(frame):
|
|
194
|
+
# type: (FrameType) -> Optional[str]
|
|
195
|
+
try:
|
|
196
|
+
return frame.f_code.co_filename
|
|
197
|
+
except Exception:
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _should_be_included(
|
|
202
|
+
is_sentry_sdk_frame, # type: bool
|
|
203
|
+
namespace, # type: Optional[str]
|
|
204
|
+
in_app_include, # type: Optional[list[str]]
|
|
205
|
+
in_app_exclude, # type: Optional[list[str]]
|
|
206
|
+
abs_path, # type: Optional[str]
|
|
207
|
+
project_root, # type: Optional[str]
|
|
208
|
+
):
|
|
209
|
+
# type: (...) -> bool
|
|
210
|
+
# in_app_include takes precedence over in_app_exclude
|
|
211
|
+
should_be_included = _module_in_list(namespace, in_app_include)
|
|
212
|
+
should_be_excluded = _is_external_source(abs_path) or _module_in_list(
|
|
213
|
+
namespace, in_app_exclude
|
|
214
|
+
)
|
|
215
|
+
return not is_sentry_sdk_frame and (
|
|
216
|
+
should_be_included
|
|
217
|
+
or (_is_in_project_root(abs_path, project_root) and not should_be_excluded)
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def add_source(span, project_root, in_app_include, in_app_exclude):
|
|
222
|
+
# type: (sentry_sdk.tracing.Span, Optional[str], Optional[list[str]], Optional[list[str]]) -> None
|
|
223
|
+
"""
|
|
224
|
+
Adds OTel compatible source code information to the span
|
|
225
|
+
"""
|
|
226
|
+
# Find the correct frame
|
|
227
|
+
frame = sys._getframe() # type: Union[FrameType, None]
|
|
228
|
+
while frame is not None:
|
|
229
|
+
abs_path = _get_frame_module_abs_path(frame)
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
namespace = frame.f_globals.get("__name__") # type: Optional[str]
|
|
233
|
+
except Exception:
|
|
234
|
+
namespace = None
|
|
235
|
+
|
|
236
|
+
is_sentry_sdk_frame = namespace is not None and namespace.startswith(
|
|
237
|
+
"sentry_sdk."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
should_be_included = _should_be_included(
|
|
241
|
+
is_sentry_sdk_frame=is_sentry_sdk_frame,
|
|
242
|
+
namespace=namespace,
|
|
243
|
+
in_app_include=in_app_include,
|
|
244
|
+
in_app_exclude=in_app_exclude,
|
|
245
|
+
abs_path=abs_path,
|
|
246
|
+
project_root=project_root,
|
|
247
|
+
)
|
|
248
|
+
if should_be_included:
|
|
249
|
+
break
|
|
250
|
+
|
|
251
|
+
frame = frame.f_back
|
|
252
|
+
else:
|
|
253
|
+
frame = None
|
|
254
|
+
|
|
255
|
+
# Set the data
|
|
256
|
+
if frame is not None:
|
|
257
|
+
try:
|
|
258
|
+
lineno = frame.f_lineno
|
|
259
|
+
except Exception:
|
|
260
|
+
lineno = None
|
|
261
|
+
if lineno is not None:
|
|
262
|
+
span.set_data(SPANDATA.CODE_LINENO, frame.f_lineno)
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
namespace = frame.f_globals.get("__name__")
|
|
266
|
+
except Exception:
|
|
267
|
+
namespace = None
|
|
268
|
+
if namespace is not None:
|
|
269
|
+
span.set_data(SPANDATA.CODE_NAMESPACE, namespace)
|
|
270
|
+
|
|
271
|
+
filepath = _get_frame_module_abs_path(frame)
|
|
272
|
+
if filepath is not None:
|
|
273
|
+
if namespace is not None:
|
|
274
|
+
in_app_path = filename_for_module(namespace, filepath)
|
|
275
|
+
elif project_root is not None and filepath.startswith(project_root):
|
|
276
|
+
in_app_path = filepath.replace(project_root, "").lstrip(os.sep)
|
|
277
|
+
else:
|
|
278
|
+
in_app_path = filepath
|
|
279
|
+
span.set_data(SPANDATA.CODE_FILEPATH, in_app_path)
|
|
280
|
+
|
|
281
|
+
try:
|
|
282
|
+
code_function = frame.f_code.co_name
|
|
283
|
+
except Exception:
|
|
284
|
+
code_function = None
|
|
285
|
+
|
|
286
|
+
if code_function is not None:
|
|
287
|
+
span.set_data(SPANDATA.CODE_FUNCTION, frame.f_code.co_name)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def add_query_source(span):
|
|
291
|
+
# type: (sentry_sdk.tracing.Span) -> None
|
|
292
|
+
"""
|
|
293
|
+
Adds OTel compatible source code information to a database query span
|
|
294
|
+
"""
|
|
295
|
+
client = sentry_sdk.get_client()
|
|
296
|
+
if not client.is_active():
|
|
297
|
+
return
|
|
298
|
+
|
|
299
|
+
if span.timestamp is None or span.start_timestamp is None:
|
|
300
|
+
return
|
|
301
|
+
|
|
302
|
+
should_add_query_source = client.options.get("enable_db_query_source", True)
|
|
303
|
+
if not should_add_query_source:
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
duration = span.timestamp - span.start_timestamp
|
|
307
|
+
threshold = client.options.get("db_query_source_threshold_ms", 0)
|
|
308
|
+
slow_query = duration / timedelta(milliseconds=1) > threshold
|
|
309
|
+
|
|
310
|
+
if not slow_query:
|
|
311
|
+
return
|
|
312
|
+
|
|
313
|
+
add_source(
|
|
314
|
+
span=span,
|
|
315
|
+
project_root=client.options["project_root"],
|
|
316
|
+
in_app_include=client.options.get("in_app_include"),
|
|
317
|
+
in_app_exclude=client.options.get("in_app_exclude"),
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def add_http_request_source(span):
|
|
322
|
+
# type: (sentry_sdk.tracing.Span) -> None
|
|
323
|
+
"""
|
|
324
|
+
Adds OTel compatible source code information to a span for an outgoing HTTP request
|
|
325
|
+
"""
|
|
326
|
+
client = sentry_sdk.get_client()
|
|
327
|
+
if not client.is_active():
|
|
328
|
+
return
|
|
329
|
+
|
|
330
|
+
if span.timestamp is None or span.start_timestamp is None:
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
should_add_request_source = client.options.get("enable_http_request_source", True)
|
|
334
|
+
if not should_add_request_source:
|
|
335
|
+
return
|
|
336
|
+
|
|
337
|
+
duration = span.timestamp - span.start_timestamp
|
|
338
|
+
threshold = client.options.get("http_request_source_threshold_ms", 0)
|
|
339
|
+
slow_query = duration / timedelta(milliseconds=1) > threshold
|
|
340
|
+
|
|
341
|
+
if not slow_query:
|
|
342
|
+
return
|
|
343
|
+
|
|
344
|
+
add_source(
|
|
345
|
+
span=span,
|
|
346
|
+
project_root=client.options["project_root"],
|
|
347
|
+
in_app_include=client.options.get("in_app_include"),
|
|
348
|
+
in_app_exclude=client.options.get("in_app_exclude"),
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def extract_sentrytrace_data(header):
|
|
353
|
+
# type: (Optional[str]) -> Optional[Dict[str, Union[str, bool, None]]]
|
|
354
|
+
"""
|
|
355
|
+
Given a `sentry-trace` header string, return a dictionary of data.
|
|
356
|
+
"""
|
|
357
|
+
if not header:
|
|
358
|
+
return None
|
|
359
|
+
|
|
360
|
+
if header.startswith("00-") and header.endswith("-00"):
|
|
361
|
+
header = header[3:-3]
|
|
362
|
+
|
|
363
|
+
match = SENTRY_TRACE_REGEX.match(header)
|
|
364
|
+
if not match:
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
trace_id, parent_span_id, sampled_str = match.groups()
|
|
368
|
+
parent_sampled = None
|
|
369
|
+
|
|
370
|
+
if trace_id:
|
|
371
|
+
trace_id = "{:032x}".format(int(trace_id, 16))
|
|
372
|
+
if parent_span_id:
|
|
373
|
+
parent_span_id = "{:016x}".format(int(parent_span_id, 16))
|
|
374
|
+
if sampled_str:
|
|
375
|
+
parent_sampled = sampled_str != "0"
|
|
376
|
+
|
|
377
|
+
return {
|
|
378
|
+
"trace_id": trace_id,
|
|
379
|
+
"parent_span_id": parent_span_id,
|
|
380
|
+
"parent_sampled": parent_sampled,
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _format_sql(cursor, sql):
|
|
385
|
+
# type: (Any, str) -> Optional[str]
|
|
386
|
+
|
|
387
|
+
real_sql = None
|
|
388
|
+
|
|
389
|
+
# If we're using psycopg2, it could be that we're
|
|
390
|
+
# looking at a query that uses Composed objects. Use psycopg2's mogrify
|
|
391
|
+
# function to format the query. We lose per-parameter trimming but gain
|
|
392
|
+
# accuracy in formatting.
|
|
393
|
+
try:
|
|
394
|
+
if hasattr(cursor, "mogrify"):
|
|
395
|
+
real_sql = cursor.mogrify(sql)
|
|
396
|
+
if isinstance(real_sql, bytes):
|
|
397
|
+
real_sql = real_sql.decode(cursor.connection.encoding)
|
|
398
|
+
except Exception:
|
|
399
|
+
real_sql = None
|
|
400
|
+
|
|
401
|
+
return real_sql or to_string(sql)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class PropagationContext:
|
|
405
|
+
"""
|
|
406
|
+
The PropagationContext represents the data of a trace in Sentry.
|
|
407
|
+
"""
|
|
408
|
+
|
|
409
|
+
__slots__ = (
|
|
410
|
+
"_trace_id",
|
|
411
|
+
"_span_id",
|
|
412
|
+
"parent_span_id",
|
|
413
|
+
"parent_sampled",
|
|
414
|
+
"dynamic_sampling_context",
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
def __init__(
|
|
418
|
+
self,
|
|
419
|
+
trace_id=None, # type: Optional[str]
|
|
420
|
+
span_id=None, # type: Optional[str]
|
|
421
|
+
parent_span_id=None, # type: Optional[str]
|
|
422
|
+
parent_sampled=None, # type: Optional[bool]
|
|
423
|
+
dynamic_sampling_context=None, # type: Optional[Dict[str, str]]
|
|
424
|
+
):
|
|
425
|
+
# type: (...) -> None
|
|
426
|
+
self._trace_id = trace_id
|
|
427
|
+
"""The trace id of the Sentry trace."""
|
|
428
|
+
|
|
429
|
+
self._span_id = span_id
|
|
430
|
+
"""The span id of the currently executing span."""
|
|
431
|
+
|
|
432
|
+
self.parent_span_id = parent_span_id
|
|
433
|
+
"""The id of the parent span that started this span.
|
|
434
|
+
The parent span could also be a span in an upstream service."""
|
|
435
|
+
|
|
436
|
+
self.parent_sampled = parent_sampled
|
|
437
|
+
"""Boolean indicator if the parent span was sampled.
|
|
438
|
+
Important when the parent span originated in an upstream service,
|
|
439
|
+
because we want to sample the whole trace, or nothing from the trace."""
|
|
440
|
+
|
|
441
|
+
self.dynamic_sampling_context = dynamic_sampling_context
|
|
442
|
+
"""Data that is used for dynamic sampling decisions."""
|
|
443
|
+
|
|
444
|
+
@classmethod
|
|
445
|
+
def from_incoming_data(cls, incoming_data):
|
|
446
|
+
# type: (Dict[str, Any]) -> Optional[PropagationContext]
|
|
447
|
+
propagation_context = None
|
|
448
|
+
|
|
449
|
+
normalized_data = normalize_incoming_data(incoming_data)
|
|
450
|
+
baggage_header = normalized_data.get(BAGGAGE_HEADER_NAME)
|
|
451
|
+
if baggage_header:
|
|
452
|
+
propagation_context = PropagationContext()
|
|
453
|
+
propagation_context.dynamic_sampling_context = Baggage.from_incoming_header(
|
|
454
|
+
baggage_header
|
|
455
|
+
).dynamic_sampling_context()
|
|
456
|
+
|
|
457
|
+
sentry_trace_header = normalized_data.get(SENTRY_TRACE_HEADER_NAME)
|
|
458
|
+
if sentry_trace_header:
|
|
459
|
+
sentrytrace_data = extract_sentrytrace_data(sentry_trace_header)
|
|
460
|
+
if sentrytrace_data is not None:
|
|
461
|
+
if propagation_context is None:
|
|
462
|
+
propagation_context = PropagationContext()
|
|
463
|
+
propagation_context.update(sentrytrace_data)
|
|
464
|
+
|
|
465
|
+
if propagation_context is not None:
|
|
466
|
+
propagation_context._fill_sample_rand()
|
|
467
|
+
|
|
468
|
+
return propagation_context
|
|
469
|
+
|
|
470
|
+
@property
|
|
471
|
+
def trace_id(self):
|
|
472
|
+
# type: () -> str
|
|
473
|
+
"""The trace id of the Sentry trace."""
|
|
474
|
+
if not self._trace_id:
|
|
475
|
+
# New trace, don't fill in sample_rand
|
|
476
|
+
self._trace_id = uuid.uuid4().hex
|
|
477
|
+
|
|
478
|
+
return self._trace_id
|
|
479
|
+
|
|
480
|
+
@trace_id.setter
|
|
481
|
+
def trace_id(self, value):
|
|
482
|
+
# type: (str) -> None
|
|
483
|
+
self._trace_id = value
|
|
484
|
+
|
|
485
|
+
@property
|
|
486
|
+
def span_id(self):
|
|
487
|
+
# type: () -> str
|
|
488
|
+
"""The span id of the currently executed span."""
|
|
489
|
+
if not self._span_id:
|
|
490
|
+
self._span_id = uuid.uuid4().hex[16:]
|
|
491
|
+
|
|
492
|
+
return self._span_id
|
|
493
|
+
|
|
494
|
+
@span_id.setter
|
|
495
|
+
def span_id(self, value):
|
|
496
|
+
# type: (str) -> None
|
|
497
|
+
self._span_id = value
|
|
498
|
+
|
|
499
|
+
def update(self, other_dict):
|
|
500
|
+
# type: (Dict[str, Any]) -> None
|
|
501
|
+
"""
|
|
502
|
+
Updates the PropagationContext with data from the given dictionary.
|
|
503
|
+
"""
|
|
504
|
+
for key, value in other_dict.items():
|
|
505
|
+
try:
|
|
506
|
+
setattr(self, key, value)
|
|
507
|
+
except AttributeError:
|
|
508
|
+
pass
|
|
509
|
+
|
|
510
|
+
def __repr__(self):
|
|
511
|
+
# type: (...) -> str
|
|
512
|
+
return "<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} dynamic_sampling_context={}>".format(
|
|
513
|
+
self._trace_id,
|
|
514
|
+
self._span_id,
|
|
515
|
+
self.parent_span_id,
|
|
516
|
+
self.parent_sampled,
|
|
517
|
+
self.dynamic_sampling_context,
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
def _fill_sample_rand(self):
|
|
521
|
+
# type: () -> None
|
|
522
|
+
"""
|
|
523
|
+
Ensure that there is a valid sample_rand value in the dynamic_sampling_context.
|
|
524
|
+
|
|
525
|
+
If there is a valid sample_rand value in the dynamic_sampling_context, we keep it.
|
|
526
|
+
Otherwise, we generate a sample_rand value according to the following:
|
|
527
|
+
|
|
528
|
+
- If we have a parent_sampled value and a sample_rate in the DSC, we compute
|
|
529
|
+
a sample_rand value randomly in the range:
|
|
530
|
+
- [0, sample_rate) if parent_sampled is True,
|
|
531
|
+
- or, in the range [sample_rate, 1) if parent_sampled is False.
|
|
532
|
+
|
|
533
|
+
- If either parent_sampled or sample_rate is missing, we generate a random
|
|
534
|
+
value in the range [0, 1).
|
|
535
|
+
|
|
536
|
+
The sample_rand is deterministically generated from the trace_id, if present.
|
|
537
|
+
|
|
538
|
+
This function does nothing if there is no dynamic_sampling_context.
|
|
539
|
+
"""
|
|
540
|
+
if self.dynamic_sampling_context is None:
|
|
541
|
+
return
|
|
542
|
+
|
|
543
|
+
sample_rand = try_convert(
|
|
544
|
+
float, self.dynamic_sampling_context.get("sample_rand")
|
|
545
|
+
)
|
|
546
|
+
if sample_rand is not None and 0 <= sample_rand < 1:
|
|
547
|
+
# sample_rand is present and valid, so don't overwrite it
|
|
548
|
+
return
|
|
549
|
+
|
|
550
|
+
# Get the sample rate and compute the transformation that will map the random value
|
|
551
|
+
# to the desired range: [0, 1), [0, sample_rate), or [sample_rate, 1).
|
|
552
|
+
sample_rate = try_convert(
|
|
553
|
+
float, self.dynamic_sampling_context.get("sample_rate")
|
|
554
|
+
)
|
|
555
|
+
lower, upper = _sample_rand_range(self.parent_sampled, sample_rate)
|
|
556
|
+
|
|
557
|
+
try:
|
|
558
|
+
sample_rand = _generate_sample_rand(self.trace_id, interval=(lower, upper))
|
|
559
|
+
except ValueError:
|
|
560
|
+
# ValueError is raised if the interval is invalid, i.e. lower >= upper.
|
|
561
|
+
# lower >= upper might happen if the incoming trace's sampled flag
|
|
562
|
+
# and sample_rate are inconsistent, e.g. sample_rate=0.0 but sampled=True.
|
|
563
|
+
# We cannot generate a sensible sample_rand value in this case.
|
|
564
|
+
logger.debug(
|
|
565
|
+
f"Could not backfill sample_rand, since parent_sampled={self.parent_sampled} "
|
|
566
|
+
f"and sample_rate={sample_rate}."
|
|
567
|
+
)
|
|
568
|
+
return
|
|
569
|
+
|
|
570
|
+
self.dynamic_sampling_context["sample_rand"] = f"{sample_rand:.6f}" # noqa: E231
|
|
571
|
+
|
|
572
|
+
def _sample_rand(self):
|
|
573
|
+
# type: () -> Optional[str]
|
|
574
|
+
"""Convenience method to get the sample_rand value from the dynamic_sampling_context."""
|
|
575
|
+
if self.dynamic_sampling_context is None:
|
|
576
|
+
return None
|
|
577
|
+
|
|
578
|
+
return self.dynamic_sampling_context.get("sample_rand")
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
class Baggage:
|
|
582
|
+
"""
|
|
583
|
+
The W3C Baggage header information (see https://www.w3.org/TR/baggage/).
|
|
584
|
+
|
|
585
|
+
Before mutating a `Baggage` object, calling code must check that `mutable` is `True`.
|
|
586
|
+
Mutating a `Baggage` object that has `mutable` set to `False` is not allowed, but
|
|
587
|
+
it is the caller's responsibility to enforce this restriction.
|
|
588
|
+
"""
|
|
589
|
+
|
|
590
|
+
__slots__ = ("sentry_items", "third_party_items", "mutable")
|
|
591
|
+
|
|
592
|
+
SENTRY_PREFIX = "sentry-"
|
|
593
|
+
SENTRY_PREFIX_REGEX = re.compile("^sentry-")
|
|
594
|
+
|
|
595
|
+
def __init__(
|
|
596
|
+
self,
|
|
597
|
+
sentry_items, # type: Dict[str, str]
|
|
598
|
+
third_party_items="", # type: str
|
|
599
|
+
mutable=True, # type: bool
|
|
600
|
+
):
|
|
601
|
+
self.sentry_items = sentry_items
|
|
602
|
+
self.third_party_items = third_party_items
|
|
603
|
+
self.mutable = mutable
|
|
604
|
+
|
|
605
|
+
@classmethod
|
|
606
|
+
def from_incoming_header(
|
|
607
|
+
cls,
|
|
608
|
+
header, # type: Optional[str]
|
|
609
|
+
*,
|
|
610
|
+
_sample_rand=None, # type: Optional[str]
|
|
611
|
+
):
|
|
612
|
+
# type: (...) -> Baggage
|
|
613
|
+
"""
|
|
614
|
+
freeze if incoming header already has sentry baggage
|
|
615
|
+
"""
|
|
616
|
+
sentry_items = {}
|
|
617
|
+
third_party_items = ""
|
|
618
|
+
mutable = True
|
|
619
|
+
|
|
620
|
+
if header:
|
|
621
|
+
for item in header.split(","):
|
|
622
|
+
if "=" not in item:
|
|
623
|
+
continue
|
|
624
|
+
|
|
625
|
+
with capture_internal_exceptions():
|
|
626
|
+
item = item.strip()
|
|
627
|
+
key, val = item.split("=")
|
|
628
|
+
if Baggage.SENTRY_PREFIX_REGEX.match(key):
|
|
629
|
+
baggage_key = unquote(key.split("-")[1])
|
|
630
|
+
sentry_items[baggage_key] = unquote(val)
|
|
631
|
+
mutable = False
|
|
632
|
+
else:
|
|
633
|
+
third_party_items += ("," if third_party_items else "") + item
|
|
634
|
+
|
|
635
|
+
if _sample_rand is not None:
|
|
636
|
+
sentry_items["sample_rand"] = str(_sample_rand)
|
|
637
|
+
mutable = False
|
|
638
|
+
|
|
639
|
+
return Baggage(sentry_items, third_party_items, mutable)
|
|
640
|
+
|
|
641
|
+
@classmethod
|
|
642
|
+
def from_options(cls, scope):
|
|
643
|
+
# type: (sentry_sdk.scope.Scope) -> Optional[Baggage]
|
|
644
|
+
|
|
645
|
+
sentry_items = {} # type: Dict[str, str]
|
|
646
|
+
third_party_items = ""
|
|
647
|
+
mutable = False
|
|
648
|
+
|
|
649
|
+
client = sentry_sdk.get_client()
|
|
650
|
+
|
|
651
|
+
if not client.is_active() or scope._propagation_context is None:
|
|
652
|
+
return Baggage(sentry_items)
|
|
653
|
+
|
|
654
|
+
options = client.options
|
|
655
|
+
propagation_context = scope._propagation_context
|
|
656
|
+
|
|
657
|
+
if propagation_context is not None:
|
|
658
|
+
sentry_items["trace_id"] = propagation_context.trace_id
|
|
659
|
+
|
|
660
|
+
if options.get("environment"):
|
|
661
|
+
sentry_items["environment"] = options["environment"]
|
|
662
|
+
|
|
663
|
+
if options.get("release"):
|
|
664
|
+
sentry_items["release"] = options["release"]
|
|
665
|
+
|
|
666
|
+
if options.get("dsn"):
|
|
667
|
+
sentry_items["public_key"] = Dsn(options["dsn"]).public_key
|
|
668
|
+
|
|
669
|
+
if options.get("traces_sample_rate"):
|
|
670
|
+
sentry_items["sample_rate"] = str(options["traces_sample_rate"])
|
|
671
|
+
|
|
672
|
+
return Baggage(sentry_items, third_party_items, mutable)
|
|
673
|
+
|
|
674
|
+
@classmethod
|
|
675
|
+
def populate_from_transaction(cls, transaction):
|
|
676
|
+
# type: (sentry_sdk.tracing.Transaction) -> Baggage
|
|
677
|
+
"""
|
|
678
|
+
Populate fresh baggage entry with sentry_items and make it immutable
|
|
679
|
+
if this is the head SDK which originates traces.
|
|
680
|
+
"""
|
|
681
|
+
client = sentry_sdk.get_client()
|
|
682
|
+
sentry_items = {} # type: Dict[str, str]
|
|
683
|
+
|
|
684
|
+
if not client.is_active():
|
|
685
|
+
return Baggage(sentry_items)
|
|
686
|
+
|
|
687
|
+
options = client.options or {}
|
|
688
|
+
|
|
689
|
+
sentry_items["trace_id"] = transaction.trace_id
|
|
690
|
+
sentry_items["sample_rand"] = f"{transaction._sample_rand:.6f}" # noqa: E231
|
|
691
|
+
|
|
692
|
+
if options.get("environment"):
|
|
693
|
+
sentry_items["environment"] = options["environment"]
|
|
694
|
+
|
|
695
|
+
if options.get("release"):
|
|
696
|
+
sentry_items["release"] = options["release"]
|
|
697
|
+
|
|
698
|
+
if options.get("dsn"):
|
|
699
|
+
sentry_items["public_key"] = Dsn(options["dsn"]).public_key
|
|
700
|
+
|
|
701
|
+
if (
|
|
702
|
+
transaction.name
|
|
703
|
+
and transaction.source not in LOW_QUALITY_TRANSACTION_SOURCES
|
|
704
|
+
):
|
|
705
|
+
sentry_items["transaction"] = transaction.name
|
|
706
|
+
|
|
707
|
+
if transaction.sample_rate is not None:
|
|
708
|
+
sentry_items["sample_rate"] = str(transaction.sample_rate)
|
|
709
|
+
|
|
710
|
+
if transaction.sampled is not None:
|
|
711
|
+
sentry_items["sampled"] = "true" if transaction.sampled else "false"
|
|
712
|
+
|
|
713
|
+
# there's an existing baggage but it was mutable,
|
|
714
|
+
# which is why we are creating this new baggage.
|
|
715
|
+
# However, if by chance the user put some sentry items in there, give them precedence.
|
|
716
|
+
if transaction._baggage and transaction._baggage.sentry_items:
|
|
717
|
+
sentry_items.update(transaction._baggage.sentry_items)
|
|
718
|
+
|
|
719
|
+
return Baggage(sentry_items, mutable=False)
|
|
720
|
+
|
|
721
|
+
def freeze(self):
|
|
722
|
+
# type: () -> None
|
|
723
|
+
self.mutable = False
|
|
724
|
+
|
|
725
|
+
def dynamic_sampling_context(self):
|
|
726
|
+
# type: () -> Dict[str, str]
|
|
727
|
+
header = {}
|
|
728
|
+
|
|
729
|
+
for key, item in self.sentry_items.items():
|
|
730
|
+
header[key] = item
|
|
731
|
+
|
|
732
|
+
return header
|
|
733
|
+
|
|
734
|
+
def serialize(self, include_third_party=False):
|
|
735
|
+
# type: (bool) -> str
|
|
736
|
+
items = []
|
|
737
|
+
|
|
738
|
+
for key, val in self.sentry_items.items():
|
|
739
|
+
with capture_internal_exceptions():
|
|
740
|
+
item = Baggage.SENTRY_PREFIX + quote(key) + "=" + quote(str(val))
|
|
741
|
+
items.append(item)
|
|
742
|
+
|
|
743
|
+
if include_third_party:
|
|
744
|
+
items.append(self.third_party_items)
|
|
745
|
+
|
|
746
|
+
return ",".join(items)
|
|
747
|
+
|
|
748
|
+
@staticmethod
|
|
749
|
+
def strip_sentry_baggage(header):
|
|
750
|
+
# type: (str) -> str
|
|
751
|
+
"""Remove Sentry baggage from the given header.
|
|
752
|
+
|
|
753
|
+
Given a Baggage header, return a new Baggage header with all Sentry baggage items removed.
|
|
754
|
+
"""
|
|
755
|
+
return ",".join(
|
|
756
|
+
(
|
|
757
|
+
item
|
|
758
|
+
for item in header.split(",")
|
|
759
|
+
if not Baggage.SENTRY_PREFIX_REGEX.match(item.strip())
|
|
760
|
+
)
|
|
761
|
+
)
|
|
762
|
+
|
|
763
|
+
def _sample_rand(self):
|
|
764
|
+
# type: () -> Optional[float]
|
|
765
|
+
"""Convenience method to get the sample_rand value from the sentry_items.
|
|
766
|
+
|
|
767
|
+
We validate the value and parse it as a float before returning it. The value is considered
|
|
768
|
+
valid if it is a float in the range [0, 1).
|
|
769
|
+
"""
|
|
770
|
+
sample_rand = try_convert(float, self.sentry_items.get("sample_rand"))
|
|
771
|
+
|
|
772
|
+
if sample_rand is not None and 0.0 <= sample_rand < 1.0:
|
|
773
|
+
return sample_rand
|
|
774
|
+
|
|
775
|
+
return None
|
|
776
|
+
|
|
777
|
+
def __repr__(self):
|
|
778
|
+
# type: () -> str
|
|
779
|
+
return f'<Baggage "{self.serialize(include_third_party=True)}", mutable={self.mutable}>'
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def should_propagate_trace(client, url):
|
|
783
|
+
# type: (sentry_sdk.client.BaseClient, str) -> bool
|
|
784
|
+
"""
|
|
785
|
+
Returns True if url matches trace_propagation_targets configured in the given client. Otherwise, returns False.
|
|
786
|
+
"""
|
|
787
|
+
trace_propagation_targets = client.options["trace_propagation_targets"]
|
|
788
|
+
|
|
789
|
+
if is_sentry_url(client, url):
|
|
790
|
+
return False
|
|
791
|
+
|
|
792
|
+
return match_regex_list(url, trace_propagation_targets, substring_matching=True)
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def normalize_incoming_data(incoming_data):
|
|
796
|
+
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
797
|
+
"""
|
|
798
|
+
Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes.
|
|
799
|
+
"""
|
|
800
|
+
data = {}
|
|
801
|
+
for key, value in incoming_data.items():
|
|
802
|
+
if key.startswith("HTTP_"):
|
|
803
|
+
key = key[5:]
|
|
804
|
+
|
|
805
|
+
key = key.replace("_", "-").lower()
|
|
806
|
+
data[key] = value
|
|
807
|
+
|
|
808
|
+
return data
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def create_span_decorator(
|
|
812
|
+
op=None, name=None, attributes=None, template=SPANTEMPLATE.DEFAULT
|
|
813
|
+
):
|
|
814
|
+
# type: (Optional[Union[str, OP]], Optional[str], Optional[dict[str, Any]], SPANTEMPLATE) -> Any
|
|
815
|
+
"""
|
|
816
|
+
Create a span decorator that can wrap both sync and async functions.
|
|
817
|
+
|
|
818
|
+
:param op: The operation type for the span.
|
|
819
|
+
:type op: str or :py:class:`sentry_sdk.consts.OP` or None
|
|
820
|
+
:param name: The name of the span.
|
|
821
|
+
:type name: str or None
|
|
822
|
+
:param attributes: Additional attributes to set on the span.
|
|
823
|
+
:type attributes: dict or None
|
|
824
|
+
:param template: The type of span to create. This determines what kind of
|
|
825
|
+
span instrumentation and data collection will be applied. Use predefined
|
|
826
|
+
constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
|
|
827
|
+
The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
|
|
828
|
+
use cases.
|
|
829
|
+
:type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
|
|
830
|
+
"""
|
|
831
|
+
from sentry_sdk.scope import should_send_default_pii
|
|
832
|
+
|
|
833
|
+
def span_decorator(f):
|
|
834
|
+
# type: (Any) -> Any
|
|
835
|
+
"""
|
|
836
|
+
Decorator to create a span for the given function.
|
|
837
|
+
"""
|
|
838
|
+
|
|
839
|
+
@functools.wraps(f)
|
|
840
|
+
async def async_wrapper(*args, **kwargs):
|
|
841
|
+
# type: (*Any, **Any) -> Any
|
|
842
|
+
current_span = get_current_span()
|
|
843
|
+
|
|
844
|
+
if current_span is None:
|
|
845
|
+
logger.debug(
|
|
846
|
+
"Cannot create a child span for %s. "
|
|
847
|
+
"Please start a Sentry transaction before calling this function.",
|
|
848
|
+
qualname_from_function(f),
|
|
849
|
+
)
|
|
850
|
+
return await f(*args, **kwargs)
|
|
851
|
+
|
|
852
|
+
span_op = op or _get_span_op(template)
|
|
853
|
+
function_name = name or qualname_from_function(f) or ""
|
|
854
|
+
span_name = _get_span_name(template, function_name, kwargs)
|
|
855
|
+
send_pii = should_send_default_pii()
|
|
856
|
+
|
|
857
|
+
with current_span.start_child(
|
|
858
|
+
op=span_op,
|
|
859
|
+
name=span_name,
|
|
860
|
+
) as span:
|
|
861
|
+
span.update_data(attributes or {})
|
|
862
|
+
_set_input_attributes(
|
|
863
|
+
span, template, send_pii, function_name, f, args, kwargs
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
result = await f(*args, **kwargs)
|
|
867
|
+
|
|
868
|
+
_set_output_attributes(span, template, send_pii, result)
|
|
869
|
+
|
|
870
|
+
return result
|
|
871
|
+
|
|
872
|
+
try:
|
|
873
|
+
async_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined]
|
|
874
|
+
except Exception:
|
|
875
|
+
pass
|
|
876
|
+
|
|
877
|
+
@functools.wraps(f)
|
|
878
|
+
def sync_wrapper(*args, **kwargs):
|
|
879
|
+
# type: (*Any, **Any) -> Any
|
|
880
|
+
current_span = get_current_span()
|
|
881
|
+
|
|
882
|
+
if current_span is None:
|
|
883
|
+
logger.debug(
|
|
884
|
+
"Cannot create a child span for %s. "
|
|
885
|
+
"Please start a Sentry transaction before calling this function.",
|
|
886
|
+
qualname_from_function(f),
|
|
887
|
+
)
|
|
888
|
+
return f(*args, **kwargs)
|
|
889
|
+
|
|
890
|
+
span_op = op or _get_span_op(template)
|
|
891
|
+
function_name = name or qualname_from_function(f) or ""
|
|
892
|
+
span_name = _get_span_name(template, function_name, kwargs)
|
|
893
|
+
send_pii = should_send_default_pii()
|
|
894
|
+
|
|
895
|
+
with current_span.start_child(
|
|
896
|
+
op=span_op,
|
|
897
|
+
name=span_name,
|
|
898
|
+
) as span:
|
|
899
|
+
span.update_data(attributes or {})
|
|
900
|
+
_set_input_attributes(
|
|
901
|
+
span, template, send_pii, function_name, f, args, kwargs
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
result = f(*args, **kwargs)
|
|
905
|
+
|
|
906
|
+
_set_output_attributes(span, template, send_pii, result)
|
|
907
|
+
|
|
908
|
+
return result
|
|
909
|
+
|
|
910
|
+
try:
|
|
911
|
+
sync_wrapper.__signature__ = inspect.signature(f) # type: ignore[attr-defined]
|
|
912
|
+
except Exception:
|
|
913
|
+
pass
|
|
914
|
+
|
|
915
|
+
if inspect.iscoroutinefunction(f):
|
|
916
|
+
return async_wrapper
|
|
917
|
+
else:
|
|
918
|
+
return sync_wrapper
|
|
919
|
+
|
|
920
|
+
return span_decorator
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def get_current_span(scope=None):
|
|
924
|
+
# type: (Optional[sentry_sdk.Scope]) -> Optional[Span]
|
|
925
|
+
"""
|
|
926
|
+
Returns the currently active span if there is one running, otherwise `None`
|
|
927
|
+
"""
|
|
928
|
+
scope = scope or sentry_sdk.get_current_scope()
|
|
929
|
+
current_span = scope.span
|
|
930
|
+
return current_span
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
def set_span_errored(span=None):
|
|
934
|
+
# type: (Optional[Span]) -> None
|
|
935
|
+
"""
|
|
936
|
+
Set the status of the current or given span to ERROR.
|
|
937
|
+
Also sets the status of the transaction (root span) to ERROR.
|
|
938
|
+
"""
|
|
939
|
+
span = span or get_current_span()
|
|
940
|
+
if span is not None:
|
|
941
|
+
span.set_status(SPANSTATUS.ERROR)
|
|
942
|
+
if span.containing_transaction is not None:
|
|
943
|
+
span.containing_transaction.set_status(SPANSTATUS.ERROR)
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
def _generate_sample_rand(
|
|
947
|
+
trace_id, # type: Optional[str]
|
|
948
|
+
*,
|
|
949
|
+
interval=(0.0, 1.0), # type: tuple[float, float]
|
|
950
|
+
):
|
|
951
|
+
# type: (...) -> float
|
|
952
|
+
"""Generate a sample_rand value from a trace ID.
|
|
953
|
+
|
|
954
|
+
The generated value will be pseudorandomly chosen from the provided
|
|
955
|
+
interval. Specifically, given (lower, upper) = interval, the generated
|
|
956
|
+
value will be in the range [lower, upper). The value has 6-digit precision,
|
|
957
|
+
so when printing with .6f, the value will never be rounded up.
|
|
958
|
+
|
|
959
|
+
The pseudorandom number generator is seeded with the trace ID.
|
|
960
|
+
"""
|
|
961
|
+
lower, upper = interval
|
|
962
|
+
if not lower < upper: # using `if lower >= upper` would handle NaNs incorrectly
|
|
963
|
+
raise ValueError("Invalid interval: lower must be less than upper")
|
|
964
|
+
|
|
965
|
+
rng = Random(trace_id)
|
|
966
|
+
lower_scaled = int(lower * 1_000_000)
|
|
967
|
+
upper_scaled = int(upper * 1_000_000)
|
|
968
|
+
try:
|
|
969
|
+
sample_rand_scaled = rng.randrange(lower_scaled, upper_scaled)
|
|
970
|
+
except ValueError:
|
|
971
|
+
# In some corner cases it might happen that the range is too small
|
|
972
|
+
# In that case, just take the lower bound
|
|
973
|
+
sample_rand_scaled = lower_scaled
|
|
974
|
+
|
|
975
|
+
return sample_rand_scaled / 1_000_000
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def _sample_rand_range(parent_sampled, sample_rate):
|
|
979
|
+
# type: (Optional[bool], Optional[float]) -> tuple[float, float]
|
|
980
|
+
"""
|
|
981
|
+
Compute the lower (inclusive) and upper (exclusive) bounds of the range of values
|
|
982
|
+
that a generated sample_rand value must fall into, given the parent_sampled and
|
|
983
|
+
sample_rate values.
|
|
984
|
+
"""
|
|
985
|
+
if parent_sampled is None or sample_rate is None:
|
|
986
|
+
return 0.0, 1.0
|
|
987
|
+
elif parent_sampled is True:
|
|
988
|
+
return 0.0, sample_rate
|
|
989
|
+
else: # parent_sampled is False
|
|
990
|
+
return sample_rate, 1.0
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _get_value(source, key):
|
|
994
|
+
# type: (Any, str) -> Optional[Any]
|
|
995
|
+
"""
|
|
996
|
+
Gets a value from a source object. The source can be a dict or an object.
|
|
997
|
+
It is checked for dictionary keys and object attributes.
|
|
998
|
+
"""
|
|
999
|
+
value = None
|
|
1000
|
+
if isinstance(source, dict):
|
|
1001
|
+
value = source.get(key)
|
|
1002
|
+
else:
|
|
1003
|
+
if hasattr(source, key):
|
|
1004
|
+
try:
|
|
1005
|
+
value = getattr(source, key)
|
|
1006
|
+
except Exception:
|
|
1007
|
+
value = None
|
|
1008
|
+
return value
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def _get_span_name(template, name, kwargs=None):
|
|
1012
|
+
# type: (Union[str, SPANTEMPLATE], str, Optional[dict[str, Any]]) -> str
|
|
1013
|
+
"""
|
|
1014
|
+
Get the name of the span based on the template and the name.
|
|
1015
|
+
"""
|
|
1016
|
+
span_name = name
|
|
1017
|
+
|
|
1018
|
+
if template == SPANTEMPLATE.AI_CHAT:
|
|
1019
|
+
model = None
|
|
1020
|
+
if kwargs:
|
|
1021
|
+
for key in ("model", "model_name"):
|
|
1022
|
+
if kwargs.get(key) and isinstance(kwargs[key], str):
|
|
1023
|
+
model = kwargs[key]
|
|
1024
|
+
break
|
|
1025
|
+
|
|
1026
|
+
span_name = f"chat {model}" if model else "chat"
|
|
1027
|
+
|
|
1028
|
+
elif template == SPANTEMPLATE.AI_AGENT:
|
|
1029
|
+
span_name = f"invoke_agent {name}"
|
|
1030
|
+
|
|
1031
|
+
elif template == SPANTEMPLATE.AI_TOOL:
|
|
1032
|
+
span_name = f"execute_tool {name}"
|
|
1033
|
+
|
|
1034
|
+
return span_name
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def _get_span_op(template):
|
|
1038
|
+
# type: (Union[str, SPANTEMPLATE]) -> str
|
|
1039
|
+
"""
|
|
1040
|
+
Get the operation of the span based on the template.
|
|
1041
|
+
"""
|
|
1042
|
+
mapping = {
|
|
1043
|
+
SPANTEMPLATE.AI_CHAT: OP.GEN_AI_CHAT,
|
|
1044
|
+
SPANTEMPLATE.AI_AGENT: OP.GEN_AI_INVOKE_AGENT,
|
|
1045
|
+
SPANTEMPLATE.AI_TOOL: OP.GEN_AI_EXECUTE_TOOL,
|
|
1046
|
+
} # type: dict[Union[str, SPANTEMPLATE], Union[str, OP]]
|
|
1047
|
+
op = mapping.get(template, OP.FUNCTION)
|
|
1048
|
+
|
|
1049
|
+
return str(op)
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def _get_input_attributes(template, send_pii, args, kwargs):
|
|
1053
|
+
# type: (Union[str, SPANTEMPLATE], bool, tuple[Any, ...], dict[str, Any]) -> dict[str, Any]
|
|
1054
|
+
"""
|
|
1055
|
+
Get input attributes for the given span template.
|
|
1056
|
+
"""
|
|
1057
|
+
attributes = {} # type: dict[str, Any]
|
|
1058
|
+
|
|
1059
|
+
if template in [SPANTEMPLATE.AI_AGENT, SPANTEMPLATE.AI_TOOL, SPANTEMPLATE.AI_CHAT]:
|
|
1060
|
+
mapping = {
|
|
1061
|
+
"model": (SPANDATA.GEN_AI_REQUEST_MODEL, str),
|
|
1062
|
+
"model_name": (SPANDATA.GEN_AI_REQUEST_MODEL, str),
|
|
1063
|
+
"agent": (SPANDATA.GEN_AI_AGENT_NAME, str),
|
|
1064
|
+
"agent_name": (SPANDATA.GEN_AI_AGENT_NAME, str),
|
|
1065
|
+
"max_tokens": (SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, int),
|
|
1066
|
+
"frequency_penalty": (SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, float),
|
|
1067
|
+
"presence_penalty": (SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, float),
|
|
1068
|
+
"temperature": (SPANDATA.GEN_AI_REQUEST_TEMPERATURE, float),
|
|
1069
|
+
"top_p": (SPANDATA.GEN_AI_REQUEST_TOP_P, float),
|
|
1070
|
+
"top_k": (SPANDATA.GEN_AI_REQUEST_TOP_K, int),
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
def _set_from_key(key, value):
|
|
1074
|
+
# type: (str, Any) -> None
|
|
1075
|
+
if key in mapping:
|
|
1076
|
+
(attribute, data_type) = mapping[key]
|
|
1077
|
+
if value is not None and isinstance(value, data_type):
|
|
1078
|
+
attributes[attribute] = value
|
|
1079
|
+
|
|
1080
|
+
for key, value in list(kwargs.items()):
|
|
1081
|
+
if key == "prompt" and isinstance(value, str):
|
|
1082
|
+
attributes.setdefault(SPANDATA.GEN_AI_REQUEST_MESSAGES, []).append(
|
|
1083
|
+
{"role": "user", "content": value}
|
|
1084
|
+
)
|
|
1085
|
+
continue
|
|
1086
|
+
|
|
1087
|
+
if key == "system_prompt" and isinstance(value, str):
|
|
1088
|
+
attributes.setdefault(SPANDATA.GEN_AI_REQUEST_MESSAGES, []).append(
|
|
1089
|
+
{"role": "system", "content": value}
|
|
1090
|
+
)
|
|
1091
|
+
continue
|
|
1092
|
+
|
|
1093
|
+
_set_from_key(key, value)
|
|
1094
|
+
|
|
1095
|
+
if template == SPANTEMPLATE.AI_TOOL and send_pii:
|
|
1096
|
+
attributes[SPANDATA.GEN_AI_TOOL_INPUT] = safe_repr(
|
|
1097
|
+
{"args": args, "kwargs": kwargs}
|
|
1098
|
+
)
|
|
1099
|
+
|
|
1100
|
+
# Coerce to string
|
|
1101
|
+
if SPANDATA.GEN_AI_REQUEST_MESSAGES in attributes:
|
|
1102
|
+
attributes[SPANDATA.GEN_AI_REQUEST_MESSAGES] = safe_repr(
|
|
1103
|
+
attributes[SPANDATA.GEN_AI_REQUEST_MESSAGES]
|
|
1104
|
+
)
|
|
1105
|
+
|
|
1106
|
+
return attributes
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def _get_usage_attributes(usage):
|
|
1110
|
+
# type: (Any) -> dict[str, Any]
|
|
1111
|
+
"""
|
|
1112
|
+
Get usage attributes.
|
|
1113
|
+
"""
|
|
1114
|
+
attributes = {}
|
|
1115
|
+
|
|
1116
|
+
def _set_from_keys(attribute, keys):
|
|
1117
|
+
# type: (str, tuple[str, ...]) -> None
|
|
1118
|
+
for key in keys:
|
|
1119
|
+
value = _get_value(usage, key)
|
|
1120
|
+
if value is not None and isinstance(value, int):
|
|
1121
|
+
attributes[attribute] = value
|
|
1122
|
+
|
|
1123
|
+
_set_from_keys(
|
|
1124
|
+
SPANDATA.GEN_AI_USAGE_INPUT_TOKENS,
|
|
1125
|
+
("prompt_tokens", "input_tokens"),
|
|
1126
|
+
)
|
|
1127
|
+
_set_from_keys(
|
|
1128
|
+
SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS,
|
|
1129
|
+
("completion_tokens", "output_tokens"),
|
|
1130
|
+
)
|
|
1131
|
+
_set_from_keys(
|
|
1132
|
+
SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS,
|
|
1133
|
+
("total_tokens",),
|
|
1134
|
+
)
|
|
1135
|
+
|
|
1136
|
+
return attributes
|
|
1137
|
+
|
|
1138
|
+
|
|
1139
|
+
def _get_output_attributes(template, send_pii, result):
|
|
1140
|
+
# type: (Union[str, SPANTEMPLATE], bool, Any) -> dict[str, Any]
|
|
1141
|
+
"""
|
|
1142
|
+
Get output attributes for the given span template.
|
|
1143
|
+
"""
|
|
1144
|
+
attributes = {} # type: dict[str, Any]
|
|
1145
|
+
|
|
1146
|
+
if template in [SPANTEMPLATE.AI_AGENT, SPANTEMPLATE.AI_TOOL, SPANTEMPLATE.AI_CHAT]:
|
|
1147
|
+
with capture_internal_exceptions():
|
|
1148
|
+
# Usage from result, result.usage, and result.metadata.usage
|
|
1149
|
+
usage_candidates = [result]
|
|
1150
|
+
|
|
1151
|
+
usage = _get_value(result, "usage")
|
|
1152
|
+
usage_candidates.append(usage)
|
|
1153
|
+
|
|
1154
|
+
meta = _get_value(result, "metadata")
|
|
1155
|
+
usage = _get_value(meta, "usage")
|
|
1156
|
+
usage_candidates.append(usage)
|
|
1157
|
+
|
|
1158
|
+
for usage_candidate in usage_candidates:
|
|
1159
|
+
if usage_candidate is not None:
|
|
1160
|
+
attributes.update(_get_usage_attributes(usage_candidate))
|
|
1161
|
+
|
|
1162
|
+
# Response model
|
|
1163
|
+
model_name = _get_value(result, "model")
|
|
1164
|
+
if model_name is not None and isinstance(model_name, str):
|
|
1165
|
+
attributes[SPANDATA.GEN_AI_RESPONSE_MODEL] = model_name
|
|
1166
|
+
|
|
1167
|
+
model_name = _get_value(result, "model_name")
|
|
1168
|
+
if model_name is not None and isinstance(model_name, str):
|
|
1169
|
+
attributes[SPANDATA.GEN_AI_RESPONSE_MODEL] = model_name
|
|
1170
|
+
|
|
1171
|
+
# Tool output
|
|
1172
|
+
if template == SPANTEMPLATE.AI_TOOL and send_pii:
|
|
1173
|
+
attributes[SPANDATA.GEN_AI_TOOL_OUTPUT] = safe_repr(result)
|
|
1174
|
+
|
|
1175
|
+
return attributes
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def _set_input_attributes(span, template, send_pii, name, f, args, kwargs):
|
|
1179
|
+
# type: (Span, Union[str, SPANTEMPLATE], bool, str, Any, tuple[Any, ...], dict[str, Any]) -> None
|
|
1180
|
+
"""
|
|
1181
|
+
Set span input attributes based on the given span template.
|
|
1182
|
+
|
|
1183
|
+
:param span: The span to set attributes on.
|
|
1184
|
+
:param template: The template to use to set attributes on the span.
|
|
1185
|
+
:param send_pii: Whether to send PII data.
|
|
1186
|
+
:param f: The wrapped function.
|
|
1187
|
+
:param args: The arguments to the wrapped function.
|
|
1188
|
+
:param kwargs: The keyword arguments to the wrapped function.
|
|
1189
|
+
"""
|
|
1190
|
+
attributes = {} # type: dict[str, Any]
|
|
1191
|
+
|
|
1192
|
+
if template == SPANTEMPLATE.AI_AGENT:
|
|
1193
|
+
attributes = {
|
|
1194
|
+
SPANDATA.GEN_AI_OPERATION_NAME: "invoke_agent",
|
|
1195
|
+
SPANDATA.GEN_AI_AGENT_NAME: name,
|
|
1196
|
+
}
|
|
1197
|
+
elif template == SPANTEMPLATE.AI_CHAT:
|
|
1198
|
+
attributes = {
|
|
1199
|
+
SPANDATA.GEN_AI_OPERATION_NAME: "chat",
|
|
1200
|
+
}
|
|
1201
|
+
elif template == SPANTEMPLATE.AI_TOOL:
|
|
1202
|
+
attributes = {
|
|
1203
|
+
SPANDATA.GEN_AI_OPERATION_NAME: "execute_tool",
|
|
1204
|
+
SPANDATA.GEN_AI_TOOL_NAME: name,
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
docstring = f.__doc__
|
|
1208
|
+
if docstring is not None:
|
|
1209
|
+
attributes[SPANDATA.GEN_AI_TOOL_DESCRIPTION] = docstring
|
|
1210
|
+
|
|
1211
|
+
attributes.update(_get_input_attributes(template, send_pii, args, kwargs))
|
|
1212
|
+
span.update_data(attributes or {})
|
|
1213
|
+
|
|
1214
|
+
|
|
1215
|
+
def _set_output_attributes(span, template, send_pii, result):
|
|
1216
|
+
# type: (Span, Union[str, SPANTEMPLATE], bool, Any) -> None
|
|
1217
|
+
"""
|
|
1218
|
+
Set span output attributes based on the given span template.
|
|
1219
|
+
|
|
1220
|
+
:param span: The span to set attributes on.
|
|
1221
|
+
:param template: The template to use to set attributes on the span.
|
|
1222
|
+
:param send_pii: Whether to send PII data.
|
|
1223
|
+
:param result: The result of the wrapped function.
|
|
1224
|
+
"""
|
|
1225
|
+
span.update_data(_get_output_attributes(template, send_pii, result) or {})
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
# Circular imports
|
|
1229
|
+
from sentry_sdk.tracing import (
|
|
1230
|
+
BAGGAGE_HEADER_NAME,
|
|
1231
|
+
LOW_QUALITY_TRANSACTION_SOURCES,
|
|
1232
|
+
SENTRY_TRACE_HEADER_NAME,
|
|
1233
|
+
)
|
|
1234
|
+
|
|
1235
|
+
if TYPE_CHECKING:
|
|
1236
|
+
from sentry_sdk.tracing import Span
|