Skip to content

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

Handle returning response for failed deliveries in sync webhook (#9082)

Marcin Gębala60d8dd3f0ab7
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index b3163142c8..02bfb2fd03 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -3,7 +3,7 @@ import logging
from dataclasses import dataclass
from enum import Enum
from json import JSONDecodeError
-from typing import TYPE_CHECKING, Callable, Dict, Optional, Tuple, Type
+from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type
from urllib.parse import urlparse, urlunparse
import boto3
@@ -93,7 +93,9 @@ def trigger_webhooks_async(data, event_type, webhooks):
send_webhook_request_async.delay(delivery.id)
-def trigger_webhook_sync(event_type: str, data: str, app: "App", timeout=None):
+def trigger_webhook_sync(
+ event_type: str, data: str, app: "App", timeout=None
+) -> Optional[Dict[Any, Any]]:
"""Send a synchronous webhook request."""
webhooks = _get_webhooks_for_event(event_type, app.webhooks.all())
webhook = webhooks.first()
@@ -289,14 +291,15 @@ def send_webhook_request_async(self, event_delivery_id):
delivery.id,
)
delivery_status = EventDeliveryStatus.FAILED
+ elif response.status == EventDeliveryStatus.SUCCESS:
+ task_logger.info(
+ "[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",
+ webhook.id,
+ webhook.target_url,
+ delivery.event_type,
+ delivery.id,
+ )
delivery_update(delivery, delivery_status)
- task_logger.info(
- "[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",
- webhook.id,
- webhook.target_url,
- delivery.event_type,
- delivery.id,
- )
except ValueError as e:
response = WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)
attempt_update(attempt, response)
@@ -304,7 +307,9 @@ def send_webhook_request_async(self, event_delivery_id):
clear_successful_delivery(delivery)
-def send_webhook_request_sync(app_name, delivery, timeout=WEBHOOK_SYNC_TIMEOUT):
+def send_webhook_request_sync(
+ app_name, delivery, timeout=WEBHOOK_SYNC_TIMEOUT
+) -> Optional[Dict[Any, Any]]:
event_payload = delivery.payload
data = event_payload.payload
webhook = delivery.webhook
@@ -313,65 +318,68 @@ def send_webhook_request_sync(app_name, delivery, timeout=WEBHOOK_SYNC_TIMEOUT):
message = data.encode("utf-8")
signature = signature_for_payload(message, webhook.secret_key)
+ if parts.scheme.lower() not in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:
+ delivery_update(delivery, EventDeliveryStatus.FAILED)
+ raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+
+ logger.debug(
+ "[Webhook] Sending payload to %r for event %r.",
+ webhook.target_url,
+ delivery.event_type,
+ )
+ attempt = create_attempt(delivery=delivery, task_id=None)
response = WebhookResponse(content="")
response_data = None
- if parts.scheme.lower() in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:
- logger.debug(
- "[Webhook] Sending payload to %r for event %r.",
- webhook.target_url,
- delivery.event_type,
- )
- attempt = create_attempt(delivery=delivery, task_id=None)
- try:
- with webhooks_opentracing_trace(
- delivery.event_type, domain, sync=True, app_name=app_name
- ):
- response = send_webhook_using_http(
- webhook.target_url,
- message,
- domain,
- signature,
- delivery.event_type,
- timeout=timeout,
- )
- response_data = json.loads(response.content)
- except RequestException as e:
- logger.warning(
- "[Webhook] Failed request to %r: %r. "
- "ID of failed DeliveryAttempt: %r . ",
- webhook.target_url,
- e,
- attempt.id,
- )
- response.status = EventDeliveryStatus.FAILED
- if e.response:
- response.content = e.response.text
- response.response_headers = dict(e.response.headers)
-
- except JSONDecodeError as e:
- logger.warning(
- "[Webhook] Failed parsing JSON response from %r: %r."
- "ID of failed DeliveryAttempt: %r . ",
+
+ try:
+ with webhooks_opentracing_trace(
+ delivery.event_type, domain, sync=True, app_name=app_name
+ ):
+ response = send_webhook_using_http(
webhook.target_url,
- e,
- attempt.id,
+ message,
+ domain,
+ signature,
+ delivery.event_type,
+ timeout=timeout,
)
- response.status = EventDeliveryStatus.FAILED
- else:
+ response_data = json.loads(response.content)
+ except RequestException as e:
+ logger.warning(
+ "[Webhook] Failed request to %r: %r. "
+ "ID of failed DeliveryAttempt: %r . ",
+ webhook.target_url,
+ e,
+ attempt.id,
+ )
+ response.status = EventDeliveryStatus.FAILED
+ if e.response:
+ response.content = e.response.text
+ response.response_headers = dict(e.response.headers)
+
+ except JSONDecodeError as e:
+ logger.warning(
+ "[Webhook] Failed parsing JSON response from %r: %r."
+ "ID of failed DeliveryAttempt: %r . ",
+ webhook.target_url,
+ e,
+ attempt.id,
+ )
+ response.status = EventDeliveryStatus.FAILED
+ else:
+ if response.status == EventDeliveryStatus.SUCCESS:
logger.debug(
"[Webhook] Success response from %r."
- "Succesfull DeliveryAttempt id: %r",
+ "Successful DeliveryAttempt id: %r",
webhook.target_url,
attempt.id,
)
- attempt_update(attempt, response)
- else:
- delivery_update(delivery, EventDeliveryStatus.FAILED)
- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+ attempt_update(attempt, response)
delivery_update(delivery, response.status)
clear_successful_delivery(delivery)
- return response_data
+
+ return response_data if response.status == EventDeliveryStatus.SUCCESS else None
# DEPRECATED
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 3c5390c640..2ba73fab14 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -94,7 +94,7 @@ def test_send_webhook_request_sync_failed_attempt(mock_post, app, event_delivery
mock_post().headers = expected_data["headers"]
mock_post().elapsed = expected_data["duration"]
# when
- send_webhook_request_sync(app.name, event_delivery)
+ response_data = send_webhook_request_sync(app.name, event_delivery)
attempt = EventDeliveryAttempt.objects.first()
# then
@@ -103,6 +103,7 @@ def test_send_webhook_request_sync_failed_attempt(mock_post, app, event_delivery
assert attempt.duration == expected_data["duration"].total_seconds()
assert attempt.response == expected_data["content"]
assert attempt.response_headers == json.dumps(expected_data["headers"])
+ assert response_data is None
@mock.patch("saleor.plugins.webhook.tasks.requests.post")
@@ -121,7 +122,7 @@ def test_send_webhook_request_sync_successful_attempt(
mock_post().headers = expected_data["headers"]
mock_post().elapsed = expected_data["duration"]
# when
- send_webhook_request_sync(app.name, event_delivery)
+ response_data = send_webhook_request_sync(app.name, event_delivery)
attempt = EventDeliveryAttempt.objects.first()
@@ -132,12 +133,13 @@ def test_send_webhook_request_sync_successful_attempt(
assert attempt.duration == expected_data["duration"].total_seconds()
assert attempt.response == expected_data["content"]
assert attempt.response_headers == json.dumps(expected_data["headers"])
+ assert response_data == json.loads(expected_data["content"])
@mock.patch("saleor.plugins.webhook.tasks.requests.post", side_effect=RequestException)
def test_send_webhook_request_sync_request_exception(mock_post, app, event_delivery):
# when
- send_webhook_request_sync(app.name, event_delivery)
+ response_data = send_webhook_request_sync(app.name, event_delivery)
attempt = EventDeliveryAttempt.objects.first()
# then
@@ -147,6 +149,7 @@ def test_send_webhook_request_sync_request_exception(mock_post, app, event_deliv
assert attempt.response == ""
assert attempt.response_headers == "null"
assert attempt.request_headers == "null"
+ assert response_data is None
@mock.patch("saleor.plugins.webhook.tasks.requests.post")
@@ -179,7 +182,7 @@ def test_send_webhook_request_sync_json_parsing_error(mock_post, app, event_deli
mock_post().elapsed = expected_data["duration"]
# when
- send_webhook_request_sync(app.name, event_delivery)
+ response_data = send_webhook_request_sync(app.name, event_delivery)
attempt = EventDeliveryAttempt.objects.first()
# then
@@ -188,6 +191,7 @@ def test_send_webhook_request_sync_json_parsing_error(mock_post, app, event_deli
assert attempt.duration == expected_data["duration"].total_seconds()
assert attempt.response == expected_data["incorrect_content"]
assert attempt.response_headers == json.dumps(expected_data["response_headers"])
+ assert response_data is None
@mock.patch("saleor.plugins.webhook.tasks.requests.post")
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
index 2125e45d0c..bc0beb1339 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
@@ -71,6 +71,19 @@ def test_parse_list_payment_gateways_response_no_id(app):
assert gateways == []
+def test_parse_list_payment_gateways_response_dict_response(app):
+ # We expect that the response_data is a list of dicts, otherwise it won't be
+ # parsed.
+ response_data = {
+ "id": "credit-card",
+ "name": "Credit Card",
+ "currencies": ["USD", "EUR"],
+ "config": [{"field": "example-key", "value": "example-value"}],
+ }
+ gateways = parse_list_payment_gateways_response(response_data, app)
+ assert gateways == []
+
+
@pytest.fixture
def payment_action_response(dummy_webhook_app_payment_data):
return {
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index 89ee0c94e5..9521e8dde7 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -58,7 +58,10 @@ def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
def parse_list_payment_gateways_response(
response_data: Any, app: "App"
) -> List["PaymentGateway"]:
- gateways = []
+ gateways: List[PaymentGateway] = []
+ if not isinstance(response_data, list):
+ return gateways
+
for gateway_data in response_data:
gateway_id = gateway_data.get("id")
gateway_name = gateway_data.get("name")