Skip to content

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

Introduce a metric for tracking GraphQL field usage (#18941)

Przemysław Łada696e4ff9b383
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02dd654e7c..856c617868 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Fix Google OAuth OIDC login failing with `invalid_scope` error when `enable_refresh_token` is enabled. Google does not support the `offline_access` scope; use `access_type=offline` authorization parameter instead. - #18919 by @dnplkndll
+- Add `saleor.graphql.field.usage` OTel metric to track GraphQL field resolver call counts. The metric is emitted for deprecated fields (detected automatically) and for fields explicitly opted in with `monitor_usage=True` on a `BaseField` declaration.
- Fix send order confirmation email to staff - #18342 by @Shaokun-X
- Validation on `AppExtension` is now removed. Saleor will accept string values for `mount` and `target` from Manifest during App installation and JSON value for `options` field.
Validation is now performed on the frontend (Dashboard). This change increases velocity of features related to apps and extensions, now Dashboard is only entity that ensures the contract
diff --git a/saleor/core/telemetry/saleor_attributes.py b/saleor/core/telemetry/saleor_attributes.py
index d1bdc20509..ae9f1c1d56 100644
--- a/saleor/core/telemetry/saleor_attributes.py
+++ b/saleor/core/telemetry/saleor_attributes.py
@@ -13,6 +13,7 @@ GRAPHQL_OPERATION_COST: Final = "graphql.operation.cost"
GRAPHQL_OPERATION_IDENTIFIER: Final = "graphql.operation.identifier"
GRAPHQL_PARENT_TYPE: Final = "graphql.parent_type"
GRAPHQL_RESOLVER_ROW_COUNT: Final = "graphql.resolver.row_count"
+GRAPHQL_FIELD_DEPRECATED: Final = "graphql.field.deprecated"
# Http
SALEOR_SOURCE_SERVICE_NAME: Final = "saleor.source.service.name"
diff --git a/saleor/core/telemetry/utils.py b/saleor/core/telemetry/utils.py
index 194be49241..4c5b88615f 100644
--- a/saleor/core/telemetry/utils.py
+++ b/saleor/core/telemetry/utils.py
@@ -36,6 +36,7 @@ class Unit(Enum):
BYTE = "By"
COST = "{cost}"
EVENT = "{event}"
+ CALL = "{call}"
UNIT_CONVERSIONS: dict[tuple[Unit, Unit], float] = {
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 50791968a7..8e7696d365 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -1,4 +1,4 @@
-from functools import partial
+from functools import partial, wraps
import graphql
from django.urls import reverse
@@ -6,6 +6,8 @@ from django.utils.functional import SimpleLazyObject
from graphql import (
GraphQLCachedBackend,
GraphQLCoreBackend,
+ GraphQLInterfaceType,
+ GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
execute,
@@ -32,6 +34,7 @@ from .giftcard.schema import GiftCardMutations, GiftCardQueries
from .invoice.schema import InvoiceMutations
from .menu.schema import MenuMutations, MenuQueries
from .meta.schema import MetaMutations
+from .metrics import record_field_usage
from .order.schema import OrderMutations, OrderQueries
from .page.schema import PageMutations, PageQueries
from .payment.schema import PAYMENT_ADDITIONAL_TYPES, PaymentMutations, PaymentQueries
@@ -53,6 +56,39 @@ from .webhook.subscription_types import WEBHOOK_TYPES_MAP, Subscription
API_PATH = SimpleLazyObject(lambda: reverse("api"))
+def monitor_fields_usage(schema: graphql.GraphQLSchema) -> None:
+ """Wrap resolvers of tracked fields to record usage metrics on each call.
+
+ A field is tracked when at least one of the following is true:
+ - `deprecation_reason` is set.
+ - `monitor_usage=True` is passed to a `BaseField` declaration.
+ """
+ for gql_type in schema.get_type_map().values():
+ if not isinstance(
+ gql_type, GraphQLObjectType | GraphQLInterfaceType
+ ) or gql_type.name.startswith("__"):
+ continue
+ for gql_field_name, gql_field in gql_type.fields.items():
+ if gql_field.resolver is None:
+ continue
+ is_deprecated = bool(gql_field.deprecation_reason)
+ should_monitor = getattr(gql_field.resolver, "monitor_usage", False)
+ if not is_deprecated and not should_monitor:
+ continue
+
+ def wrapper(original, type_name, field_name, deprecated):
+ @wraps(original)
+ def _wrapper(*args, **kwargs):
+ record_field_usage(type_name, field_name, deprecated)
+ return original(*args, **kwargs)
+
+ return _wrapper
+
+ gql_field.resolver = wrapper(
+ gql_field.resolver, gql_type.name, gql_field_name, is_deprecated
+ )
+
+
class Query(
AccountQueries,
AppQueries,
@@ -188,6 +224,7 @@ schema = build_federated_schema(
directives=graphql.specified_directives
+ [GraphQLDocDirective, GraphQLWebhookEventsInfoDirective],
)
+monitor_fields_usage(schema)
def _fail(errors, **_kwargs) -> ExecutionResult:
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.py
index 9a9cb3965b..9081f3bb4a 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -15,6 +15,7 @@ class BaseField(graphene.Field):
description: str | None
doc_category: str | None
webhook_events_info: list[WebhookEventInfo] | None
+ monitor_usage: bool
def __init__(self, *args, **kwargs):
auto_webhook_events_info_message = kwargs.pop(
@@ -22,6 +23,7 @@ class BaseField(graphene.Field):
)
self.doc_category = kwargs.pop("doc_category", None)
self.webhook_events_info = kwargs.pop("webhook_events_info", None)
+ self.monitor_usage = kwargs.pop("monitor_usage", False)
super().__init__(*args, **kwargs)
@@ -34,6 +36,7 @@ class BaseField(graphene.Field):
resolver = self.resolver or parent_resolver
setattr(resolver, "doc_category", self.doc_category)
setattr(resolver, "webhook_events_info", self.webhook_events_info)
+ setattr(resolver, "monitor_usage", self.monitor_usage)
return resolver
diff --git a/saleor/graphql/core/tests/test_deprecated_field_monitoring.py b/saleor/graphql/core/tests/test_deprecated_field_monitoring.py
new file mode 100644
index 0000000000..923f80dbf0
--- /dev/null
+++ b/saleor/graphql/core/tests/test_deprecated_field_monitoring.py
@@ -0,0 +1,304 @@
+from unittest.mock import patch
+
+import graphene
+import pytest
+
+from ....shipping.utils import convert_to_shipping_method_data
+from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...tests.utils import get_graphql_content
+from ...webhook.subscription_payload import (
+ generate_payload_from_subscription,
+ generate_payload_promise_from_subscription,
+)
+from ...webhook.tests.test_subscription_payload import initialize_request
+
+# These tests use `Order.token` as a representative deprecated field to verify field usage monitoring.
+# If `Order.token` is ever removed from the schema, replace it with another deprecated field.
+
+QUERY_WITH_DEPRECATED_FIELD = """
+ query GetOrder($id: ID!) {
+ order(id: $id) {
+ token
+ }
+ }
+"""
+
+QUERY_WITH_DEPRECATED_FIELD_ALIASED = """
+ query GetOrder($id: ID!) {
+ order(id: $id) {
+ orderToken: token
+ }
+ }
+"""
+
+QUERY_WITH_DEPRECATED_FIELD_IN_FRAGMENT = """
+ fragment OrderFields on Order {
+ token
+ }
+
+ query GetOrder($id: ID!) {
+ order(id: $id) {
+ ...OrderFields
+ }
+ }
+"""
+
+QUERY_WITHOUT_DEPRECATED_FIELD = """
+ query GetOrder($id: ID!) {
+ order(id: $id) {
+ number
+ }
+ }
+"""
+
+SUBSCRIPTION_QUERY_WITH_DEPRECATED_FIELD = """
+ subscription {
+ event {
+ ... on OrderUpdated {
+ order {
+ token
+ }
+ }
+ }
+ }
+"""
+
+# `ShippingListMethodsForCheckout.shippingMethods` is declared with
+# `monitor_usage=True` (not deprecated) and is used here to test the explicit
+# opt-in monitoring path. If the field is ever removed or its `monitor_usage`
+# flag is dropped, replace with another field that carries `monitor_usage=True`.
+SUBSCRIPTION_QUERY_WITH_MONITORED_FIELD = """
+ subscription {
+ event {
+ ... on ShippingListMethodsForCheckout {
+ shippingMethods {
+ id
+ name
+ }
+ }
+ }
+ }
+"""
+
+SUBSCRIPTION_QUERY_WITHOUT_DEPRECATED_FIELD = """
+ subscription {
+ event {
+ ... on OrderUpdated {
+ order {
+ number
+ }
+ }
+ }
+ }
+"""
+
+
+# `DraftOrderCreate.orderErrors` is a deprecated field and is used here to
+# test that deprecated field usage is monitored in mutations.
+# If the field is ever removed from the schema, replace it with another deprecated
+# mutation output field.
+MUTATION_WITH_DEPRECATED_FIELD = """
+ mutation CreateDraftOrder($input: DraftOrderCreateInput!) {
+ draftOrderCreate(input: $input) {
+ orderErrors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+MUTATION_WITHOUT_DEPRECATED_FIELD = """
+ mutation CreateDraftOrder($input: DraftOrderCreateInput!) {
+ draftOrderCreate(input: $input) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+ "query",
+ [
+ QUERY_WITH_DEPRECATED_FIELD,
+ QUERY_WITH_DEPRECATED_FIELD_ALIASED,
+ QUERY_WITH_DEPRECATED_FIELD_IN_FRAGMENT,
+ ],
+ ids=["direct", "alias", "fragment"],
+)
+@patch("saleor.graphql.api.record_field_usage")
+def test_deprecated_field_query_triggers_monitoring(
+ mock_record, query, staff_api_client, permission_group_manage_orders, order
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ get_graphql_content(response)
+
+ # then
+ mock_record.assert_called_once_with("Order", "token", True)
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_non_deprecated_field_query_does_not_trigger_monitoring(
+ mock_record, staff_api_client, permission_group_manage_orders, order
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order_id = graphene.Node.to_global_id("Order", order.pk)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_WITHOUT_DEPRECATED_FIELD, variables)
+ get_graphql_content(response)
+
+ # then
+ mock_record.assert_not_called()
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_deprecated_field_mutation_triggers_monitoring(
+ mock_record, staff_api_client, permission_group_manage_orders, channel_USD
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"input": {"channelId": channel_id}}
+
+ # when
+ response = staff_api_client.post_graphql(MUTATION_WITH_DEPRECATED_FIELD, variables)
+ get_graphql_content(response)
+
+ # then
+ mock_record.assert_called_once_with("DraftOrderCreate", "orderErrors", True)
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_non_deprecated_field_mutation_does_not_trigger_monitoring(
+ mock_record, staff_api_client, permission_group_manage_orders, channel_USD
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"input": {"channelId": channel_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_WITHOUT_DEPRECATED_FIELD, variables
+ )
+ get_graphql_content(response)
+
+ # then
+ mock_record.assert_not_called()
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_deprecated_field_subscription_payload_triggers_monitoring(
+ mock_record, order, subscription_webhook, app
+):
+ # given
+ webhook = subscription_webhook(
+ SUBSCRIPTION_QUERY_WITH_DEPRECATED_FIELD,
+ WebhookEventAsyncType.ORDER_UPDATED,
+ )
+ request = initialize_request(app=webhook.app)
+
+ # when
+ generate_payload_from_subscription(
+ event_type=WebhookEventAsyncType.ORDER_UPDATED,
+ subscribable_object=order,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ )
+
+ # then
+ mock_record.assert_called_once_with("Order", "token", True)
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_deprecated_field_subscription_promise_payload_triggers_monitoring(
+ mock_record, order, subscription_webhook
+):
+ # given
+ webhook = subscription_webhook(
+ SUBSCRIPTION_QUERY_WITH_DEPRECATED_FIELD,
+ WebhookEventAsyncType.ORDER_UPDATED,
+ )
+ request = initialize_request(app=webhook.app)
+
+ # when
+ promise = generate_payload_promise_from_subscription(
+ event_type=WebhookEventAsyncType.ORDER_UPDATED,
+ subscribable_object=order,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ )
+ promise.get()
+
+ # then
+ mock_record.assert_called_once_with("Order", "token", True)
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_non_deprecated_field_subscription_payload_does_not_trigger_monitoring(
+ mock_record, order, subscription_webhook, app
+):
+ # given
+ webhook = subscription_webhook(
+ SUBSCRIPTION_QUERY_WITHOUT_DEPRECATED_FIELD,
+ WebhookEventAsyncType.ORDER_UPDATED,
+ )
+ request = initialize_request(app=webhook.app)
+
+ # when
+ generate_payload_from_subscription(
+ event_type=WebhookEventAsyncType.ORDER_UPDATED,
+ subscribable_object=order,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ )
+
+ # then
+ mock_record.assert_not_called()
+
+
+@patch("saleor.graphql.api.record_field_usage")
+def test_monitor_usage_field_subscription_payload_triggers_monitoring(
+ mock_record,
+ checkout_with_shipping_required,
+ shipping_method,
+ address,
+ subscription_webhook,
+):
+ # given
+ checkout = checkout_with_shipping_required
+ checkout.shipping_address = address
+ webhook = subscription_webhook(
+ SUBSCRIPTION_QUERY_WITH_MONITORED_FIELD,
+ WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ )
+ request = initialize_request(app=webhook.app)
+ shipping_method_data = convert_to_shipping_method_data(
+ shipping_method,
+ shipping_method.channel_listings.get(channel=checkout.channel),
+ )
+
+ # when
+ generate_payload_from_subscription(
+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,
+ subscribable_object=(checkout, [shipping_method_data]),
+ subscription_query=webhook.subscription_query,
+ request=request,
+ )
+
+ # then
+ mock_record.assert_called_once_with(
+ "ShippingListMethodsForCheckout", "shippingMethods", False
+ )
diff --git a/saleor/graphql/metrics.py b/saleor/graphql/metrics.py
index ee0fc94c2d..549e13f805 100644
--- a/saleor/graphql/metrics.py
+++ b/saleor/graphql/metrics.py
@@ -43,6 +43,14 @@ METRIC_GRAPHQL_SLOW_OPERATION_DURATION = meter.create_metric(
bucket_boundaries=DEFAULT_DURATION_BUCKETS,
)
+METRIC_GRAPHQL_FIELD_USAGE = meter.create_metric(
+ "saleor.graphql.field.usage",
+ scope=Scope.CORE,
+ type=MetricType.COUNTER,
+ unit=Unit.CALL,
+ description="Number of times a GraphQL field was resolved.",
+)
+
QUERY_COST_BUCKETS = [
0,
5,
@@ -155,3 +163,13 @@ def record_request_count(
def record_request_duration() -> AbstractContextManager[dict[str, AttributeValue]]:
attributes: dict[str, AttributeValue] = {}
return meter.record_duration(METRIC_REQUEST_DURATION, attributes=attributes)
+
+
+def record_field_usage(parent_type: str, field_name: str, deprecated: bool) -> None:
+ attributes: dict[str, AttributeValue] = {
+ saleor_attributes.GRAPHQL_PARENT_TYPE: parent_type,
+ saleor_attributes.GRAPHQL_FIELD_NAME: field_name,
+ }
+ if deprecated:
+ attributes[saleor_attributes.GRAPHQL_FIELD_DEPRECATED] = True
+ meter.record(METRIC_GRAPHQL_FIELD_USAGE, 1, Unit.CALL, attributes=attributes)
diff --git a/saleor/graphql/tests/test_metrics.py b/saleor/graphql/tests/test_metrics.py
index 727f2e43e8..ce9b411690 100644
--- a/saleor/graphql/tests/test_metrics.py
+++ b/saleor/graphql/tests/test_metrics.py
@@ -10,6 +10,7 @@ from ...core.telemetry import DEFAULT_DURATION_BUCKETS, Scope, Unit, saleor_attr
from ...graphql.api import backend, schema
from ...tests.utils import get_metric_and_data_point, get_metric_data
from ..metrics import (
+ METRIC_GRAPHQL_FIELD_USAGE,
METRIC_GRAPHQL_QUERY_COST,
METRIC_GRAPHQL_QUERY_COUNT,
METRIC_GRAPHQL_QUERY_DURATION,
@@ -17,12 +18,49 @@ from ..metrics import (
METRIC_REQUEST_COUNT,
METRIC_REQUEST_DURATION,
QUERY_COST_BUCKETS,
+ record_field_usage,
record_graphql_query_count,
record_graphql_query_duration,
)
from ..views import GraphQLView
+def test_record_field_usage_with_deprecated_field(get_test_metrics_data):
+ # when
+ record_field_usage("Order", "token", deprecated=True)
+
+ # then
+ metric_data, data_point = get_metric_and_data_point(
+ get_test_metrics_data(), METRIC_GRAPHQL_FIELD_USAGE, scope=Scope.CORE
+ )
+ assert metric_data.unit == Unit.CALL.value
+ assert data_point.attributes == {
+ saleor_attributes.GRAPHQL_PARENT_TYPE: "Order",
+ saleor_attributes.GRAPHQL_FIELD_NAME: "token",
+ saleor_attributes.GRAPHQL_FIELD_DEPRECATED: True,
+ }
+ assert data_point.value == 1
+
+
+def test_record_field_usage_explicit(get_test_metrics_data):
+ # when
+ record_field_usage(
+ "ShippingListMethodsForCheckout", "shippingMethods", deprecated=False
+ )
+
+ # then
+ metric_data, data_point = get_metric_and_data_point(
+ get_test_metrics_data(), METRIC_GRAPHQL_FIELD_USAGE, scope=Scope.CORE
+ )
+ assert metric_data.unit == Unit.CALL.value
+ assert data_point.attributes == {
+ saleor_attributes.GRAPHQL_PARENT_TYPE: "ShippingListMethodsForCheckout",
+ saleor_attributes.GRAPHQL_FIELD_NAME: "shippingMethods",
+ }
+ assert saleor_attributes.GRAPHQL_FIELD_DEPRECATED not in data_point.attributes
+ assert data_point.value == 1
+
+
def test_record_graphql_query_count(get_test_metrics_data):
# when
record_graphql_query_count(operation_type="query")
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index d3f063bea4..b064c3fb5f 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -2468,9 +2468,10 @@ class PaymentListGateways(SubscriptionObjectType, CheckoutBase):
class ShippingListMethodsForCheckout(SubscriptionObjectType, CheckoutBase):
- shipping_methods = NonNullList(
- ShippingMethod,
+ shipping_methods = BaseField(
+ NonNullList(ShippingMethod),
description="Shipping methods that can be used with this checkout.",
+ monitor_usage=True,
)
@staticmethod