Skip to content

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

feat(graphql): add additional metrics (#19055)

Mikailb79b0871f8c5
diff --git a/saleor/core/telemetry/utils.py b/saleor/core/telemetry/utils.py
index 4c5b88615f..611a76b980 100644
--- a/saleor/core/telemetry/utils.py
+++ b/saleor/core/telemetry/utils.py
@@ -37,6 +37,7 @@ class Unit(Enum):
COST = "{cost}"
EVENT = "{event}"
CALL = "{call}"
+ COUNT = "{count}" # generic unit
UNIT_CONVERSIONS: dict[tuple[Unit, Unit], float] = {
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index 7338259276..448e2baeca 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -10,10 +10,13 @@ from django.test import override_settings
from graphql.execution.base import ExecutionResult
from .... import __version__ as saleor_version
-from ....graphql.api import backend, schema
-from ....graphql.utils import INTERNAL_ERROR_MESSAGE
+from ....core.telemetry import Scope, Unit
+from ....tests.utils import get_metric_data
+from ...api import backend, schema
+from ...metrics import METRIC_GRAPHQL_BATCH_SIZE
from ...tests.fixtures import API_PATH
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
+from ...utils import INTERNAL_ERROR_MESSAGE
from ...views import GraphQLView, generate_cache_key
@@ -100,6 +103,49 @@ def test_rejects_based_on_number_batch_queries(api_client, settings):
assert resp.status_code == 400
+ ("data", "expected_count"),
+ [
+ (
+ [{"query": "{__typename}"}] * 3,
+ 3,
+ ),
+ (
+ # Sending too many batched queries should cause the metric to not be recorded
+ [{"query": "{__typename}"}] * 4,
+ None,
+ ),
+ (
+ # Sending only 1 query in a batch shouldn't be recorded as it's effectively
+ # *not* using batch queries
+ [{"query": "{__typename}"}],
+ None,
+ ),
+ ],
+)
+def test_batch_query_size_metric_is_recorded(
+ get_test_metrics_data, rf, settings, data: list[dict], expected_count: int | None
+):
+ settings.GRAPHQL_BATCH_MAX_COUNT = 3
+
+ # Send the request
+ request = rf.post(path="/graphql/", data=data, content_type="application/json")
+ GraphQLView.as_view(backend=backend, schema=schema)(request)
+
+ # Check the metric
+ metrics_data = get_test_metrics_data()
+ metric = get_metric_data(metrics_data, METRIC_GRAPHQL_BATCH_SIZE, scope=Scope.CORE)
+
+ if expected_count is None:
+ assert metric is None, "shouldn't have recorded the metric"
+ else:
+ assert metric is not None, "should have found a metric"
+ data_point = metric.data.data_points[0]
+ assert metric.unit == Unit.COUNT.value
+ assert data_point.attributes == {}
+ assert data_point.max == expected_count
+
+
def test_graphql_view_query_with_invalid_object_type(
staff_api_client, product, permission_manage_orders, graphql_log_handler
):
diff --git a/saleor/graphql/core/validators/alias_count_limit_rule.py b/saleor/graphql/core/validators/alias_count_limit_rule.py
index c0ebe5b9ee..6528c04dc2 100644
--- a/saleor/graphql/core/validators/alias_count_limit_rule.py
+++ b/saleor/graphql/core/validators/alias_count_limit_rule.py
@@ -6,6 +6,8 @@ from graphql.language.ast import Field
from graphql.validation.rules.base import ValidationRule
from graphql.validation.validation import ValidationContext
+from ...metrics import record_graphql_alias_count
+
class AliasCountLimitRule(ValidationRule):
"""Limits the number of aliases that can be sent within a query."""
@@ -24,3 +26,6 @@ class AliasCountLimitRule(ValidationRule):
self.context.report_error(
GraphQLError(f"Number of aliases exceed the limit of {self.limit}")
)
+ elif self.alias_count_seen > 0:
+ # We only want to record successful requests
+ record_graphql_alias_count(self.alias_count_seen)
diff --git a/saleor/graphql/core/validators/mutation_count_limit_rule.py b/saleor/graphql/core/validators/mutation_count_limit_rule.py
index 62e3c343c7..224f64b79a 100644
--- a/saleor/graphql/core/validators/mutation_count_limit_rule.py
+++ b/saleor/graphql/core/validators/mutation_count_limit_rule.py
@@ -6,6 +6,8 @@ from graphql.language.ast import OperationDefinition
from graphql.validation.rules.base import ValidationRule
from graphql.validation.validation import ValidationContext
+from ...metrics import record_graphql_mutation_count
+
class MutationCountLimitRule(ValidationRule):
"""Limits the number of mutations within a single request."""
@@ -24,3 +26,7 @@ class MutationCountLimitRule(ValidationRule):
self.context.report_error(
GraphQLError(f"Number of mutations exceed the limit of {self.limit}")
)
+ # We only want to record successful requests & requests that use more than 1
+ # mutation
+ elif self.seen_count > 1:
+ record_graphql_mutation_count(self.seen_count)
diff --git a/saleor/graphql/core/validators/tests/test_alias_count_limit.py b/saleor/graphql/core/validators/tests/test_alias_count_limit.py
index fad963f612..64ec0d2d5b 100644
--- a/saleor/graphql/core/validators/tests/test_alias_count_limit.py
+++ b/saleor/graphql/core/validators/tests/test_alias_count_limit.py
@@ -1,5 +1,11 @@
import pytest
+from .....core.telemetry import Scope, Unit
+from .....tests.utils import get_metric_data
+from ....api import backend, schema
+from ....metrics import METRIC_GRAPHQL_ALIAS_COUNT
+from ....views import GraphQLView
+
@pytest.mark.parametrize(
("_case", "is_valid", "query"),
@@ -80,3 +86,56 @@ def test_limits_number_of_aliases(
]
}
assert resp.status_code == 400
+
+
+ ("query", "expected_count"),
+ [
+ (
+ """
+ {
+ alias1: __typename
+ alias2: __typename
+ alias3: __typename
+ }
+ """,
+ 3,
+ ),
+ (
+ # Sending too many aliases should cause the metric to not be recorded
+ """
+ {
+ alias1: __typename
+ alias2: __typename
+ alias3: __typename
+ alias4: __typename
+ }
+ """,
+ None,
+ ),
+ # Shouldn't measure queries without any aliases
+ ("{__typename}", None),
+ ],
+)
+def test_metric_recorded(
+ get_test_metrics_data, rf, settings, query: str, expected_count: int | None
+):
+ settings.GRAPHQL_ALIAS_COUNT_LIMIT = 3
+
+ # Send the request
+ data = {"query": query}
+ request = rf.post(path="/graphql/", data=data, content_type="application/json")
+ GraphQLView.as_view(backend=backend, schema=schema)(request)
+
+ # Check the metric
+ metrics_data = get_test_metrics_data()
+ metric = get_metric_data(metrics_data, METRIC_GRAPHQL_ALIAS_COUNT, scope=Scope.CORE)
+
+ if expected_count is None:
+ assert metric is None, "shouldn't have recorded the metric"
+ else:
+ assert metric is not None, "should have found a metric"
+ data_point = metric.data.data_points[0]
+ assert metric.unit == Unit.COUNT.value
+ assert data_point.attributes == {}
+ assert data_point.max == expected_count
diff --git a/saleor/graphql/core/validators/tests/test_mutation_count_limit.py b/saleor/graphql/core/validators/tests/test_mutation_count_limit.py
index 9f6c6e8343..0800e08893 100644
--- a/saleor/graphql/core/validators/tests/test_mutation_count_limit.py
+++ b/saleor/graphql/core/validators/tests/test_mutation_count_limit.py
@@ -1,5 +1,11 @@
import pytest
+from .....core.telemetry import Scope, Unit
+from .....tests.utils import get_metric_data
+from ....api import backend, schema
+from ....metrics import METRIC_GRAPHQL_MUTATION_COUNT
+from ....views import GraphQLView
+
@pytest.mark.parametrize(
("_case", "is_valid", "query"),
@@ -77,3 +83,73 @@ def test_limits_number_of_aliases(
]
}
assert resp.status_code == 400
+
+
+ ("query", "expected_count"),
+ [
+ (
+ # Sends 2 mutations
+ """
+ mutation {
+ productUpdate(input: {name: "my-product"}, id: "UHJvZHVjdDox") {
+ __typename
+ }
+ collectionUpdate(input: {name: "my-collection"}, id: "Q29sbGVjdGlvbjoy") {
+ __typename
+ }
+ }
+ """,
+ 2,
+ ),
+ (
+ # Sends 1 mutations. We expect it to not be recorded as 1 mutation
+ # per API request is a typical use.
+ """
+ mutation {
+ tokenCreate(email: "x", password: "x") { __typename}
+ }
+ """,
+ None,
+ ),
+ (
+ # Sends 3 mutations which is too many.
+ # Ensures users sending too many mutations aren't counted
+ """
+ mutation {
+ mutation1: tokenCreate(email: "x", password: "x")
+ mutation2: tokenCreate(email: "x", password: "x")
+ mutation3: tokenCreate(email: "x", password: "x")
+ }
+ """,
+ None,
+ ),
+ ],
+)
+def test_metric_recorded(
+ get_test_metrics_data, rf, settings, query: str, expected_count: int | None
+):
+ """Should record the number of mutations sent."""
+
+ settings.GRAPHQL_ALIAS_COUNT_LIMIT = 10
+ settings.GRAPHQL_MUTATION_COUNT_LIMIT = 2
+
+ # Send the request
+ data = {"query": query}
+ request = rf.post(path="/graphql/", data=data, content_type="application/json")
+ GraphQLView.as_view(backend=backend, schema=schema)(request)
+
+ # Check the metric
+ metrics_data = get_test_metrics_data()
+ metric = get_metric_data(
+ metrics_data, METRIC_GRAPHQL_MUTATION_COUNT, scope=Scope.CORE
+ )
+
+ if expected_count is None:
+ assert metric is None, "shouldn't have recorded the metric"
+ else:
+ assert metric is not None, "should have found a metric"
+ data_point = metric.data.data_points[0]
+ assert metric.unit == Unit.COUNT.value
+ assert data_point.attributes == {}
+ assert data_point.max == expected_count
diff --git a/saleor/graphql/metrics.py b/saleor/graphql/metrics.py
index 549e13f805..3a27c22d8f 100644
--- a/saleor/graphql/metrics.py
+++ b/saleor/graphql/metrics.py
@@ -95,6 +95,30 @@ METRIC_REQUEST_DURATION = meter.create_metric(
bucket_boundaries=DEFAULT_DURATION_BUCKETS,
)
+METRIC_GRAPHQL_BATCH_SIZE = meter.create_metric(
+ "saleor.graphql.batch_size",
+ scope=Scope.CORE,
+ type=MetricType.HISTOGRAM,
+ unit=Unit.COUNT,
+ description="Number of GraphQL operations sent within a batched request.",
+)
+
+METRIC_GRAPHQL_ALIAS_COUNT = meter.create_metric(
+ "saleor.graphql.alias_count",
+ scope=Scope.CORE,
+ type=MetricType.HISTOGRAM,
+ unit=Unit.COUNT,
+ description="Number of aliases contained within a GraphQL request.",
+)
+
+METRIC_GRAPHQL_MUTATION_COUNT = meter.create_metric(
+ "saleor.graphql.mutation_count",
+ scope=Scope.CORE,
+ type=MetricType.HISTOGRAM,
+ unit=Unit.COUNT,
+ description="Number of mutations sent within a GraphQL request.",
+)
+
# Helper functions
def record_graphql_query_count(
@@ -173,3 +197,15 @@ def record_field_usage(parent_type: str, field_name: str, deprecated: bool) -> N
if deprecated:
attributes[saleor_attributes.GRAPHQL_FIELD_DEPRECATED] = True
meter.record(METRIC_GRAPHQL_FIELD_USAGE, 1, Unit.CALL, attributes=attributes)
+
+
+def record_graphql_batch_size(batch_size: int) -> None:
+ meter.record(METRIC_GRAPHQL_BATCH_SIZE, amount=batch_size, unit=Unit.COUNT)
+
+
+def record_graphql_alias_count(count: int) -> None:
+ meter.record(METRIC_GRAPHQL_ALIAS_COUNT, amount=count, unit=Unit.COUNT)
+
+
+def record_graphql_mutation_count(count: int) -> None:
+ meter.record(METRIC_GRAPHQL_MUTATION_COUNT, amount=count, unit=Unit.COUNT)
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 5637187953..3fd25309db 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -38,6 +38,7 @@ from .context import clear_context, get_context_value
from .core.validators import validate_query
from .error import clear_errors
from .metrics import (
+ record_graphql_batch_size,
record_graphql_query_cost,
record_graphql_query_count,
record_graphql_query_duration,
@@ -181,7 +182,8 @@ class GraphQLView(View):
result: GraphQLOperationResult | None | list[GraphQLOperationResult | None]
if isinstance(data, list):
- if len(data) > settings.GRAPHQL_BATCH_MAX_COUNT:
+ batch_size = len(data)
+ if batch_size > settings.GRAPHQL_BATCH_MAX_COUNT:
return JsonResponse(
data={
"errors": [
@@ -192,6 +194,9 @@ class GraphQLView(View):
},
status=400,
)
+ # We only want to record successful requests
+ if batch_size > 1:
+ record_graphql_batch_size(batch_size)
responses = [self.get_response(request, entry) for entry in data]
result = [response for response, code in responses]