|
| 1 | +from sentry_sdk.hub import Hub |
| 2 | +from sentry_sdk.integrations import DidNotEnable, Integration |
| 3 | +from sentry_sdk.utils import parse_version |
| 4 | +from sentry_sdk._types import TYPE_CHECKING |
| 5 | + |
| 6 | +try: |
| 7 | + from graphql import version as GRAPHQL_CORE_VERSION |
| 8 | +except ImportError: |
| 9 | + raise DidNotEnable("graphql-core not installed") |
| 10 | + |
| 11 | +supported_library_installed = False |
| 12 | + |
| 13 | +try: |
| 14 | + from graphene.types import schema as graphene_schema |
| 15 | + |
| 16 | + supported_library_installed = True |
| 17 | +except ImportError: |
| 18 | + graphene_schema = None |
| 19 | + |
| 20 | + |
| 21 | +if not supported_library_installed: |
| 22 | + raise DidNotEnable("graphene not installed") # XXX more server impls |
| 23 | + |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + pass |
| 27 | + |
| 28 | + |
| 29 | +class GraphQLServerIntegration(Integration): |
| 30 | + identifier = "graphql_server" |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def setup_once(): |
| 34 | + # type: () -> None |
| 35 | + global graphene_schema |
| 36 | + |
| 37 | + version = parse_version(GRAPHQL_CORE_VERSION) |
| 38 | + |
| 39 | + if version is None: |
| 40 | + raise DidNotEnable( |
| 41 | + "Unparsable graphql-core version: {}".format(GRAPHQL_CORE_VERSION) |
| 42 | + ) |
| 43 | + |
| 44 | + if version < (3, 2): |
| 45 | + raise DidNotEnable("graphql-core 3.2 or newer required.") |
| 46 | + |
| 47 | + # XXX async |
| 48 | + if graphene_schema is not None: |
| 49 | + old_execute_sync = graphene_schema.graphql_sync |
| 50 | + |
| 51 | + def sentry_patched_graphql_sync(*args, **kwargs): |
| 52 | + hub = Hub.current |
| 53 | + integration = hub.get_integration(GraphQLServerIntegration) |
| 54 | + if integration is None or hub.client is None: |
| 55 | + return old_execute_sync(*args, **kwargs) |
| 56 | + |
| 57 | + result = old_execute_sync(*args, **kwargs) |
| 58 | + |
| 59 | + for error in result.errors or []: |
| 60 | + hub.capture_exception(error) |
| 61 | + |
| 62 | + return result |
| 63 | + |
| 64 | + graphene_schema.graphql_sync = sentry_patched_graphql_sync |
0 commit comments