Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix deadlocks caused by adding variants to the checkout process. (#18206)
Filip Owczarek9698135fe4fc
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 73738873ed..2a2c6a74f7 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -16,7 +16,11 @@ from prices import Moneyfrom ..account.models import Userfrom ..checkout.fetch import update_delivery_method_lists_for_checkout_infofrom ..core.db.connection import allow_writer-from ..core.exceptions import NonExistingCheckoutLines, ProductNotPublished+from ..core.exceptions import (+ NonExistingCheckout,+ NonExistingCheckoutLines,+ ProductNotPublished,+)from ..core.prices import quantize_pricefrom ..core.taxes import zero_taxed_moneyfrom ..core.utils.metadata_manager import (@@ -61,7 +65,10 @@ from ..warehouse.models import Warehousefrom ..warehouse.reservations import reserve_stocks_and_preordersfrom . import AddressType, base_calculations, calculationsfrom .error_codes import CheckoutErrorCode-from .lock_objects import checkout_lines_qs_select_for_update+from .lock_objects import (+ checkout_lines_qs_select_for_update,+ checkout_qs_select_for_update,+)from .models import Checkout, CheckoutLine, CheckoutMetadataif TYPE_CHECKING:@@ -306,6 +313,17 @@ def add_variants_to_checkout("""country_code = checkout.get_country()with transaction.atomic():+ # We need to lock checkout first to avoid deadlocks.+ # When this function try to create new lines, the checkout is locked after+ # the lines are locked manually. We should always lock checkout first to+ # avoid deadlocks.+ try:+ _locked_checkout = (+ checkout_qs_select_for_update().only("pk").get(token=checkout.token)+ )+ except Checkout.DoesNotExist as e:+ raise NonExistingCheckout(checkout.token) from e+checkout_lines = list(checkout_lines_qs_select_for_update().select_related("variant")@@ -357,6 +375,8 @@ def add_variants_to_checkout()if to_create:+ # This operation is safe to do without locking as we already locked checkout+ # on the beginning of this transaction.CheckoutLine.objects.bulk_create(to_create)to_reserve = to_create + to_updatediff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex f5399d73a8..0862246fc9 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -29,6 +29,12 @@ class NonExistingCheckoutLines(Exception):super().__init__("Checkout lines don't exist.")+class NonExistingCheckout(Exception):+ def __init__(self, checkout_token: UUID):+ self.checkout_token = checkout_token+ super().__init__(f"Checkout: {checkout_token} doesn't exist.")++class InsufficientStock(Exception):def __init__(self, items: list[InsufficientStockData]):details = [str(item.variant or item.order_line) for item in items]diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex e367d503ba..a33f1b4ba7 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -482,6 +482,9 @@ class CheckoutCreate(DeprecatedModelMutation, I18nMixin):checkout_lines_data = cleaned_input.get("lines_data")if variants and checkout_lines_data:site = get_site_promise(info.context).get()+ # Doesn't make sense to handle `NonExistingCheckout` here,+ # as we just created the checkout above. No-one knows checkout's+ # token except us.add_variants_to_checkout(instance,variants,diff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.pyindex 41ea486476..67fcf1c898 100644--- a/saleor/graphql/checkout/mutations/checkout_create_from_order.py+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py@@ -402,6 +402,9 @@ class CheckoutCreateFromOrder(BaseMutation):)if variants and valid_order_lines:+ # Doesn't make sense to handle `NonExistingCheckout` here,+ # as we just created the checkout above. No-one knows checkout's+ # token except us.checkout = add_variants_to_checkout(checkout,variants,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex a5b14cc9f8..70c02dd31d 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -9,6 +9,7 @@ from ....checkout.fetch import (update_delivery_method_lists_for_checkout_info,)from ....checkout.utils import add_variants_to_checkout, invalidate_checkout+from ....core.exceptions import NonExistingCheckoutfrom ....core.utils import metadata_managerfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabledfrom ....webhook.event_types import WebhookEventAsyncType@@ -18,7 +19,7 @@ from ...core.context import SyncWebhookControlContextfrom ...core.descriptions import DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_CHECKOUTfrom ...core.enums import MetadataErrorCode-from ...core.mutations import BaseMutation+from ...core.mutations import MISSING_NODE_ERROR_MESSAGE_PREFIX, BaseMutationfrom ...core.scalars import UUIDfrom ...core.types import CheckoutError, NonNullListfrom ...core.utils import WebhookEventInfo@@ -122,18 +123,29 @@ class CheckoutLinesAdd(BaseMutation):):if variants and checkout_lines_data:site = get_site_promise(info.context).get()- checkout = add_variants_to_checkout(- checkout,- variants,- checkout_lines_data,- checkout_info.channel,- replace=replace,- replace_reservations=True,- reservation_length=get_reservation_length(- site=site, user=info.context.user- ),- raise_error_for_missing_lines=raise_error_for_missing_lines,- )+ try:+ checkout = add_variants_to_checkout(+ checkout,+ variants,+ checkout_lines_data,+ checkout_info.channel,+ replace=replace,+ replace_reservations=True,+ reservation_length=get_reservation_length(+ site=site, user=info.context.user+ ),+ raise_error_for_missing_lines=raise_error_for_missing_lines,+ )+ except NonExistingCheckout as e:+ graphql_id = graphene.Node.to_global_id("Checkout", e.checkout_token)+ raise ValidationError(+ {+ "id": ValidationError(+ f"{MISSING_NODE_ERROR_MESSAGE_PREFIX} {graphql_id}",+ code=CheckoutErrorCode.NOT_FOUND.value,+ )+ }+ ) from elines, _ = fetch_checkout_lines(checkout)shipping_channel_listings = checkout.channel.shipping_method_listings.all()diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 78a0c0ba55..703148b490 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -422,7 +422,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(85):+ with django_assert_num_queries(86):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -440,7 +440,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(85):+ with django_assert_num_queries(86):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10@@ -572,7 +572,7 @@ def test_create_checkout_with_order_promotion(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(91):+ with django_assert_num_queries(92):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# then@@ -828,7 +828,7 @@ def test_update_checkout_lines_with_reservations()user_api_client.ensure_access_token()- with django_assert_num_queries(107):+ with django_assert_num_queries(108):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -842,7 +842,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(107):+ with django_assert_num_queries(108):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -1103,7 +1103,7 @@ def test_add_checkout_lines_with_reservations(user_api_client.ensure_access_token()# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(104):+ with django_assert_num_queries(105):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -1116,7 +1116,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(104):+ with django_assert_num_queries(105):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,@@ -1167,7 +1167,7 @@ def test_add_checkout_lines_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(95):+ with django_assert_num_queries(96):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1253,7 +1253,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(95):+ with django_assert_num_queries(96):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1289,7 +1289,7 @@ def test_add_checkout_lines_order_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(101):+ with django_assert_num_queries(102):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1324,7 +1324,7 @@ def test_add_checkout_lines_gift_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(128):+ with django_assert_num_queries(129):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 7758584cbf..20f0768c9f 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -25,14 +25,19 @@ from .....discount import RewardType, RewardValueTypefrom .....plugins.manager import get_plugins_managerfrom .....product.models import ProductChannelListing, ProductVariantChannelListingfrom .....shipping.interface import ShippingMethodData+from .....tests import race_conditionfrom .....warehouse import WarehouseClickAndCollectOptionfrom .....warehouse.models import Reservation, Stockfrom .....warehouse.tests.utils import get_available_quantity_for_stockfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom .....webhook.transport.asynchronous.transport import send_webhook_request_asyncfrom .....webhook.transport.utils import WebhookResponse+from ....core.mutations import MISSING_NODE_ERROR_MESSAGE_PREFIXfrom ....core.utils import to_global_id_or_none-from ....tests.utils import assert_no_permission, get_graphql_content+from ....tests.utils import (+ assert_no_permission,+ get_graphql_content,+)from ...mutations.utils import update_checkout_shipping_method_if_invalidMUTATION_CHECKOUT_LINES_ADD = """@@ -2220,3 +2225,49 @@ def test_checkout_lines_add_with_prior_price(checkout["lines"][0]["priorTotalPrice"]["amount"]== variant_channel_listing.prior_price_amount * 2)+++def test_checkout_lines_add_checkout_removed_before_adding_variants_to_checkout(+ user_api_client,+ checkout_with_item,+ stock,+):+ # given+ variant = stock.product_variant+ checkout = checkout_with_item+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ checkout_global_id = to_global_id_or_none(checkout)++ variables = {+ "id": checkout_global_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ def delete_checkout(*args, **kwargs):+ # Simulate checkout deletion. We can't run `delete()` on `checkout_with_prices`, because+ # it's would pass `checkout` without `pk` to `checkout_info`.+ Checkout.objects.filter(pk=checkout.pk).delete()++ with race_condition.RunBefore(+ "saleor.graphql.checkout.mutations.checkout_lines_add.add_variants_to_checkout",+ delete_checkout,+ ):+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["checkout"]+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name+ # Ensure that checkout removed during the mutation execution was handled in same way+ # as if it was removed before the mutation execution.+ assert (+ data["errors"][0]["message"]+ == f"{MISSING_NODE_ERROR_MESSAGE_PREFIX} {checkout_global_id}"+ )diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex c403074a12..4826c12b15 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -31,6 +31,7 @@ from .....warehouse.models import Reservation, Stockfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom .....webhook.transport.asynchronous.transport import send_webhook_request_asyncfrom .....webhook.transport.utils import WebhookResponse+from ....core.mutations import MISSING_NODE_ERROR_MESSAGE_PREFIXfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import assert_no_permission, get_graphql_contentfrom ...mutations.utils import update_checkout_shipping_method_if_invalid@@ -1973,3 +1974,49 @@ def test_checkout_lines_update_checkout_updated_during_price_recalculation(checkout.refresh_from_db()assert checkout.email == expected_email+++def test_checkout_lines_update_checkout_removed_before_adding_variants_to_checkout(+ user_api_client,+ checkout_with_item,+):+ # given+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)+ checkout_global_id = to_global_id_or_none(checkout)++ variables = {+ "id": checkout_global_id,+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ def delete_checkout(*args, **kwargs):+ # Simulate checkout deletion. We can't run `delete()` on `checkout_with_prices`, because+ # it's would pass `checkout` without `pk` to `checkout_info`.+ Checkout.objects.filter(pk=checkout.pk).delete()++ with race_condition.RunBefore(+ "saleor.graphql.checkout.mutations.checkout_lines_add.add_variants_to_checkout",+ delete_checkout,+ ):+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE, variables+ )++ content = get_graphql_content(response)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["checkout"]+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name+ # Ensure that checkout removed during the mutation execution was handled in same way+ # as if it was removed before the mutation execution.+ assert (+ data["errors"][0]["message"]+ == f"{MISSING_NODE_ERROR_MESSAGE_PREFIX} {checkout_global_id}"+ )diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 87b308090d..b682b6b769 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -59,6 +59,8 @@ from .utils import ()from .utils.error_codes import get_error_code_from_error+MISSING_NODE_ERROR_MESSAGE_PREFIX = "Couldn't resolve to a node:"+def get_model_name(model):"""Return name of the model with first letter lowercase."""@@ -371,7 +373,7 @@ class BaseMutation(graphene.Mutation):raise ValidationError({field: ValidationError(- f"Couldn't resolve to a node: {node_id}", code=code+ f"{MISSING_NODE_ERROR_MESSAGE_PREFIX} {node_id}", code=code)})