Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Telemetry - add webhook metrics (#17636)
Przemysław Łada2eeeb45c2431
diff --git a/saleor/core/telemetry/utils.py b/saleor/core/telemetry/utils.pyindex 6197142917..9e606270d4 100644--- a/saleor/core/telemetry/utils.py+++ b/saleor/core/telemetry/utils.py@@ -33,6 +33,7 @@ class Unit(Enum):MILLISECOND = "ms"NANOSECOND = "ns"REQUEST = "{request}"+ BYTE = "By"UNIT_CONVERSIONS: dict[tuple[Unit, Unit], float] = {diff --git a/saleor/core/tracing.py b/saleor/core/tracing.pyindex 3d1e910343..14c532a8fb 100644--- a/saleor/core/tracing.py+++ b/saleor/core/tracing.py@@ -3,6 +3,7 @@ from contextlib import contextmanagerfrom django.db import transaction+from ..app.models import Appfrom ..core.telemetry import Link, Scope, SpanKind, saleor_attributes, tracer@@ -23,11 +24,10 @@ def otel_trace(span_name, component_name):@contextmanagerdef webhooks_otel_trace(- span_name,- domain,+ event_type: str,payload_size: int,sync=False,- app=None,+ app: App | None = None,span_links: Sequence[Link] | None = None,):"""Context manager for tracing webhooks.@@ -35,7 +35,7 @@ def webhooks_otel_trace(:param payload_size: size of the payload in bytes"""with tracer.start_as_current_span(- f"webhooks.{span_name}",+ f"webhooks.{event_type}",scope=Scope.SERVICE,kind=SpanKind.CLIENT,links=span_links,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex fc310dc31e..86de4e4261 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -12,6 +12,12 @@ from django.db import connectionfrom django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContextfrom freezegun import freeze_timefrom opentelemetry import trace as trace_api+from opentelemetry.metrics import set_meter_provider+from opentelemetry.sdk.metrics import Counter, Histogram, MeterProvider, UpDownCounter+from opentelemetry.sdk.metrics.export import (+ AggregationTemporality,+ InMemoryMetricReader,+)from opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter@@ -118,6 +124,28 @@ def get_test_spans(in_memory_span_exporter):in_memory_span_exporter.clear()[email protected](scope="session")+def in_memory_metric_reader():+ temporality = {+ Counter: AggregationTemporality.DELTA,+ Histogram: AggregationTemporality.DELTA,+ UpDownCounter: AggregationTemporality.DELTA,+ }+ metric_reader = InMemoryMetricReader(preferred_temporality=temporality)+ set_meter_provider(MeterProvider((metric_reader,)))+ initialize_telemetry()+ return metric_reader+++def get_test_metrics_data(in_memory_metric_reader):+ # Clear any existing metrics data from the buffer before test execution+ in_memory_metric_reader.get_metrics_data()+ yield in_memory_metric_reader.get_metrics_data+ # Clean up by clearing the buffer after test completion+ in_memory_metric_reader.get_metrics_data()++@pytest.fixturedef capture_queries(pytestconfig):cfg = pytestconfigdiff --git a/saleor/tests/utils.py b/saleor/tests/utils.pyindex b876346aec..ccc181126a 100644--- a/saleor/tests/utils.py+++ b/saleor/tests/utils.py@@ -4,6 +4,7 @@ from decimal import Decimalfrom django.conf import settingsfrom django.db import connections+from opentelemetry.sdk.metrics.export import MetricsDatafrom ..core.db.connection import allow_writer@@ -66,3 +67,16 @@ def round_down(price: Decimal) -> Decimal:def round_up(price: Decimal) -> Decimal:return Decimal(math.ceil(price * 100)) / 100+++def get_metric_data_points(metrics_data: MetricsData, metric_name: str):+ for resource in metrics_data.resource_metrics:+ for scope_metrics in resource.scope_metrics:+ for metric in scope_metrics.metrics:+ if metric.name == metric_name:+ datapoints_count = len(metric.data.data_points)+ assert datapoints_count == 1, (+ f"For metric {metric_name} found {datapoints_count} instead of 1"+ )+ return metric.data.data_points[0]+ raise KeyError(f"Metric {metric_name} not found in metrics data")diff --git a/saleor/webhook/transport/asynchronous/tests/test_transport.py b/saleor/webhook/transport/asynchronous/tests/test_transport.pyindex 77b08ce582..11b3769c53 100644--- a/saleor/webhook/transport/asynchronous/tests/test_transport.py+++ b/saleor/webhook/transport/asynchronous/tests/test_transport.py@@ -1,8 +1,16 @@from unittest.mock import MagicMock, patch+import pytest+from celery.exceptions import Retry as CeleryTaskRetryErrorfrom opentelemetry.trace import StatusCodefrom .....core.models import EventDeliveryStatus+from .....tests.utils import get_metric_data_points+from ...metrics import (+ METRIC_EXTERNAL_REQUEST_BODY_SIZE,+ METRIC_EXTERNAL_REQUEST_COUNT,+ METRIC_EXTERNAL_REQUEST_DURATION,+)from ...utils import WebhookResponsefrom ..transport import send_webhook_request_async@@ -40,3 +48,146 @@ def test_send_webhook_request_async_set_span_status_failed(mock_span.set_status.assert_called_once_with(StatusCode.ERROR,)+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"+)+def test_send_webhook_request_async_record_external_request(+ mock_send_webhook_using_scheme_method,+ event_delivery,+ webhook_response,+ get_test_metrics_data,+):+ # given+ mock_send_webhook_using_scheme_method.return_value = webhook_response+ payload_size = len(event_delivery.payload.get_payload().encode("utf-8"))+ global_attributes = {"global.attr": "value"}++ # when+ send_webhook_request_async(+ event_delivery_id=event_delivery.id,+ telemetry_context={"global_attributes": global_attributes},+ )++ # then+ attributes = {+ "server.address": "www.example.com",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == webhook_response.duration++ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_size+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"+)+def test_send_webhook_request_async_record_external_request_when_delivery_attempt_failed(+ mock_send_webhook_using_scheme_method,+ event_delivery,+ webhook_response_failed,+ get_test_metrics_data,+):+ # given+ mock_send_webhook_using_scheme_method.return_value = webhook_response_failed+ payload_size = len(event_delivery.payload.get_payload().encode("utf-8"))+ global_attributes = {"global.attr": "value"}++ # when+ with pytest.raises(CeleryTaskRetryError):+ send_webhook_request_async(+ event_delivery_id=event_delivery.id,+ telemetry_context={"global_attributes": global_attributes},+ )++ # then+ attributes = {+ "server.address": "www.example.com",+ "error.type": "request_error",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == webhook_response_failed.duration+ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_size+++@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"+)+def test_send_webhook_request_async_record_external_request_with_unknown_webhook_scheme(+ mock_send_webhook_using_scheme_method,+ event_delivery,+ get_test_metrics_data,+):+ # given+ mock_send_webhook_using_scheme_method.side_effect = ValueError(+ "Unknown webhook scheme: unknown"+ )+ payload_size = len(event_delivery.payload.get_payload().encode("utf-8"))+ global_attributes = {"global.attr": "value"}++ # when+ send_webhook_request_async(+ event_delivery_id=event_delivery.id,+ telemetry_context={"global_attributes": global_attributes},+ )++ # then+ attributes = {+ "server.address": "www.example.com",+ "error.type": "request_error",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == 0+ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_sizediff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 79652f2246..296e0e6917 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -37,6 +37,9 @@ from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAPfrom ... import observabilityfrom ...event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...observability import WebhookData+from ..metrics import (+ record_external_request,+)from ..utils import (DeferredPayloadData,RequestorModelName,@@ -593,6 +596,8 @@ def send_webhook_request_async(webhook = delivery.webhookdomain = get_domain()attempt = create_attempt(delivery, self.request.id)+ response = WebhookResponse(content="", status=EventDeliveryStatus.FAILED)+ payload_size = 0try:if not delivery.payload:@@ -606,7 +611,6 @@ def send_webhook_request_async(payload_size = len(data)with webhooks_otel_trace(delivery.event_type,- domain,payload_size,app=webhook.app,span_links=telemetry_context.links,@@ -638,9 +642,11 @@ def send_webhook_request_async(# update attempt without save to provide proper data in observabilityattempt_update(attempt, response, with_save=False)except ValueError as e:- response = WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)+ response.content = str(e)attempt_update(attempt, response)delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)+ finally:+ record_external_request(webhook.target_url, response, payload_size)observability.report_event_delivery_attempt(attempt)clear_successful_delivery(delivery)diff --git a/saleor/webhook/transport/metrics.py b/saleor/webhook/transport/metrics.pynew file mode 100644index 0000000000..744b61c856--- /dev/null+++ b/saleor/webhook/transport/metrics.py@@ -0,0 +1,51 @@+from urllib.parse import urlparse++from opentelemetry.semconv.attributes import error_attributes, server_attributes++from ...core.models import EventDeliveryStatus+from ...core.telemetry import MetricType, Scope, Unit, meter+from .utils import WebhookResponse++# Initialize metrics+METRIC_EXTERNAL_REQUEST_COUNT = meter.create_metric(+ "saleor.external_request.count",+ scope=Scope.SERVICE,+ type=MetricType.COUNTER,+ unit=Unit.REQUEST,+ description="Number of webhook events.",+)+METRIC_EXTERNAL_REQUEST_DURATION = meter.create_metric(+ "saleor.external_request.duration",+ scope=Scope.SERVICE,+ type=MetricType.HISTOGRAM,+ unit=Unit.SECOND,+ description="Duration of webhook event delivery.",+)+METRIC_EXTERNAL_REQUEST_BODY_SIZE = meter.create_metric(+ "saleor.external_request.body.size",+ scope=Scope.SERVICE,+ type=MetricType.HISTOGRAM,+ unit=Unit.BYTE,+ description="Size of webhook event payloads.",+)+++def record_external_request(+ target_url: str, webhook_response: WebhookResponse, payload_size: int+) -> None:+ attributes = {server_attributes.SERVER_ADDRESS: urlparse(target_url).hostname or ""}+ if webhook_response.status == EventDeliveryStatus.FAILED:+ attributes[error_attributes.ERROR_TYPE] = "request_error"+ meter.record(METRIC_EXTERNAL_REQUEST_COUNT, 1, Unit.REQUEST, attributes=attributes)+ meter.record(+ METRIC_EXTERNAL_REQUEST_BODY_SIZE,+ payload_size,+ Unit.BYTE,+ attributes=attributes,+ )+ meter.record(+ METRIC_EXTERNAL_REQUEST_DURATION,+ webhook_response.duration,+ Unit.SECOND,+ attributes=attributes,+ )diff --git a/saleor/webhook/transport/synchronous/tests/test_transport.py b/saleor/webhook/transport/synchronous/tests/test_transport.pyindex 2ccb9a1936..2d48275329 100644--- a/saleor/webhook/transport/synchronous/tests/test_transport.py+++ b/saleor/webhook/transport/synchronous/tests/test_transport.py@@ -1,8 +1,16 @@from unittest.mock import MagicMock, patch+import pytestfrom opentelemetry.trace import StatusCodefrom .....core.models import EventDeliveryStatus+from .....core.telemetry import set_global_attributes+from .....tests.utils import get_metric_data_points+from ...metrics import (+ METRIC_EXTERNAL_REQUEST_BODY_SIZE,+ METRIC_EXTERNAL_REQUEST_COUNT,+ METRIC_EXTERNAL_REQUEST_DURATION,+)from ...utils import WebhookResponsefrom ..transport import _send_webhook_request_sync@@ -24,6 +32,7 @@ def test_send_webhook_request_sync_set_span_status_failed_invalid_json(mock_response.response_status_code = 200mock_response.status = EventDeliveryStatus.SUCCESSmock_response.content = "" # Simulating invalid JSON+ mock_response.duration = 2.0mock_send_webhook_using_http.return_value = mock_response# when@@ -52,6 +61,7 @@ def test_send_webhook_request_sync_set_span_status_failed_error_response(mock_response.response_status_code = 500mock_response.status = EventDeliveryStatus.FAILEDmock_response.content = "{}"+ mock_response.duration = 2.0mock_send_webhook_using_http.return_value = mock_response# when@@ -61,3 +71,189 @@ def test_send_webhook_request_sync_set_span_status_failed_error_response(mock_span.set_status.assert_called_once_with(StatusCode.ERROR,)+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_using_http")+def test_send_webhook_request_sync_record_external_request(+ mock_send_webhook_using_http,+ webhook_response,+ event_delivery_payload_in_database,+ get_test_metrics_data,+):+ # given+ webhook_response.content = "{}"+ mock_send_webhook_using_http.return_value = webhook_response+ payload_size = len(+ event_delivery_payload_in_database.payload.get_payload().encode("utf-8")+ )+ global_attributes = {"global.attr": "value"}++ # when+ with set_global_attributes(global_attributes):+ _send_webhook_request_sync(event_delivery_payload_in_database)++ # then+ attributes = {+ "server.address": "www.example.com",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == webhook_response.duration++ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_size+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_using_http")+def test_send_webhook_request_sync_record_external_request_when_delivery_attempt_failed(+ mock_send_webhook_using_http,+ webhook_response_failed,+ event_delivery_payload_in_database,+ get_test_metrics_data,+):+ # given+ webhook_response_failed.content = "{}"+ mock_send_webhook_using_http.return_value = webhook_response_failed+ payload_size = len(+ event_delivery_payload_in_database.payload.get_payload().encode("utf-8")+ )+ global_attributes = {"global.attr": "value"}++ # when+ with set_global_attributes(global_attributes):+ _send_webhook_request_sync(event_delivery_payload_in_database)++ # then+ attributes = {+ "server.address": "www.example.com",+ "error.type": "request_error",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == webhook_response_failed.duration++ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_size+++@patch("saleor.webhook.transport.synchronous.transport.send_webhook_using_http")+def test_send_webhook_request_sync_record_external_request_with_invalid_json_response(+ mock_send_webhook_using_http,+ webhook_response,+ event_delivery_payload_in_database,+ get_test_metrics_data,+):+ # given+ webhook_response.content = "Invalid JSON"+ mock_send_webhook_using_http.return_value = webhook_response+ payload_size = len(+ event_delivery_payload_in_database.payload.get_payload().encode("utf-8")+ )+ global_attributes = {"global.attr": "value"}++ # when+ with set_global_attributes(global_attributes):+ _send_webhook_request_sync(event_delivery_payload_in_database)++ # then+ attributes = {+ "server.address": "www.example.com",+ "error.type": "request_error",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == webhook_response.duration++ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_size+++def test_send_webhook_request_sync_record_external_request_with_unknown_webhook_scheme(+ event_delivery_payload_in_database,+ get_test_metrics_data,+):+ # given+ event_delivery_payload_in_database.webhook.target_url = (+ "unknown://www.example.com/test"+ )+ payload_size = len(+ event_delivery_payload_in_database.payload.get_payload().encode("utf-8")+ )+ global_attributes = {"global.attr": "value"}++ # when+ with set_global_attributes(global_attributes):+ with pytest.raises(ValueError, match=r"Unknown webhook scheme: 'unknown'"):+ _send_webhook_request_sync(event_delivery_payload_in_database)++ # then+ attributes = {+ "server.address": "www.example.com",+ "error.type": "request_error",+ **global_attributes,+ }+ metrics_data = get_test_metrics_data()+ external_request_count = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_COUNT+ )+ assert external_request_count.value == 1+ assert external_request_count.attributes == attributes++ external_request_duration = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_DURATION+ )+ assert external_request_duration.attributes == attributes+ assert external_request_duration.count == 1+ assert external_request_duration.sum == 0++ external_request_content_length = get_metric_data_points(+ metrics_data, METRIC_EXTERNAL_REQUEST_BODY_SIZE+ )+ assert external_request_content_length.attributes == attributes+ assert external_request_content_length.count == 1+ assert external_request_content_length.sum == payload_sizediff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 995963cdde..0338ae77f8 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -43,6 +43,7 @@ from ...event_types import WebhookEventSyncTypefrom ...payloads import generate_transaction_action_request_payloadfrom ...utils import get_webhooks_for_eventfrom .. import signature_for_payload+from ..metrics import record_external_requestfrom ..utils import (WebhookResponse,WebhookSchemes,@@ -112,9 +113,12 @@ def _send_webhook_request_sync(message = data.encode("utf-8")payload_size = len(message)signature = signature_for_payload(message, webhook.secret_key)+ response = WebhookResponse(content="", status=EventDeliveryStatus.FAILED)+ response_data = Noneif parts.scheme.lower() not in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:delivery_update(delivery, EventDeliveryStatus.FAILED)+ record_external_request(webhook.target_url, response, payload_size)raise ValueError(f"Unknown webhook scheme: {parts.scheme!r}")logger.debug(@@ -124,11 +128,9 @@ def _send_webhook_request_sync()if attempt is None:attempt = create_attempt(delivery=delivery, task_id=None, with_save=False)- response = WebhookResponse(content="")- response_data = Nonewith webhooks_otel_trace(- delivery.event_type, domain, payload_size, sync=True, app=webhook.app+ delivery.event_type, payload_size, sync=True, app=webhook.app) as span:try:response = send_webhook_using_http(@@ -168,6 +170,7 @@ def _send_webhook_request_sync(finally:if response.status == EventDeliveryStatus.FAILED:span.set_status(StatusCode.ERROR)+ record_external_request(webhook.target_url, response, payload_size)attempt_update(attempt, response)delivery_update(delivery, response.status)