Skip to content

Commit 75b33d2

Browse files
authored
ref(starlite): Use new scopes API (#2876)
1 parent 343bca9 commit 75b33d2

File tree

1 file changed

+105
-103
lines changed

1 file changed

+105
-103
lines changed

sentry_sdk/integrations/starlite.py

Lines changed: 105 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from typing import TYPE_CHECKING
22

3+
import sentry_sdk
34
from sentry_sdk.consts import OP
4-
from sentry_sdk.hub import Hub, _should_send_default_pii
55
from sentry_sdk.integrations import DidNotEnable, Integration
66
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
7+
from sentry_sdk.scope import Scope as SentryScope, should_send_default_pii
78
from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE
89
from sentry_sdk.utils import event_from_exception, transaction_from_function
910

@@ -20,12 +21,13 @@
2021
from typing import Any, Dict, List, Optional, Union
2122
from starlite.types import ( # type: ignore
2223
ASGIApp,
24+
Hint,
2325
HTTPReceiveMessage,
2426
HTTPScope,
2527
Message,
2628
Middleware,
2729
Receive,
28-
Scope,
30+
Scope as StarliteScope,
2931
Send,
3032
WebSocketReceiveMessage,
3133
)
@@ -114,51 +116,50 @@ def enable_span_for_middleware(middleware: "Middleware") -> "Middleware":
114116
old_call = middleware.__call__
115117

116118
async def _create_span_call(
117-
self: "MiddlewareProtocol", scope: "Scope", receive: "Receive", send: "Send"
119+
self: "MiddlewareProtocol",
120+
scope: "StarliteScope",
121+
receive: "Receive",
122+
send: "Send",
118123
) -> None:
119-
hub = Hub.current
120-
integration = hub.get_integration(StarliteIntegration)
121-
if integration is not None:
122-
middleware_name = self.__class__.__name__
123-
with hub.start_span(
124-
op=OP.MIDDLEWARE_STARLITE, description=middleware_name
125-
) as middleware_span:
126-
middleware_span.set_tag("starlite.middleware_name", middleware_name)
127-
128-
# Creating spans for the "receive" callback
129-
async def _sentry_receive(
130-
*args: "Any", **kwargs: "Any"
131-
) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]":
132-
hub = Hub.current
133-
with hub.start_span(
134-
op=OP.MIDDLEWARE_STARLITE_RECEIVE,
135-
description=getattr(receive, "__qualname__", str(receive)),
136-
) as span:
137-
span.set_tag("starlite.middleware_name", middleware_name)
138-
return await receive(*args, **kwargs)
139-
140-
receive_name = getattr(receive, "__name__", str(receive))
141-
receive_patched = receive_name == "_sentry_receive"
142-
new_receive = _sentry_receive if not receive_patched else receive
143-
144-
# Creating spans for the "send" callback
145-
async def _sentry_send(message: "Message") -> None:
146-
hub = Hub.current
147-
with hub.start_span(
148-
op=OP.MIDDLEWARE_STARLITE_SEND,
149-
description=getattr(send, "__qualname__", str(send)),
150-
) as span:
151-
span.set_tag("starlite.middleware_name", middleware_name)
152-
return await send(message)
153-
154-
send_name = getattr(send, "__name__", str(send))
155-
send_patched = send_name == "_sentry_send"
156-
new_send = _sentry_send if not send_patched else send
157-
158-
return await old_call(self, scope, new_receive, new_send)
159-
else:
124+
if sentry_sdk.get_client().get_integration(StarliteIntegration) is None:
160125
return await old_call(self, scope, receive, send)
161126

127+
middleware_name = self.__class__.__name__
128+
with sentry_sdk.start_span(
129+
op=OP.MIDDLEWARE_STARLITE, description=middleware_name
130+
) as middleware_span:
131+
middleware_span.set_tag("starlite.middleware_name", middleware_name)
132+
133+
# Creating spans for the "receive" callback
134+
async def _sentry_receive(
135+
*args: "Any", **kwargs: "Any"
136+
) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]":
137+
with sentry_sdk.start_span(
138+
op=OP.MIDDLEWARE_STARLITE_RECEIVE,
139+
description=getattr(receive, "__qualname__", str(receive)),
140+
) as span:
141+
span.set_tag("starlite.middleware_name", middleware_name)
142+
return await receive(*args, **kwargs)
143+
144+
receive_name = getattr(receive, "__name__", str(receive))
145+
receive_patched = receive_name == "_sentry_receive"
146+
new_receive = _sentry_receive if not receive_patched else receive
147+
148+
# Creating spans for the "send" callback
149+
async def _sentry_send(message: "Message") -> None:
150+
with sentry_sdk.start_span(
151+
op=OP.MIDDLEWARE_STARLITE_SEND,
152+
description=getattr(send, "__qualname__", str(send)),
153+
) as span:
154+
span.set_tag("starlite.middleware_name", middleware_name)
155+
return await send(message)
156+
157+
send_name = getattr(send, "__name__", str(send))
158+
send_patched = send_name == "_sentry_send"
159+
new_send = _sentry_send if not send_patched else send
160+
161+
return await old_call(self, scope, new_receive, new_send)
162+
162163
not_yet_patched = old_call.__name__ not in ["_create_span_call"]
163164

