ariadne.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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():
  30. # type: () -> None
  31. version = package_version("ariadne")
  32. _check_minimum_version(AriadneIntegration, version)
  33. ignore_logger("ariadne")
  34. _patch_graphql()
  35. def _patch_graphql():
  36. # type: () -> None
  37. old_parse_query = ariadne_graphql.parse_query
  38. old_handle_errors = ariadne_graphql.handle_graphql_errors
  39. old_handle_query_result = ariadne_graphql.handle_query_result
  40. @ensure_integration_enabled(AriadneIntegration, old_parse_query)
  41. def _sentry_patched_parse_query(context_value, query_parser, data):
  42. # type: (Optional[Any], Optional[QueryParser], Any) -> DocumentNode
  43. event_processor = _make_request_event_processor(data)
  44. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  45. result = old_parse_query(context_value, query_parser, data)
  46. return result
  47. @ensure_integration_enabled(AriadneIntegration, old_handle_errors)
  48. def _sentry_patched_handle_graphql_errors(errors, *args, **kwargs):
  49. # type: (List[GraphQLError], Any, Any) -> GraphQLResult
  50. result = old_handle_errors(errors, *args, **kwargs)
  51. event_processor = _make_response_event_processor(result[1])
  52. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  53. client = get_client()
  54. if client.is_active():
  55. with capture_internal_exceptions():
  56. for error in errors:
  57. event, hint = event_from_exception(
  58. error,
  59. client_options=client.options,
  60. mechanism={
  61. "type": AriadneIntegration.identifier,
  62. "handled": False,
  63. },
  64. )
  65. capture_event(event, hint=hint)
  66. return result
  67. @ensure_integration_enabled(AriadneIntegration, old_handle_query_result)
  68. def _sentry_patched_handle_query_result(result, *args, **kwargs):
  69. # type: (Any, Any, Any) -> GraphQLResult
  70. query_result = old_handle_query_result(result, *args, **kwargs)
  71. event_processor = _make_response_event_processor(query_result[1])
  72. sentry_sdk.get_isolation_scope().add_event_processor(event_processor)
  73. client = get_client()
  74. if client.is_active():
  75. with capture_internal_exceptions():
  76. for error in result.errors or []:
  77. event, hint = event_from_exception(
  78. error,
  79. client_options=client.options,
  80. mechanism={
  81. "type": AriadneIntegration.identifier,
  82. "handled": False,
  83. },
  84. )
  85. capture_event(event, hint=hint)
  86. return query_result
  87. ariadne_graphql.parse_query = _sentry_patched_parse_query # type: ignore
  88. ariadne_graphql.handle_graphql_errors = _sentry_patched_handle_graphql_errors # type: ignore
  89. ariadne_graphql.handle_query_result = _sentry_patched_handle_query_result # type: ignore
  90. def _make_request_event_processor(data):
  91. # type: (GraphQLSchema) -> EventProcessor
  92. """Add request data and api_target to events."""
  93. def inner(event, hint):
  94. # type: (Event, dict[str, Any]) -> Event
  95. if not isinstance(data, dict):
  96. return event
  97. with capture_internal_exceptions():
  98. try:
  99. content_length = int(
  100. (data.get("headers") or {}).get("Content-Length", 0)
  101. )
  102. except (TypeError, ValueError):
  103. return event
  104. if should_send_default_pii() and request_body_within_bounds(
  105. get_client(), content_length
  106. ):
  107. request_info = event.setdefault("request", {})
  108. request_info["api_target"] = "graphql"
  109. request_info["data"] = data
  110. elif event.get("request", {}).get("data"):
  111. del event["request"]["data"]
  112. return event
  113. return inner
  114. def _make_response_event_processor(response):
  115. # type: (Dict[str, Any]) -> EventProcessor
  116. """Add response data to the event's response context."""
  117. def inner(event, hint):
  118. # type: (Event, dict[str, Any]) -> Event
  119. with capture_internal_exceptions():
  120. if should_send_default_pii() and response.get("errors"):
  121. contexts = event.setdefault("contexts", {})
  122. contexts["response"] = {
  123. "data": response,
  124. }
  125. return event
  126. return inner