Skip to content

Commit 1c1b0a1

Browse files
committed
Fix non scope related types
1 parent 3c7bb1e commit 1c1b0a1

File tree

10 files changed

+58
-86
lines changed

10 files changed

+58
-86
lines changed

MIGRATION_GUIDE.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Looking to upgrade from Sentry SDK 2.x to 3.x? Here's a comprehensive list of wh
1414
- You can no longer change the sampled status of a span with `span.sampled = False` after starting it.
1515
- The `Span()` constructor does not accept a `hub` parameter anymore.
1616
- `Span.finish()` does not accept a `hub` parameter anymore.
17+
- `Span.finish()` no longer returns the `event_id` if the event is sent to sentry.
1718
- The `Profile()` constructor does not accept a `hub` parameter anymore.
1819
- A `Profile` object does not have a `.hub` property anymore.
1920
- `sentry_sdk.continue_trace` no longer returns a `Transaction` and is now a context manager.
@@ -146,6 +147,7 @@ Looking to upgrade from Sentry SDK 2.x to 3.x? Here's a comprehensive list of wh
146147
- `continue_from_headers`, `continue_from_environ` and `from_traceparent` have been removed, please use top-level API `sentry_sdk.continue_trace` instead.
147148
- `PropagationContext` constructor no longer takes a `dynamic_sampling_context` but takes a `baggage` object instead.
148149
- `ThreadingIntegration` no longer takes the `propagate_hub` argument.
150+
- `Baggage.populate_from_transaction` has been removed.
149151

150152
### Deprecated
151153

sentry_sdk/client.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ def _prepare_event(
449449
)
450450
return None
451451

452-
event = event_
452+
event = event_ # type: Optional[Event] # type: ignore[no-redef]
453453

