Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
b4d5997
Remove store endpoint
szokeasaurusrex Jan 18, 2024
9335bd0
Fix linter error
szokeasaurusrex Jan 19, 2024
df4bdc8
Add stacklevel to warn call
szokeasaurusrex Jan 19, 2024
f5fb97d
Remove `store_api_url` test, update `get_api_url` test
szokeasaurusrex Jan 19, 2024
8f5871a
Fix mypy
szokeasaurusrex Jan 19, 2024
9a7904d
Correct import
szokeasaurusrex Jan 19, 2024
805d849
Use `Enum` instead of `StrEnum`
szokeasaurusrex Jan 19, 2024
e1e6437
Update `envelope.py`
szokeasaurusrex Jan 22, 2024
addd2a8
Remove `Envelope.events` calls
szokeasaurusrex Jan 22, 2024
5b547d1
Fix `capture_events_forksafe`
szokeasaurusrex Jan 22, 2024
7105849
Hopefully fix circular import
szokeasaurusrex Jan 22, 2024
65d830b
Manually set TestTransport
szokeasaurusrex Jan 22, 2024
e681bdb
Fix circular import
szokeasaurusrex Jan 22, 2024
ba02bc4
Revert "Fix circular import"
szokeasaurusrex Jan 22, 2024
e4b9e99
Revert "Hopefully fix circular import"
szokeasaurusrex Jan 22, 2024
bc4627f
Move EndpointType to top of file
szokeasaurusrex Jan 22, 2024
61db076
Fix AWS tests
szokeasaurusrex Jan 22, 2024
607c7a9
Remove TODO comment
szokeasaurusrex Jan 22, 2024
a93d435
Undo ABC change
szokeasaurusrex Jan 22, 2024
18b13ca
Update
szokeasaurusrex Jan 23, 2024
1ac13a5
Rename envelope_item to envelope_items
szokeasaurusrex Jan 24, 2024
df28d81
Remove unneeded import statement
szokeasaurusrex Jan 24, 2024
7dd6a2a
Updated migration guide
szokeasaurusrex Jan 24, 2024
ff425fa
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 24, 2024
cf3b0c2
Put back `has_tracing_enabled` check
szokeasaurusrex Jan 25, 2024
c419c78
Remove test for replay context
szokeasaurusrex Jan 25, 2024
6ee30a4
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
2a15dc5
Update MIGRATION_GUIDE.md
szokeasaurusrex Jan 29, 2024
2ab3ef4
Auto-enable more integrations (#2671)
sentrivana Jan 29, 2024
1e65a98
Remove deprecated code (#2666)
szokeasaurusrex Jan 29, 2024
184dd9c
Merge branch 'sentry-sdk-2.0' into szokeasaurusrex/remove-store-endpoint
szokeasaurusrex Jan 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions MIGRATION_GUIDE.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,17 @@
- A number of compatibility utilities were removed from `sentry_sdk._compat`: the constants `PY2` and `PY33`; the functions `datetime_utcnow`, `utc_from_timestamp`, `implements_str`, `contextmanager`; and the aliases `text_type`, `string_types`, `number_types`, `int_types`, `iteritems`, `binary_sequence_types`.
- The deprecated `with_locals` configuration option was removed. Use `include_local_variables` instead. See https://docs.sentry.io/platforms/python/configuration/options/#include-local-variables.
- The deprecated `request_bodies` configuration option was removed. Use `max_request_body_size`. See https://docs.sentry.io/platforms/python/configuration/options/#max-request-body-size.
- Removed `sentry_sdk.utils.Auth.store_api_url`.
- `sentry_sdk.utils.Auth.get_api_url`'s now accepts a `sentry_sdk.consts.EndpointType` enum instead of a string as its only parameter. We recommend omitting this argument when calling the function, since the parameter's default value is the only possible `sentry_sdk.consts.EndpointType` value. The parameter exists for future compatibility.
- Removed `tracing_utils_py2.py`. The `start_child_span_decorator` is now in `sentry_sdk.tracing_utils`.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.
- Removed support for the `install` method for custom integrations. Please use `setup_once` instead.
- Removed `sentry_sdk.tracing.Span.new_span`. Use `sentry_sdk.tracing.Span.start_child` instead.
- Removed `sentry_sdk.tracing.Transaction.new_span`. Use `sentry_sdk.tracing.Transaction.start_child` instead.

## Deprecated

- Deprecated `sentry_sdk.transport.Transport.capture_event`. Please use `sentry_sdk.transport.Transport.capture_envelope`, instead.
- Passing a function to `sentry_sdk.init`'s `transport` keyword argument has been deprecated. If you wish to provide a custom transport, please pass a `sentry_sdk.transport.Transport` instance or a subclass.
1 change: 0 additions & 1 deletion sentry_sdk/_types.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,7 +57,6 @@
"monitor",
]
SessionStatus = Literal["ok", "exited", "crashed", "abnormal"]
EndpointType = Literal["store", "envelope"]

DurationUnit = Literal[
"nanosecond",
Expand Down
66 changes: 24 additions & 42 deletions sentry_sdk/client.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@
logger,
)
from sentry_sdk.serializer import serialize
from sentry_sdk.tracing import trace, has_tracing_enabled
from sentry_sdk.tracing import trace
from sentry_sdk.transport import make_transport
from sentry_sdk.consts import (
DEFAULT_MAX_VALUE_LENGTH,
Expand DownExpand Up@@ -588,58 +588,40 @@ def capture_event(
):
return None

tracing_enabled = has_tracing_enabled(self.options)
attachments = hint.get("attachments")

trace_context = event_opt.get("contexts", {}).get("trace") or {}
dynamic_sampling_context = trace_context.pop("dynamic_sampling_context", {})

# If tracing is enabled all events should go to /envelope endpoint.
# If no tracing is enabled only transactions, events with attachments, and checkins should go to the /envelope endpoint.
should_use_envelope_endpoint = (
tracing_enabled
or is_transaction
or is_checkin
or bool(attachments)
or bool(self.spotlight)
)
if should_use_envelope_endpoint:
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

envelope = Envelope(headers=headers)

if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)
headers = {
"event_id": event_opt["event_id"],
"sent_at": format_timestamp(datetime.now(timezone.utc)),
}

for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())
if dynamic_sampling_context:
headers["trace"] = dynamic_sampling_context