164165
if not_yet_patched:
@@ -176,66 +177,67 @@ def patch_http_route_handle() -> None:
176177
async def handle_wrapper(
177178
self: "HTTPRoute", scope: "HTTPScope", receive: "Receive", send: "Send"
178179
) -> None:
179-
hub = Hub.current
180-
integration: StarliteIntegration = hub.get_integration(StarliteIntegration)
180+
integration: StarliteIntegration = sentry_sdk.get_client().get_integration(
181+
StarliteIntegration
182+
)
181183
if integration is None:
182184
return await old_handle(self, scope, receive, send)
183185

184-
with hub.configure_scope() as sentry_scope:
185-
request: "Request[Any, Any]" = scope["app"].request_class(
186-
scope=scope, receive=receive, send=send
186+
sentry_scope = SentryScope.get_isolation_scope()
187+
request: "Request[Any, Any]" = scope["app"].request_class(
188+
scope=scope, receive=receive, send=send
189+
)
190+
extracted_request_data = ConnectionDataExtractor(
191+
parse_body=True, parse_query=True
192+
)(request)
193+
body = extracted_request_data.pop("body")
194+
195+
request_data = await body
196+
197+
def event_processor(event: "Event", _: "Hint") -> "Event":
198+
route_handler = scope.get("route_handler")
199+
200+
request_info = event.get("request", {})
201+
request_info["content_length"] = len(scope.get("_body", b""))
202+
if should_send_default_pii():
203+
request_info["cookies"] = extracted_request_data["cookies"]
204+
if request_data is not None:
205+
request_info["data"] = request_data
206+
207+
func = None
208+
if route_handler.name is not None:
209+
tx_name = route_handler.name
210+
elif isinstance(route_handler.fn, Ref):
211+
func = route_handler.fn.value
212+
else:
213+
func = route_handler.fn
214+
if func is not None:
215+
tx_name = transaction_from_function(func)
216+
217+
tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
218+
219+
if not tx_name:
220+
tx_name = _DEFAULT_TRANSACTION_NAME
221+
tx_info = {"source": TRANSACTION_SOURCE_ROUTE}
222+
223+
event.update(
224+
{
225+
"request": request_info,
226+
"transaction": tx_name,
227+
"transaction_info": tx_info,
228+
}
187229
)
188-
extracted_request_data = ConnectionDataExtractor(
189-
parse_body=True, parse_query=True
190-
)(request)
191-
body = extracted_request_data.pop("body")
192-
193-
request_data = await body
194-
195-
def event_processor(event: "Event", _: "Dict[str, Any]") -> "Event":
196-
route_handler = scope.get("route_handler")
197-
198-
request_info = event.get("request", {})
199-
request_info["content_length"] = len(scope.get("_body", b""))
200-
if _should_send_default_pii():
201-
request_info["cookies"] = extracted_request_data["cookies"]
202-
if request_data is not None:
203-
request_info["data"] = request_data
204-
205-
func = None
206-
if route_handler.name is not None:
207-
tx_name = route_handler.name
208-
elif isinstance(route_handler.fn, Ref):
209-
func = route_handler.fn.value
210-
else:
211-
func = route_handler.fn
212-
if func is not None:
213-
tx_name = transaction_from_function(func)
214-
215-
tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
216-
217-
if not tx_name:
218-
tx_name = _DEFAULT_TRANSACTION_NAME
219-
tx_info = {"source": TRANSACTION_SOURCE_ROUTE}
220-
221-
event.update(
222-
{
223-
"request": request_info,
224-
"transaction": tx_name,
225-
"transaction_info": tx_info,
226-
}
227-
)
228-
return event
229-
230-
sentry_scope._name = StarliteIntegration.identifier
231-
sentry_scope.add_event_processor(event_processor)
230+
return event
232231

233-
return await old_handle(self, scope, receive, send)
232+
sentry_scope._name = StarliteIntegration.identifier
233+
sentry_scope.add_event_processor(event_processor)
234+
235+
return await old_handle(self, scope, receive, send)
234236

235237
HTTPRoute.handle = handle_wrapper
236238

237239

238-
def retrieve_user_from_scope(scope: "Scope") -> "Optional[Dict[str, Any]]":
240+
def retrieve_user_from_scope(scope: "StarliteScope") -> "Optional[Dict[str, Any]]":
239241
scope_user = scope.get("user", {})
240242
if not scope_user:
241243
return None
@@ -253,22 +255,22 @@ def retrieve_user_from_scope(scope: "Scope") -> "Optional[Dict[str, Any]]":
253255
return None
254256

255257

256-
def exception_handler(exc: Exception, scope: "Scope", _: "State") -> None:
257-
hub = Hub.current
258-
if hub.get_integration(StarliteIntegration) is None:
258+
def exception_handler(exc: Exception, scope: "StarliteScope", _: "State") -> None:
259+
client = sentry_sdk.get_client()
260+
if client.get_integration(StarliteIntegration) is None:
259261
return
260262

261263
user_info: "Optional[Dict[str, Any]]" = None
262-
if _should_send_default_pii():
264+
if should_send_default_pii():
263265
user_info = retrieve_user_from_scope(scope)
264266
if user_info and isinstance(user_info, dict):
265-
with hub.configure_scope() as sentry_scope:
266-
sentry_scope.set_user(user_info)
267+
sentry_scope = SentryScope.get_isolation_scope()
268+
sentry_scope.set_user(user_info)
267269

268270
event, hint = event_from_exception(
269271
exc,
270-
client_options=hub.client.options if hub.client else None,
272+
client_options=client.options,
271273
mechanism={"type": StarliteIntegration.identifier, "handled": False},
272274
)
273275

274-
hub.capture_event(event, hint=hint)
276+
sentry_sdk.capture_event(event, hint=hint)

0 commit comments

Comments
 (0)