Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add HTTP metrics (#17663)
Marcin Gębala4046e3c1f00a
diff --git a/saleor/core/telemetry/utils.py b/saleor/core/telemetry/utils.pyindex 9e606270d4..cc7c53dcb7 100644--- a/saleor/core/telemetry/utils.py+++ b/saleor/core/telemetry/utils.py@@ -34,6 +34,7 @@ class Unit(Enum):NANOSECOND = "ns"REQUEST = "{request}"BYTE = "By"+ COST = "{cost}"UNIT_CONVERSIONS: dict[tuple[Unit, Unit], float] = {diff --git a/saleor/graphql/metrics.py b/saleor/graphql/metrics.pyindex 7015e9c20f..de917ce7e7 100644--- a/saleor/graphql/metrics.py+++ b/saleor/graphql/metrics.py@@ -27,10 +27,26 @@ METRIC_GRAPHQL_QUERY_COST = meter.create_metric("saleor.graphql.operation.cost",scope=Scope.SERVICE,type=MetricType.HISTOGRAM,- unit=Unit.REQUEST,+ unit=Unit.COST,description="Cost of GraphQL queries.",)+METRIC_REQUEST_COUNT = meter.create_metric(+ "saleor.request.count",+ scope=Scope.SERVICE,+ type=MetricType.COUNTER,+ unit=Unit.REQUEST,+ description="Number of API requests.",+)++METRIC_REQUEST_DURATION = meter.create_metric(+ "saleor.request.duration",+ scope=Scope.SERVICE,+ type=MetricType.HISTOGRAM,+ unit=Unit.SECOND,+ description="Duration of API requests.",+)+# Helper functionsdef record_graphql_query_count(@@ -77,4 +93,19 @@ def record_graphql_query_cost(}if error_type:attributes[error_attributes.ERROR_TYPE] = error_type- meter.record(METRIC_GRAPHQL_QUERY_COST, cost, Unit.REQUEST, attributes=attributes)+ meter.record(METRIC_GRAPHQL_QUERY_COST, cost, Unit.COST, attributes=attributes)+++def record_request_count(+ amount: int = 1,+ error_type: str | None = None,+) -> None:+ attributes = {}+ if error_type:+ attributes[error_attributes.ERROR_TYPE] = error_type+ meter.record(METRIC_REQUEST_COUNT, amount, Unit.REQUEST, attributes=attributes)+++def record_request_duration() -> AbstractContextManager[dict[str, AttributeValue]]:+ attributes: dict[str, AttributeValue] = {}+ return meter.record_duration(METRIC_REQUEST_DURATION, attributes=attributes)diff --git a/saleor/graphql/tests/test_metrics.py b/saleor/graphql/tests/test_metrics.pyindex f35bfd0696..79478138a3 100644--- a/saleor/graphql/tests/test_metrics.py+++ b/saleor/graphql/tests/test_metrics.py@@ -1,4 +1,4 @@-from unittest.mock import call, patch+from unittest.mock import MagicMock, call, patchimport grapheneimport pytest@@ -12,6 +12,8 @@ from ..metrics import (METRIC_GRAPHQL_QUERY_COST,METRIC_GRAPHQL_QUERY_COUNT,METRIC_GRAPHQL_QUERY_DURATION,+ METRIC_REQUEST_COUNT,+ METRIC_REQUEST_DURATION,record_graphql_query_count,record_graphql_query_duration,)@@ -26,7 +28,7 @@ def test_record_graphql_query_count(mock_meter):)# then- mock_meter.record.assert_called_once_with(+ mock_meter.record.assert_any_call(METRIC_GRAPHQL_QUERY_COUNT,1,Unit.REQUEST,@@ -53,7 +55,7 @@ def test_record_graphql_query_duration(mock_meter):graphql_attributes.GRAPHQL_OPERATION_TYPE: "",saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",}- mock_meter.record_duration.assert_called_once_with(+ mock_meter.record_duration.assert_any_call(METRIC_GRAPHQL_QUERY_DURATION, attributes=call_attributes)assert result == mock_context_manager@@ -93,7 +95,7 @@ def test_graphql_query_record_metrics(mock_meter, rf, channel_USD, product_list)mock_meter.record.assert_any_call(METRIC_GRAPHQL_QUERY_COST,5,- Unit.REQUEST,+ Unit.COST,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "products",graphql_attributes.GRAPHQL_OPERATION_NAME: "productsQuery",@@ -102,7 +104,7 @@ def test_graphql_query_record_metrics(mock_meter, rf, channel_USD, product_list))# check that saleor.graphql.operation.duration is recorded and has correct attributes- mock_meter.record_duration.assert_called_once_with(+ mock_meter.record_duration.assert_any_call(METRIC_GRAPHQL_QUERY_DURATION,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",@@ -182,7 +184,7 @@ def test_graphql_query_record_metrics_invalid_query(mock_meter.record.assert_any_call(METRIC_GRAPHQL_QUERY_COST,1,- Unit.REQUEST,+ Unit.COST,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: operation_identifier,graphql_attributes.GRAPHQL_OPERATION_NAME: operation_name,@@ -191,7 +193,7 @@ def test_graphql_query_record_metrics_invalid_query(},)- mock_meter.record_duration.assert_called_once_with(+ mock_meter.record_duration.assert_any_call(METRIC_GRAPHQL_QUERY_DURATION,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",@@ -261,7 +263,7 @@ def test_graphql_query_record_metrics_cost_exceeded(mock_meter.record.assert_any_call(METRIC_GRAPHQL_QUERY_COST,20,- Unit.REQUEST,+ Unit.COST,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "productVariant",graphql_attributes.GRAPHQL_OPERATION_NAME: "",@@ -271,7 +273,7 @@ def test_graphql_query_record_metrics_cost_exceeded()# check that saleor.graphql.operation.duration is recorded and has correct attributes- mock_meter.record_duration.assert_called_once_with(+ mock_meter.record_duration.assert_any_call(METRIC_GRAPHQL_QUERY_DURATION,attributes={saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER: "",@@ -291,3 +293,73 @@ def test_graphql_query_record_metrics_cost_exceeded(call(saleor_attributes.GRAPHQL_OPERATION_IDENTIFIER, "productVariant")in mock_meter.record_duration().__enter__().__setitem__.call_args_list)+++@patch("saleor.graphql.metrics.meter")+def test_graphql_view_record_http_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.request.count is recorded+ mock_meter.record.assert_any_call(+ METRIC_REQUEST_COUNT,+ 1,+ Unit.REQUEST,+ attributes={},+ )++ # check that saleor.request.duration is recorded+ mock_meter.record_duration.assert_any_call(+ METRIC_REQUEST_DURATION,+ attributes={},+ )+++@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):+ # given+ mock_handle_query.return_value = MagicMock(status_code=500)+ request = rf.post(+ path="/graphql/",+ data={+ "query": "query { shop { name } }",+ },+ content_type="application/json",+ )++ # when+ view = GraphQLView.as_view(backend=backend, schema=schema)+ view(request)++ # then+ # 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"},+ )++ # 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+ )diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex e392f7760f..c57e28e97b 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -40,6 +40,8 @@ from .metrics import (record_graphql_query_cost,record_graphql_query_count,record_graphql_query_duration,+ record_request_count,+ record_request_duration,)from .query_cost_map import COST_MAP, QUERY_COST_FAILED_OPERATIONfrom .utils import (@@ -158,9 +160,12 @@ class GraphQLView(View):return JsonResponse(data=result, status=status_code, safe=False)def handle_query(self, request: HttpRequest) -> JsonResponse:- with tracer.start_as_current_span(- request.path, scope=Scope.SERVICE, kind=SpanKind.SERVER- ) as span:+ with (+ tracer.start_as_current_span(+ request.path, scope=Scope.SERVICE, kind=SpanKind.SERVER+ ) as span,+ record_request_duration() as request_duration_attrs,+ ):span.set_attribute(saleor_attributes.COMPONENT, "http")span.set_attribute(saleor_attributes.OPERATION_NAME, "http")span.set_attribute(http_attributes.HTTP_REQUEST_METHOD, request.method) # type: ignore[arg-type]@@ -208,6 +213,14 @@ class GraphQLView(View):incubating_http_attributes.HTTP_RESPONSE_BODY_SIZE,len(response.content),)++ error_type = (+ str(response.status_code) if response.status_code >= 500 else None+ )+ record_request_count(error_type=error_type)+ if error_type:+ request_duration_attrs[error_attributes.ERROR_TYPE] = error_type+with observability.report_api_call(request) as api_call:api_call.response = responseapi_call.report()