if self.spotlight:
self.spotlight.capture_envelope(envelope)
envelope = Envelope(headers=headers)

if self.transport is None:
return None
if is_transaction:
if profile is not None:
envelope.add_profile(profile.to_json(event_opt, self.options))
envelope.add_transaction(event_opt)
elif is_checkin:
envelope.add_checkin(event_opt)
else:
envelope.add_event(event_opt)

self.transport.capture_envelope(envelope)
for attachment in attachments or ():
envelope.add_item(attachment.to_envelope_item())

else:
if self.transport is None:
return None
if self.spotlight:
self.spotlight.capture_envelope(envelope)

if self.transport is None:
return None

# All other events go to the legacy /store/ endpoint (will be removed in the future).
self.transport.capture_event(event_opt)
self.transport.capture_envelope(envelope)

return event_id

Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/consts.py
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
from enum import Enum
from sentry_sdk._types import TYPE_CHECKING

# up top to prevent circular import due to integration import
DEFAULT_MAX_VALUE_LENGTH = 1024


# Also needs to be at the top to prevent circular import
class EndpointType(Enum):
"""
The type of an endpoint. This is an enum, rather than a constant, for historical reasons
(the old /store endpoint). The enum also preserve future compatibility, in case we ever
have a new endpoint.
"""

ENVELOPE = "envelope"


if TYPE_CHECKING:
import sentry_sdk

Expand Down
6 changes: 6 additions & 0 deletions sentry_sdk/envelope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,12 @@ def parse_json(data):


class Envelope:
"""
Represents a Sentry Envelope. The calling code is responsible for adhering to the constraints
documented in the Sentry docs: https://develop.sentry.dev/sdk/envelopes/#data-model. In particular,
each envelope may have at most one Item with type "event" or "transaction" (but not both).
"""

