Skip to content

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

Optimize GraphQL metrics (#18314)

Przemysław Łada5c728c13cab6
diff --git a/saleor/core/telemetry/tests/test_metric.py b/saleor/core/telemetry/tests/test_metric.py
index 03d5b90215..9fd1da90df 100644
--- a/saleor/core/telemetry/tests/test_metric.py
+++ b/saleor/core/telemetry/tests/test_metric.py
@@ -431,7 +431,7 @@ def test_meter_create_histogram_with_explicit_bucket_boundaries(get_test_metrics
meter.record(name, 20, unit=Unit.SECOND, attributes=attributes)
# then
- metric_data = get_metric_data(get_test_metrics_data(), name)
+ metric_data = get_metric_data(get_test_metrics_data(), name, scope=Scope.CORE)
assert metric_data.name == name
assert metric_data.unit == unit.value
assert metric_data.description == description
diff --git a/saleor/graphql/metrics.py b/saleor/graphql/metrics.py
index c09fbadd7d..ee0fc94c2d 100644
--- a/saleor/graphql/metrics.py
+++ b/saleor/graphql/metrics.py
@@ -1,5 +1,8 @@
-from contextlib import AbstractContextManager
+import time
+from collections.abc import Iterator
+from contextlib import AbstractContextManager, contextmanager
+from django.conf import settings
from opentelemetry.semconv._incubating.attributes import graphql_attributes
from opentelemetry.semconv.attributes import error_attributes
from opentelemetry.util.types import AttributeValue
@@ -31,6 +34,15 @@ METRIC_GRAPHQL_QUERY_DURATION = meter.create_metric(
bucket_boundaries=DEFAULT_DURATION_BUCKETS,
)
+METRIC_GRAPHQL_SLOW_OPERATION_DURATION = meter.create_metric(
+ "saleor.graphql.slow_operation.duration",
+ scope=Scope.CORE,
+ type=MetricType.HISTOGRAM,
+ unit=Unit.SECOND,
+ description="Duration of slow GraphQL operations.",
+ bucket_boundaries=DEFAULT_DURATION_BUCKETS,
+)
+
QUERY_COST_BUCKETS = [
0,
5,
@@ -79,15 +91,11 @@ METRIC_REQUEST_DURATION = meter.create_metric(
# 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_TYPE: operation_type or "",
- }
+ attributes = {graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type or ""}
if error_type:
attributes[error_attributes.ERROR_TYPE] = error_type
meter.record(
@@ -95,27 +103,40 @@ def record_graphql_query_count(
)
-def record_graphql_query_duration() -> AbstractContextManager[
- dict[str, AttributeValue]
-]:
+@contextmanager
+def record_graphql_query_duration() -> Iterator[dict[str, AttributeValue]]:
+ start = time.monotonic()
attributes: dict[str, AttributeValue] = {
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "",
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",
+ graphql_attributes.GRAPHQL_OPERATION_TYPE: ""
}
- return meter.record_duration(METRIC_GRAPHQL_QUERY_DURATION, attributes=attributes)
+ try:
+ yield attributes
+ finally:
+ duration = time.monotonic() - start
+ if duration >= settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD:
+ meter.record(
+ METRIC_GRAPHQL_SLOW_OPERATION_DURATION,
+ duration,
+ unit=Unit.SECOND,
+ attributes=attributes,
+ )
+ # Set graphql.document_fingerprint attribute only for slow operations metric
+ attributes.pop(saleor_attributes.GRAPHQL_DOCUMENT_FINGERPRINT, None)
+ meter.record(
+ METRIC_GRAPHQL_QUERY_DURATION,
+ duration,
+ unit=Unit.SECOND,
+ 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_TYPE: operation_type or "",
- }
+ attributes = {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.COST, attributes=attributes)
diff --git a/saleor/graphql/tests/test_metrics.py b/saleor/graphql/tests/test_metrics.py
index 668a02470b..727f2e43e8 100644
--- a/saleor/graphql/tests/test_metrics.py
+++ b/saleor/graphql/tests/test_metrics.py
@@ -1,67 +1,110 @@
-from unittest.mock import MagicMock, call, patch
+from unittest.mock import MagicMock, patch
import graphene
import pytest
from django.test import override_settings
+from freezegun import freeze_time
from opentelemetry.semconv._incubating.attributes import graphql_attributes
-from opentelemetry.semconv.attributes import error_attributes
-from ...core.telemetry import Unit, saleor_attributes
+from ...core.telemetry import DEFAULT_DURATION_BUCKETS, Scope, Unit, saleor_attributes
from ...graphql.api import backend, schema
+from ...tests.utils import get_metric_and_data_point, get_metric_data
from ..metrics import (
METRIC_GRAPHQL_QUERY_COST,
METRIC_GRAPHQL_QUERY_COUNT,
METRIC_GRAPHQL_QUERY_DURATION,
+ METRIC_GRAPHQL_SLOW_OPERATION_DURATION,
METRIC_REQUEST_COUNT,
METRIC_REQUEST_DURATION,
+ QUERY_COST_BUCKETS,
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):
+def test_record_graphql_query_count(get_test_metrics_data):
# when
- record_graphql_query_count(
- operation_name="name", operation_type="query", operation_identifier="identifier"
+ record_graphql_query_count(operation_type="query")
+ # then
+ metric_data, data_point = get_metric_and_data_point(
+ get_test_metrics_data(), METRIC_GRAPHQL_QUERY_COUNT
)
+ assert metric_data.unit == Unit.REQUEST.value
+ assert data_point.attributes == {"graphql.operation.type": "query"}
+ assert data_point.value == 1
+
+
+def test_record_graphql_query_duration(get_test_metrics_data, settings):
+ # given
+ settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = 1.0
+ operation_duration = 0.25
+ fingerprint = "query:productsQuery:4aace3b174967edf8ed6e6c894d26f9d"
+ # when
+ with freeze_time("2025-10-13 12:00:00") as frozen_datetime:
+ with record_graphql_query_duration() as query_duration_attrs:
+ query_duration_attrs[graphql_attributes.GRAPHQL_OPERATION_TYPE] = "query"
+ query_duration_attrs[saleor_attributes.GRAPHQL_DOCUMENT_FINGERPRINT] = (
+ fingerprint
+ )
+ frozen_datetime.tick(delta=operation_duration)
# then
- mock_meter.record.assert_any_call(
- METRIC_GRAPHQL_QUERY_COUNT,
- 1,
- Unit.REQUEST,
- attributes={
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "identifier",
- },
+ metrics_data = get_test_metrics_data()
+ metric_data, data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_DURATION
)
+ assert metric_data.unit == Unit.SECOND.value
+ assert data_point.attributes == {"graphql.operation.type": "query"}
+ assert data_point.explicit_bounds == tuple(DEFAULT_DURATION_BUCKETS)
+ assert data_point.count == 1
+ assert data_point.sum == operation_duration
+ assert get_metric_data(metrics_data, METRIC_GRAPHQL_SLOW_OPERATION_DURATION) is None
-@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
+def test_record_graphql_query_duration_with_slow_query(get_test_metrics_data, settings):
+ # given
+ settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = operation_duration = 1.0
+ fingerprint = "query:productsQuery:4aace3b174967edf8ed6e6c894d26f9d"
# when
- result = record_graphql_query_duration()
+ with freeze_time("2025-10-13 12:00:00") as frozen_datetime:
+ with record_graphql_query_duration() as query_duration_attrs:
+ query_duration_attrs[graphql_attributes.GRAPHQL_OPERATION_TYPE] = "query"
+ query_duration_attrs[saleor_attributes.GRAPHQL_DOCUMENT_FINGERPRINT] = (
+ fingerprint
+ )
+ frozen_datetime.tick(delta=operation_duration)
# then
- call_attributes = {
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "",
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",
- }
- mock_meter.record_duration.assert_any_call(
- METRIC_GRAPHQL_QUERY_DURATION, attributes=call_attributes
+ metrics_data = get_test_metrics_data()
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_DURATION
)
- assert result == mock_context_manager
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == {"graphql.operation.type": "query"}
+ assert duration_data_point.explicit_bounds == tuple(DEFAULT_DURATION_BUCKETS)
+ assert duration_data_point.count == 1
+ assert duration_data_point.sum == operation_duration
+
+ slow_operation_metric, slow_operation_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_SLOW_OPERATION_DURATION, scope=Scope.CORE
+ )
+ assert slow_operation_metric.unit == Unit.SECOND.value
+ assert slow_operation_data_point.attributes == {
+ "graphql.operation.type": "query",
+ "graphql.document_fingerprint": fingerprint,
+ }
+ assert slow_operation_data_point.explicit_bounds == tuple(DEFAULT_DURATION_BUCKETS)
+ assert slow_operation_data_point.count == 1
+ assert slow_operation_data_point.sum == operation_duration
-@patch("saleor.graphql.metrics.meter")
-def test_graphql_query_record_metrics(mock_meter, rf, channel_USD, product_list):
+def test_graphql_query_record_metrics(
+ get_test_metrics_data, rf, channel_USD, product_list, settings
+):
# given
+ settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = 0.0
request = rf.post(
path="/graphql/",
data={
@@ -78,145 +121,136 @@ def test_graphql_query_record_metrics(mock_meter, rf, channel_USD, product_list)
# 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_TYPE: "query",
- },
+ metrics_data = get_test_metrics_data()
+ count_metric, count_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COUNT
)
+ assert count_metric.unit == Unit.REQUEST.value
+ assert count_data_point.attributes == {"graphql.operation.type": "query"}
+ assert count_data_point.value == 1
# check that saleor.graphql.operation.cost is recorded
- mock_meter.record.assert_any_call(
- METRIC_GRAPHQL_QUERY_COST,
- 5,
- Unit.COST,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "products",
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",
- },
+ cost_metric, cost_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COST
)
+ assert cost_metric.unit == Unit.COST.value
+ assert cost_data_point.attributes == {"graphql.operation.type": "query"}
+ assert cost_data_point.explicit_bounds == tuple(QUERY_COST_BUCKETS)
+ assert cost_data_point.count == 1
+ assert cost_data_point.sum == 5
# check that saleor.graphql.operation.duration is recorded and has correct attributes
- mock_meter.record_duration.assert_any_call(
- METRIC_GRAPHQL_QUERY_DURATION,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "",
- },
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_DURATION
)
- 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.type", "query") in set_attr_calls
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == {"graphql.operation.type": "query"}
+ assert duration_data_point.count == 1
+
+ # check that saleor.graphql.slow_operation.duration is recorded and has correct attributes
+ slow_operation_metric, slow_operation_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_SLOW_OPERATION_DURATION, scope=Scope.CORE
+ )
+ assert slow_operation_metric.unit == Unit.SECOND.value
+ assert slow_operation_data_point.attributes == {
+ "graphql.operation.type": "query",
+ "graphql.document_fingerprint": "query:productsQuery:4aace3b174967edf8ed6e6c894d26f9d",
+ }
+ assert slow_operation_data_point.count == 1
@pytest.mark.parametrize(
- ("data", "error_type", "operation_name", "operation_type", "operation_identifier"),
+ ("data", "error_type", "operation_type", "slow_operation_attributes"),
[
- ("", "GraphQLError", "", "", ""),
- (
- {"query": "{"},
- "GraphQLSyntaxError",
- "",
- "",
- "",
- ),
+ ("", "GraphQLError", "", {}),
+ ({"query": "{"}, "GraphQLSyntaxError", "", {}),
(
{
"query": "query { ... { __schema { __typename } } ... { shop { name } } }"
},
"GraphQLError",
"",
- "",
- "",
+ {},
),
(
{"query": "{ products(first: 9999999999) { edges { node { id } } } }"},
"GraphQLError",
- "",
"query",
- "products",
+ {"graphql.document_fingerprint": "query:22f6cfd4453eeba3e758ccda9f6b0e93"},
),
],
)
-@patch("saleor.graphql.metrics.meter")
def test_graphql_query_record_metrics_invalid_query(
- mock_meter,
+ get_test_metrics_data,
data,
error_type,
- operation_name,
operation_type,
- operation_identifier,
+ slow_operation_attributes,
rf,
+ settings,
):
# given
+ settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = 0.0
request = rf.post(
path="/graphql/",
data=data,
content_type="application/json",
)
+ attributes = {
+ "graphql.operation.type": operation_type,
+ "error.type": error_type,
+ }
# 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_TYPE: operation_type,
- error_attributes.ERROR_TYPE: error_type,
- },
+ metrics_data = get_test_metrics_data()
+ count_metric, count_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COUNT
)
+ assert count_metric.unit == Unit.REQUEST.value
+ assert count_data_point.attributes == attributes
+ assert count_data_point.value == 1
- mock_meter.record.assert_any_call(
- METRIC_GRAPHQL_QUERY_COST,
- 1,
- Unit.COST,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier,
- graphql_attributes.GRAPHQL_OPERATION_TYPE: operation_type,
- error_attributes.ERROR_TYPE: error_type,
- },
+ cost_metric, cost_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COST
)
-
- mock_meter.record_duration.assert_any_call(
- METRIC_GRAPHQL_QUERY_DURATION,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "",
- },
+ assert cost_metric.unit == Unit.COST.value
+ assert cost_data_point.attributes == attributes
+ assert cost_data_point.explicit_bounds == tuple(QUERY_COST_BUCKETS)
+ assert cost_data_point.count == 1
+ assert cost_data_point.sum == 1
+
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_DURATION
)
- assert (
- call(error_attributes.ERROR_TYPE, error_type)
- in mock_meter.record_duration().__enter__().__setitem__.call_args_list
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == attributes
+ assert duration_data_point.count == 1
+
+ slow_operation_metric, slow_operation_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_SLOW_OPERATION_DURATION, scope=Scope.CORE
)
- 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
- )
+ assert slow_operation_metric.unit == Unit.SECOND.value
+ assert slow_operation_data_point.attributes == {
+ **attributes,
+ **slow_operation_attributes,
+ }
+ assert slow_operation_data_point.count == 1
@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=1)
-@patch("saleor.graphql.metrics.meter")
def test_graphql_query_record_metrics_cost_exceeded(
- mock_meter,
+ get_test_metrics_data,
api_client,
variant_with_many_stocks,
channel_USD,
+ settings,
):
# given
+ settings.TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = 0.0
query_fields = "\n".join(
[
f"p{i}: productVariant(id: $id, channel: $channel) {{ id }}"
@@ -234,57 +268,55 @@ def test_graphql_query_record_metrics_cost_exceeded(
"channel": channel_USD.slug,
}
+ attributes = {
+ "graphql.operation.type": "query",
+ "error.type": "QueryCostError",
+ }
+
# when
api_client.post_graphql(query, variables)
# then
+ metrics_data = get_test_metrics_data()
# 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_TYPE: "query",
- error_attributes.ERROR_TYPE: "QueryCostError",
- },
+ count_metric, count_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COUNT
)
+ assert count_metric.unit == Unit.REQUEST.value
+ assert count_data_point.attributes == attributes
+ assert count_data_point.value == 1
- mock_meter.record.assert_any_call(
- METRIC_GRAPHQL_QUERY_COST,
- 20,
- Unit.COST,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "productVariant",
- graphql_attributes.GRAPHQL_OPERATION_TYPE: "query",
- error_attributes.ERROR_TYPE: "QueryCostError",
- },
+ cost_metric, cost_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_COST
)
+ assert cost_metric.unit == Unit.COST.value
+ assert cost_data_point.attributes == attributes
+ assert cost_data_point.explicit_bounds == tuple(QUERY_COST_BUCKETS)
+ assert cost_data_point.count == 1
+ assert cost_data_point.sum == 20
# check that saleor.graphql.operation.duration is recorded and has correct attributes
- mock_meter.record_duration.assert_any_call(
- METRIC_GRAPHQL_QUERY_DURATION,
- attributes={
- saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",
- 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
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_QUERY_DURATION
)
- assert (
- call(saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, "productVariant")
- in mock_meter.record_duration().__enter__().__setitem__.call_args_list
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == attributes
+ assert duration_data_point.count == 1
+
+ slow_operation_metric, slow_operation_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_GRAPHQL_SLOW_OPERATION_DURATION, scope=Scope.CORE
)
+ assert slow_operation_metric.unit == Unit.SECOND.value
+ assert slow_operation_data_point.attributes == {
+ **attributes,
+ "graphql.document_fingerprint": "query:variantAvailability:ddeb5d8f061864b4b3ab75418e225cc1",
+ }
+ assert slow_operation_data_point.count == 1
-@patch("saleor.graphql.metrics.meter")
-def test_graphql_view_record_http_metrics(mock_meter, rf, channel_USD, product_list):
+def test_graphql_view_record_http_metrics(
+ get_test_metrics_data, rf, channel_USD, product_list
+):
# given
request = rf.post(
path="/graphql/",
@@ -301,24 +333,29 @@ def test_graphql_view_record_http_metrics(mock_meter, rf, channel_USD, product_l
view(request)
# then
+ metrics_data = get_test_metrics_data()
# check that saleor.request.count is recorded
- mock_meter.record.assert_any_call(
- METRIC_REQUEST_COUNT,
- 1,
- Unit.REQUEST,
- attributes={},
+ count_metric, count_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_REQUEST_COUNT
)
+ assert count_metric.unit == Unit.REQUEST.value
+ assert count_data_point.attributes == {}
+ assert count_data_point.value == 1
# check that saleor.request.duration is recorded
- mock_meter.record_duration.assert_any_call(
- METRIC_REQUEST_DURATION,
- attributes={},
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_REQUEST_DURATION
)
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == {}
+ assert duration_data_point.explicit_bounds == tuple(DEFAULT_DURATION_BUCKETS)
+ assert duration_data_point.count == 1
-@patch("saleor.graphql.metrics.meter")
@patch("saleor.graphql.views.GraphQLView._handle_query")
-def test_graphql_view_record_http_metrics_error_type(mock_handle_query, mock_meter, rf):
+def test_graphql_view_record_http_metrics_error_type(
+ mock_handle_query, get_test_metrics_data, rf
+):
# given
mock_handle_query.return_value = MagicMock(status_code=500)
request = rf.post(
@@ -334,20 +371,19 @@ def test_graphql_view_record_http_metrics_error_type(mock_handle_query, mock_met
view(request)
# then
+ metrics_data = get_test_metrics_data()
# check that saleor.request.count is recorded
- mock_meter.record.assert_any_call(
- METRIC_REQUEST_COUNT,
- 1,
- Unit.REQUEST,
- attributes={error_attributes.ERROR_TYPE: "500"},
+ count_metric, count_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_REQUEST_COUNT
)
+ assert count_metric.unit == Unit.REQUEST.value
+ assert count_data_point.attributes == {"error.type": "500"}
+ assert count_data_point.value == 1
# check that saleor.request.duration is recorded
- mock_meter.record_duration.assert_any_call(
- METRIC_REQUEST_DURATION,
- attributes={},
- )
- assert (
- call(error_attributes.ERROR_TYPE, "500")
- in mock_meter.record_duration().__enter__().__setitem__.call_args_list
+ duration_metric, duration_data_point = get_metric_and_data_point(
+ metrics_data, METRIC_REQUEST_DURATION
)
+ assert duration_metric.unit == Unit.SECOND.value
+ assert duration_data_point.attributes == {"error.type": "500"}
+ assert duration_data_point.count == 1
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index a64198a8b2..affb242951 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -334,13 +334,13 @@ class GraphQLView(View):
span.set_attribute(
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,
operation_fingerprint,
)
+ query_duration_attrs[saleor_attributes.GRAPHQL_DOCUMENT_FINGERPRINT] = (
+ operation_fingerprint
+ )
source_service_name = get_source_service_name_value(
request.headers.get("source-service-name")
@@ -365,17 +365,11 @@ class GraphQLView(View):
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,
+ query_cost, operation_type=operation_type, error_type=error_type
)
if error_type:
query_duration_attrs[error_attributes.ERROR_TYPE] = error_type
@@ -423,15 +417,11 @@ class GraphQLView(View):
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,
)
@@ -448,15 +438,11 @@ class GraphQLView(View):
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,
)
diff --git a/saleor/settings.py b/saleor/settings.py
index e6c44ecb6b..6fa52ebd5d 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1090,6 +1090,11 @@ TELEMETRY_METER_CLASS = "saleor.core.telemetry.metric.Meter"
# Whether to raise or log exceptions for telemetry unit conversion errors
# Disabled by default to prevent disruptions caused by unexpected unit conversion issues
TELEMETRY_RAISE_UNIT_CONVERSION_ERRORS = False
+# The default threshold for slow operations is set to 1 second, based on production monitoring data.
+# Only a small percentage of queries are expected to exceed this threshold.
+TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD = float(
+ os.environ.get("TELEMETRY_SLOW_GRAPHQL_OPERATION_THRESHOLD", 1.0)
+)
# Additional hash suffix, allowing to invalidate cached schema. In production usually we want this to be empty.
# For development envs, where schema may change often, it may be convenient to set it to e.g. commit hash value.
diff --git a/saleor/tests/utils.py b/saleor/tests/utils.py
index d62fd03c84..643d600af4 100644
--- a/saleor/tests/utils.py
+++ b/saleor/tests/utils.py
@@ -9,6 +9,7 @@ from opentelemetry.sdk.metrics.export import DataPointT, Metric, MetricsData
from opentelemetry.sdk.trace import ReadableSpan
from ..core.db.connection import allow_writer
+from ..core.telemetry import Scope
class FakeDbReplicaConnection:
@@ -71,22 +72,42 @@ def round_up(price: Decimal) -> Decimal:
return Decimal(math.ceil(price * 100)) / 100
-def get_metric_data(metrics_data: MetricsData, metric_name: str) -> Metric:
- for resource in metrics_data.resource_metrics:
- for scope_metrics in resource.scope_metrics:
+def get_metric_data(
+ metrics_data: MetricsData, metric_name: str, *, scope=Scope.SERVICE
+) -> Metric | None:
+ __tracebackhide__ = True # make failures point to the test, not here
+ if len(metrics_data.resource_metrics) != 1:
+ pytest.fail("Metrics recorded as multiple resources")
+ for scope_metrics in metrics_data.resource_metrics[0].scope_metrics:
+ if scope_metrics.scope.name == scope.value:
for metric in scope_metrics.metrics:
if metric.name == metric_name:
return metric
- raise KeyError(f"Metric {metric_name} not found in metrics data")
-
-
-def get_metric_data_point(metrics_data: MetricsData, metric_name: str) -> DataPointT:
- metric_data = get_metric_data(metrics_data, metric_name)
- datapoints_count = len(metric_data.data.data_points)
- assert datapoints_count == 1, (
- f"For metric {metric_name} found {datapoints_count} instead of 1"
- )
- return metric_data.data.data_points[0]
+ return None
+
+
+def get_metric_and_data_point(
+ metrics_data: MetricsData, metric_name: str, *, scope=Scope.SERVICE
+) -> tuple[Metric, DataPointT]:
+ __tracebackhide__ = True # make failures point to the test, not here
+ metric_data = get_metric_data(metrics_data, metric_name, scope=scope)
+ if metric_data is None:
+ pytest.fail(f"Metric {metric_name} not found in metrics data")
+ if len(metric_data.data.data_points) == 0:
+ pytest.fail(f"No data points found for metric: {metric_name}")
+ elif len(metric_data.data.data_points) > 1:
+ pytest.fail(
+ f"Multiple data points ({len(metric_data.data.data_points)}) found for metric: {metric_name}"
+ )
+ return metric_data, metric_data.data.data_points[0]
+
+
+def get_metric_data_point(
+ metrics_data: MetricsData, metric_name: str, *, scope=Scope.SERVICE
+) -> DataPointT:
+ __tracebackhide__ = True # make failures point to the test, not here
+ _, data_point = get_metric_and_data_point(metrics_data, metric_name, scope=scope)
+ return data_point
def filter_spans_by_name(