Skip to content

Commit ac90b7e

Browse files
antonpirkersentrivanaszokeasaurusrex
authored
Use new scopes default integrations. (#2856)
Updated the default integrations and related ones (aiohttp and httpx) to use the new scopes API. --------- Co-authored-by: Ivana Kellyerova <[email protected]> Co-authored-by: Daniel Szoke <[email protected]>
1 parent f39cdbc commit ac90b7e

File tree

12 files changed

+115
-134
lines changed

12 files changed

+115
-134
lines changed

sentry_sdk/integrations/aiohttp.py

Lines changed: 30 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import sys
22
import weakref
33

4+
import sentry_sdk
45
from sentry_sdk.api import continue_trace
56
from sentry_sdk.consts import OP, SPANDATA
6-
from sentry_sdk.hub import Hub
77
from sentry_sdk.integrations import Integration, DidNotEnable
88
from sentry_sdk.integrations.logging import ignore_logger
99
from sentry_sdk.scope import Scope
10-
from sentry_sdk.sessions import auto_session_tracking
10+
from sentry_sdk.sessions import auto_session_tracking_scope
1111
from sentry_sdk.integrations._wsgi_common import (
1212
_filter_headers,
1313
request_body_within_bounds,
@@ -20,6 +20,8 @@
2020
from sentry_sdk.tracing_utils import should_propagate_trace
2121
from sentry_sdk.utils import (
2222
capture_internal_exceptions,
23+
ensure_integration_enabled,
24+
ensure_integration_enabled_async,
2325
event_from_exception,
2426
logger,
2527
parse_url,
@@ -96,21 +98,18 @@ def setup_once():
9698

9799
old_handle = Application._handle
98100

101+
@ensure_integration_enabled_async(AioHttpIntegration, old_handle)
99102
async def sentry_app_handle(self, request, *args, **kwargs):
100103
# type: (Any, Request, *Any, **Any) -> Any
101-
hub = Hub.current
102-
if hub.get_integration(AioHttpIntegration) is None:
103-
return await old_handle(self, request, *args, **kwargs)
104-
105104
weak_request = weakref.ref(request)
106105

107-
with Hub(hub) as hub:
108-
with auto_session_tracking(hub, session_mode="request"):
106+
with sentry_sdk.isolation_scope() as scope:
107+
with auto_session_tracking_scope(scope, session_mode="request"):
109108
# Scope data will not leak between requests because aiohttp
110109
# create a task to wrap each request.
111-
with hub.configure_scope() as scope:
112-
scope.clear_breadcrumbs()
113-
scope.add_event_processor(_make_request_processor(weak_request))
110+
scope.generate_propagation_context()
111+
scope.clear_breadcrumbs()
112+
scope.add_event_processor(_make_request_processor(weak_request))
114113

115114
headers = dict(request.headers)
116115
transaction = continue_trace(
@@ -121,7 +120,7 @@ async def sentry_app_handle(self, request, *args, **kwargs):
121120
name="generic AIOHTTP request",
122121
source=TRANSACTION_SOURCE_ROUTE,
123122
)
124-
with hub.start_transaction(
123+
with sentry_sdk.start_transaction(
125124
transaction,
126125
custom_sampling_context={"aiohttp_request": request},
127126
):
@@ -136,7 +135,7 @@ async def sentry_app_handle(self, request, *args, **kwargs):
136135
except Exception:
137136
# This will probably map to a 500 but seems like we
138137
# have no way to tell. Do not set span status.
139-
reraise(*_capture_exception(hub))
138+
reraise(*_capture_exception())
140139

141140
transaction.set_http_status(response.status)
142141
return response
@@ -149,8 +148,7 @@ async def sentry_urldispatcher_resolve(self, request):
149148
# type: (UrlDispatcher, Request) -> UrlMappingMatchInfo
150149
rv = await old_urldispatcher_resolve(self, request)
151150

152-
hub = Hub.current
153-
integration = hub.get_integration(AioHttpIntegration)
151+
integration = sentry_sdk.get_client().get_integration(AioHttpIntegration)
154152

155153
name = None
156154

@@ -176,12 +174,9 @@ async def sentry_urldispatcher_resolve(self, request):
176174

177175
old_client_session_init = ClientSession.__init__
178176

177+
@ensure_integration_enabled(AioHttpIntegration, old_client_session_init)
179178
def init(*args, **kwargs):
180179
# type: (Any, Any) -> None
181-
hub = Hub.current
182-
if hub.get_integration(AioHttpIntegration) is None:
183-
return old_client_session_init(*args, **kwargs)
184-
185180
client_trace_configs = list(kwargs.get("trace_configs") or ())
186181
trace_config = create_trace_config()
187182
client_trace_configs.append(trace_config)
@@ -194,10 +189,11 @@ def init(*args, **kwargs):
194189

195190
def create_trace_config():
196191
# type: () -> TraceConfig
192+
197193
async def on_request_start(session, trace_config_ctx, params):
198194
# type: (ClientSession, SimpleNamespace, TraceRequestStartParams) -> None
199-
hub = Hub.current
200-
if hub.get_integration(AioHttpIntegration) is None:
195+
client = sentry_sdk.get_client()
196+
if client.get_integration(AioHttpIntegration) is None:
201197
return
202198

203199
method = params.method.upper()
@@ -206,7 +202,7 @@ async def on_request_start(session, trace_config_ctx, params):
206202
with capture_internal_exceptions():
207203
parsed_url = parse_url(str(params.url), sanitize=False)
208204

209-
span = hub.start_span(
205+
span = sentry_sdk.start_span(
210206
op=OP.HTTP_CLIENT,
211207
description="%s %s"
212208
% (method, parsed_url.url if parsed_url else SENSITIVE_DATA_SUBSTITUTE),
@@ -217,8 +213,10 @@ async def on_request_start(session, trace_config_ctx, params):
217213
span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
218214
span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
219215

220-
if should_propagate_trace(hub, str(params.url)):
221-
for key, value in hub.iter_trace_propagation_headers(span):
216+
if should_propagate_trace(client, str(params.url)):
217+
for key, value in Scope.get_current_scope().iter_trace_propagation_headers(
218+
span=span
219+
):
222220
logger.debug(
223221
"[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
224222
key=key, value=value, url=params.url
@@ -275,42 +273,40 @@ def aiohttp_processor(
275273
request_info["query_string"] = request.query_string
276274
request_info["method"] = request.method
277275
request_info["env"] = {"REMOTE_ADDR": request.remote}
278-
279-
hub = Hub.current
280276
request_info["headers"] = _filter_headers(dict(request.headers))
281277

282278
# Just attach raw data here if it is within bounds, if available.
283279
# Unfortunately there's no way to get structured data from aiohttp
284280
# without awaiting on some coroutine.
285-
request_info["data"] = get_aiohttp_request_data(hub, request)
281+
request_info["data"] = get_aiohttp_request_data(request)
286282

287283
return event
288284

289285
return aiohttp_processor
290286

291287

292-
def _capture_exception(hub):
293-
# type: (Hub) -> ExcInfo
288+
def _capture_exception():
289+
# type: () -> ExcInfo
294290
exc_info = sys.exc_info()
295291
event, hint = event_from_exception(
296292
exc_info,
297-
client_options=hub.client.options, # type: ignore
293+
client_options=sentry_sdk.get_client().options,
298294
mechanism={"type": "aiohttp", "handled": False},
299295
)
300-
hub.capture_event(event, hint=hint)
296+
sentry_sdk.capture_event(event, hint=hint)
301297
return exc_info
302298

303299

304300
BODY_NOT_READ_MESSAGE = "[Can't show request body due to implementation details.]"
305301

306302

307-
def get_aiohttp_request_data(hub, request):
308-
# type: (Hub, Request) -> Union[Optional[str], AnnotatedValue]
303+
def get_aiohttp_request_data(request):
304+
# type: (Request) -> Union[Optional[str], AnnotatedValue]
309305
bytes_body = request._read_bytes
310306

311307
if bytes_body is not None:
312308
# we have body to show
313-
if not request_body_within_bounds(hub.client, len(bytes_body)):
309+
if not request_body_within_bounds(sentry_sdk.get_client(), len(bytes_body)):
314310
return AnnotatedValue.removed_because_over_size_limit()
315311

316312
encoding = request.charset or "utf-8"

sentry_sdk/integrations/argv.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

3-
from sentry_sdk.hub import Hub
3+
import sentry_sdk
44
from sentry_sdk.integrations import Integration
55
from sentry_sdk.scope import add_global_event_processor
66

@@ -21,7 +21,7 @@ def setup_once():
2121
@add_global_event_processor
2222
def processor(event, hint):
2323
# type: (Event, Optional[Hint]) -> Optional[Event]
24-
if Hub.current.get_integration(ArgvIntegration) is not None:
24+
if sentry_sdk.get_client().get_integration(ArgvIntegration) is not None:
2525
extra = event.setdefault("extra", {})
2626
# If some event processor decided to set extra to e.g. an
2727
# `int`, don't crash. Not here.

sentry_sdk/integrations/atexit.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
import sys
33
import atexit
44

5-
from sentry_sdk.hub import Hub
5+
import sentry_sdk
6+
from sentry_sdk import Scope
67
from sentry_sdk.utils import logger
78
from sentry_sdk.integrations import Integration
89

@@ -46,14 +47,10 @@ def setup_once():
4647
def _shutdown():
4748
# type: () -> None
4849
logger.debug("atexit: got shutdown signal")
49-
hub = Hub.main
50-
integration = hub.get_integration(AtexitIntegration)
50+
client = sentry_sdk.get_client()
51+
integration = client.get_integration(AtexitIntegration)
5152
if integration is not None:
5253
logger.debug("atexit: shutting down client")
5354

54-
# If there is a session on the hub, close it now.
55-
hub.end_session()
56-
57-
# If an integration is there, a client has to be there.
58-
client = hub.client # type: Any
55+
Scope.get_isolation_scope().end_session()
5956
client.close(callback=integration.callback)

sentry_sdk/integrations/dedupe.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from sentry_sdk.hub import Hub
1+
import sentry_sdk
22
from sentry_sdk.utils import ContextVar
33
from sentry_sdk.integrations import Integration
44
from sentry_sdk.scope import add_global_event_processor
@@ -27,8 +27,7 @@ def processor(event, hint):
2727
if hint is None:
2828
return event
2929

30-
integration = Hub.current.get_integration(DedupeIntegration)
31-
30+
integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
3231
if integration is None:
3332
return event
3433

sentry_sdk/integrations/excepthook.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

3-
from sentry_sdk.hub import Hub
3+
import sentry_sdk
44
from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
55
from sentry_sdk.integrations import Integration
66

@@ -45,20 +45,16 @@ def _make_excepthook(old_excepthook):
4545
# type: (Excepthook) -> Excepthook
4646
def sentry_sdk_excepthook(type_, value, traceback):
4747
# type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None
48-
hub = Hub.current
49-
integration = hub.get_integration(ExcepthookIntegration)
48+
integration = sentry_sdk.get_client().get_integration(ExcepthookIntegration)
5049

5150
if integration is not None and _should_send(integration.always_run):
52-
# If an integration is there, a client has to be there.
53-
client = hub.client # type: Any
54-
5551
with capture_internal_exceptions():
5652
event, hint = event_from_exception(
5753
(type_, value, traceback),
58-
client_options=client.options,
54+
client_options=sentry_sdk.get_client().options,
5955
mechanism={"type": "excepthook", "handled": False},
6056
)
61-
hub.capture_event(event, hint=hint)
57+
sentry_sdk.capture_event(event, hint=hint)
6258

6359
return old_excepthook(type_, value, traceback)
6460

sentry_sdk/integrations/httpx.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
from sentry_sdk import Hub
1+
import sentry_sdk
22
from sentry_sdk.consts import OP, SPANDATA
33
from sentry_sdk.integrations import Integration, DidNotEnable
4+
from sentry_sdk.scope import Scope
45
from sentry_sdk.tracing import BAGGAGE_HEADER_NAME
56
from sentry_sdk.tracing_utils import should_propagate_trace
67
from sentry_sdk.utils import (
78
SENSITIVE_DATA_SUBSTITUTE,
89
capture_internal_exceptions,
10+
ensure_integration_enabled,
11+
ensure_integration_enabled_async,
912
logger,
1013
parse_url,
1114
)
@@ -42,17 +45,14 @@ def _install_httpx_client():
4245
# type: () -> None
4346
real_send = Client.send
4447

48+
@ensure_integration_enabled(HttpxIntegration, real_send)
4549
def send(self, request, **kwargs):
4650
# type: (Client, Request, **Any) -> Response
47-
hub = Hub.current
48-
if hub.get_integration(HttpxIntegration) is None:
49-
return real_send(self, request, **kwargs)
50-
5151
parsed_url = None
5252
with capture_internal_exceptions():
5353
parsed_url = parse_url(str(request.url), sanitize=False)
5454

55-
with hub.start_span(
55+
with sentry_sdk.start_span(
5656
op=OP.HTTP_CLIENT,
5757
description="%s %s"
5858
% (
@@ -66,8 +66,11 @@ def send(self, request, **kwargs):
6666
span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
6767
span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
6868

69-
if should_propagate_trace(hub, str(request.url)):
70-
for key, value in hub.iter_trace_propagation_headers():
69+
if should_propagate_trace(sentry_sdk.get_client(), str(request.url)):
70+
for (
71+
key,
72+
value,
73+
) in Scope.get_current_scope().iter_trace_propagation_headers():
7174
logger.debug(
7275
"[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
7376
key=key, value=value, url=request.url
@@ -95,17 +98,14 @@ def _install_httpx_async_client():
9598
# type: () -> None
9699
real_send = AsyncClient.send
97100

101+
@ensure_integration_enabled_async(HttpxIntegration, real_send)
98102
async def send(self, request, **kwargs):
99103
# type: (AsyncClient, Request, **Any) -> Response
100-
hub = Hub.current
101-
if hub.get_integration(HttpxIntegration) is None:
102-
return await real_send(self, request, **kwargs)
103-
104104
parsed_url = None
105105
with capture_internal_exceptions():
106106
parsed_url = parse_url(str(request.url), sanitize=False)
107107

108-
with hub.start_span(
108+
with sentry_sdk.start_span(
109109
op=OP.HTTP_CLIENT,
110110
description="%s %s"
111111
% (
@@ -119,8 +119,11 @@ async def send(self, request, **kwargs):
119119
span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
120120
span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
121121

122-
if should_propagate_trace(hub, str(request.url)):
123-
for key, value in hub.iter_trace_propagation_headers():
122+
if should_propagate_trace(sentry_sdk.get_client(), str(request.url)):
123+
for (
124+
key,
125+
value,
126+
) in Scope.get_current_scope().iter_trace_propagation_headers():
124127
logger.debug(
125128
"[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format(
126129
key=key, value=value, url=request.url

sentry_sdk/integrations/modules.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from sentry_sdk.hub import Hub
1+
import sentry_sdk
22
from sentry_sdk.integrations import Integration
33
from sentry_sdk.scope import add_global_event_processor
44
from sentry_sdk.utils import _get_installed_modules
@@ -22,7 +22,7 @@ def processor(event, hint):
2222
if event.get("type") == "transaction":
2323
return event
2424

25-
if Hub.current.get_integration(ModulesIntegration) is None:
25+
if sentry_sdk.get_client().get_integration(ModulesIntegration) is None:
2626
return event
2727

2828
event["modules"] = _get_installed_modules()

0 commit comments

Comments
 (0)