8000 Cleanup scope types · getsentry/sentry-python@5905d6a · GitHub
[go: up one dir, main page]

Skip to content

Commit 5905d6a

Browse files
committed
Cleanup scope types
1 parent 37d8599 commit 5905d6a

File tree

6 files changed

+73
-142
lines changed

6 files changed

+73
-142
lines changed

sentry_sdk/api.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from sentry_sdk.crons import monitor
88

99
# TODO-neel-potel make 2 scope strategies/impls and switch
10+
from sentry_sdk.scope import Scope as BaseScope
1011
from sentry_sdk.integrations.opentelemetry.scope import (
1112
PotelScope as Scope,
1213
new_scope,
@@ -123,7 +124,7 @@ def is_initialized():
123124

124125
@scopemethod
125126
def get_global_scope():
126-
# type: () -> Scope
127+
# type: () -> BaseScope
127128
return Scope.get_global_scope()
128129

129130

@@ -239,7 +240,7 @@ def flush(
239240

240241

241242
def start_span(**kwargs):
242-
# type: (type.Any) -> Span
243+
# type: (Any) -> Span
243244
"""
244245
Start and return a span.
245246

sentry_sdk/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -483,7 +483,7 @@ def _prepare_event(
483483

484484
for key in "release", "environment", "server_name", "dist":
485485
if event.get(key) is None and self.options[key] is not None:
486-
event[key] = str(self.options[key]).strip() # type: ignore[literal-required]
486+
event[key] = str(self.options[key]).strip()
487487
if event.get("sdk") is None:
488488
sdk_info = dict(SDK_INFO)
489489
sdk_info["integrations"] = sorted(self.integrations.keys())

sentry_sdk/integrations/opentelemetry/scope.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from sentry_sdk.integrations.opentelemetry.utils import trace_state_from_baggage
3030
from sentry_sdk.scope import Scope, ScopeType
3131
from sentry_sdk.tracing import Span
32+
from sentry_sdk.utils import logger
3233
from sentry_sdk._types import TYPE_CHECKING
3334

3435
if TYPE_CHECKING:
@@ -41,23 +42,25 @@
4142
class PotelScope(Scope):
4243
@classmethod
4344
def _get_scopes(cls):
44-
# type: () -> Optional[Tuple[Scope, Scope]]
45+
# type: () -> Optional[Tuple[PotelScope, PotelScope]]
4546
"""
4647
Returns the current scopes tuple on the otel context. Internal use only.
4748
"""
48-
return cast("Optional[Tuple[Scope, Scope]]", get_value(SENTRY_SCOPES_KEY))
49+
return cast(
50+
"Optional[Tuple[PotelScope, PotelScope]]", get_value(SENTRY_SCOPES_KEY)
51+
)
4952

5053
@classmethod
5154
def get_current_scope(cls):
52-
# type: () -> Scope
55+
# type: () -> PotelScope
5356
"""
5457
Returns the current scope.
5558
"""
5659
return cls._get_current_scope() or _INITIAL_CURRENT_SCOPE
5760

5861
@classmethod
5962
def _get_current_scope(cls):
60-
# type: () -> Optional[Scope]
63+
# type: () -> Optional[PotelScope]
6164
"""
6265
Returns the current scope without creating a new one. Internal use only.
6366
"""
@@ -66,15 +69,15 @@ def _get_current_scope(cls):
6669

6770
@classmethod
6871
def get_isolation_scope(cls):
69-
# type: () -> Scope
72+
# type: () -> PotelScope
7073
"""
7174
Returns the isolatio F438 n scope.
7275
"""
7376
return cls._get_isolation_scope() or _INITIAL_ISOLATION_SCOPE
7477

7578
@classmethod
7679
def _get_isolation_scope(cls):
77-
# type: () -> Optional[Scope]
80+
# type: () -> Optional[PotelScope]
7881
"""
7982
Returns the isolation scope without creating a new one. Internal use only.
8083
"""
@@ -84,6 +87,11 @@ def _get_isolation_scope(cls):
8487
@contextmanager
8588
def continue_trace(self, environ_or_headers):
8689
# type: (Dict[str, Any]) -> Generator[None, None, None]
90+
"""
91+
Sets the propagation context from environment or headers to continue an incoming trace.
92+
Any span started within this context manager will use the same trace_id, parent_span_id
93+
and inherit the sampling decision from the incoming trace.
94+
"""
8795
self.generate_propagation_context(environ_or_headers)
8896

8997
span_context = self._incoming_otel_span_context()
@@ -118,8 +126,8 @@ def _incoming_otel_span_context(self):
118126
trace_state = trace_state.add(TRACESTATE_SAMPLED_KEY, "deferred")
119127

120128
span_context = SpanContext(
121-
trace_id=int(self._propagation_context.trace_id, 16), # type: ignore
122-
span_id=int(self._propagation_context.parent_span_id, 16), # type: ignore
129+
trace_id=int(self._propagation_context.trace_id, 16),
130+
span_id=int(self._propagation_context.parent_span_id, 16),
123131
is_remote=True,
124132
trace_flags=trace_flags,
125133
trace_state=trace_state,
@@ -134,18 +142,22 @@ def start_transaction(self, **kwargs):
134142
This function is deprecated and will be removed in a future release.
135143
Use :py:meth:`sentry_sdk.start_span` instead.
136144
"""
145+
logger.warning(
146+
"The `start_transaction` method is deprecated, please use `sentry_sdk.start_span instead.`"
147+
)
137148
return self.start_span(**kwargs)
138149

139150
def start_span(self, **kwargs):
140151
# type: (Any) -> Span
141-
return Span(**kwargs, scope=self)
152+
return Span(**kwargs)
142153

143154

144-
_INITIAL_CURRENT_SCOPE = None
145-
_INITIAL_ISOLATION_SCOPE = None
155+
_INITIAL_CURRENT_SCOPE = PotelScope(ty=ScopeType.CURRENT)
156+
_INITIAL_ISOLATION_SCOPE = PotelScope(ty=ScopeType.ISOLATION)
146157

147158

148159
def setup_initial_scopes():
160+
# type: () -> None
149161
global _INITIAL_CURRENT_SCOPE, _INITIAL_ISOLATION_SCOPE
150162
_INITIAL_CURRENT_SCOPE = PotelScope(ty=ScopeType.CURRENT)
151163
_INITIAL_ISOLATION_SCOPE = PotelScope(ty=ScopeType.ISOLATION)

sentry_sdk/integrations/opentelemetry/utils.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def convert_from_otel_timestamp(time):
9595

9696

9797
def convert_to_otel_timestamp(time):
98-
# type: (Union[datetime.datetime, float]) -> int
98+
# type: (Union[datetime, float]) -> int
9999
"""Convert a datetime to an OTel timestamp (with nanosecond precision)."""
100100
if isinstance(time, datetime):
101101
return int(time.timestamp() * 1e9)
@@ -121,9 +121,12 @@ def extract_span_data(span):
121121
if span.attributes is None:
122122
return (op, description, status, http_status, origin)
123123

124-
op = span.attributes.get(SentrySpanAttribute.OP) or op
125-
description = span.attributes.get(SentrySpanAttribute.DESCRIPTION) or description
126-
origin = span.attributes.get(SentrySpanAttribute.ORIGIN)
124+
attribute_op = cast("Optional[str]", span.attributes.get(SentrySpanAttribute.OP))
125+
op = attribute_op or op
126+
description = cast(
127+
"str", span.attributes.get(SentrySpanAttribute.DESCRIPTION) or description
128+
)
129+
origin = cast("Optional[str]", span.attributes.get(SentrySpanAttribute.ORIGIN))
127130

128131
http_method = span.attributes.get(SpanAttributes.HTTP_METHOD) 83CB
129132
http_method = cast("Optional[str]", http_method)
@@ -137,7 +140,7 @@ def extract_span_data(span):
137140
rpc_service = span.attributes.get(SpanAttributes.RPC_SERVICE)
138141
if rpc_service:
139142
return (
140-
span.attributes.get(SentrySpanAttribute.OP) or "rpc",
143+
attribute_op or "rpc",
141144
description,
142145
status,
143146
http_status,
@@ -147,7 +150,7 @@ def extract_span_data(span):
147150
messaging_system = span.attributes.get(SpanAttributes.MESSAGING_SYSTEM)
148151
if messaging_system:
149152
return (
150-
span.attributes.get(SentrySpanAttribute.OP) or "message",
153+
attribute_op or "message",
151154
description,
152155
status,
153156
http_status,
@@ -165,7 +168,7 @@ def span_data_for_http_method(span):
165168
# type: (ReadableSpan) -> OtelExtractedSpanData
166169
span_attributes = span.attributes or {}
167170

168-
op = span_attributes.get(SentrySpanAttribute.OP)
171+
op = cast("Optional[str]", span_attributes.get(SentrySpanAttribute.OP))
169172
if op is None:
170173
op = "http"
171174

@@ -183,6 +186,7 @@ def span_data_for_http_method(span):
183186
description = span_attributes.get(
184187
SentrySpanAttribute.DESCRIPTION
185188
) or span_attributes.get(SentrySpanAttribute.NAME)
189+
description = cast("Optional[str]", description)
186190
if description is None:
187191
description = f"{http_method}"
188192

@@ -205,7 +209,7 @@ def span_data_for_http_method(span):
205209

206210
status, http_status = extract_span_status(span)
207211

208-
origin = span_attributes.get(SentrySpanAttribute.ORIGIN)
212+
origin = cast("Optional[str]", span_attributes.get(SentrySpanAttribute.ORIGIN))
209213

210214
return (op, description, status, http_status, origin)
211215

@@ -214,13 +218,13 @@ def span_data_for_db_query(span):
214218
# type: (ReadableSpan) -> OtelExtractedSpanData
215219
span_attributes = span.attributes or {}
216220

217-
op = span_attributes.get(SentrySpanAttribute.OP, OP.DB)
221+
op = cast("str", span_attributes.get(SentrySpanAttribute.OP, OP.DB))
218222

219223
statement = span_attributes.get(SpanAttributes.DB_STATEMENT, None)
220224
statement = cast("Optional[str]", statement)
221225

222226
description = statement or span.name
223-
origin = span_attributes.get(SentrySpanAttribute.ORIGIN)
227+
origin = cast("Optional[str]", span_attributes.get(SentrySpanAttribute.ORIGIN))
224228

225229
return (op, description, None, None, origin)
226230

@@ -293,19 +297,20 @@ def extract_span_attributes(span, namespace):
293297
"""
294298
Extract Sentry-specific span attributes and make them look the way Sentry expects.
295299
"""
296-
extracted_attrs = {}
300+
extracted_attrs = {} # type: dict[str, Any]
297301

298302
for attr, value in (span.attributes or {}).items():
299303
if attr.startswith(namespace):
300304
key = attr[len(namespace) + 1 :]
301305

302306
if namespace == SentrySpanAttribute.MEASUREMENT:
303-
value = {
307+
value = cast("tuple[str, str]", value)
308+
extracted_attrs[key] = {
304309
"value": float(value[0]),
305310
"unit": value[1],
306311
}
307-
308-
extracted_attrs[key] = value
312+
else:
313+
extracted_attrs[key] = value
309314

310315
return extracted_attrs
311316

@@ -457,7 +462,7 @@ def set_sentry_meta(span, key, value):
457462
# type: (Union[AbstractSpan, ReadableSpan], str, Any) -> None
458463
sentry_meta = getattr(span, "_sentry_meta", {})
459464
sentry_meta[key] = value
460-
span._sentry_meta = sentry_meta
465+
span._sentry_meta = sentry_meta # type: ignore[union-attr]
461466

462467

463468
def get_profile_context(span):

0 commit comments

Comments
 (0)
0