def __init__(
self,
headers=None, # type: Optional[Dict[str, Any]]
Expand Down
11 changes: 0 additions & 11 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -1077,17 +1077,6 @@ def _apply_contexts_to_event(self, event, hint, options):
else:
contexts["trace"] = self.get_trace_context()

# Add "reply_id" context
try:
replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
except (KeyError, TypeError):
replay_id = None

if replay_id is not None:
contexts["replay"] = {
"replay_id": replay_id,
}

@_disable_capture
def apply_to_event(
self,
Expand Down
130 changes: 57 additions & 73 deletions sentry_sdk/transport.py
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
import io
import warnings
import urllib3
import certifi
import gzip
import time
from datetime import datetime, timedelta, timezone
from collections import defaultdict

from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps
from sentry_sdk.consts import EndpointType
from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions
from sentry_sdk.worker import BackgroundWorker
from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -25,7 +27,7 @@
from urllib3.poolmanager import PoolManager
from urllib3.poolmanager import ProxyManager

from sentry_sdk._types import Event, EndpointType
from sentry_sdk._types import Event

DataCategory = Optional[str]

Expand DownExpand Up@@ -58,10 +60,21 @@ def capture_event(
):
# type: (...) -> None
"""
DEPRECATED: Please use capture_envelope instead.

This gets invoked with the event dictionary when an event should
be sent to sentry.
"""
raise NotImplementedError()

warnings.warn(
"capture_event is deprecated, please use capture_envelope instead!",
DeprecationWarning,
stacklevel=2,
)

envelope = Envelope()
envelope.add_event(event)
self.capture_envelope(envelope)

def capture_envelope(
self, envelope # type: Envelope
Expand All@@ -71,9 +84,8 @@ def capture_envelope(
Send an envelope to Sentry.

Envelopes are a data container format that can hold any type of data
submitted to Sentry. We use it for transactions and sessions, but
regular "error" events should go through `capture_event` for backwards
compat.
submitted to Sentry. We use it to send all event data (including errors,
transactions, crons checkins, etc.) to Sentry.
"""
raise NotImplementedError()

Expand All@@ -83,13 +95,23 @@ def flush(
callback=None, # type: Optional[Any]
):
# type: (...) -> None
"""Wait `timeout` seconds for the current events to be sent out."""
pass
"""
Wait `timeout` seconds for the current events to be sent out.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def kill(self):
# type: () -> None
"""Forcefully kills the transport."""
pass
"""
Forcefully kills the transport.

The default implementation is a no-op, since this method may only be relevant to some transports.
Subclasses should override this method if necessary.
"""
return None

def record_lost_event(
self,
Expand DownExpand Up@@ -216,7 +238,7 @@ def _send_request(
self,
body, # type: bytes
headers, # type: Dict[str, str]
endpoint_type="store", # type: EndpointType
endpoint_type=EndpointType.ENVELOPE, # type: EndpointType
envelope=None, # type: Optional[Envelope]
):
# type: (...) -> None
Expand DownExpand Up@@ -333,46 +355,6 @@ def is_healthy(self):
# type: () -> bool
return not (self._is_worker_full() or self._is_rate_limited())

def _send_event(
self, event # type: Event
):
# type: (...) -> None

if self._check_disabled("error"):
self.on_dropped_event("self_rate_limits")
self.record_lost_event("ratelimit_backoff", data_category="error")
return None

body = io.BytesIO()
if self._compresslevel == 0:
body.write(json_dumps(event))
else:
with gzip.GzipFile(
fileobj=body, mode="w", compresslevel=self._compresslevel
) as f:
f.write(json_dumps(event))

assert self.parsed_dsn is not None
logger.debug(
"Sending event, type:%s level:%s event_id:%s project:%s host:%s"
% (
event.get("type") or "null",
event.get("level") or "null",
event.get("event_id") or "null",
self.parsed_dsn.project_id,
self.parsed_dsn.host,
)
)

headers = {
"Content-Type": "application/json",
}
if self._compresslevel > 0:
headers["Content-Encoding"] = "gzip"

self._send_request(body.getvalue(), headers=headers)
return None

def _send_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -430,7 +412,7 @@ def _send_envelope(
self._send_request(
body.getvalue(),
headers=headers,
endpoint_type="envelope",
endpoint_type=EndpointType.ENVELOPE,
envelope=envelope,
)
return None
Expand DownExpand Up@@ -501,23 +483,6 @@ def _make_pool(
else:
return urllib3.PoolManager(**opts)

def capture_event(
self, event # type: Event
):
# type: (...) -> None
hub = self.hub_cls.current

def send_event_wrapper():
# type: () -> None
with hub:
with capture_internal_exceptions():
self._send_event(event)
self._flush_client_reports()

if not self._worker.submit(send_event_wrapper):
self.on_dropped_event("full_queue")
self.record_lost_event("queue_overflow", data_category="error")

def capture_envelope(
self, envelope # type: Envelope
):
Expand DownExpand Up@@ -555,6 +520,11 @@ def kill(self):


class _FunctionTransport(Transport):
"""
DEPRECATED: Users wishing to provide a custom transport should subclass
the Transport class, rather than providing a function.
"""

def __init__(
self, func # type: Callable[[Event], None]
):
Expand All@@ -569,19 +539,33 @@ def capture_event(
self._func(event)
return None

def capture_envelope(self, envelope: Envelope) -> None:
# Since function transports expect to be called with an event, we need
# to iterate over the envelope and call the function for each event, via
# the deprecated capture_event method.
event = envelope.get_event()
if event is not None:
self.capture_event(event)


def make_transport(options):
# type: (Dict[str, Any]) -> Optional[Transport]
ref_transport = options["transport"]

# If no transport is given, we use the http transport class
if ref_transport is None:
transport_cls = HttpTransport # type: Type[Transport]
elif isinstance(ref_transport, Transport):
# By default, we use the http transport class
transport_cls = HttpTransport # type: Type[Transport]

if isinstance(ref_transport, Transport):
return ref_transport
elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport):
transport_cls = ref_transport
elif callable(ref_transport):
warnings.warn(
"Function transports are deprecated and will be removed in a future release."
"Please provide a Transport instance or subclass, instead.",
DeprecationWarning,
stacklevel=2,
)
return _FunctionTransport(ref_transport)

# if a transport class is given only instantiate it if the dsn is not
Expand Down
Loading