Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Webhooks tracing 3.1 (#8424)
Tomasz Szymański9eaaa483c204
diff --git a/saleor/core/tracing.py b/saleor/core/tracing.pyindex b3de530c5a..bb8a749adf 100644--- a/saleor/core/tracing.py+++ b/saleor/core/tracing.py@@ -35,3 +35,18 @@ def opentracing_trace(span_name, component_name, service_name):span.set_tag(opentracing.tags.COMPONENT, component_name)span.set_tag("service.name", service_name)yield+++@contextmanager+def webhooks_opentracing_trace(span_name, domain, sync=False, app_name=None):+ with opentracing.global_tracer().start_active_span(+ f"webhooks.{span_name}"+ ) as scope:+ span = scope.span+ if app_name:+ span.set_tag("webhooks.app", app_name)+ span.set_tag(opentracing.tags.COMPONENT, "webhooks")+ span.set_tag("service.name", "webhooks")+ span.set_tag("webhooks.domain", domain)+ span.set_tag("webhooks.execution_mode", "sync" if sync else "async")+ yielddiff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex d3da981214..5b6b3f7338 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -170,8 +170,6 @@ class GraphQLView(View):span.set_tag(opentracing.tags.PEER_HOST_IPV6, ip)else:continue- span.set_tag("http.client_ip", ip)- span.set_tag("http.client_ip_originated_from", settings.REAL_IP_ENVIRON)breakresponse = self._handle_query(request)@@ -252,6 +250,10 @@ class GraphQLView(View):with opentracing.global_tracer().start_active_span("graphql_query") as scope:span = scope.spanspan.set_tag(opentracing.tags.COMPONENT, "graphql")+ span.set_tag(+ opentracing.tags.HTTP_URL,+ request.build_absolute_uri(request.get_full_path()),+ )query, variables, operation_name = self.get_graphql_params(request, data)diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 403624dd76..963dce3a07 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -13,6 +13,7 @@ from google.cloud import pubsub_v1from requests.exceptions import RequestExceptionfrom ...celeryconf import app+from ...core.tracing import webhooks_opentracing_tracefrom ...payment import PaymentErrorfrom ...settings import WEBHOOK_SYNC_TIMEOUT, WEBHOOK_TIMEOUTfrom ...site.models import Site@@ -65,7 +66,12 @@ def trigger_webhooks_for_event(event_type, data):webhooks = _get_webhooks_for_event(event_type)for webhook in webhooks:send_webhook_request.delay(- webhook.pk, webhook.target_url, webhook.secret_key, event_type, data+ webhook.app.name,+ webhook.pk,+ webhook.target_url,+ webhook.secret_key,+ event_type,+ data,)@@ -77,13 +83,25 @@ def trigger_webhook_sync(event_type: str, data: str, app: "App"):raise PaymentError(f"No payment webhook found for event: {event_type}.")return send_webhook_request_sync(- webhook.target_url, webhook.secret_key, event_type, data+ app.name, webhook.target_url, webhook.secret_key, event_type, data)def send_webhook_using_http(target_url, message, domain, signature, event_type, timeout=WEBHOOK_TIMEOUT):+ """Send a webhook requst using http / https protocol.++ :param target_url: Target URL request will be sent to.+ :param message: Payload that will be used.+ :param domain: Current site domain.+ :param signature: Webhook secret key checksum.+ :param event_type: Webhook event type.+ :param timeout: Request timeout.++ :raises HTTPError: Requests exception class containg error message.+ :return: HTTP response object.+ """headers = {"Content-Type": "application/json",# X- headers will be deprecated in Saleor 4.0, proper headers are without X-@@ -155,7 +173,9 @@ def send_webhook_using_google_cloud_pubsub(retry_kwargs={"max_retries": 5},compression="zlib",)-def send_webhook_request(self, webhook_id, target_url, secret, event_type, data):+def send_webhook_request(+ self, app_name, webhook_id, target_url, secret, event_type, data+):parts = urlparse(target_url)domain = Site.objects.get_current().domainmessage = data.encode("utf-8")@@ -174,7 +194,8 @@ def send_webhook_request(self, webhook_id, target_url, secret, event_type, data)if methods := scheme_matrix.get(parts.scheme.lower()):send_method, send_exception = methodstry:- send_method(target_url, message, domain, signature, event_type)+ with webhooks_opentracing_trace(event_type, domain, app_name=app_name):+ send_method(target_url, message, domain, signature, event_type)except send_exception as e:task_logger.info("[Webhook] Failed request to %r: %r.", target_url, e)try:@@ -195,7 +216,7 @@ def send_webhook_request(self, webhook_id, target_url, secret, event_type, data)raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))-def send_webhook_request_sync(target_url, secret, event_type, data: str):+def send_webhook_request_sync(app_name, target_url, secret, event_type, data: str):parts = urlparse(target_url)domain = Site.objects.get_current().domainmessage = data.encode("utf-8")@@ -207,19 +228,22 @@ def send_webhook_request_sync(target_url, secret, event_type, data: str):"[Webhook] Sending payload to %r for event %r.", target_url, event_type)try:- response = send_webhook_using_http(- target_url,- message,- domain,- signature,- event_type,- timeout=WEBHOOK_SYNC_TIMEOUT,- )- response_data = response.json()+ with webhooks_opentracing_trace(+ event_type, domain, sync=True, app_name=app_name+ ):+ response = send_webhook_using_http(+ target_url,+ message,+ domain,+ signature,+ event_type,+ timeout=WEBHOOK_SYNC_TIMEOUT,+ )+ response_data = response.json()except RequestException as e:- logger.debug("[Webhook] Failed request to %r: %r.", target_url, e)+ logger.warning("[Webhook] Failed request to %r: %r.", target_url, e)except JSONDecodeError as e:- logger.debug(+ logger.warning("[Webhook] Failed parsing JSON response from %r: %r.", target_url, e)else:diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex c565d60e49..b1cea23d59 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -62,6 +62,7 @@ def test_trigger_webhook_sync(mock_request, payment_app):trigger_webhook_sync(WebhookEventType.PAYMENT_CAPTURE, data, payment_app)webhook = payment_app.webhooks.first()mock_request.assert_called_once_with(+ payment_app.name,webhook.target_url,webhook.secret_key,WebhookEventType.PAYMENT_CAPTURE,@@ -85,6 +86,7 @@ def test_trigger_webhook_sync_use_first_webhook(mock_request, payment_app):data = {"key": "value"}trigger_webhook_sync(WebhookEventType.PAYMENT_CAPTURE, data, payment_app)mock_request.assert_called_once_with(+ payment_app.name,webhook_1.target_url,webhook_1.secret_key,WebhookEventType.PAYMENT_CAPTURE,@@ -108,7 +110,11 @@ def test_send_webhook_request_sync(mock_send_http, target_url, site_settings, webhook_data):send_webhook_request_sync(- target_url, webhook_data.secret, webhook_data.event_type, webhook_data.data+ "app_name",+ target_url,+ webhook_data.secret,+ webhook_data.event_type,+ webhook_data.data,)mock_send_http.assert_called_once_with(target_url,@@ -129,6 +135,7 @@ def test_send_webhook_request_with_proper_timeout(mock_post, target_url, site_settings, webhook_data):send_webhook_request(+ "app_name","ID",target_url,webhook_data.secret,@@ -142,7 +149,7 @@ def test_send_webhook_request_with_proper_timeout(def test_send_webhook_request_sync_invalid_scheme():with pytest.raises(ValueError):target_url = "gcpubsub://cloud.google.com/projects/saleor/topics/test"- send_webhook_request_sync(target_url, "", "", "")+ send_webhook_request_sync("", target_url, "", "", "")@mock.patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex 9aa4cba560..5dc09fb48c 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -32,6 +32,7 @@ def test_trigger_webhook_sync(mock_request, shipping_app):)webhook = shipping_app.webhooks.first()mock_request.assert_called_once_with(+ shipping_app.name,webhook.target_url,webhook.secret_key,WebhookEventType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex ae49673b72..6ac70df68b 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -91,7 +91,7 @@ def test_trigger_webhooks_for_event_calls_expected_events(trigger_webhooks_for_event(event_name, data="")assert mock_request.call_count == total_webhook_calls- target_url_calls = {call[0][1] for call in mock_request.call_args_list}+ target_url_calls = {call[0][2] for call in mock_request.call_args_list}assert target_url_calls == expected_target_urls