ariadne.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. from importlib import import_module
  2. import sentry_sdk
  3. from sentry_sdk import get_client, capture_event
  4. from sentry_sdk.integrations import _check_minimum_version, DidNotEnable, Integration
  5. from sentry_sdk.integrations.logging import ignore_logger
  6. from sentry_sdk.integrations._wsgi_common import request_body_within_bounds
  7. from sentry_sdk.scope import should_send_default_pii
  8. from sentry_sdk.utils import (
  9. capture_internal_exceptions,
  10. ensure_integration_enabled,
  11. event_from_exception,
  12. package_version,
  13. )
  14. try:
  15. # importing like this is necessary due to name shadowing in ariadne
  16. # (ariadne.graphql is also a function)
  17. ariadne_graphql = import_module("ariadne.graphql")
  18. except ImportError:
  19. raise DidNotEnable("ariadne is not installed")
  20. from typing import TYPE_CHECKING
  21. if TYPE_CHECKING:
  22. from typing import Any, Dict, List, Optional
  23. from ariadne.types import GraphQLError, GraphQLResult, GraphQLSchema, QueryParser # type: ignore
  24. from graphql.language.ast import DocumentNode
  25. from sentry_sdk._types import Event, EventProcessor
  26. class AriadneIntegration(Integration):
  27. identifier = "ariadne"
  28. @staticmethod
  29. def setup_once() -> None:
  30. version = package_version("ariadne")
  31. _check_minimum_version(AriadneIntegration, version)
  32. ignore_logger("ariadne")
  33. _patch_graphql()
  34. def _patch_graphql() -> None:
  35. old_parse_query = ariadne_graphql.parse_query
  36. old_handle_errors = ariadne_graphql.handle_graphql_errors
  37. old_handle_query_result = ariadne_graphql.handle_query_result
  38. @ensure_integration_enabled(AriadneIntegration, old_parse_query)
  39. def _sentry_patched_parse_query(
  40. context_value: "Optional[Any]",
  41. query_parser: "Optional[QueryParser]",
  42. data: "Any",
  43. ) -> "DocumentNode":
  44. event_processor = _make_request_event_processor(data)
  45. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  46. result = old_parse_query(context_value, query_parser, data)
  47. return result
  48. @ensure_integration_enabled(AriadneIntegration, old_handle_errors)
  49. def _sentry_patched_handle_graphql_errors(
  50. errors: "List[GraphQLError]", *args: "Any", **kwargs: "Any"
  51. ) -> "GraphQLResult":
  52. result = old_handle_errors(errors, *args, **kwargs)
  53. event_processor = _make_response_event_processor(result[1])
  54. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  55. client = get_client()
  56. if client.is_active():
  57. with capture_internal_exceptions():
  58. for error in errors:
  59. event, hint = event_from_exception(
  60. error,
  61. client_options=client.options,
  62. mechanism={
  63. "type": AriadneIntegration.identifier,
  64. "handled": False,
  65. },
  66. )
  67. capture_event(event, hint=hint)
  68. return result
  69. @ensure_integration_enabled(AriadneIntegration, old_handle_query_result)
  70. def _sentry_patched_handle_query_result(
  71. result: "Any", *args: "Any", **kwargs: "Any"
  72. ) -> "GraphQLResult":
  73. query_result = old_handle_query_result(result, *args, **kwargs)
  74. event_processor = _make_response_event_processor(query_result[1])
  75. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  76. client = get_client()
  77. if client.is_active():
  78. with capture_internal_exceptions():
  79. for error in result.errors or []:
  80. event, hint = event_from_exception(
  81. error,
  82. client_options=client.options,
  83. mechanism={
  84. "type": AriadneIntegration.identifier,
  85. "handled": False,
  86. },
  87. )
  88. capture_event(event, hint=hint)
  89. return query_result
  90. ariadne_graphql.parse_query = _sentry_patched_parse_query # type: ignore
  91. ariadne_graphql.handle_graphql_errors = _sentry_patched_handle_graphql_errors # type: ignore
  92. ariadne_graphql.handle_query_result = _sentry_patched_handle_query_result # type: ignore
  93. def _make_request_event_processor(data: "GraphQLSchema") -> "EventProcessor":
  94. """Add request data and api_target to events."""
  95. def inner(event: "Event", hint: "dict[str, Any]") -> "Event":
  96. if not isinstance(data, dict):
  97. return event
  98. with capture_internal_exceptions():
  99. try:
  100. content_length = int(
  101. (data.get("headers") or {}).get("Content-Length", 0)
  102. )
  103. except (TypeError, ValueError):
  104. return event
  105. if should_send_default_pii() and request_body_within_bounds(
  106. get_client(), content_length
  107. ):
  108. request_info = event.setdefault("request", {})
  109. request_info["api_target"] = "graphql"
  110. request_info["data"] = data
  111. elif event.get("request", {}).get("data"):
  112. del event["request"]["data"]
  113. return event
  114. return inner
  115. def _make_response_event_processor(response: "Dict[str, Any]") -> "EventProcessor":
  116. """Add response data to the event's response context."""
  117. def inner(event: "Event", hint: "dict[str, Any]") -> "Event":
  118. with capture_internal_exceptions():
  119. if should_send_default_pii() and response.get("errors"):
  120. contexts = event.setdefault("contexts", {})
  121. contexts["response"] = {
  122. "data": response,
  123. }
  124. return event
  125. return inner