454454
spans_delta = spans_before - len(event.get("spans", []))
455455
if is_transaction and spans_delta > 0 and self.transport is not None:
@@ -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()
486+
event[key] = str(self.options[key]).strip() # type: ignore[literal-required]
487487
if event.get("sdk") is None:
488488
sdk_info = dict(SDK_INFO)
489489
sdk_info["integrations"] = sorted(self.integrations.keys())
@@ -523,7 +523,7 @@ def _prepare_event(
523523
and event is not None
524524
and event.get("type") != "transaction"
525525
):
526-
new_event = None
526+
new_event = None # type: Optional[Event]
527527
with capture_internal_exceptions():
528528
new_event = before_send(event, hint or {})
529529
if new_event is None:
@@ -532,7 +532,7 @@ def _prepare_event(
532532
self.transport.record_lost_event(
533533
"before_send", data_category="error"
534534
)
535-
event = new_event
535+
event = new_event # type: Optional[Event] # type: ignore[no-redef]
536536

537537
before_send_transaction = self.options["before_send_transaction"]
538538
if (
@@ -562,7 +562,7 @@ def _prepare_event(
562562
reason="before_send", data_category="span", quantity=spans_delta
563563
)
564564

565-
event = new_event
565+
event = new_event # type: Optional[Event] # type: ignore[no-redef]
566566

567567
return event
568568

sentry_sdk/integrations/asyncpg.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ async def _inner(*args: Any, **kwargs: Any) -> T:
189189

190190
def _get_db_data(
191191
conn: Any = None,
192-
addr: Optional[tuple[str]] = None,
192+
addr: Optional[tuple[str, ...]] = None,
193193
database: Optional[str] = None,
194194
user: Optional[str] = None,
195195
) -> dict[str, str]:
@@ -218,6 +218,6 @@ def _get_db_data(
218218
return data
219219

220220

221-
def _set_on_span(span: Span, data: dict[str, Any]):
221+
def _set_on_span(span: Span, data: dict[str, Any]) -> None:
222222
for key, value in data.items():
223223
span.set_attribute(key, value)

sentry_sdk/integrations/clickhouse_driver.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
ensure_integration_enabled,
1010
)
1111

12-
from typing import TYPE_CHECKING, Any, Dict, TypeVar
12+
from typing import TYPE_CHECKING, cast, Any, Dict, TypeVar
1313

1414
# Hack to get new Python features working in older versions
1515
# without introducing a hard dependency on `typing_extensions`
@@ -94,6 +94,7 @@ def _inner(*args: P.args, **kwargs: P.kwargs) -> T:
9494
connection._sentry_span = span # type: ignore[attr-defined]
9595

9696
data = _get_db_data(connection)
97+
data = cast("dict[str, Any]", data)
9798
data["db.query.text"] = query
9899

99100
if query_id:
@@ -116,9 +117,10 @@ def _inner(*args: P.args, **kwargs: P.kwargs) -> T:
116117
def _wrap_end(f: Callable[P, T]) -> Callable[P, T]:
117118
def _inner_end(*args: P.args, **kwargs: P.kwargs) -> T:
118119
res = f(*args, **kwargs)
119-
connection = args[0].connection
120+
client = cast("clickhouse_driver.client.Client", args[0])
121+
connection = client.connection
120122

121-
span = getattr(connection, "_sentry_span", None) # type: ignore[attr-defined]
123+
span = getattr(connection, "_sentry_span", None)
122124
if span is not None:
123125
data = getattr(connection, "_sentry_db_data", {})
124126

@@ -148,17 +150,18 @@ def _inner_end(*args: P.args, **kwargs: P.kwargs) -> T:
148150

149151
def _wrap_send_data(f: Callable[P, T]) -> Callable[P, T]:
150152
def _inner_send_data(*args: P.args, **kwargs: P.kwargs) -> T:
151-
connection = args[0].connection
152-
db_params_data = args[2]
153+
client = cast("clickhouse_driver.client.Client", args[0])
154+
connection = client.connection
155+
db_params_data = cast("list[Any]", args[2])
153156
span = getattr(connection, "_sentry_span", None)
154157

155158
if span is not None:
156159
data = _get_db_data(connection)
157160
_set_on_span(span, data)
158161

159162
if should_send_default_pii():
160-
saved_db_data = getattr(connection, "_sentry_db_data", {})
161-
db_params = saved_db_data.get("db.params") or []
163+
saved_db_data = getattr(connection, "_sentry_db_data", {}) # type: dict[str, Any]
164+
db_params = saved_db_data.get("db.params") or [] # type: list[Any]
162165
db_params.extend(db_params_data)
163166
saved_db_data["db.params"] = db_params
164167
span.set_attribute("db.params", _serialize_span_attribute(db_params))
@@ -178,6 +181,6 @@ def _get_db_data(connection: clickhouse_driver.connection.Connection) -> Dict[st
178181
}
179182

180183

181-
def _set_on_span(span: Span, data: Dict[str, Any]):
184+
def _set_on_span(span: Span, data: Dict[str, Any]) -> None:
182185
for key, value in data.items():
183186
span.set_attribute(key, _serialize_span_attribute(value))

sentry_sdk/integrations/opentelemetry/integration.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,10 @@ def _patch_readable_span():
5959
def sentry_patched_readable_span(self):
6060
# type: (Span) -> ReadableSpan
6161
readable_span = old_readable_span(self)
62-
readable_span._sentry_meta = getattr(self, "_sentry_meta", {})
62+
readable_span._sentry_meta = getattr(self, "_sentry_meta", {}) # type: ignore[attr-defined]
6363
return readable_span
6464

65-
Span._readable_span = sentry_patched_readable_span
65+
Span._readable_span = sentry_patched_readable_span # type: ignore[method-assign]
6666

6767

6868
def _setup_sentry_tracing():

sentry_sdk/integrations/opentelemetry/sampler.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,13 @@ def should_sample(
132132
# parent_span_context.is_valid means this span has a parent, remote or local
133133
is_root_span = not parent_span_context.is_valid or parent_span_context.is_remote
134134

135+
sample_rate = None
136+
135137
# Explicit sampled value provided at start_span
136-
if attributes.get(SentrySpanAttribute.CUSTOM_SAMPLED) is not None:
138+
custom_sampled = cast("Optional[bool]", attributes.get(SentrySpanAttribute.CUSTOM_SAMPLED))
139+
if custom_sampled is not None:
137140
if is_root_span:
138-
sample_rate = float(attributes[SentrySpanAttribute.CUSTOM_SAMPLED])
141+
sample_rate = float(custom_sampled)
139142
if sample_rate > 0:
140143
return sampled_result(parent_span_context, attributes, sample_rate)
141144
else:
@@ -145,8 +148,6 @@ def should_sample(
145148
f"[Tracing] Ignoring sampled param for non-root span {name}"
146149
)
147150

148-
sample_rate = None
149-
150151
# Check if there is a traces_sampler
151152
# Traces_sampler is responsible to check parent sampled to have full transactions.
152153
has_traces_sampler = callable(client.options.get("traces_sampler"))
@@ -190,16 +191,17 @@ def get_description(self) -> str:
190191

191192

192193
def create_sampling_context(name, attributes, parent_span_context, trace_id):
193-
# type: (str, Attributes, SpanContext, str) -> dict[str, Any]
194+
# type: (str, Attributes, Optional[SpanContext], int) -> dict[str, Any]
194195
sampling_context = {
195196
"transaction_context": {
196197
"name": name,
197-
"op": attributes.get(SentrySpanAttribute.OP),
198-
"source": attributes.get(SentrySpanAttribute.SOURCE),
198+
"op": attributes.get(SentrySpanAttribute.OP) if attributes else None,
199+
"source": attributes.get(SentrySpanAttribute.SOURCE) if attributes else None,
199200
},
200201
"parent_sampled": get_parent_sampled(parent_span_context, trace_id),
201-
}
202+
} # type: dict[str, Any]
202203

203-
sampling_context.update(attributes)
204+
if attributes is not None:
205+
sampling_context.update(attributes)
204206

205207
return sampling_context

sentry_sdk/integrations/opentelemetry/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,12 @@
1818
import sentry_sdk
1919
from sentry_sdk.utils import Dsn
2020
from sentry_sdk.consts import SPANSTATUS, OP, SPANDATA
21-
from sentry_sdk.tracing import get_span_status_from_http_code, DEFAULT_SPAN_ORIGIN
22-
from sentry_sdk.tracing_utils import Baggage, LOW_QUALITY_TRANSACTION_SOURCES
21+
from sentry_sdk.tracing import (
22+
get_span_status_from_http_code,
23+
DEFAULT_SPAN_ORIGIN,
24+
LOW_QUALITY_TRANSACTION_SOURCES,
25+
)
26+
from sentry_sdk.tracing_utils import Baggage
2327
from sentry_sdk.integrations.opentelemetry.consts import SentrySpanAttribute
2428

2529
from sentry_sdk._types import TYPE_CHECKING

sentry_sdk/tracing.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ def finish(
266266
scope=None, # type: Optional[sentry_sdk.Scope]
267267
end_timestamp=None, # type: Optional[Union[float, datetime]]
268268
):
269-
# type: (...) -> Optional[str]
269+
# type: (...) -> None
270270
pass
271271

272272
def set_measurement(self, name, value, unit=""):
@@ -375,7 +375,9 @@ def __init__(
375375
self.set_status(status)
376376

377377
def __eq__(self, other):
378-
# type: (Span) -> bool
378+
# type: (object) -> bool
379+
if not isinstance(other, Span):
380+
return False
379381
return self._otel_span == other._otel_span
380382

381383
def __repr__(self):
@@ -526,7 +528,6 @@ def sample_rate(self):
526528
sample_rate = self._otel_span.get_span_context().trace_state.get(
527529
TRACESTATE_SAMPLE_RATE_KEY
528530
)
529-
sample_rate = cast("Optional[str]", sample_rate)
530531
return float(sample_rate) if sample_rate is not None else None
531532

532533
@property
@@ -668,18 +669,24 @@ def set_data(self, key, value):
668669

669670
def get_attribute(self, name):
670671
# type: (str) -> Optional[Any]
671-
if not isinstance(self._otel_span, ReadableSpan):
672+
if (
673+
not isinstance(self._otel_span, ReadableSpan)
674+
or not self._otel_span.attributes
675+
):
672676
return None
673677
return self._otel_span.attributes.get(name)
674678

675679
def set_attribute(self, key, value):
676680
# type: (str, Any) -> None
681+
# otel doesn't support None as values, preferring to not set the key
682+
# at all instead
677683
if value is None:
678-
# otel doesn't support None as values, preferring to not set the key
679-
# at all instead
684+
return
685+
serialized_value = _serialize_span_attribute(value)
686+
if serialized_value is None:
680687
return
681688

682-
self._otel_span.set_attribute(key, _serialize_span_attribute(value))
689+
self._otel_span.set_attribute(key, serialized_value)
683690

684691
@property
685692
def status(self):
@@ -690,7 +697,7 @@ def status(self):
690697
Sentry `SPANSTATUS` it can not be guaranteed that the status
691698
set in `set_status()` will be the same as the one returned here.
692699
"""
693-
if not hasattr(self._otel_span, "status"):
700+
if not isinstance(self._otel_span, ReadableSpan):
694701
return None
695702

696703
if self._otel_span.status.status_code == StatusCode.UNSET:
@@ -740,10 +747,10 @@ def set_http_status(self, http_status):
740747

741748
def is_success(self):
742749
# type: () -> bool
743-
return self._otel_span.status.code == StatusCode.OK
750+
return self.status == SPANSTATUS.OK
744751

745752
def finish(self, end_timestamp=None):
746-
# type: (Optional[Union[float, datetime]]) -> Optional[str]
753+
# type: (Optional[Union[float, datetime]]) -> None
747754
if end_timestamp is not None:
748755
from sentry_sdk.integrations.opentelemetry.utils import (
749756
convert_to_otel_timestamp,

sentry_sdk/tracing_utils.py

Lines changed: 0 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -525,52 +525,6 @@ def from_options(cls, scope):
525525

526526
return Baggage(sentry_items, third_party_items, mutable)
527527

528-
@classmethod
529-
def populate_from_transaction(cls, transaction):
530-
# type: (sentry_sdk.tracing.Transaction) -> Baggage
531-
"""
532-
Populate fresh baggage entry with sentry_items and make it immutable
533-
if this is the head SDK which originates traces.
534-
"""
535-
client = sentry_sdk.get_client()
536-
sentry_items = {} # type: Dict[str, str]
537-
538-
if not client.is_active():
539-
return Baggage(sentry_items)
540-
541-
options = client.options or {}
542-
543-
sentry_items["trace_id"] = transaction.trace_id
544-
545-
if options.get("environment"):
546-
sentry_items["environment"] = options["environment"]
547-
548-
if options.get("release"):
549-
sentry_items["release"] = options["release"]
550-
551-
if options.get("dsn"):
552-
sentry_items["public_key"] = Dsn(options["dsn"]).public_key
553-
554-
if (
555-
transaction.name
556-
and transaction.source not in LOW_QUALITY_TRANSACTION_SOURCES
557-
):
558-
sentry_items["transaction"] = transaction.name
559-
560-
if transaction.sample_rate is not None:
561-
sentry_items["sample_rate"] = str(transaction.sample_rate)
562-
563-
if transaction.sampled is not None:
564-
sentry_items["sampled"] = "true" if transaction.sampled else "false"
565-
566-
# there's an existing baggage but it was mutable,
567-
# which is why we are creating this new baggage.
568-
# However, if by chance the user put some sentry items in there, give them precedence.
569-
if transaction._baggage and transaction._baggage.sentry_items:
570-
sentry_items.update(transaction._baggage.sentry_items)
571-
572-
return Baggage(sentry_items, mutable=False)
573-
574528
def freeze(self):
575529
# type: () -> None
576530
self.mutable = False
@@ -722,6 +676,5 @@ def get_current_span(scope=None):
722676
# Circular imports
723677
from sentry_sdk.tracing import (
724678
BAGGAGE_HEADER_NAME,
725-
LOW_QUALITY_TRANSACTION_SOURCES,
726679
SENTRY_TRACE_HEADER_NAME,
727680
)

sentry_sdk/transport.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from sentry_sdk.worker import BackgroundWorker
2424
from sentry_sdk.envelope import Envelope, Item, PayloadRef
2525

26-
from typing import TYPE_CHECKING
26+
from typing import TYPE_CHECKING, cast
2727

2828
if TYPE_CHECKING:
2929
from typing import Any
@@ -179,6 +179,7 @@ def _parse_rate_limits(header, now=None):
179179

180180
retry_after = now + timedelta(seconds=int(retry_after_val))
181181
for category in categories and categories.split(";") or (None,):
182+
category = cast("Optional[EventDataCategory]", category)
182183
yield category, retry_after
183184
except (LookupError, ValueError):
184185
continue

0 commit comments

Comments
 (0)