Skip to content

Commit 094b9a8

Browse files
committed
Cleanup scopes wip
1 parent 37d8599 commit 094b9a8

File tree

3 files changed

+39
-117
lines changed

3 files changed

+39
-117
lines changed

sentry_sdk/integrations/opentelemetry/scope.py

Lines changed: 20 additions & 9 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 isolation 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()
@@ -134,15 +142,18 @@ 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():

sentry_sdk/scope.py

Lines changed: 16 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,11 @@
1212
from sentry_sdk.attachments import Attachment
1313
from sentry_sdk.consts import DEFAULT_MAX_BREADCRUMBS, FALSE_VALUES
1414
from sentry_sdk.feature_flags import FlagBuffer, DEFAULT_FLAG_CAPACITY
15-
from sentry_sdk.profiler.continuous_profiler import try_autostart_continuous_profiler
1615
from sentry_sdk.profiler.transaction_profiler import Profile
1716
from sentry_sdk.session import Session
1817
from sentry_sdk.tracing_utils import (
1918
Baggage,
2019
has_tracing_enabled,
21-
normalize_incoming_data,
2220
PropagationContext,
2321
)
2422
from sentry_sdk.tracing import (
@@ -67,7 +65,6 @@
6765
ExcInfo,
6866
Hint,
6967
LogLevelStr,
70-
SamplingContext,
7168
Type,
7269
)
7370

@@ -949,71 +946,20 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
949946
while len(self._breadcrumbs) > max_breadcrumbs:
950947
self._breadcrumbs.popleft()
951948

952-
def start_transaction(self, transaction=None, **kwargs):
953-
# type: (Optional[Span], Optional[SamplingContext], Unpack[TransactionKwargs]) -> Union[Span, NoOpSpan]
949+
def start_transaction(self, **kwargs):
950+
# type: (Unpack[TransactionKwargs]) -> Union[NoOpSpan, Span]
954951
"""
955-
Start and return a transaction.
956-
957-
Start an existing transaction if given, otherwise create and start a new
958-
transaction with kwargs.
959-
960-
This is the entry point to manual tracing instrumentation.
961-
962-
A tree structure can be built by adding child spans to the transaction,
963-
and child spans to other spans. To start a new child span within the
964-
transaction or any span, call the respective `.start_child()` method.
965-
966-
Every child span must be finished before the transaction is finished,
967-
otherwise the unfinished spans are discarded.
968-
969-
When used as context managers, spans and transactions are automatically
970-
finished at the end of the `with` block. If not using context managers,
971-
call the `.finish()` method.
972-
973-
When the transaction is finished, it will be sent to Sentry with all its
974-
finished child spans.
975-
976-
:param transaction: The transaction to start. If omitted, we create and
977-
start a new transaction.
978-
:param kwargs: Optional keyword arguments to be passed to the Transaction
979-
constructor. See :py:class:`sentry_sdk.tracing.Transaction` for
980-
available arguments.
952+
.. deprecated:: 3.0.0
953+
This function is deprecated and will be removed in a future release.
954+
Use :py:meth:`sentry_sdk.start_span` instead.
981955
"""
982-
# TODO-neel-potel fix signature and no op
983-
kwargs.setdefault("scope", self)
984-
985-
client = self.get_client()
986-
987-
try_autostart_continuous_profiler()
988-
989-
# if we haven't been given a transaction, make one
990-
transaction = Span(**kwargs)
991-
992-
# use traces_sample_rate, traces_sampler, and/or inheritance to make a
993-
# sampling decision
994-
sampling_context = {
995-
"transaction_context": transaction.to_json(),
996-
"parent_sampled": transaction.parent_sampled,
997-
}
998-
transaction._set_initial_sampling_decision(sampling_context=sampling_context)
999-
1000-
if transaction.sampled:
1001-
profile = Profile(
1002-
transaction.sampled, transaction._start_timestamp_monotonic_ns
1003-
)
1004-
profile._set_initial_sampling_decision(sampling_context=sampling_context)
1005-
1006-
transaction._profile = profile
1007-
1008-
# we don't bother to keep spans if we already know we're not going to
1009-
# send the transaction
1010-
max_spans = (client.options["_experiments"].get("max_spans")) or 1000
1011-
transaction.init_span_recorder(maxlen=max_spans)
1012-
1013-
return transaction
956+
logger.warning(
957+
"The `start_transaction` method is deprecated, please use `sentry_sdk.start_span instead.`"
958+
)
959+
return NoOpSpan(**kwargs)
1014960

1015961
def start_span(self, **kwargs):
1016-
# type: (Optional[Span], Any) -> Span
962+
# type: (Optional[Span], Any) -> Union[NoOpSpan, Span]
1017963
"""
1018964
Start a span whose parent is the currently active span, if any.
1019965
@@ -1023,53 +969,16 @@ def start_span(self, **kwargs):
1023969
1024970
For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
1025971
"""
1026-
# TODO-neel-potel fix signature and no op
1027-
if kwargs.get("description") is not None:
1028-
warnings.warn(
1029-
"The `description` parameter is deprecated. Please use `name` instead.",
1030-
DeprecationWarning,
1031-
stacklevel=2,
1032-
)
1033-
1034-
with new_scope():
1035-
kwargs.setdefault("scope", self)
1036-
1037-
# get current span or transaction
1038-
span = self.span or self.get_isolation_scope().span
972+
return NoOpSpan(**kwargs)
1039973

1040-
if span is None:
1041-
# New spans get the `trace_id` from the scope
1042-
if "trace_id" not in kwargs:
1043-
propagation_context = self.get_active_propagation_context()
1044-
if propagation_context is not None:
1045-
kwargs["trace_id"] = propagation_context.trace_id
1046-
1047-
span = Span(**kwargs)
1048-
else:
1049-
# Children take `trace_id`` from the parent span.
1050-
span = span.start_child(**kwargs)
1051-
1052-
return span
1053-
1054-
def continue_trace(
1055-
self, environ_or_headers, op=None, name=None, source=None, origin=None
1056-
):
1057-
# TODO-neel-potel fix signature and no op
1058-
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str], Optional[str]) -> Span
974+
@contextmanager
975+
def continue_trace(self, environ_or_headers):
976+
# type: (Dict[str, Any]) -> Generator[None, None, None]
1059977
"""
1060-
Sets the propagation context from environment or headers and returns a transaction.
978+
Sets the propagation context from environment or headers to continue an incoming trace.
1061979
"""
1062980
self.generate_propagation_context(environ_or_headers)
1063-
1064-
transaction = Span.continue_from_headers(
1065-
normalize_incoming_data(environ_or_headers),
1066-
op=op,
1067-
origin=origin,
1068-
name=name,
1069-
source=source,
1070-
)
1071-
1072-
return transaction
981+
yield
1073982

1074983
def capture_event(self, event, hint=None, scope=None, **scope_kwargs):
1075984
# type: (Event, Optional[Hint], Optional[Scope], Any) -> Optional[str]

sentry_sdk/tracing.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,9 @@ def get_span_status_from_http_code(http_status_code):
200200

201201

202202
class NoOpSpan:
203+
def __init__(self, **kwargs):
204+
pass
205+
203206
def __repr__(self):
204207
# type: () -> str
205208
return "<%s>" % self.__class__.__name__
@@ -263,7 +266,6 @@ def get_profile_context(self):
263266

264267
def finish(
265268
self,
266-
scope=None, # type: Optional[sentry_sdk.Scope]
267269
end_timestamp=None, # type: Optional[Union[float, datetime]]
268270
):
269271
# type: (...) -> None

0 commit comments

Comments
 (0)