Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Query fingerprint in span info (#8203)

Tomasz Szymańskieb64c5336481
diff --git a/saleor/graphql/tests/test_tracing.py b/saleor/graphql/tests/test_tracing.py
new file mode 100644
index 0000000000..6a4b893afc
--- /dev/null
+++ b/saleor/graphql/tests/test_tracing.py
@@ -0,0 +1,194 @@
+import hashlib
+from unittest.mock import patch
+
+import graphene
+from opentracing.mocktracer import MockTracer
+
+
+def _get_graphql_span(spans):
+ return next(_get_graphql_spans(spans))
+
+
+def _get_graphql_spans(spans):
+ return filter(lambda item: item.tags["component"] == "GraphQL", spans)
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_query_hashing(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_products,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ query = """
+ query test {
+ products(first:5) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ staff_api_client.post_graphql(query)
+ span = _get_graphql_span(tracer.finished_spans())
+ hash = hashlib.md5(span.tags["graphql.query"].encode("utf-8")).hexdigest()
+ assert span.tags["graphql.query_fingerprint"] == f"query:test:{hash}"
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_query_hashing_with_fragment(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_products,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ query = """
+ fragment ProductVariant on ProductVariant {
+ id
+ }
+ query test {
+ products(first:5) {
+ edges{
+ node{
+ id
+ name
+ variants {
+ ...ProductVariant
+ }
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ staff_api_client.post_graphql(query)
+ span = _get_graphql_span(tracer.finished_spans())
+ hash = hashlib.md5(span.tags["graphql.query"].encode("utf-8")).hexdigest()
+ assert span.tags["graphql.query_fingerprint"] == f"query:test:{hash}"
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_query_hashing_different_vars_same_checksum(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_products,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ query = """
+ query test($first: Int!) {
+ products(first: $first) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ QUERIES = 5
+ for i in range(QUERIES):
+ staff_api_client.post_graphql(query, {"first": i + 1})
+ fingerprints = list(
+ map(
+ lambda span: span.tags["graphql.query_fingerprint"],
+ _get_graphql_spans(tracer.finished_spans()),
+ )
+ )
+ assert len(fingerprints) == QUERIES
+ assert len(set(fingerprints)) == 1
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_query_hashing_unnamed_query(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_products,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ query = """
+ query {
+ products(first:5) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ staff_api_client.post_graphql(query)
+ span = _get_graphql_span(tracer.finished_spans())
+ hash = hashlib.md5(span.tags["graphql.query"].encode("utf-8")).hexdigest()
+ assert span.tags["graphql.query_fingerprint"] == f"query:{hash}"
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_query_hashing_unnamed_query_no_query_spec(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_products,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ query = """
+ {
+ products(first:5) {
+ edges{
+ node{
+ id
+ name
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ staff_api_client.post_graphql(query)
+ span = _get_graphql_span(tracer.finished_spans())
+ hash = hashlib.md5(span.tags["graphql.query"].encode("utf-8")).hexdigest()
+ assert span.tags["graphql.query_fingerprint"] == f"query:{hash}"
+
+
+@patch("saleor.graphql.views.opentracing.global_tracer")
+def test_tracing_mutation_hashing(
+ tracing_mock,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+):
+ tracer = MockTracer()
+ tracing_mock.return_value = tracer
+ order = order_with_lines
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ mutation = """
+ mutation cancelOrder($id: ID!) {
+ orderCancel(id: $id) {
+ order {
+ status
+ }
+ errors{
+ field
+ code
+ }
+ }
+ }
+ """
+ staff_api_client.post_graphql(
+ mutation, variables, permissions=[permission_manage_orders]
+ )
+ span = _get_graphql_span(tracer.finished_spans())
+ hash = hashlib.md5(span.tags["graphql.query"].encode("utf-8")).hexdigest()
+ assert span.tags["graphql.query_fingerprint"] == f"mutation:cancelOrder:{hash}"
diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.py
index a795207a78..ccf29761a1 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -1,9 +1,11 @@
+import hashlib
from typing import Union
import graphene
from django.db.models import Value
from django.db.models.functions import Concat
from graphene_django.registry import get_global_registry
+from graphql import GraphQLDocument
from graphql.error import GraphQLError
from graphql_relay import from_global_id
@@ -130,3 +132,21 @@ def get_user_or_app_from_context(context):
def requestor_is_superuser(requestor):
"""Return True if requestor is superuser."""
return getattr(requestor, "is_superuser", False)
+
+
+def query_fingerprint(document: GraphQLDocument) -> str:
+ """Generate a fingerprint for a GraphQL query."""
+ label = "unknown"
+ for definition in document.document_ast.definitions:
+ if getattr(definition, "operation", None) in {
+ "query",
+ "mutation",
+ "subscription",
+ }:
+ if definition.name:
+ label = f"{definition.operation}:{definition.name.value}"
+ else:
+ label = definition.operation
+ break
+ query_hash = hashlib.md5(document.document_string.encode("utf-8")).hexdigest()
+ return f"{label}:{query_hash}"
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 7bfca7f081..ea42addfb7 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -27,6 +27,7 @@ from jwt.exceptions import PyJWTError
from .. import __version__ as saleor_version
from ..core.exceptions import PermissionDenied, ReadOnlyException
from ..core.utils import is_valid_ipv4, is_valid_ipv6
+from .utils import query_fingerprint
API_PATH = SimpleLazyObject(lambda: reverse("api"))
INT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"
@@ -261,6 +262,7 @@ class GraphQLView(View):
if document is not None:
raw_query_string = document.document_string
span.set_tag("graphql.query", raw_query_string)
+ span.set_tag("graphql.query_fingerprint", query_fingerprint(document))
try:
query_contains_schema = self.check_if_query_contains_only_schema(
document