Skip to content

Cleanup imports to always use the top level api. #93307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 5 additions & 5 deletions src/sentry/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import Callable, Iterable
from typing import Any, ClassVar

import sentry_sdk
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.urls import resolve
Expand Down Expand Up @@ -43,7 +44,6 @@
from sentry.users.services.user import RpcUser
from sentry.users.services.user.service import user_service
from sentry.utils.linksign import process_signature
from sentry.utils.sdk import Scope
from sentry.utils.security.orgauthtoken_token import SENTRY_ORG_AUTH_TOKEN_PREFIX, hash_token

logger = logging.getLogger("sentry.api.authentication")
Expand Down Expand Up @@ -169,7 +169,7 @@ def transform_auth(

auth_token = AuthenticatedToken.from_token(request_auth)
if auth_token and entity_id_tag:
scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
scope.set_tag(entity_id_tag, auth_token.entity_id)
for k, v in tags.items():
scope.set_tag(k, v)
Expand Down Expand Up @@ -216,7 +216,7 @@ def authenticate(self, request: Request):
def authenticate_credentials(
self, relay_id: str, relay_sig: str, request=None
) -> tuple[AnonymousUser, None]:
Scope.get_isolation_scope().set_tag("relay_id", relay_id)
sentry_sdk.get_isolation_scope().set_tag("relay_id", relay_id)

if request is None:
raise AuthenticationFailed("missing request")
Expand Down Expand Up @@ -511,7 +511,7 @@ def authenticate_token(self, request: Request, token: str) -> tuple[Any, Any]:
if not key.is_active:
raise AuthenticationFailed("Invalid dsn")

scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
scope.set_tag("api_token_type", self.token_name)
scope.set_tag("api_project_key", key.id)

Expand Down Expand Up @@ -547,6 +547,6 @@ def authenticate_token(self, request: Request, token: str) -> tuple[Any, Any]:
if not compare_signature(request.path_info, request.body, token):
raise AuthenticationFailed("Invalid signature")

Scope.get_isolation_scope().set_tag("rpc_auth", True)
sentry_sdk.get_isolation_scope().set_tag("rpc_auth", True)

return (AnonymousUser(), token)
5 changes: 3 additions & 2 deletions src/sentry/api/bases/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging

import sentry_sdk
from rest_framework.permissions import SAFE_METHODS
from rest_framework.request import Request

Expand All @@ -14,7 +15,7 @@
from sentry.models.group import Group, GroupStatus, get_group_with_redirect
from sentry.models.grouplink import GroupLink
from sentry.models.organization import Organization
from sentry.utils.sdk import Scope, bind_organization_context
from sentry.utils.sdk import bind_organization_context

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -80,7 +81,7 @@ def convert_args(

self.check_object_permissions(request, group)

Scope.get_isolation_scope().set_tag("project", group.project_id)
sentry_sdk.get_isolation_scope().set_tag("project", group.project_id)

# we didn't bind context above, so do it now
if not organization:
Expand Down
3 changes: 2 additions & 1 deletion src/sentry/api/bases/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections.abc import Mapping
from typing import Any

import sentry_sdk
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
Expand Down Expand Up @@ -183,7 +184,7 @@ def convert_args(

self.check_object_permissions(request, project)

Scope.get_isolation_scope().set_tag("project", project.id)
sentry_sdk.get_isolation_scope().set_tag("project", project.id)

bind_organization_context(project.organization)

Expand Down
12 changes: 6 additions & 6 deletions src/sentry/api/endpoints/internal/rpc.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import pydantic
import sentry_sdk
from rest_framework.exceptions import NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from sentry_sdk import Scope, capture_exception

from sentry.api.api_owners import ApiOwner
from sentry.api.api_publish_status import ApiPublishStatus
Expand Down Expand Up @@ -32,7 +32,7 @@ def _is_authorized(self, request: Request) -> bool:
return False

def post(self, request: Request, service_name: str, method_name: str) -> Response:
Scope.get_isolation_scope().set_tag("rpc_method", f"{service_name}.{method_name}")
sentry_sdk.get_isolation_scope().set_tag("rpc_method", f"{service_name}.{method_name}")
if not self._is_authorized(request):
raise PermissionDenied

Expand All @@ -53,24 +53,24 @@ def post(self, request: Request, service_name: str, method_name: str) -> Respons
# from within the privileged RPC channel.
auth_context = AuthenticationContext.parse_obj(auth_context_json)
except pydantic.ValidationError as e:
capture_exception()
sentry_sdk.capture_exception()
raise ParseError from e

try:
with auth_context.applied_to_request(request):
result = dispatch_to_local_service(service_name, method_name, arguments)
except RpcResolutionException as e:
capture_exception()
sentry_sdk.capture_exception()
raise NotFound from e
except SerializableFunctionValueException as e:
capture_exception()
sentry_sdk.capture_exception()
raise ParseError from e
except Exception as e:
# Produce more detailed log
if in_test_environment():
raise Exception(
f"Problem processing rpc service endpoint {service_name}/{method_name}"
) from e
capture_exception()
sentry_sdk.capture_exception()
raise ValidationError from e
return Response(data=result)
5 changes: 3 additions & 2 deletions src/sentry/api/endpoints/organization_release_details.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sentry_sdk
from django.db.models import Q
from drf_spectacular.utils import extend_schema, extend_schema_serializer
from rest_framework.exceptions import ParseError
Expand Down Expand Up @@ -38,7 +39,7 @@
from sentry.models.releases.exceptions import ReleaseCommitError, UnsafeReleaseDeletion
from sentry.snuba.sessions import STATS_PERIODS
from sentry.types.activity import ActivityType
from sentry.utils.sdk import Scope, bind_organization_context
from sentry.utils.sdk import bind_organization_context


class InvalidSortException(Exception):
Expand Down Expand Up @@ -435,7 +436,7 @@ def put(self, request: Request, organization, version) -> Response:
"""
bind_organization_context(organization)

scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
scope.set_tag("version", version)
try:
release = Release.objects.get(organization_id=organization, version=version)
Expand Down
5 changes: 3 additions & 2 deletions src/sentry/api/endpoints/organization_releases.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import re
from datetime import datetime, timedelta

import sentry_sdk
from django.db import IntegrityError
from django.db.models import F, Q
from rest_framework.exceptions import ParseError
Expand Down Expand Up @@ -47,7 +48,7 @@
from sentry.snuba.sessions import STATS_PERIODS
from sentry.types.activity import ActivityType
from sentry.utils.cache import cache
from sentry.utils.sdk import Scope, bind_organization_context
from sentry.utils.sdk import bind_organization_context

ERR_INVALID_STATS_PERIOD = "Invalid %s. Valid choices are %s"

Expand Down Expand Up @@ -476,7 +477,7 @@ def post(self, request: Request, organization) -> Response:
data=request.data, context={"organization": organization}
)

scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
if serializer.is_valid():
result = serializer.validated_data
scope.set_tag("version", result["version"])
Expand Down
5 changes: 3 additions & 2 deletions src/sentry/api/endpoints/project_release_details.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sentry_sdk
from rest_framework.exceptions import ParseError
from rest_framework.request import Request
from rest_framework.response import Response
Expand All @@ -16,7 +17,7 @@
from sentry.plugins.interfaces.releasehook import ReleaseHook
from sentry.snuba.sessions import STATS_PERIODS
from sentry.types.activity import ActivityType
from sentry.utils.sdk import Scope, bind_organization_context
from sentry.utils.sdk import bind_organization_context


@region_silo_endpoint
Expand Down Expand Up @@ -95,7 +96,7 @@ def put(self, request: Request, project, version) -> Response:
:auth: required
"""
bind_organization_context(project.organization)
scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
scope.set_tag("version", version)
try:
release = Release.objects.get(
Expand Down
5 changes: 3 additions & 2 deletions src/sentry/api/endpoints/project_releases.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import sentry_sdk
from django.db import IntegrityError, router, transaction
from django.db.models import Q
from rest_framework.request import Request
Expand All @@ -22,7 +23,7 @@
from sentry.ratelimits.config import SENTRY_RATELIMITER_GROUP_DEFAULTS, RateLimitConfig
from sentry.signals import release_created
from sentry.types.activity import ActivityType
from sentry.utils.sdk import Scope, bind_organization_context
from sentry.utils.sdk import bind_organization_context


@region_silo_endpoint
Expand Down Expand Up @@ -117,7 +118,7 @@ def post(self, request: Request, project) -> Response:
data=request.data, context={"organization": project.organization}
)

scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()

if serializer.is_valid():
result = serializer.validated_data
Expand Down
6 changes: 3 additions & 3 deletions src/sentry/api/endpoints/project_stacktrace_coverage.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

import sentry_sdk
from rest_framework.request import Request
from rest_framework.response import Response
from sentry_sdk import Scope, start_span

from sentry.api.api_owners import ApiOwner
from sentry.api.api_publish_status import ApiPublishStatus
Expand Down Expand Up @@ -58,14 +58,14 @@ def get(self, request: Request, project: Project) -> Response:

# Post-processing before exiting scope context
if result["current_config"]:
scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()

serialized_config = serialize(result["current_config"]["config"], request.user)
provider = serialized_config["provider"]["key"]
# Use the provider key to split up stacktrace-link metrics by integration type
scope.set_tag("integration_provider", provider) # e.g. github

with start_span(op="fetch_codecov_data"):
with sentry_sdk.start_span(op="fetch_codecov_data"):
with metrics.timer("issues.stacktrace.fetch_codecov_data"):
codecov_data = fetch_codecov_data(
config={
Expand Down
12 changes: 6 additions & 6 deletions src/sentry/api/endpoints/seer_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from collections.abc import Callable
from typing import Any

import sentry_sdk
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ObjectDoesNotExist
Expand All @@ -24,7 +25,6 @@
)
from sentry_protos.snuba.v1.request_common_pb2 import RequestMeta, TraceItemType
from sentry_protos.snuba.v1.trace_item_attribute_pb2 import AttributeKey
from sentry_sdk import Scope, capture_exception

from sentry import options
from sentry.api.api_owners import ApiOwner
Expand Down Expand Up @@ -116,7 +116,7 @@ def authenticate_token(self, request: Request, token: str) -> tuple[Any, Any]:
if not compare_signature(request.path_info, request.body, token):
raise AuthenticationFailed("Invalid signature")

Scope.get_isolation_scope().set_tag("seer_rpc_auth", True)
sentry_sdk.get_isolation_scope().set_tag("seer_rpc_auth", True)

return (AnonymousUser(), token)

Expand Down Expand Up @@ -164,21 +164,21 @@ def post(self, request: Request, method_name: str) -> Response:
try:
result = self._dispatch_to_local_method(method_name, arguments)
except RpcResolutionException as e:
capture_exception()
sentry_sdk.capture_exception()
raise NotFound from e
except SerializableFunctionValueException as e:
capture_exception()
sentry_sdk.capture_exception()
raise ParseError from e
except ObjectDoesNotExist as e:
# Let this fall through, this is normal.
capture_exception()
sentry_sdk.capture_exception()
raise NotFound from e
except Exception as e:
if in_test_environment():
raise
if settings.DEBUG:
raise Exception(f"Problem processing seer rpc endpoint {method_name}") from e
capture_exception()
sentry_sdk.capture_exception()
raise ValidationError from e
return Response(data=result)

Expand Down
4 changes: 2 additions & 2 deletions src/sentry/integrations/api/bases/doc_integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import Any

import sentry_sdk
from django.http import Http404
from rest_framework.request import Request
from rest_framework.views import APIView
Expand All @@ -12,7 +13,6 @@
from sentry.integrations.api.bases.integration import PARANOID_GET
from sentry.integrations.api.parsers.doc_integration import METADATA_PROPERTIES
from sentry.integrations.models.doc_integration import DocIntegration
from sentry.utils.sdk import Scope


class DocIntegrationsPermission(SentryPermission):
Expand Down Expand Up @@ -89,7 +89,7 @@ def convert_args(

self.check_object_permissions(request, doc_integration)

Scope.get_isolation_scope().set_tag("doc_integration", doc_integration.slug)
sentry_sdk.get_isolation_scope().set_tag("doc_integration", doc_integration.slug)

kwargs["doc_integration"] = doc_integration
return (args, kwargs)
4 changes: 2 additions & 2 deletions src/sentry/integrations/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from functools import cached_property
from typing import TYPE_CHECKING, Any, NamedTuple, Never, NoReturn, NotRequired, TypedDict

import sentry_sdk
from rest_framework.exceptions import NotFound
from rest_framework.request import Request

Expand Down Expand Up @@ -46,7 +47,6 @@
)
from sentry.users.models.identity import Identity
from sentry.utils.audit import create_audit_entry, create_system_audit_entry
from sentry.utils.sdk import Scope

if TYPE_CHECKING:
from django.utils.functional import _StrPromise
Expand Down Expand Up @@ -452,7 +452,7 @@ def default_identity(self) -> RpcIdentity:
raise Identity.DoesNotExist
identity = identity_service.get_identity(filter={"id": org_integration.default_auth_id})
if identity is None:
scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()
scope.set_tag("integration_provider", self.model.get_provider().name)
scope.set_tag("org_integration_id", org_integration.id)
scope.set_tag("default_auth_id", org_integration.default_auth_id)
Expand Down
3 changes: 1 addition & 2 deletions src/sentry/integrations/github_enterprise/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from sentry.integrations.utils.metrics import IntegrationWebhookEvent
from sentry.integrations.utils.scope import clear_tags_and_context
from sentry.utils import metrics
from sentry.utils.sdk import Scope

logger = logging.getLogger("sentry.webhooks")
from sentry.api.base import Endpoint, region_silo_endpoint
Expand Down Expand Up @@ -152,7 +151,7 @@ def get_secret(self, event, host):

def _handle(self, request: HttpRequest) -> HttpResponse:
clear_tags_and_context()
scope = Scope.get_isolation_scope()
scope = sentry_sdk.get_isolation_scope()

try:
host = get_host(request=request)
Expand Down
Loading
Loading