11import sys
22import weakref
33
4+ import sentry_sdk
45from sentry_sdk .api import continue_trace
56from sentry_sdk .consts import OP , SPANDATA
6- from sentry_sdk .hub import Hub
77from sentry_sdk .integrations import Integration , DidNotEnable
88from sentry_sdk .integrations .logging import ignore_logger
99from sentry_sdk .scope import Scope
10- from sentry_sdk .sessions import auto_session_tracking
10+ from sentry_sdk .sessions import auto_session_tracking_scope
1111from sentry_sdk .integrations ._wsgi_common import (
1212 _filter_headers ,
1313 request_body_within_bounds ,
2020from sentry_sdk .tracing_utils import should_propagate_trace
2121from 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
195190def 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
304300BODY_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"
0 commit comments