Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into potel-base
Browse files Browse the repository at this point in the history
  • Loading branch information
sl0thentr0py committed Jul 9, 2024
2 parents f0c1a84 + ee84c81 commit de1b0e3
Show file tree
Hide file tree
Showing 23 changed files with 279 additions and 127 deletions.
1 change: 0 additions & 1 deletion .tool-versions

This file was deleted.

21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# Changelog

## 2.8.0

### Various fixes & improvements

- `profiler_id` uses underscore (#3249) by @Zylphrex
- Don't send full env to subprocess (#3251) by @kmichel-aiven
- Stop using `Hub` in `HttpTransport` (#3247) by @szokeasaurusrex
- Remove `ipdb` from test requirements (#3237) by @rominf
- Avoid propagation of empty baggage (#2968) by @hartungstenio
- Add entry point for `SentryPropagator` (#3086) by @mender
- Bump checkouts/data-schemas from `8c13457` to `88273a9` (#3225) by @dependabot

## 2.7.1

### Various fixes & improvements

- fix(otel): Fix missing baggage (#3218) by @sentrivana
- This is the config file of asdf-vm which we do not use. (#3215) by @antonpirker
- Added option to disable middleware spans in Starlette (#3052) by @antonpirker
- build: Update tornado version in setup.py to match code check. (#3206) by @aclemons

## 2.7.0

- Add `origin` to spans and transactions (#3133) by @antonpirker
Expand Down
2 changes: 1 addition & 1 deletion checkouts/data-schemas
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
copyright = "2019-{}, Sentry Team and Contributors".format(datetime.now().year)
author = "Sentry Team and Contributors"

release = "2.7.0"
release = "2.8.0"
version = ".".join(release.split(".")[:2]) # The short X.Y version.


Expand Down
1 change: 0 additions & 1 deletion requirements-testing.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,4 @@ executing
asttokens
responses
pysocks
ipdb
setuptools
4 changes: 2 additions & 2 deletions sentry_sdk/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ class SPANDATA:
Example: "MainThread"
"""

PROFILER_ID = "profiler.id"
PROFILER_ID = "profiler_id"
"""
Label identifying the profiler id that the span occurred in. This should be a string.
Example: "5249fbada8d5416482c2f6e47e337372"
Expand Down Expand Up @@ -529,4 +529,4 @@ def _get_default_options():
del _get_default_options


VERSION = "2.7.0"
VERSION = "2.8.0"
11 changes: 6 additions & 5 deletions sentry_sdk/integrations/opentelemetry/propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,23 @@
SpanContext,
TraceFlags,
)

from sentry_sdk._types import TYPE_CHECKING
from sentry_sdk.integrations.opentelemetry.consts import (
SENTRY_BAGGAGE_KEY,
SENTRY_TRACE_KEY,
)
from sentry_sdk.integrations.opentelemetry.span_processor import (
SentrySpanProcessor,
)

from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
)
from sentry_sdk.tracing_utils import Baggage, extract_sentrytrace_data
from sentry_sdk._types import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Optional
from typing import Set
from typing import Optional, Set


class SentryPropagator(TextMapPropagator):
Expand Down Expand Up @@ -107,7 +106,9 @@ def inject(self, carrier, context=None, setter=default_setter):
if sentry_span.containing_transaction:
baggage = sentry_span.containing_transaction.get_baggage()
if baggage:
setter.set(carrier, BAGGAGE_HEADER_NAME, baggage.serialize())
baggage_data = baggage.serialize()
if baggage_data:
setter.set(carrier, BAGGAGE_HEADER_NAME, baggage_data)

@property
def fields(self):
Expand Down
17 changes: 7 additions & 10 deletions sentry_sdk/integrations/opentelemetry/span_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,17 +253,14 @@ def _get_trace_data(self, otel_span, parent_context):
)
trace_data["parent_span_id"] = parent_span_id

if parent_context is not None:
sentry_trace_data = get_value(SENTRY_TRACE_KEY, parent_context)
sentry_trace_data = cast(
"dict[str, Union[str, bool, None]]", sentry_trace_data
)
trace_data["parent_sampled"] = (
sentry_trace_data["parent_sampled"] if sentry_trace_data else None
)
sentry_trace_data = get_value(SENTRY_TRACE_KEY, parent_context)
sentry_trace_data = cast("dict[str, Union[str, bool, None]]", sentry_trace_data)
trace_data["parent_sampled"] = (
sentry_trace_data["parent_sampled"] if sentry_trace_data else None
)

baggage = get_value(SENTRY_BAGGAGE_KEY, parent_context)
trace_data["baggage"] = baggage
baggage = get_value(SENTRY_BAGGAGE_KEY, parent_context)
trace_data["baggage"] = baggage

return trace_data

Expand Down
6 changes: 5 additions & 1 deletion sentry_sdk/integrations/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,11 @@ def sentry_patched_popen_init(self, *a, **kw):
):
if env is None:
env = _init_argument(
a, kw, "env", 10, lambda x: dict(x or os.environ)
a,
kw,
"env",
10,
lambda x: dict(x if x is not None else os.environ),
)
env["SUBPROCESS_" + k.upper().replace("-", "_")] = v

Expand Down
4 changes: 2 additions & 2 deletions sentry_sdk/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class TransactionKwargs(SpanKwargs, total=False):
ProfileContext = TypedDict(
"ProfileContext",
{
"profiler.id": str,
"profiler_id": str,
},
)

Expand Down Expand Up @@ -693,7 +693,7 @@ def get_profile_context(self):
return None

return {
"profiler.id": profiler_id,
"profiler_id": profiler_id,
}


Expand Down
54 changes: 36 additions & 18 deletions sentry_sdk/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import urllib3
import certifi

import sentry_sdk
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
Expand All @@ -33,10 +34,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event

DataCategory = Optional[str]

from sentry_sdk._types import Event, EventDataCategory

KEEP_ALIVE_SOCKET_OPTIONS = []
for option in [
Expand Down Expand Up @@ -133,7 +131,7 @@ def kill(self):
def record_lost_event(
self,
reason, # type: str
data_category=None, # type: Optional[str]
data_category=None, # type: Optional[EventDataCategory]
item=None, # type: Optional[Item]
):
# type: (...) -> None
Expand All @@ -155,7 +153,7 @@ def __del__(self):


def _parse_rate_limits(header, now=None):
# type: (Any, Optional[datetime]) -> Iterable[Tuple[DataCategory, datetime]]
# type: (Any, Optional[datetime]) -> Iterable[Tuple[Optional[EventDataCategory], datetime]]
if now is None:
now = datetime.now(timezone.utc)

Expand Down Expand Up @@ -195,11 +193,11 @@ def __init__(
self.options = options # type: Dict[str, Any]
self._worker = BackgroundWorker(queue_size=options["transport_queue_size"])
self._auth = self.parsed_dsn.to_auth("sentry.python/%s" % VERSION)
self._disabled_until = {} # type: Dict[DataCategory, datetime]
self._disabled_until = {} # type: Dict[Optional[EventDataCategory], datetime]
self._retry = urllib3.util.Retry()
self._discarded_events = defaultdict(
int
) # type: DefaultDict[Tuple[str, str], int]
) # type: DefaultDict[Tuple[EventDataCategory, str], int]
self._last_client_report_sent = time.time()

compresslevel = options.get("_experiments", {}).get(
Expand All @@ -218,14 +216,13 @@ def __init__(
proxy_headers=options["proxy_headers"],
)

from sentry_sdk import Hub

self.hub_cls = Hub
# Backwards compatibility for deprecated `self.hub_class` attribute
self._hub_cls = sentry_sdk.Hub

def record_lost_event(
self,
reason, # type: str
data_category=None, # type: Optional[str]
data_category=None, # type: Optional[EventDataCategory]
item=None, # type: Optional[Item]
):
# type: (...) -> None
Expand Down Expand Up @@ -548,14 +545,11 @@ def capture_envelope(
self, envelope # type: Envelope
):
# type: (...) -> None
hub = self.hub_cls.current

def send_envelope_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_envelope(envelope)
self._flush_client_reports()
with capture_internal_exceptions():
self._send_envelope(envelope)
self._flush_client_reports()

if not self._worker.submit(send_envelope_wrapper):
self.on_dropped_event("full_queue")
Expand All @@ -579,6 +573,30 @@ def kill(self):
logger.debug("Killing HTTP transport")
self._worker.kill()

@staticmethod
def _warn_hub_cls():
# type: () -> None
"""Convenience method to warn users about the deprecation of the `hub_cls` attribute."""
warnings.warn(
"The `hub_cls` attribute is deprecated and will be removed in a future release.",
DeprecationWarning,
stacklevel=3,
)

@property
def hub_cls(self):
# type: () -> type[sentry_sdk.Hub]
"""DEPRECATED: This attribute is deprecated and will be removed in a future release."""
HttpTransport._warn_hub_cls()
return self._hub_cls

@hub_cls.setter
def hub_cls(self, value):
# type: (type[sentry_sdk.Hub]) -> None
"""DEPRECATED: This attribute is deprecated and will be removed in a future release."""
HttpTransport._warn_hub_cls()
self._hub_cls = value


class _FunctionTransport(Transport):
"""
Expand Down
5 changes: 3 additions & 2 deletions sentry_sdk/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from sentry_sdk._types import Event, Hint
from sentry_sdk._types import Event, EventDataCategory, Hint
else:
from typing import Any

# The lines below allow the types to be imported from outside `if TYPE_CHECKING`
# guards. The types in this module are only intended to be used for type hints.
Event = Any
EventDataCategory = Any
Hint = Any

__all__ = ("Event", "Hint")
__all__ = ("Event", "EventDataCategory", "Hint")
7 changes: 6 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def get_file_text(file_name):

setup(
name="sentry-sdk",
version="2.7.0",
version="2.8.0",
author="Sentry Team and Contributors",
author_email="[email protected]",
url="https://github.com/getsentry/sentry-python",
Expand Down Expand Up @@ -131,6 +131,11 @@ def get_file_text(file_name):
"starlite": ["starlite>=1.48"],
"tornado": ["tornado>=6"],
},
entry_points={
"opentelemetry_propagator": [
"sentry=sentry_sdk.integrations.opentelemetry:SentryPropagator"
]
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
Expand Down
12 changes: 5 additions & 7 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,20 +248,18 @@ def append_envelope(envelope):


@pytest.fixture
def capture_client_reports(monkeypatch):
def capture_record_lost_event_calls(monkeypatch):
def inner():
reports = []
test_client = sentry_sdk.Hub.current.client
calls = []
test_client = sentry_sdk.get_client()

def record_lost_event(reason, data_category=None, item=None):
if data_category is None:
data_category = item.data_category
return reports.append((reason, data_category))
calls.append((reason, data_category, item))

monkeypatch.setattr(
test_client.transport, "record_lost_event", record_lost_event
)
return reports
return calls

return inner

Expand Down
17 changes: 17 additions & 0 deletions tests/integrations/opentelemetry/test_entry_points.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import importlib
import os
from unittest.mock import patch

from opentelemetry import propagate
from sentry_sdk.integrations.opentelemetry import SentryPropagator


def test_propagator_loaded_if_mentioned_in_environment_variable():
try:
with patch.dict(os.environ, {"OTEL_PROPAGATORS": "sentry"}):
importlib.reload(propagate)

assert len(propagate.propagators) == 1
assert isinstance(propagate.propagators[0], SentryPropagator)
finally:
importlib.reload(propagate)
Loading

0 comments on commit de1b0e3

Please sign in to comment.