litestar.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. from collections.abc import Set
  2. from copy import deepcopy
  3. import sentry_sdk
  4. from sentry_sdk.consts import OP
  5. from sentry_sdk.integrations import (
  6. _DEFAULT_FAILED_REQUEST_STATUS_CODES,
  7. DidNotEnable,
  8. Integration,
  9. )
  10. from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
  11. from sentry_sdk.integrations.logging import ignore_logger
  12. from sentry_sdk.scope import should_send_default_pii
  13. from sentry_sdk.tracing import TransactionSource, SOURCE_FOR_STYLE
  14. from sentry_sdk.utils import (
  15. ensure_integration_enabled,
  16. event_from_exception,
  17. transaction_from_function,
  18. )
  19. try:
  20. from litestar import Request, Litestar # type: ignore
  21. from litestar.handlers.base import BaseRouteHandler # type: ignore
  22. from litestar.middleware import DefineMiddleware # type: ignore
  23. from litestar.routes.http import HTTPRoute # type: ignore
  24. from litestar.data_extractors import ConnectionDataExtractor # type: ignore
  25. from litestar.exceptions import HTTPException # type: ignore
  26. except ImportError:
  27. raise DidNotEnable("Litestar is not installed")
  28. from typing import TYPE_CHECKING
  29. if TYPE_CHECKING:
  30. from typing import Any, Optional, Union
  31. from litestar.types.asgi_types import ASGIApp # type: ignore
  32. from litestar.types import ( # type: ignore
  33. HTTPReceiveMessage,
  34. HTTPScope,
  35. Message,
  36. Middleware,
  37. Receive,
  38. Scope as LitestarScope,
  39. Send,
  40. WebSocketReceiveMessage,
  41. )
  42. from litestar.middleware import MiddlewareProtocol
  43. from sentry_sdk._types import Event, Hint
  44. _DEFAULT_TRANSACTION_NAME = "generic Litestar request"
  45. class LitestarIntegration(Integration):
  46. identifier = "litestar"
  47. origin = f"auto.http.{identifier}"
  48. def __init__(
  49. self,
  50. failed_request_status_codes: "Set[int]" = _DEFAULT_FAILED_REQUEST_STATUS_CODES,
  51. ) -> None:
  52. self.failed_request_status_codes = failed_request_status_codes
  53. @staticmethod
  54. def setup_once() -> None:
  55. patch_app_init()
  56. patch_middlewares()
  57. patch_http_route_handle()
  58. # The following line follows the pattern found in other integrations such as `DjangoIntegration.setup_once`.
  59. # The Litestar `ExceptionHandlerMiddleware.__call__` catches exceptions and does the following
  60. # (among other things):
  61. # 1. Logs them, some at least (such as 500s) as errors
  62. # 2. Calls after_exception hooks
  63. # The `LitestarIntegration`` provides an after_exception hook (see `patch_app_init` below) to create a Sentry event
  64. # from an exception, which ends up being called during step 2 above. However, the Sentry `LoggingIntegration` will
  65. # by default create a Sentry event from error logs made in step 1 if we do not prevent it from doing so.
  66. ignore_logger("litestar")
  67. class SentryLitestarASGIMiddleware(SentryAsgiMiddleware):
  68. def __init__(
  69. self, app: "ASGIApp", span_origin: str = LitestarIntegration.origin
  70. ) -> None:
  71. super().__init__(
  72. app=app,
  73. unsafe_context_data=False,
  74. transaction_style="endpoint",
  75. mechanism_type="asgi",
  76. span_origin=span_origin,
  77. asgi_version=3,
  78. )
  79. def _capture_request_exception(self, exc: Exception) -> None:
  80. """Avoid catching exceptions from request handlers.
  81. Those exceptions are already handled in Litestar.after_exception handler.
  82. We still catch exceptions from application lifespan handlers.
  83. """
  84. pass
  85. def patch_app_init() -> None:
  86. """
  87. Replaces the Litestar class's `__init__` function in order to inject `after_exception` handlers and set the
  88. `SentryLitestarASGIMiddleware` as the outmost middleware in the stack.
  89. See:
  90. - https://docs.litestar.dev/2/usage/applications.html#after-exception
  91. - https://docs.litestar.dev/2/usage/middleware/using-middleware.html
  92. """
  93. old__init__ = Litestar.__init__
  94. @ensure_integration_enabled(LitestarIntegration, old__init__)
  95. def injection_wrapper(self: "Litestar", *args: "Any", **kwargs: "Any") -> None:
  96. kwargs["after_exception"] = [
  97. exception_handler,
  98. *(kwargs.get("after_exception") or []),
  99. ]
  100. middleware = kwargs.get("middleware") or []
  101. kwargs["middleware"] = [SentryLitestarASGIMiddleware, *middleware]
  102. old__init__(self, *args, **kwargs)
  103. Litestar.__init__ = injection_wrapper
  104. def patch_middlewares() -> None:
  105. old_resolve_middleware_stack = BaseRouteHandler.resolve_middleware
  106. @ensure_integration_enabled(LitestarIntegration, old_resolve_middleware_stack)
  107. def resolve_middleware_wrapper(self: "BaseRouteHandler") -> "list[Middleware]":
  108. return [
  109. enable_span_for_middleware(middleware)
  110. for middleware in old_resolve_middleware_stack(self)
  111. ]
  112. BaseRouteHandler.resolve_middleware = resolve_middleware_wrapper
  113. def enable_span_for_middleware(middleware: "Middleware") -> "Middleware":
  114. if (
  115. not hasattr(middleware, "__call__") # noqa: B004
  116. or middleware is SentryLitestarASGIMiddleware
  117. ):
  118. return middleware
  119. if isinstance(middleware, DefineMiddleware):
  120. old_call: "ASGIApp" = middleware.middleware.__call__
  121. else:
  122. old_call = middleware.__call__
  123. async def _create_span_call(
  124. self: "MiddlewareProtocol",
  125. scope: "LitestarScope",
  126. receive: "Receive",
  127. send: "Send",
  128. ) -> None:
  129. if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
  130. return await old_call(self, scope, receive, send)
  131. middleware_name = self.__class__.__name__
  132. with sentry_sdk.start_span(
  133. op=OP.MIDDLEWARE_LITESTAR,
  134. name=middleware_name,
  135. origin=LitestarIntegration.origin,
  136. ) as middleware_span:
  137. middleware_span.set_tag("litestar.middleware_name", middleware_name)
  138. # Creating spans for the "receive" callback
  139. async def _sentry_receive(
  140. *args: "Any", **kwargs: "Any"
  141. ) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]":
  142. if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
  143. return await receive(*args, **kwargs)
  144. with sentry_sdk.start_span(
  145. op=OP.MIDDLEWARE_LITESTAR_RECEIVE,
  146. name=getattr(receive, "__qualname__", str(receive)),
  147. origin=LitestarIntegration.origin,
  148. ) as span:
  149. span.set_tag("litestar.middleware_name", middleware_name)
  150. return await receive(*args, **kwargs)
  151. receive_name = getattr(receive, "__name__", str(receive))
  152. receive_patched = receive_name == "_sentry_receive"
  153. new_receive = _sentry_receive if not receive_patched else receive
  154. # Creating spans for the "send" callback
  155. async def _sentry_send(message: "Message") -> None:
  156. if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
  157. return await send(message)
  158. with sentry_sdk.start_span(
  159. op=OP.MIDDLEWARE_LITESTAR_SEND,
  160. name=getattr(send, "__qualname__", str(send)),
  161. origin=LitestarIntegration.origin,
  162. ) as span:
  163. span.set_tag("litestar.middleware_name", middleware_name)
  164. return await send(message)
  165. send_name = getattr(send, "__name__", str(send))
  166. send_patched = send_name == "_sentry_send"
  167. new_send = _sentry_send if not send_patched else send
  168. return await old_call(self, scope, new_receive, new_send)
  169. not_yet_patched = old_call.__name__ not in ["_create_span_call"]
  170. if not_yet_patched:
  171. if isinstance(middleware, DefineMiddleware):
  172. middleware.middleware.__call__ = _create_span_call
  173. else:
  174. middleware.__call__ = _create_span_call
  175. return middleware
  176. def patch_http_route_handle() -> None:
  177. old_handle = HTTPRoute.handle
  178. async def handle_wrapper(
  179. self: "HTTPRoute", scope: "HTTPScope", receive: "Receive", send: "Send"
  180. ) -> None:
  181. if sentry_sdk.get_client().get_integration(LitestarIntegration) is None:
  182. return await old_handle(self, scope, receive, send)
  183. sentry_scope = sentry_sdk.get_isolation_scope()
  184. request: "Request[Any, Any]" = scope["app"].request_class(
  185. scope=scope, receive=receive, send=send
  186. )
  187. extracted_request_data = ConnectionDataExtractor(
  188. parse_body=True, parse_query=True
  189. )(request)
  190. body = extracted_request_data.pop("body")
  191. request_data = await body
  192. def event_processor(event: "Event", _: "Hint") -> "Event":
  193. route_handler = scope.get("route_handler")
  194. request_info = event.get("request", {})
  195. request_info["content_length"] = len(scope.get("_body", b""))
  196. if should_send_default_pii():
  197. request_info["cookies"] = extracted_request_data["cookies"]
  198. if request_data is not None:
  199. request_info["data"] = request_data
  200. func = None
  201. if route_handler.name is not None:
  202. tx_name = route_handler.name
  203. # Accounts for use of type `Ref` in earlier versions of litestar without the need to reference it as a type
  204. elif hasattr(route_handler.fn, "value"):
  205. func = route_handler.fn.value
  206. else:
  207. func = route_handler.fn
  208. if func is not None:
  209. tx_name = transaction_from_function(func)
  210. tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]}
  211. if not tx_name:
  212. tx_name = _DEFAULT_TRANSACTION_NAME
  213. tx_info = {"source": TransactionSource.ROUTE}
  214. event.update(
  215. {
  216. "request": deepcopy(request_info),
  217. "transaction": tx_name,
  218. "transaction_info": tx_info,
  219. }
  220. )
  221. return event
  222. sentry_scope._name = LitestarIntegration.identifier
  223. sentry_scope.add_event_processor(event_processor)
  224. return await old_handle(self, scope, receive, send)
  225. HTTPRoute.handle = handle_wrapper
  226. def retrieve_user_from_scope(scope: "LitestarScope") -> "Optional[dict[str, Any]]":
  227. scope_user = scope.get("user")
  228. if isinstance(scope_user, dict):
  229. return scope_user
  230. if hasattr(scope_user, "asdict"): # dataclasses
  231. return scope_user.asdict()
  232. return None
  233. @ensure_integration_enabled(LitestarIntegration)
  234. def exception_handler(exc: Exception, scope: "LitestarScope") -> None:
  235. user_info: "Optional[dict[str, Any]]" = None
  236. if should_send_default_pii():
  237. user_info = retrieve_user_from_scope(scope)
  238. if user_info and isinstance(user_info, dict):
  239. sentry_scope = sentry_sdk.get_isolation_scope()
  240. sentry_scope.set_user(user_info)
  241. if isinstance(exc, HTTPException):
  242. integration = sentry_sdk.get_client().get_integration(LitestarIntegration)
  243. if (
  244. integration is not None
  245. and exc.status_code not in integration.failed_request_status_codes
  246. ):
  247. return
  248. event, hint = event_from_exception(
  249. exc,
  250. client_options=sentry_sdk.get_client().options,
  251. mechanism={"type": LitestarIntegration.identifier, "handled": False},
  252. )
  253. sentry_sdk.capture_event(event, hint=hint)