Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add GraphQL metrics (#17639)
Marcin Gębala5646e7c4fbaa
diff --git a/saleor/core/telemetry/__init__.py b/saleor/core/telemetry/__init__.pyindex 6376eb6ad1..c43b7c9cf2 100644--- a/saleor/core/telemetry/__init__.py+++ b/saleor/core/telemetry/__init__.py@@ -2,8 +2,7 @@ from importlib import import_modulefrom typing import Anyfrom django.conf import settings-from opentelemetry.semconv.trace import SpanAttributes-from opentelemetry.util.types import Attributes, AttributeValue+from opentelemetry.util.types import Attributesfrom .metric import Meter, MeterProxy, MetricTypefrom .trace import Link, SpanKind, Tracer, TracerProxy@@ -59,8 +58,6 @@ __all__ = ["Unit","MetricType","SpanKind",- "SpanAttributes",- "AttributeValue","Scope","Link","TelemetryTaskContext",diff --git a/saleor/core/telemetry/metric.py b/saleor/core/telemetry/metric.pyindex 9dc9449429..81c96bde58 100644--- a/saleor/core/telemetry/metric.py+++ b/saleor/core/telemetry/metric.py@@ -135,9 +135,12 @@ class Meter:return get_instrument_method(instrument)(amount, attributes)@contextmanager- def record_duration(self, metric_name: str) -> Iterator[dict[str, AttributeValue]]:+ def record_duration(+ self, metric_name: str, attributes: dict[str, AttributeValue] | None = None+ ) -> Iterator[dict[str, AttributeValue]]:start = time.monotonic_ns()- attributes: dict[str, AttributeValue] = {}+ if attributes is None:+ attributes = {}try:yield attributesfinally:diff --git a/saleor/graphql/metrics.py b/saleor/graphql/metrics.pynew file mode 100644index 0000000000..7015e9c20f--- /dev/null+++ b/saleor/graphql/metrics.py@@ -0,0 +1,80 @@+from contextlib import AbstractContextManager++from opentelemetry.semconv._incubating.attributes import graphql_attributes+from opentelemetry.semconv.attributes import error_attributes+from opentelemetry.util.types import AttributeValue++from ..core.telemetry import MetricType, Scope, Unit, meter, saleor_attributes++# Initialize metrics+METRIC_GRAPHQL_QUERY_COUNT = meter.create_metric(+ "saleor.graphql.operation.count",+ scope=Scope.SERVICE,+ type=MetricType.COUNTER,+ unit=Unit.REQUEST,+ description="Number of GraphQL queries.",+)++METRIC_GRAPHQL_QUERY_DURATION = meter.create_metric(+ "saleor.graphql.operation.duration",+ scope=Scope.SERVICE,+ type=MetricType.HISTOGRAM,+ unit=Unit.SECOND,+ description="Duration of GraphQL queries.",+)++METRIC_GRAPHQL_QUERY_COST = meter.create_metric(+ "saleor.graphql.operation.cost",+ scope=Scope.SERVICE,+ type=MetricType.HISTOGRAM,+ unit=Unit.REQUEST,+ description="Cost of GraphQL queries.",+)+++# Helper functions+def record_graphql_query_count(+ amount: int = 1,+ operation_name: str | None = "",+ operation_type: str | None = "",+ operation_identifier: str | None = "",+ error_type: str | None = None,+) -> None:+ attributes = {+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier or "",+ graphql_attributes.GRAPHQL_OPERATION_NAME: operation_name or "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type or "",+ }+ if error_type:+ attributes[error_attributes.ERROR_TYPE] = error_type+ meter.record(+ METRIC_GRAPHQL_QUERY_COUNT, amount, Unit.REQUEST, attributes=attributes+ )+++def record_graphql_query_duration() -> AbstractContextManager[+ dict[str, AttributeValue]+]:+ attributes: dict[str, AttributeValue] = {+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "",+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",+ }+ return meter.record_duration(METRIC_GRAPHQL_QUERY_DURATION, attributes=attributes)+++def record_graphql_query_cost(+ cost: int,+ operation_name: str | None = "",+ operation_type: str | None = "",+ operation_identifier: str | None = "",+ error_type: str | None = None,+) -> None:+ attributes = {+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier or "",+ graphql_attributes.GRAPHQL_OPERATION_NAME: operation_name or "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type or "",+ }+ if error_type:+ attributes[error_attributes.ERROR_TYPE] = error_type+ meter.record(METRIC_GRAPHQL_QUERY_COST, cost, Unit.REQUEST, attributes=attributes)diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.pyindex 318aed2c6d..bc28ba52fb 100644--- a/saleor/graphql/query_cost_map.py+++ b/saleor/graphql/query_cost_map.py@@ -51,6 +51,9 @@ This query will have cost of 200 (100 x 2 for each product):{ products(first: 100) { complexity } }"""+# GraphQL operations that fail before cost can be calculated have a fixed cost of 1.+QUERY_COST_FAILED_OPERATION = 1+COST_MAP = {"Query": {"address": {"complexity": 1},diff --git a/saleor/graphql/tests/test_metrics.py b/saleor/graphql/tests/test_metrics.pynew file mode 100644index 0000000000..f35bfd0696--- /dev/null+++ b/saleor/graphql/tests/test_metrics.py@@ -0,0 +1,293 @@+from unittest.mock import call, patch++import graphene+import pytest+from django.test import override_settings+from opentelemetry.semconv._incubating.attributes import graphql_attributes+from opentelemetry.semconv.attributes import error_attributes++from ...core.telemetry import Unit, saleor_attributes+from ...graphql.api import backend, schema+from ..metrics import (+ METRIC_GRAPHQL_QUERY_COST,+ METRIC_GRAPHQL_QUERY_COUNT,+ METRIC_GRAPHQL_QUERY_DURATION,+ record_graphql_query_count,+ record_graphql_query_duration,+)+from ..views import GraphQLView+++@patch("saleor.graphql.metrics.meter")+def test_record_graphql_query_count(mock_meter):+ # when+ record_graphql_query_count(+ operation_name="name", operation_type="query", operation_identifier="identifier"+ )++ # then+ mock_meter.record.assert_called_once_with(+ METRIC_GRAPHQL_QUERY_COUNT,+ 1,+ Unit.REQUEST,+ attributes={+ graphql_attributes.GRAPHQL_OPERATION_NAME: "name",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "identifier",+ },+ )+++@patch("saleor.graphql.metrics.meter")+def test_record_graphql_query_duration(mock_meter):+ # given+ mock_context_manager = object()+ mock_meter.record_duration.return_value = mock_context_manager++ # when+ result = record_graphql_query_duration()++ # then+ call_attributes = {+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "",+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",+ }+ mock_meter.record_duration.assert_called_once_with(+ METRIC_GRAPHQL_QUERY_DURATION, attributes=call_attributes+ )+ assert result == mock_context_manager+++@patch("saleor.graphql.metrics.meter")+def test_graphql_query_record_metrics(mock_meter, rf, channel_USD, product_list):+ # given+ request = rf.post(+ path="/graphql/",+ data={+ "query": "query productsQuery($channel: String!) { products(first: 5, channel: $channel) { edges { node { name } } } }",+ "operationName": "productsQuery",+ "variables": {"channel": channel_USD.slug},+ },+ content_type="application/json",+ )++ # when+ view = GraphQLView.as_view(backend=backend, schema=schema)+ view(request)++ # then+ # check that saleor.graphql.operation.count is recorded+ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COUNT,+ 1,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "products",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "productsQuery",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",+ },+ )++ # check that saleor.graphql.operation.cost is recorded+ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COST,+ 5,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "products",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "productsQuery",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",+ },+ )++ # check that saleor.graphql.operation.duration is recorded and has correct attributes+ mock_meter.record_duration.assert_called_once_with(+ METRIC_GRAPHQL_QUERY_DURATION,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "",+ },+ )+ set_attr_calls = mock_meter.record_duration().__enter__().__setitem__.call_args_list+ assert call("graphql.operation.identifier", "products") in set_attr_calls+ assert call("graphql.operation.name", "productsQuery") in set_attr_calls+ assert call("graphql.operation.type", "query") in set_attr_calls+++ ("data", "error_type", "operation_name", "operation_type", "operation_identifier"),+ [+ ("", "GraphQLError", "", "", ""),+ (+ {"query": "{"},+ "GraphQLSyntaxError",+ "",+ "",+ "",+ ),+ (+ {+ "query": "query { ... { __schema { __typename } } ... { shop { name } } }"+ },+ "GraphQLError",+ "",+ "",+ "",+ ),+ (+ {"query": "{ products(first: 9999999999) { edges { node { id } } } }"},+ "GraphQLError",+ "",+ "query",+ "products",+ ),+ ],+)+@patch("saleor.graphql.metrics.meter")+def test_graphql_query_record_metrics_invalid_query(+ mock_meter,+ data,+ error_type,+ operation_name,+ operation_type,+ operation_identifier,+ rf,+):+ # given+ request = rf.post(+ path="/graphql/",+ data=data,+ content_type="application/json",+ )++ # when+ view = GraphQLView.as_view(backend=backend, schema=schema)+ view(request)++ # then+ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COUNT,+ 1,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier,+ graphql_attributes.GRAPHQL_OPERATION_NAME: operation_name,+ graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type,+ error_attributes.ERROR_TYPE: error_type,+ },+ )++ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COST,+ 1,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier,+ graphql_attributes.GRAPHQL_OPERATION_NAME: operation_name,+ graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type,+ error_attributes.ERROR_TYPE: error_type,+ },+ )++ mock_meter.record_duration.assert_called_once_with(+ METRIC_GRAPHQL_QUERY_DURATION,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "",+ },+ )+ assert (+ call(error_attributes.ERROR_TYPE, error_type)+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )+ if operation_type:+ assert (+ call(graphql_attributes.GRAPHQL_OPERATION_TYPE, operation_type)+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )+ if operation_identifier:+ assert (+ call(saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, operation_identifier)+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )+++@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=1)+@patch("saleor.graphql.metrics.meter")+def test_graphql_query_record_metrics_cost_exceeded(+ mock_meter,+ api_client,+ variant_with_many_stocks,+ channel_USD,+):+ # given+ query_fields = "\n".join(+ [+ f"p{i}: productVariant(id: $id, channel: $channel) {{ id }}"+ for i in range(20)+ ]+ )+ query = f"""+ query variantAvailability($id: ID!, $channel: String) {{+ {query_fields}+ }}+ """++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),+ "channel": channel_USD.slug,+ }++ # when+ api_client.post_graphql(query, variables)++ # then+ # check that saleor.graphql.operation.count is recorded+ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COUNT,+ 1,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "productVariant",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",+ error_attributes.ERROR_TYPE: "QueryCostError",+ },+ )++ mock_meter.record.assert_any_call(+ METRIC_GRAPHQL_QUERY_COST,+ 20,+ Unit.REQUEST,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "productVariant",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",+ error_attributes.ERROR_TYPE: "QueryCostError",+ },+ )++ # check that saleor.graphql.operation.duration is recorded and has correct attributes+ mock_meter.record_duration.assert_called_once_with(+ METRIC_GRAPHQL_QUERY_DURATION,+ attributes={+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",+ graphql_attributes.GRAPHQL_OPERATION_NAME: "",+ graphql_attributes.GRAPHQL_OPERATION_TYPE: "",+ },+ )+ assert (+ call(error_attributes.ERROR_TYPE, "QueryCostError")+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )+ assert (+ call(graphql_attributes.GRAPHQL_OPERATION_TYPE, "query")+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )+ assert (+ call(saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, "productVariant")+ in mock_meter.record_duration().__enter__().__setitem__.call_args_list+ )diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 9ebb41a5f3..007b621a0d 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -208,7 +208,7 @@ def requestor_is_superuser(requestor):def query_identifier(document: GraphQLDocument) -> str:- """Generate a fingerprint for a GraphQL query.+ """Generate a identifier for a GraphQL query.For queries identifier is sorted set of all root objects separated by `,`.e.gdiff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 10a4bbc1c3..e392f7760f 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -20,6 +20,7 @@ from opentelemetry.semconv._incubating.attributes import ()from opentelemetry.semconv.attributes import (client_attributes,+ error_attributes,http_attributes,url_attributes,user_agent_attributes,@@ -35,7 +36,12 @@ from ..webhook import observabilityfrom .api import API_PATH, schemafrom .context import clear_context, get_context_valuefrom .core.validators.query_cost import validate_query_cost-from .query_cost_map import COST_MAP+from .metrics import (+ record_graphql_query_cost,+ record_graphql_query_count,+ record_graphql_query_duration,+)+from .query_cost_map import COST_MAP, QUERY_COST_FAILED_OPERATIONfrom .utils import (format_error,get_source_service_name_value,@@ -262,9 +268,12 @@ class GraphQLView(View):return None, ExecutionResult(errors=[e], invalid=True)def execute_graphql_request(self, request: HttpRequest, data: dict):- with tracer.start_as_current_span(- "GraphQL Operation", scope=Scope.SERVICE- ) as span:+ with (+ tracer.start_as_current_span(+ "GraphQL Operation", scope=Scope.SERVICE+ ) as span,+ record_graphql_query_duration() as query_duration_attrs,+ ):span.set_attribute(saleor_attributes.OPERATION_NAME, "graphql_query")span.set_attribute(saleor_attributes.COMPONENT, "graphql")@@ -278,35 +287,66 @@ class GraphQLView(View):if error or document is None:error_description = self.format_span_error_description(error)+ error_type = (+ error.errors[0].__class__.__name__+ if error and error.errors+ else None+ )span.set_status(status=StatusCode.ERROR, description=error_description)+ if error_type:+ record_graphql_query_count(error_type=error_type)+ record_graphql_query_cost(+ QUERY_COST_FAILED_OPERATION, error_type=error_type+ )+ query_duration_attrs[error_attributes.ERROR_TYPE] = error_typereturn errortry:query_contains_schema = check_if_query_contains_only_schema(document)except GraphQLError as e:span.set_status(status=StatusCode.ERROR, description=str(e))+ error_type = e.__class__.__name__+ record_graphql_query_count(error_type=error_type)+ record_graphql_query_cost(+ QUERY_COST_FAILED_OPERATION, error_type=error_type+ )+ query_duration_attrs[error_attributes.ERROR_TYPE] = error_typereturn ExecutionResult(errors=[e], invalid=True)- _query_identifier = query_identifier(document)- self._query = _query_identifier+ # Query identifier and fingerprint cannot be calculated earlier, as they+ # require a parsed and valid GraphQL document.+ operation_identifier = query_identifier(document)+ operation_fingerprint = query_fingerprint(document)+ operation_type = document.get_operation_type(operation_name)++ self._query = operation_identifierraw_query_string = document.document_stringspan.update_name(raw_query_string)span.set_attribute(graphql_attributes.GRAPHQL_DOCUMENT, raw_query_string)- if operation_type := document.get_operation_type(operation_name):+ if operation_type:span.set_attribute(graphql_attributes.GRAPHQL_OPERATION_TYPE, operation_type)+ query_duration_attrs[graphql_attributes.GRAPHQL_OPERATION_TYPE] = (+ operation_type+ )if operation_name:span.set_attribute(graphql_attributes.GRAPHQL_OPERATION_NAME, operation_name)+ query_duration_attrs[graphql_attributes.GRAPHQL_OPERATION_NAME] = (+ operation_name+ )span.set_attribute(- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, _query_identifier+ saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, operation_identifier+ )+ query_duration_attrs[saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER] = (+ operation_identifier)span.set_attribute(saleor_attributes.GRAPHQL_DOCUMENT_FINGERPRINT,- query_fingerprint(document),+ operation_fingerprint,)source_service_name = get_source_service_name_value(@@ -330,6 +370,22 @@ class GraphQLView(View):result = ExecutionResult(errors=cost_errors, invalid=True)error_description = self.format_span_error_description(result)span.set_status(status=StatusCode.ERROR, description=error_description)+ error_type = cost_errors[0].__class__.__name__ if cost_errors else None+ record_graphql_query_count(+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ record_graphql_query_cost(+ query_cost,+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ if error_type:+ query_duration_attrs[error_attributes.ERROR_TYPE] = error_typereturn set_query_cost_on_result(result, query_cost)extra_options: dict[str, Any | None] = {}@@ -346,6 +402,7 @@ class GraphQLView(View):try:response = None+ error_type = Noneshould_use_cache_for_scheme = query_contains_schema & (not settings.DEBUG)@@ -363,6 +420,7 @@ class GraphQLView(View):**extra_options,)if response.errors:+ error_type = response.errors[0].__class__.__name__error_description = self.format_span_error_description(response)span.set_status(status=StatusCode.ERROR, description=error_description@@ -371,6 +429,21 @@ class GraphQLView(View):if should_use_cache_for_scheme:cache.set(key, response)+ record_graphql_query_count(+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ record_graphql_query_cost(+ query_cost,+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ if error_type:+ query_duration_attrs[error_attributes.ERROR_TYPE] = error_typereturn set_query_cost_on_result(response, query_cost)except Exception as e:span.set_status(status=StatusCode.ERROR, description=str(e))@@ -380,6 +453,21 @@ class GraphQLView(View):# As it's a validation error we want to raise GraphQLError instead.if str(e).startswith(INT_ERROR_MSG) or isinstance(e, ValueError):e = GraphQLError(str(e))+ error_type = e.__class__.__name__+ record_graphql_query_count(+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ record_graphql_query_cost(+ query_cost,+ operation_name=operation_name,+ operation_identifier=operation_identifier,+ operation_type=operation_type,+ error_type=error_type,+ )+ query_duration_attrs[error_attributes.ERROR_TYPE] = error_typereturn ExecutionResult(errors=[e], invalid=True)finally:clear_context(context)