Skip to content

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

Make logic sending messages to AWS SQS and Google PubSub more tolerant to prevent task giving up without retries (#19384)

Marcin Wcisło5c05b2f96fea
diff --git a/saleor/webhook/transport/asynchronous/tests/test_transport.py b/saleor/webhook/transport/asynchronous/tests/test_transport.py
index fc09f85017..904434b058 100644
--- a/saleor/webhook/transport/asynchronous/tests/test_transport.py
+++ b/saleor/webhook/transport/asynchronous/tests/test_transport.py
@@ -1,9 +1,14 @@
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+import botocore.exceptions
+import celery
+import google.api_core.exceptions
+import google.cloud.pubsub_v1.publisher
import pytest
from celery.exceptions import Retry as CeleryTaskRetryError
from opentelemetry.trace import StatusCode
+from .....core.models import EventDelivery, EventDeliveryAttempt, EventDeliveryStatus
from .....tests.utils import get_metric_data_point, get_span_by_name
from ...metrics import (
METRIC_EXTERNAL_REQUEST_BODY_SIZE,
@@ -202,3 +207,105 @@ def test_send_webhook_request_async_fails_when_exception_raised_by_webhooks_otel
send_webhook_request_async(
event_delivery_id=event_delivery.id, telemetry_context={}
)
+
+
+ "thrown_exception",
+ [
+ google.api_core.exceptions.ClientError,
+ google.api_core.exceptions.PermissionDenied,
+ google.api_core.exceptions.InternalServerError,
+ google.api_core.exceptions.ServiceUnavailable,
+ google.api_core.exceptions.DeadlineExceeded,
+ google.cloud.pubsub_v1.publisher.exceptions.MessageTooLargeError,
+ RuntimeError,
+ TimeoutError,
+ ],
+)
+def test_send_webhook_request_async_when_google_cloud_pubsub_publish_fails(
+ thrown_exception,
+ event_delivery,
+ monkeypatch,
+):
+ # given
+ assert EventDeliveryAttempt.objects.count() == 0
+
+ webhook = event_delivery.webhook
+ webhook.target_url = "gcpubsub://cloud.google.com/projects/saleor/topics/test"
+ webhook.save(update_fields=["target_url"])
+
+ mocked_future = MagicMock()
+ mocked_future.result.side_effect = thrown_exception("")
+
+ mocked_publisher = MagicMock(spec=google.cloud.pubsub_v1.PublisherClient)
+ mocked_publisher.publish.return_value = mocked_future
+ monkeypatch.setattr(
+ "saleor.webhook.transport.utils.pubsub_v1.PublisherClient",
+ lambda: mocked_publisher,
+ )
+
+ # when
+ with pytest.raises(celery.exceptions.Retry):
+ send_webhook_request_async(
+ event_delivery_id=event_delivery.id, telemetry_context={}
+ )
+
+ # then
+ mocked_future.result.assert_called_once()
+
+ event_delivery.refresh_from_db()
+ assert event_delivery.status == EventDeliveryStatus.PENDING
+ assert EventDelivery.objects.filter(status=EventDeliveryStatus.PENDING).count() == 1
+
+ attempts = EventDeliveryAttempt.objects.all()
+ assert len(attempts) == 1
+ assert attempts[0].status == EventDeliveryStatus.FAILED
+
+
+ "thrown_exception",
+ [
+ botocore.exceptions.ClientError(
+ {"Error": {"Code": "AccessDenied", "Message": ""}}, "SendMessage"
+ ),
+ botocore.exceptions.EndpointConnectionError(endpoint_url="https://sqs"),
+ botocore.exceptions.ConnectTimeoutError(endpoint_url="https://sqs"),
+ ],
+)
+def test_send_webhook_request_async_when_aws_sqs_send_message_fails(
+ thrown_exception,
+ event_delivery,
+ monkeypatch,
+):
+ # given
+ assert EventDeliveryAttempt.objects.count() == 0
+
+ webhook = event_delivery.webhook
+ webhook.target_url = (
+ "awssqs://key_id:[email protected]/account_id/queue_name"
+ )
+ webhook.save(update_fields=["target_url"])
+
+ mocked_client = MagicMock()
+ mocked_client.send_message.side_effect = thrown_exception
+ monkeypatch.setattr(
+ "saleor.webhook.transport.utils.boto3.client",
+ lambda *args, **kwargs: mocked_client,
+ )
+
+ # when
+ with pytest.raises(celery.exceptions.Retry):
+ send_webhook_request_async(
+ event_delivery_id=event_delivery.id, telemetry_context={}
+ )
+
+ # then
+ mocked_client.send_message.assert_called_once()
+
+ event_delivery.refresh_from_db()
+ assert event_delivery.status == EventDeliveryStatus.PENDING
+ assert EventDelivery.objects.filter(status=EventDeliveryStatus.PENDING).count() == 1
+
+ attempts = EventDeliveryAttempt.objects.all()
+ assert len(attempts) == 1
+ assert attempts[0].status == EventDeliveryStatus.FAILED
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
index cfc81246b2..cffecb7e0e 100644
--- a/saleor/webhook/transport/utils.py
+++ b/saleor/webhook/transport/utils.py
@@ -13,7 +13,8 @@ from urllib.parse import unquote, urlparse, urlunparse
from uuid import UUID
import boto3
-from botocore.exceptions import ClientError
+import botocore.exceptions
+import google.api_core.exceptions
from celery import Task
from celery.exceptions import MaxRetriesExceededError, Retry
from celery.utils.log import get_task_logger
@@ -335,7 +336,10 @@ def send_webhook_using_aws_sqs(
with catch_duration_time() as duration:
try:
response = json.dumps(client.send_message(**message_kwargs))
- except ClientError as e:
+ except (
+ botocore.exceptions.ClientError,
+ botocore.exceptions.BotoCoreError,
+ ) as e:
return WebhookResponse(
content=str(e), status=EventDeliveryStatus.FAILED, duration=duration()
)
@@ -362,6 +366,7 @@ def send_webhook_using_google_cloud_pubsub(
timeout=settings.WEBHOOK_WAITING_FOR_RESPONSE_TIMEOUT
)
except (
+ google.api_core.exceptions.GoogleAPIError,
pubsub_v1.publisher.exceptions.MessageTooLargeError,
RuntimeError,
TimeoutError,