diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b31d918e88..11a1a66ceb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -100,7 +100,7 @@ uv run ruff format tests sentry_sdk We use `mypy` for typing our codebase. Use the following command to typecheck the source: ``` -uv run --group typing mypy sentry_sdk +uv run --group typing mypy sentry_sdk ``` ##### Install Coding Style Pre-commit Hooks @@ -167,7 +167,7 @@ TESTPATH=tests/integrations/logging/test_logging.py uv run tox -e py3.12-common To select specific tests, you can forward arguments to `pytest` like so ```bash -uv run tox -e py3.12-celery-v5.5.3 -- -k test_transaction_events +uv run tox -e py3.12-celery-v5.5.3 -- -k test_simple_with_performance ``` In general, you use diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 3e3a36a211..faa9ed1bf2 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -156,6 +156,7 @@ Looking to upgrade from Sentry SDK 2.x to 3.x? Here's a comprehensive list of wh - The `update_current_span` API was removed. - `SanicIntegration` no longer accepts `unsampled_statuses`. - The `trace_ignore_status_codes` option was removed. +- `add_attachment` no longer accepts an `add_to_transactions` argument. ## Deprecated diff --git a/sentry_sdk/_types.py b/sentry_sdk/_types.py index 98dff9e88c..4634a88156 100644 --- a/sentry_sdk/_types.py +++ b/sentry_sdk/_types.py @@ -394,7 +394,6 @@ class DataCollection(TypedDict): "default", "error", "crash", - "transaction", "security", "attachment", "session", diff --git a/sentry_sdk/api.py b/sentry_sdk/api.py index 3d2baef89c..bae0526442 100644 --- a/sentry_sdk/api.py +++ b/sentry_sdk/api.py @@ -174,11 +174,8 @@ def add_attachment( filename: "Optional[str]" = None, path: "Optional[str]" = None, content_type: "Optional[str]" = None, - add_to_transactions: bool = False, ) -> None: - return get_isolation_scope().add_attachment( - bytes, filename, path, content_type, add_to_transactions - ) + return get_isolation_scope().add_attachment(bytes, filename, path, content_type) @scopemethod diff --git a/sentry_sdk/attachments.py b/sentry_sdk/attachments.py index 4d69d3acf2..7bcf59e181 100644 --- a/sentry_sdk/attachments.py +++ b/sentry_sdk/attachments.py @@ -13,8 +13,7 @@ class Attachment: This class stores attachments that can be sent along with an event. Attachments are files or other data, e.g. config or log files, that are relevant to an event. Attachments are set on the ``Scope``, and are sent along with - all non-transaction events (or all events including transactions if ``add_to_transactions`` is ``True``) that are - captured within the ``Scope``. + all non-transaction events that are captured within the ``Scope``. To add an attachment to a ``Scope``, use :py:meth:`sentry_sdk.Scope.add_attachment`. The parameters for ``add_attachment`` are the same as the parameters for this class's constructor. @@ -25,7 +24,6 @@ class Attachment: :param path: Path to a file to attach. Must be provided unless ``bytes`` is provided. :param content_type: The content type of the attachment. If not provided, it will be guessed from the ``filename`` parameter, if available, or the ``path`` parameter if ``filename`` is ``None``. - :param add_to_transactions: Whether to add this attachment to transactions. Defaults to ``False``. """ def __init__( @@ -34,7 +32,6 @@ def __init__( filename: "Optional[str]" = None, path: "Optional[str]" = None, content_type: "Optional[str]" = None, - add_to_transactions: bool = False, ) -> None: if bytes is None and path is None: raise TypeError("path or raw bytes required for attachment") @@ -48,7 +45,6 @@ def __init__( self.filename = filename self.path = path self.content_type = content_type - self.add_to_transactions = add_to_transactions def to_envelope_item(self) -> "Item": """Returns an envelope item for this attachment.""" diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index d2f9086954..e2a63c1794 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -1,15 +1,12 @@ -import json import os -import platform import random import socket -import sys import uuid -from collections.abc import Iterable, Mapping +from collections.abc import Mapping from contextvars import ContextVar from datetime import datetime, timezone from importlib import import_module -from typing import TYPE_CHECKING, Dict, List, cast, overload +from typing import TYPE_CHECKING, Dict, cast, overload from sentry_sdk._compat import check_uwsgi_thread_support from sentry_sdk._log_batcher import LogBatcher @@ -18,7 +15,6 @@ from sentry_sdk.consts import ( DEFAULT_MAX_VALUE_LENGTH, DEFAULT_OPTIONS, - SPANSTATUS, VERSION, ClientConstructor, ) @@ -34,7 +30,7 @@ from sentry_sdk.scrubber import EventScrubber from sentry_sdk.serializer import serialize from sentry_sdk.sessions import SessionFlusher -from sentry_sdk.traces import SpanStatus, StreamedSpan, trace +from sentry_sdk.traces import StreamedSpan, trace from sentry_sdk.transport import ( AsyncHttpTransport, HttpTransportCore, @@ -44,7 +40,6 @@ AnnotatedValue, capture_internal_exceptions, current_stacktrace, - datetime_from_isoformat, env_to_bool, format_timestamp, get_before_send_log, @@ -70,7 +65,6 @@ Log, Metric, SDKInfo, - SerializedAttributeValue, ) from sentry_sdk.integrations import Integration from sentry_sdk.scope import Scope @@ -92,203 +86,6 @@ } -def _serialized_v1_attribute_to_serialized_v2_attribute( - attribute_value: "Any", -) -> "Optional[SerializedAttributeValue]": - if isinstance(attribute_value, bool): - return { - "value": attribute_value, - "type": "boolean", - } - - if isinstance(attribute_value, int): - return { - "value": attribute_value, - "type": "integer", - } - - if isinstance(attribute_value, float): - return { - "value": attribute_value, - "type": "double", - } - - if isinstance(attribute_value, str): - return { - "value": attribute_value, - "type": "string", - } - - if isinstance(attribute_value, list): - if not attribute_value: - return {"value": [], "type": "array"} - - ty = type(attribute_value[0]) - if ty in (int, str, bool, float) and all( - type(v) is ty for v in attribute_value - ): - return { - "value": attribute_value, - "type": "array", - } - - # Types returned when the serializer for V1 span attributes recurses into some container types. - if isinstance(attribute_value, (dict, list)): - return { - "value": json.dumps(attribute_value), - "type": "string", - } - - return None - - -def _serialized_v1_span_to_serialized_v2_span( - span: "dict[str, Any]", event: "Event" -) -> "dict[str, Any]": - # See SpanBatcher._to_transport_format() for analogous population of all entries except "attributes". - res: "dict[str, Any]" = { - "status": SpanStatus.OK.value, - "is_segment": False, - } - - if "trace_id" in span: - res["trace_id"] = span["trace_id"] - - if "span_id" in span: - res["span_id"] = span["span_id"] - - if "description" in span: - description = span["description"] - - if description is None and "op" in span: - description = span["op"] - - res["name"] = description - - if "start_timestamp" in span: - start_timestamp = None - try: - start_timestamp = datetime_from_isoformat(span["start_timestamp"]) - except Exception: - pass - - if start_timestamp is not None: - res["start_timestamp"] = start_timestamp.timestamp() - - if "timestamp" in span: - end_timestamp = None - try: - end_timestamp = datetime_from_isoformat(span["timestamp"]) - except Exception: - pass - - if end_timestamp is not None: - res["end_timestamp"] = end_timestamp.timestamp() - - if "parent_span_id" in span: - res["parent_span_id"] = span["parent_span_id"] - - if "status" in span and span["status"] != SPANSTATUS.OK: - res["status"] = "error" - - attributes: "Dict[str, Any]" = {} - - if "op" in span: - attributes["sentry.op"] = span["op"] - if "origin" in span: - attributes["sentry.origin"] = span["origin"] - - span_data = span.get("data") - if isinstance(span_data, dict): - attributes.update(span_data) - - span_tags = span.get("tags") - if isinstance(span_tags, dict): - attributes.update(span_tags) - - # See Scope._apply_user_attributes_to_telemetry() for user attributes. - user = event.get("user") - if isinstance(user, dict): - if "id" in user: - attributes["user.id"] = user["id"] - if "username" in user: - attributes["user.name"] = user["username"] - if "email" in user: - attributes["user.email"] = user["email"] - - # See Scope.set_global_attributes() for release, environment, and SDK metadata. - if "release" in event: - attributes["sentry.release"] = event["release"] - if "environment" in event: - attributes["sentry.environment"] = event["environment"] - if "server_name" in event: - attributes["server.address"] = event["server_name"] - if "transaction" in event: - attributes["sentry.segment.name"] = event["transaction"] - - trace_context = event.get("contexts", {}).get("trace", {}) - if "span_id" in trace_context: - attributes["sentry.segment.id"] = trace_context["span_id"] - - sdk_info = event.get("sdk") - if isinstance(sdk_info, dict): - if "name" in sdk_info: - attributes["sentry.sdk.name"] = sdk_info["name"] - if "version" in sdk_info: - attributes["sentry.sdk.version"] = sdk_info["version"] - - attributes["process.runtime.name"] = platform.python_implementation() - attributes["process.runtime.version"] = ( - f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}" - ) - - if not attributes: - return res - - res["attributes"] = {} - for key, value in attributes.items(): - converted_value = _serialized_v1_attribute_to_serialized_v2_attribute(value) - if converted_value is None: - continue - - res["attributes"][key] = converted_value - - # Remove redundant attribute, as status is stored in the status field. - if "status" in res["attributes"]: - del res["attributes"]["status"] - - return res - - -def _split_gen_ai_spans( - event_opt: "Event", -) -> "Optional[tuple[List[Dict[str, object]], List[Dict[str, object]]]]": - if "spans" not in event_opt: - return None - - spans: "Any" = event_opt["spans"] - if isinstance(spans, AnnotatedValue): - spans = spans.value - - if not isinstance(spans, Iterable): - return None - - non_gen_ai_spans = [] - gen_ai_spans = [] - for span in spans: - if not isinstance(span, dict): - non_gen_ai_spans.append(span) - continue - - span_op = span.get("op") - if isinstance(span_op, str) and span_op.startswith("gen_ai."): - gen_ai_spans.append(span) - else: - non_gen_ai_spans.append(span) - - return non_gen_ai_spans, gen_ai_spans - - def _get_options(*args: "Optional[str]", **kwargs: "Any") -> "Dict[str, Any]": if args and (isinstance(args[0], (bytes, str)) or args[0] is None): dsn: "Optional[str]" = args[0] diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 7cd35a08a0..665362f87a 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -1170,32 +1170,6 @@ class SPANDATA: """ -class SPANSTATUS: - """ - The status of a Sentry span. - - See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context - """ - - ABORTED = "aborted" - ALREADY_EXISTS = "already_exists" - CANCELLED = "cancelled" - DATA_LOSS = "data_loss" - DEADLINE_EXCEEDED = "deadline_exceeded" - FAILED_PRECONDITION = "failed_precondition" - INTERNAL_ERROR = "internal_error" - INVALID_ARGUMENT = "invalid_argument" - NOT_FOUND = "not_found" - OK = "ok" - OUT_OF_RANGE = "out_of_range" - PERMISSION_DENIED = "permission_denied" - RESOURCE_EXHAUSTED = "resource_exhausted" - UNAUTHENTICATED = "unauthenticated" - UNAVAILABLE = "unavailable" - UNIMPLEMENTED = "unimplemented" - UNKNOWN_ERROR = "unknown_error" - - class OP: ANTHROPIC_MESSAGES_CREATE = "ai.messages.create.anthropic" CACHE_GET = "cache.get" @@ -1613,28 +1587,28 @@ def __init__( If provided, the options will override the default `urllib3` `socket options `_. - :param traces_sample_rate: A number between `0` and `1`, controlling the percentage chance a given transaction + :param traces_sample_rate: A number between `0` and `1`, controlling the percentage chance a given service span will be sent to Sentry. - (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions created in the app. + (`0` represents 0% while `1` represents 100%.) Applies equally to all service spans created in the app. Either this or `traces_sampler` must be defined to enable tracing. If `traces_sample_rate` is `0`, this means that no new traces will be created. However, if you have another service (for example a JS frontend) that makes requests to your service that include trace - information, those traces will be continued and thus transactions will be sent to Sentry. + information, those traces will be continued and thus spans will be sent to Sentry. If you want to disable all tracing you need to set `traces_sample_rate=None`. In this case, no new traces will be started and no incoming traces will be continued. - :param traces_sampler: A function responsible for determining the percentage chance a given transaction will be + :param traces_sampler: A function responsible for determining the percentage chance a given service span will be sent to Sentry. - It will automatically be passed information about the transaction and the context in which it's being + It will automatically be passed information about the service span and the context in which it's being created, and must return a number between `0` (0% chance of being sent) and `1` (100% chance of being sent). - Can also be used for filtering transactions, by returning `0` for those that are unwanted. + Can also be used for filtering service spans, by returning `0` for those that are unwanted. Either this or `traces_sample_rate` must be defined to enable tracing. @@ -1727,9 +1701,6 @@ def __init__( Modifications to the span's attributes and name will be retained. Unlike ``before_send_log`` and ``before_send_metric``, spans cannot be dropped by returning None. - :param stream_gen_ai_spans: When set, generative AI spans are sent in a new transport format to - reduce downstream data loss. - :param ignore_spans: A sequence of span-matching rules. Matching spans are ignored. :param _experiments: Dictionary of experimental, opt-in features that are not yet stable. diff --git a/sentry_sdk/integrations/arq.py b/sentry_sdk/integrations/arq.py index fa03233bf5..ba8c7bea90 100644 --- a/sentry_sdk/integrations/arq.py +++ b/sentry_sdk/integrations/arq.py @@ -1,7 +1,7 @@ import sys import sentry_sdk -from sentry_sdk.consts import OP, SPANDATA, SPANSTATUS +from sentry_sdk.consts import OP, SPANDATA from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version from sentry_sdk.integrations.logging import ignore_logger_for_events from sentry_sdk.scope import should_send_default_pii @@ -125,15 +125,6 @@ async def _sentry_run_job(self: "Worker", job_id: str, score: int) -> None: def _capture_exception(exc_info: "ExcInfo") -> None: - scope = sentry_sdk.get_current_scope() - - if scope.transaction is not None: - if exc_info[0] in ARQ_CONTROL_FLOW_EXCEPTIONS: - scope.transaction.set_status(SPANSTATUS.ABORTED) - return - - scope.transaction.set_status(SPANSTATUS.INTERNAL_ERROR) - if exc_info[0] in ARQ_CONTROL_FLOW_EXCEPTIONS: return @@ -150,11 +141,6 @@ def _make_event_processor( ) -> "EventProcessor": def event_processor(event: "Event", hint: "Hint") -> "Optional[Event]": with capture_internal_exceptions(): - scope = sentry_sdk.get_current_scope() - if scope.transaction is not None: - scope.transaction.name = ctx["job_name"] - event["transaction"] = ctx["job_name"] - tags = event.setdefault("tags", {}) tags["arq_task_id"] = ctx["job_id"] tags["arq_task_retry"] = ctx["job_try"] > 1 diff --git a/sentry_sdk/integrations/bottle.py b/sentry_sdk/integrations/bottle.py index 06e360b06f..fb40c1b110 100644 --- a/sentry_sdk/integrations/bottle.py +++ b/sentry_sdk/integrations/bottle.py @@ -12,7 +12,6 @@ from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware from sentry_sdk.traces import SOURCE_FOR_STYLE as SEGMENT_SOURCE_FOR_STYLE -from sentry_sdk.tracing import SOURCE_FOR_STYLE as TRANSACTION_SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, ensure_integration_enabled, @@ -199,39 +198,10 @@ def _set_segment_name_and_source(transaction_style: str) -> None: pass -def _set_transaction_name_and_source( - event: "Event", transaction_style: str, request: "Any" -) -> None: - name = "" - - if transaction_style == "url": - try: - name = request.route.rule or "" - except RuntimeError: - pass - - elif transaction_style == "endpoint": - try: - name = ( - request.route.name - or transaction_from_function(request.route.callback) - or "" - ) - except RuntimeError: - pass - - event["transaction"] = name - event["transaction_info"] = { - "source": TRANSACTION_SOURCE_FOR_STYLE[transaction_style] - } - - def _make_request_event_processor( app: "Bottle", request: "LocalRequest", integration: "BottleIntegration" ) -> "EventProcessor": def event_processor(event: "Event", hint: "dict[str, Any]") -> "Event": - _set_transaction_name_and_source(event, integration.transaction_style, request) - with capture_internal_exceptions(): BottleRequestExtractor(request).extract_into_event(event) diff --git a/sentry_sdk/integrations/django/__init__.py b/sentry_sdk/integrations/django/__init__.py index 565d0e88ef..8e59a64415 100644 --- a/sentry_sdk/integrations/django/__init__.py +++ b/sentry_sdk/integrations/django/__init__.py @@ -425,11 +425,13 @@ def _set_transaction_name_and_source( if hasattr(urlconf, "handler404"): handler = urlconf.handler404 if isinstance(handler, str): - scope.transaction = handler + scope.set_transaction_name(handler) else: - scope.transaction = transaction_from_function( + name = transaction_from_function( getattr(handler, "view_class", handler) ) + if name: + scope.set_transaction_name(name) except Exception: pass diff --git a/sentry_sdk/integrations/falcon.py b/sentry_sdk/integrations/falcon.py index 3a15a77b36..a1a0df9fcd 100644 --- a/sentry_sdk/integrations/falcon.py +++ b/sentry_sdk/integrations/falcon.py @@ -5,7 +5,6 @@ from sentry_sdk.integrations import DidNotEnable, Integration, _check_minimum_version from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware -from sentry_sdk.tracing import SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, ensure_integration_enabled, @@ -228,23 +227,10 @@ def _has_http_5xx_status(response: "falcon.Response") -> bool: return response.status.startswith("5") -def _set_transaction_name_and_source( - event: "Event", transaction_style: str, request: "falcon.Request" -) -> None: - name_for_style = { - "uri_template": request.uri_template, - "path": request.path, - } - event["transaction"] = name_for_style[transaction_style] - event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} - - def _make_request_event_processor( req: "falcon.Request", integration: "FalconIntegration" ) -> "EventProcessor": def event_processor(event: "Event", hint: "dict[str, Any]") -> "Event": - _set_transaction_name_and_source(event, integration.transaction_style, req) - with capture_internal_exceptions(): FalconRequestExtractor(req).extract_into_event(event) diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index e0116a6d8d..64135476ca 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -41,7 +41,6 @@ capture_internal_exception, capture_internal_exceptions, datetime_from_isoformat, - deprecation_warning, disable_capture_event, event_from_exception, exc_info_from_error, @@ -721,75 +720,15 @@ def fingerprint(self, value: "Optional[List[str]]") -> None: """When set this overrides the default fingerprint.""" self._fingerprint = value - @property - def transaction(self) -> "Any": - # would be type: () -> Optional[Transaction], see https://github.com/python/mypy/issues/3004 - """Return the transaction (root span) in the scope, if any.""" - - # there is no span/transaction on the scope - if self._span is None: - return None - - if isinstance(self._span, StreamedSpan): - deprecation_warning( - "Scope.transaction is not available in streaming mode.", - ) - return None - - # there is an orphan span on the scope - if self._span.containing_transaction is None: - return None - - # there is either a transaction (which is its own containing - # transaction) or a non-orphan span on the scope - return self._span.containing_transaction - - @transaction.setter - def transaction(self, value: "Any") -> None: - # would be type: (Optional[str]) -> None, see https://github.com/python/mypy/issues/3004 - """When set this forces a specific transaction name to be set. - - Deprecated: use set_transaction_name instead.""" - - # XXX: the docstring above is misleading. The implementation of - # apply_to_event prefers an existing value of event.transaction over - # anything set in the scope. - # XXX: note that with the introduction of the Scope.transaction getter, - # there is a semantic and type mismatch between getter and setter. The - # getter returns a Transaction, the setter sets a transaction name. - # Without breaking version compatibility, we could make the setter set a - # transaction name or transaction (self._span) depending on the type of - # the value argument. - - logger.warning( - "Assigning to scope.transaction directly is deprecated: use scope.set_transaction_name() instead." - ) - self._transaction = value - if self._span: - if isinstance(self._span, StreamedSpan): - deprecation_warning( - "Scope.transaction is not available in streaming mode.", - ) - return None - - if self._span.containing_transaction: - self._span.containing_transaction.name = value - def set_transaction_name(self, name: str, source: "Optional[str]" = None) -> None: """Set the transaction name and optionally the transaction source.""" self._transaction = name if self._span: - if isinstance(self._span, StreamedSpan): - self._span._segment.name = name - if source: - self._span._segment.set_attribute( - "sentry.segment.name.source", getattr(source, "value", source) - ) - - elif self._span.containing_transaction: - self._span.containing_transaction.name = name - if source: - self._span.containing_transaction.source = source + self._span._segment.name = name + if source: + self._span._segment.set_attribute( + "sentry.segment.name.source", getattr(source, "value", source) + ) if source: self._transaction_info["source"] = source @@ -931,7 +870,6 @@ def add_attachment( filename: "Optional[str]" = None, path: "Optional[str]" = None, content_type: "Optional[str]" = None, - add_to_transactions: bool = False, ) -> None: """Adds an attachment to future events sent from this scope. @@ -943,7 +881,6 @@ def add_attachment( path=path, filename=filename, content_type=content_type, - add_to_transactions=add_to_transactions, ) ) diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index 045e64160f..619bb6d000 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -1,25 +1,4 @@ from enum import Enum -from typing import TYPE_CHECKING - -from sentry_sdk.consts import SPANSTATUS - -if TYPE_CHECKING: - from typing import ( - ParamSpec, - TypeVar, - ) - - from typing_extensions import TypedDict - - P = ParamSpec("P") - R = TypeVar("R") - - ProfileContext = TypedDict( - "ProfileContext", - { - "profiler_id": str, - }, - ) BAGGAGE_HEADER_NAME = "baggage" SENTRY_TRACE_HEADER_NAME = "sentry-trace" @@ -39,11 +18,6 @@ def __str__(self) -> str: return self.value -# These are typically high cardinality and the server hates them -LOW_QUALITY_TRANSACTION_SOURCES = [ - TransactionSource.URL, -] - SOURCE_FOR_STYLE = { "endpoint": TransactionSource.COMPONENT, "function_name": TransactionSource.COMPONENT, @@ -56,43 +30,4 @@ def __str__(self) -> str: "url": TransactionSource.ROUTE, } - -def get_span_status_from_http_code(http_status_code: int) -> str: - """ - Returns the Sentry status corresponding to the given HTTP status code. - - See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context - """ - if http_status_code < 400: - return SPANSTATUS.OK - - elif 400 <= http_status_code < 500: - if http_status_code == 403: - return SPANSTATUS.PERMISSION_DENIED - elif http_status_code == 404: - return SPANSTATUS.NOT_FOUND - elif http_status_code == 429: - return SPANSTATUS.RESOURCE_EXHAUSTED - elif http_status_code == 413: - return SPANSTATUS.FAILED_PRECONDITION - elif http_status_code == 401: - return SPANSTATUS.UNAUTHENTICATED - elif http_status_code == 409: - return SPANSTATUS.ALREADY_EXISTS - else: - return SPANSTATUS.INVALID_ARGUMENT - - elif 500 <= http_status_code < 600: - if http_status_code == 504: - return SPANSTATUS.DEADLINE_EXCEEDED - elif http_status_code == 501: - return SPANSTATUS.UNIMPLEMENTED - elif http_status_code == 503: - return SPANSTATUS.UNAVAILABLE - else: - return SPANSTATUS.INTERNAL_ERROR - - return SPANSTATUS.UNKNOWN_ERROR - - # Circular imports diff --git a/tests/integrations/dramatiq/test_dramatiq.py b/tests/integrations/dramatiq/test_dramatiq.py index b3c50bbb46..8f2ab13497 100644 --- a/tests/integrations/dramatiq/test_dramatiq.py +++ b/tests/integrations/dramatiq/test_dramatiq.py @@ -6,7 +6,7 @@ from dramatiq.middleware import Middleware, SkipMessage import sentry_sdk -from sentry_sdk.consts import SPANDATA, SPANSTATUS +from sentry_sdk.consts import SPANDATA from sentry_sdk.integrations.dramatiq import DramatiqIntegration from sentry_sdk.integrations.logging import ignore_logger_for_events @@ -74,28 +74,28 @@ def dummy_actor(x, y): { "traces_sample_rate": 1.0, }, - SPANSTATUS.INTERNAL_ERROR, + "error", False, ), ( { "traces_sample_rate": 1.0, }, - SPANSTATUS.OK, + "ok", False, ), ( { "traces_sample_rate": 1.0, }, - SPANSTATUS.INTERNAL_ERROR, + "error", True, ), ( { "traces_sample_rate": 1.0, }, - SPANSTATUS.OK, + "ok", True, ), ], @@ -115,7 +115,7 @@ def test_task_transaction( expected_span_status, fail_fast, ): - task_fails = expected_span_status == SPANSTATUS.INTERNAL_ERROR + task_fails = expected_span_status == "error" items = capture_items("event", "span") @@ -125,7 +125,7 @@ def dummy_actor(x, y): dummy_actor.send(1, int(not task_fails)) - if expected_span_status == SPANSTATUS.INTERNAL_ERROR and fail_fast: + if expected_span_status == "error" and fail_fast: with pytest.raises(ZeroDivisionError): broker.join(dummy_actor.queue_name, fail_fast=fail_fast) else: diff --git a/tests/tracing/test_integration_tests.py b/tests/tracing/test_integration_tests.py index b8421184b6..f23f572069 100644 --- a/tests/tracing/test_integration_tests.py +++ b/tests/tracing/test_integration_tests.py @@ -8,7 +8,6 @@ import sentry_sdk from sentry_sdk import capture_message -from sentry_sdk.consts import SPANSTATUS from sentry_sdk.transport import Transport from tests.conftest import TestTransportWithOptions @@ -363,8 +362,7 @@ def test_non_error_exceptions( sentry_init(traces_sample_rate=1.0) items = capture_items() - with sentry_sdk.traces.start_span(name="hi") as segment: - segment.status = SPANSTATUS.OK + with sentry_sdk.traces.start_span(name="hi"): with pytest.raises(exception_cls): with sentry_sdk.traces.start_span(name="foo"): raise exception_cls(exception_value)