bottle.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import functools
  2. import sentry_sdk
  3. from sentry_sdk.tracing import SOURCE_FOR_STYLE
  4. from sentry_sdk.utils import (
  5. capture_internal_exceptions,
  6. ensure_integration_enabled,
  7. event_from_exception,
  8. parse_version,
  9. transaction_from_function,
  10. )
  11. from sentry_sdk.integrations import (
  12. Integration,
  13. DidNotEnable,
  14. _DEFAULT_FAILED_REQUEST_STATUS_CODES,
  15. _check_minimum_version,
  16. )
  17. from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
  18. from sentry_sdk.integrations._wsgi_common import RequestExtractor
  19. from typing import TYPE_CHECKING
  20. if TYPE_CHECKING:
  21. from collections.abc import Set
  22. from sentry_sdk.integrations.wsgi import _ScopedResponse
  23. from typing import Any
  24. from typing import Dict
  25. from typing import Callable
  26. from typing import Optional
  27. from bottle import FileUpload, FormsDict, LocalRequest # type: ignore
  28. from sentry_sdk._types import EventProcessor, Event
  29. try:
  30. from bottle import (
  31. Bottle,
  32. HTTPResponse,
  33. Route,
  34. request as bottle_request,
  35. __version__ as BOTTLE_VERSION,
  36. )
  37. except ImportError:
  38. raise DidNotEnable("Bottle not installed")
  39. TRANSACTION_STYLE_VALUES = ("endpoint", "url")
  40. class BottleIntegration(Integration):
  41. identifier = "bottle"
  42. origin = f"auto.http.{identifier}"
  43. transaction_style = ""
  44. def __init__(
  45. self,
  46. transaction_style: str = "endpoint",
  47. *,
  48. failed_request_status_codes: "Set[int]" = _DEFAULT_FAILED_REQUEST_STATUS_CODES,
  49. ) -> None:
  50. if transaction_style not in TRANSACTION_STYLE_VALUES:
  51. raise ValueError(
  52. "Invalid value for transaction_style: %s (must be in %s)"
  53. % (transaction_style, TRANSACTION_STYLE_VALUES)
  54. )
  55. self.transaction_style = transaction_style
  56. self.failed_request_status_codes = failed_request_status_codes
  57. @staticmethod
  58. def setup_once() -> None:
  59. version = parse_version(BOTTLE_VERSION)
  60. _check_minimum_version(BottleIntegration, version)
  61. old_app = Bottle.__call__
  62. @ensure_integration_enabled(BottleIntegration, old_app)
  63. def sentry_patched_wsgi_app(
  64. self: "Any", environ: "Dict[str, str]", start_response: "Callable[..., Any]"
  65. ) -> "_ScopedResponse":
  66. middleware = SentryWsgiMiddleware(
  67. lambda *a, **kw: old_app(self, *a, **kw),
  68. span_origin=BottleIntegration.origin,
  69. )
  70. return middleware(environ, start_response)
  71. Bottle.__call__ = sentry_patched_wsgi_app
  72. old_handle = Bottle._handle
  73. @functools.wraps(old_handle)
  74. def _patched_handle(self: "Bottle", environ: "Dict[str, Any]") -> "Any":
  75. integration = sentry_sdk.get_client().get_integration(BottleIntegration)
  76. if integration is None:
  77. return old_handle(self, environ)
  78. scope = sentry_sdk.get_isolation_scope()
  79. scope._name = "bottle"
  80. scope.add_event_processor(
  81. _make_request_event_processor(self, bottle_request, integration)
  82. )
  83. res = old_handle(self, environ)
  84. return res
  85. Bottle._handle = _patched_handle
  86. old_make_callback = Route._make_callback
  87. @functools.wraps(old_make_callback)
  88. def patched_make_callback(
  89. self: "Route", *args: object, **kwargs: object
  90. ) -> "Any":
  91. prepared_callback = old_make_callback(self, *args, **kwargs)
  92. integration = sentry_sdk.get_client().get_integration(BottleIntegration)
  93. if integration is None:
  94. return prepared_callback
  95. def wrapped_callback(*args: object, **kwargs: object) -> "Any":
  96. try:
  97. res = prepared_callback(*args, **kwargs)
  98. except Exception as exception:
  99. _capture_exception(exception, handled=False)
  100. raise exception
  101. if (
  102. isinstance(res, HTTPResponse)
  103. and res.status_code in integration.failed_request_status_codes
  104. ):
  105. _capture_exception(res, handled=True)
  106. return res
  107. return wrapped_callback
  108. Route._make_callback = patched_make_callback
  109. class BottleRequestExtractor(RequestExtractor):
  110. def env(self) -> "Dict[str, str]":
  111. return self.request.environ
  112. def cookies(self) -> "Dict[str, str]":
  113. return self.request.cookies
  114. def raw_data(self) -> bytes:
  115. return self.request.body.read()
  116. def form(self) -> "FormsDict":
  117. if self.is_json():
  118. return None
  119. return self.request.forms.decode()
  120. def files(self) -> "Optional[Dict[str, str]]":
  121. if self.is_json():
  122. return None
  123. return self.request.files
  124. def size_of_file(self, file: "FileUpload") -> int:
  125. return file.content_length
  126. def _set_transaction_name_and_source(
  127. event: "Event", transaction_style: str, request: "Any"
  128. ) -> None:
  129. name = ""
  130. if transaction_style == "url":
  131. try:
  132. name = request.route.rule or ""
  133. except RuntimeError:
  134. pass
  135. elif transaction_style == "endpoint":
  136. try:
  137. name = (
  138. request.route.name
  139. or transaction_from_function(request.route.callback)
  140. or ""
  141. )
  142. except RuntimeError:
  143. pass
  144. event["transaction"] = name
  145. event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]}
  146. def _make_request_event_processor(
  147. app: "Bottle", request: "LocalRequest", integration: "BottleIntegration"
  148. ) -> "EventProcessor":
  149. def event_processor(event: "Event", hint: "dict[str, Any]") -> "Event":
  150. _set_transaction_name_and_source(event, integration.transaction_style, request)
  151. with capture_internal_exceptions():
  152. BottleRequestExtractor(request).extract_into_event(event)
  153. return event
  154. return event_processor
  155. def _capture_exception(exception: BaseException, handled: bool) -> None:
  156. event, hint = event_from_exception(
  157. exception,
  158. client_options=sentry_sdk.get_client().options,
  159. mechanism={"type": "bottle", "handled": handled},
  160. )
  161. sentry_sdk.capture_event(event, hint=hint)