Skip to content

Commit c2ce8bc

Browse files
sentrivanaericapisani
authored andcommitted
ref: Add experimental streaming API (5) (#5592)
### Description Add `sentry_sdk.traces.start_span` and the corresponding scope method. NOTE: This is experimental and not production ready code. #### Issues <!-- * resolves: #1234 * resolves: LIN-1234 --> #### Reminders - Please add tests to validate your changes, and lint your code using `tox -e linters`. - Add GH Issue ID _&_ Linear ID (if applicable) - PR title should use [conventional commit](https://develop.sentry.dev/engineering-practices/commit-messages/#type) style (`feat:`, `fix:`, `ref:`, `meta:`) - For external contributors: [CONTRIBUTING.md](https://github.com/getsentry/sentry-python/blob/master/CONTRIBUTING.md), [Sentry SDK development docs](https://develop.sentry.dev/sdk/), [Discord community](https://discord.gg/Ww9hbqr)
1 parent d204945 commit c2ce8bc

File tree

2 files changed

+157
-2
lines changed

2 files changed

+157
-2
lines changed

sentry_sdk/scope.py

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
normalize_incoming_data,
3434
PropagationContext,
3535
)
36-
from sentry_sdk.traces import StreamedSpan
36+
from sentry_sdk.traces import _DEFAULT_PARENT_SPAN, StreamedSpan, NoOpStreamedSpan
3737
from sentry_sdk.tracing import (
3838
BAGGAGE_HEADER_NAME,
3939
SENTRY_TRACE_HEADER_NAME,
@@ -1174,6 +1174,59 @@ def start_span(
11741174

11751175
return span
11761176

1177+
def start_streamed_span(
1178+
self,
1179+
name: str,
1180+
attributes: "Optional[Attributes]",
1181+
parent_span: "Optional[StreamedSpan]",
1182+
active: bool,
1183+
) -> "StreamedSpan":
1184+
# TODO: rename to start_span once we drop the old API
1185+
if isinstance(parent_span, NoOpStreamedSpan):
1186+
# parent_span is only set if the user explicitly set it
1187+
logger.debug(
1188+
"Ignored parent span provided. Span will be parented to the "
1189+
"currently active span instead."
1190+
)
1191+
1192+
if parent_span is _DEFAULT_PARENT_SPAN or isinstance(
1193+
parent_span, NoOpStreamedSpan
1194+
):
1195+
parent_span = self.span # type: ignore
1196+
1197+
# If no eligible parent_span was provided and there is no currently
1198+
# active span, this is a segment
1199+
if parent_span is None:
1200+
propagation_context = self.get_active_propagation_context()
1201+
1202+
return StreamedSpan(
1203+
name=name,
1204+
attributes=attributes,
1205+
active=active,
1206+
scope=self,
1207+
segment=None,
1208+
trace_id=propagation_context.trace_id,
1209+
parent_span_id=propagation_context.parent_span_id,
1210+
parent_sampled=propagation_context.parent_sampled,
1211+
baggage=propagation_context.baggage,
1212+
)
1213+
1214+
# This is a child span; take propagation context from the parent span
1215+
with new_scope():
1216+
if isinstance(parent_span, NoOpStreamedSpan):
1217+
return NoOpStreamedSpan()
1218+
1219+
return StreamedSpan(
1220+
name=name,
1221+
attributes=attributes,
1222+
active=active,
1223+
scope=self,
1224+
segment=parent_span._segment,
1225+
trace_id=parent_span.trace_id,
1226+
parent_span_id=parent_span.span_id,
1227+
parent_sampled=parent_span.sampled,
1228+
)
1229+
11771230
def continue_trace(
11781231
self,
11791232
environ_or_headers: "Dict[str, Any]",

sentry_sdk/traces.py

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
from enum import Enum
1010
from typing import TYPE_CHECKING
1111

12+
import sentry_sdk
13+
from sentry_sdk.tracing_utils import Baggage
1214
from sentry_sdk.utils import format_attribute, logger
1315

1416
if TYPE_CHECKING:
@@ -57,6 +59,73 @@ def __str__(self) -> str:
5759
}
5860

5961

62+
# Sentinel value for an unset parent_span to be able to distinguish it from
63+
# a None set by the user
64+
_DEFAULT_PARENT_SPAN = object()
65+
66+
67+
def start_span(
68+
name: str,
69+
attributes: "Optional[Attributes]" = None,
70+
parent_span: "Optional[StreamedSpan]" = _DEFAULT_PARENT_SPAN, # type: ignore[assignment]
71+
active: bool = True,
72+
) -> "StreamedSpan":
73+
"""
74+
Start a span.
75+
76+
The span's parent, unless provided explicitly via the `parent_span` argument,
77+
will be the current active span, if any. If there is none, this span will
78+
become the root of a new span tree. If you explicitly want this span to be
79+
top-level without a parent, set `parent_span=None`.
80+
81+
`start_span()` can either be used as context manager or you can use the span
82+
object it returns and explicitly end it via `span.end()`. The following is
83+
equivalent:
84+
85+
```python
86+
import sentry_sdk
87+
88+
with sentry_sdk.traces.start_span(name="My Span"):
89+
# do something
90+
91+
# The span automatically finishes once the `with` block is exited
92+
```
93+
94+
```python
95+
import sentry_sdk
96+
97+
span = sentry_sdk.traces.start_span(name="My Span")
98+
# do something
99+
span.end()
100+
```
101+
102+
:param name: The name to identify this span by.
103+
:type name: str
104+
105+
:param attributes: Key-value attributes to set on the span from the start.
106+
These will also be accessible in the traces sampler.
107+
:type attributes: "Optional[Attributes]"
108+
109+
:param parent_span: A span instance that the new span should consider its
110+
parent. If not provided, the parent will be set to the currently active
111+
span, if any. If set to `None`, this span will become a new root-level
112+
span.
113+
:type parent_span: "Optional[StreamedSpan]"
114+
115+
:param active: Controls whether spans started while this span is running
116+
will automatically become its children. That's the default behavior. If
117+
you want to create a span that shouldn't have any children (unless
118+
provided explicitly via the `parent_span` argument), set this to `False`.
119+
:type active: bool
120+
121+
:return: The span that has been started.
122+
:rtype: StreamedSpan
123+
"""
124+
return sentry_sdk.get_current_scope().start_streamed_span(
125+
name, attributes, parent_span, active
126+
)
127+
128+
60129
class StreamedSpan:
61130
"""
62131
A span holds timing information of a block of code.
@@ -73,7 +142,12 @@ class StreamedSpan:
73142
"_active",
74143
"_span_id",
75144
"_trace_id",
145+
"_parent_span_id",
146+
"_segment",
147+
"_parent_sampled",
76148
"_status",
149+
"_scope",
150+
"_baggage",
77151
)
78152

79153
def __init__(
@@ -82,7 +156,12 @@ def __init__(
82156
name: str,
83157
attributes: "Optional[Attributes]" = None,
84158
active: bool = True,
159+
scope: "sentry_sdk.Scope",
160+
segment: "Optional[StreamedSpan]" = None,
85161
trace_id: "Optional[str]" = None,
162+
parent_span_id: "Optional[str]" = None,
163+
parent_sampled: "Optional[bool]" = None,
164+
baggage: "Optional[Baggage]" = None,
86165
):
87166
self._name: str = name
88167
self._active: bool = active
@@ -91,8 +170,16 @@ def __init__(
91170
for attribute, value in attributes.items():
92171
self.set_attribute(attribute, value)
93172

94-
self._span_id: "Optional[str]" = None
173+
self._scope = scope
174+
175+
self._segment = segment or self
176+
95177
self._trace_id: "Optional[str]" = trace_id
178+
self._parent_span_id = parent_span_id
179+
self._parent_sampled = parent_sampled
180+
self._baggage = baggage
181+
182+
self._span_id: "Optional[str]" = None
96183

97184
self._status = SpanStatus.OK.value
98185
self.set_attribute("sentry.span.source", SegmentSource.CUSTOM.value)
@@ -103,6 +190,7 @@ def __repr__(self) -> str:
103190
f"name={self._name}, "
104191
f"trace_id={self.trace_id}, "
105192
f"span_id={self.span_id}, "
193+
f"parent_span_id={self._parent_span_id}, "
106194
f"active={self._active})>"
107195
)
108196

@@ -165,8 +253,18 @@ def trace_id(self) -> str:
165253

166254
return self._trace_id
167255

256+
@property
257+
def sampled(self) -> "Optional[bool]":
258+
return True
259+
168260

169261
class NoOpStreamedSpan(StreamedSpan):
262+
def __init__(self) -> None:
263+
pass
264+
265+
def __repr__(self) -> str:
266+
return f"<{self.__class__.__name__}(sampled={self.sampled})>"
267+
170268
def get_attributes(self) -> "Attributes":
171269
return {}
172270

@@ -206,3 +304,7 @@ def span_id(self) -> str:
206304
@property
207305
def trace_id(self) -> str:
208306
return "00000000000000000000000000000000"
307+
308+
@property
309+
def sampled(self) -> "Optional[bool]":
310+
return False

0 commit comments

Comments
 (0)