Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Catch and handle Integrity and Database error in automatic checkout completion (#17146)
Iga Karbowiakf0f1c54bf5a5
diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.pyindex 706dde6194..9ce598bb0c 100644--- a/saleor/checkout/tasks.py+++ b/saleor/checkout/tasks.py@@ -6,6 +6,7 @@ from celery.utils.log import get_task_loggerfrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db.models import Exists, OuterRef, Q, QuerySet, Subquery+from django.db.utils import DatabaseError, IntegrityErrorfrom django.utils import timezonefrom ..account.models import User@@ -124,9 +125,15 @@ def delete_expired_checkouts(return total_deleted, has_more[email protected](queue=settings.AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME)+ queue=settings.AUTOMATIC_CHECKOUT_COMPLETION_QUEUE_NAME,+ bind=True,+ default_retry_delay=60,+ retry_kwargs={"max_retries": 5},+)@allow_writer()def automatic_checkout_completion_task(+ self,checkout_pk,user_id,app_id,@@ -171,6 +178,8 @@ def automatic_checkout_completion_task(checkout_id,extra={"checkout_id": checkout_id},)++ failed_error_msg = "Automatic checkout completion failed for checkout: %s."try:complete_checkout(manager=manager,@@ -184,13 +193,32 @@ def automatic_checkout_completion_task()except ValidationError as error:task_logger.warning(- "Automatic checkout completion failed for checkout: %s.",+ failed_error_msg,+ checkout_id,+ extra={+ "checkout_id": checkout_id,+ "error": str(error),+ },+ )+ except (IntegrityError, DatabaseError) as error:+ if checkout_not_exists := not Checkout.objects.filter(pk=checkout_pk).exists():+ failed_error_msg = failed_error_msg + " The checkout no longer exists."++ task_logger.warning(+ failed_error_msg,checkout_id,extra={"checkout_id": checkout_id,"error": str(error),},)+ if not checkout_not_exists:+ task_logger.info(+ "Retrying automatic checkout completion for checkout: %s.",+ checkout_id,+ extra={"checkout_id": checkout_id},+ )+ raise self.retry() from errorelse:task_logger.info("Automatic checkout completion succeeded for checkout: %s.",diff --git a/saleor/checkout/tests/test_tasks.py b/saleor/checkout/tests/test_tasks.pyindex 013fddd83e..a9adb89734 100644--- a/saleor/checkout/tests/test_tasks.py+++ b/saleor/checkout/tests/test_tasks.py@@ -6,12 +6,19 @@ from uuid import UUIDimport grapheneimport pytest+from celery.exceptions import Retry as CeleryTaskRetryError+from django.db.utils import DatabaseError, IntegrityErrorfrom django.utils import timezone+from ...core.taxes import zero_moneyfrom ...order import OrderEventsfrom ...order.models import Order+from ...plugins.manager import get_plugins_managerfrom ...product.models import ProductChannelListing, ProductVariantChannelListing+from .. import calculations+from ..fetch import fetch_checkout_info, fetch_checkout_linesfrom ..models import Checkout, CheckoutLine+from ..payment_utils import update_checkout_payment_statusesfrom ..tasks import (automatic_checkout_completion_task,delete_expired_checkouts,@@ -823,3 +830,149 @@ def test_automatic_checkout_completion_task_error_raised(checkout, app, caplog):assert caplog.records[1].checkout_id == checkout_idassert caplog.records[1].errorassert caplog.records[1].levelno == logging.WARNING+++ "error",+ [IntegrityError, DatabaseError],+)[email protected]("saleor.checkout.tasks.complete_checkout")[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.retry")+def test_automatic_checkout_completion_task_checkout_error_task_retried(+ mocked_retry,+ mocked_complete_checkout,+ error,+ checkout_with_prices,+ transaction_item_generator,+ app,+ caplog,+ django_capture_on_commit_callbacks,+):+ # given+ checkout = checkout_with_prices+ checkout_pk = checkout.pk++ mocked_complete_checkout.side_effect = error()+ mocked_retry.side_effect = CeleryTaskRetryError()++ # allow catching the log in caplog+ parent_logger = task_logger.parent+ parent_logger.propagate = True++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ transaction_item_generator(+ checkout_id=checkout.pk, charged_value=total.gross.amount+ )+ update_checkout_payment_statuses(+ checkout, zero_money(checkout.currency), checkout_has_lines=True+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ try:+ automatic_checkout_completion_task(checkout_pk, None, app.id)+ except CeleryTaskRetryError:+ pass++ # then+ # Checkout exists so task is retired+ mocked_retry.assert_called_once()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)+ assert len(caplog.records) == 3+ assert caplog.records[0].message == (+ f"Automatic checkout completion triggered for checkout: {checkout_id}."+ )+ assert caplog.records[0].checkout_id == checkout_id+ assert caplog.records[0].levelno == logging.INFO++ assert caplog.records[1].message == (+ f"Automatic checkout completion failed for checkout: {checkout_id}."+ )+ assert caplog.records[1].checkout_id == checkout_id+ assert caplog.records[1].levelno == logging.WARNING++ assert caplog.records[2].message == (+ f"Retrying automatic checkout completion for checkout: {checkout_id}."+ )+ assert caplog.records[2].checkout_id == checkout_id+ assert caplog.records[2].levelno == logging.INFO+++ "error",+ [IntegrityError, DatabaseError],+)[email protected]("saleor.checkout.tasks.complete_checkout")[email protected]("saleor.checkout.tasks.automatic_checkout_completion_task.retry")+def test_automatic_checkout_completion_task_checkout_deleted_in_meantime(+ mocked_retry,+ mocked_complete_checkout,+ error,+ checkout_with_prices,+ transaction_item_generator,+ app,+ caplog,+ django_capture_on_commit_callbacks,+):+ # given+ checkout = checkout_with_prices+ checkout_pk = checkout.pk++ def delete_checkout_and_raise_an_error(*args, **kwargs):+ checkout.delete()+ raise error()++ mocked_complete_checkout.side_effect = delete_checkout_and_raise_an_error+ mocked_retry.side_effect = CeleryTaskRetryError()++ # allow catching the log in caplog+ parent_logger = task_logger.parent+ parent_logger.propagate = True++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.checkout_total(+ manager=manager,+ checkout_info=checkout_info,+ lines=lines,+ address=checkout.shipping_address,+ )+ transaction_item_generator(+ checkout_id=checkout.pk, charged_value=total.gross.amount+ )+ update_checkout_payment_statuses(+ checkout, zero_money(checkout.currency), checkout_has_lines=True+ )++ # when+ with django_capture_on_commit_callbacks(execute=True):+ automatic_checkout_completion_task(checkout_pk, None, app.id)++ # then+ # Checkout exists so task is retired+ mocked_retry.assert_not_called()++ checkout_id = graphene.Node.to_global_id("Checkout", checkout_pk)+ assert len(caplog.records) == 2+ assert caplog.records[0].message == (+ f"Automatic checkout completion triggered for checkout: {checkout_id}."+ )+ assert caplog.records[0].checkout_id == checkout_id+ assert caplog.records[0].levelno == logging.INFO++ assert caplog.records[1].message == (+ f"Automatic checkout completion failed for checkout: {checkout_id}. "+ "The checkout no longer exists."+ )+ assert caplog.records[1].checkout_id == checkout_id+ assert caplog.records[1].levelno == logging.WARNING