Skip to content

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

Prevent raising `DatabaseError` in `CheckoutComplete` (#18543)

Iga Karbowiak909d452917cd
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index f9bb38922a..f5790bb2f2 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -390,12 +390,16 @@ def _fetch_checkout_prices_if_expired(
checkout_info, database_connection_name
)
- recalculate_discounts(
- checkout_info,
- lines,
- database_connection_name=database_connection_name,
- force_update=force_update,
- )
+ try:
+ recalculate_discounts(
+ checkout_info,
+ lines,
+ database_connection_name=database_connection_name,
+ force_update=force_update,
+ )
+ except Checkout.DoesNotExist:
+ # Checkout was removed or converted to a order. Return data without saving.
+ return checkout_info, lines
checkout.tax_error = None
@@ -529,9 +533,8 @@ def recalculate_discounts(
else:
checkout.discount_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
- checkout.save(
+ checkout.safe_update(
update_fields=["discount_expiration"],
- using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
)
return checkout_info, lines
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 035c5f635b..56450ee606 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -917,7 +917,6 @@ def _create_order(
def _prepare_checkout(
- manager: "PluginsManager",
checkout_info: "CheckoutInfo",
lines: list["CheckoutLineInfo"],
redirect_url,
@@ -949,7 +948,7 @@ def _prepare_checkout(
if to_update:
to_update.append("last_change")
- checkout.save(update_fields=to_update)
+ checkout.safe_update(update_fields=to_update)
def _prepare_checkout_with_transactions(
@@ -983,7 +982,6 @@ def _prepare_checkout_with_transactions(
)
_validate_gift_cards(checkout_info.checkout)
_prepare_checkout(
- manager=manager,
checkout_info=checkout_info,
lines=lines,
redirect_url=redirect_url,
@@ -1013,7 +1011,6 @@ def _prepare_checkout_with_payment(
last_payment=payment,
)
_prepare_checkout(
- manager=manager,
checkout_info=checkout_info,
lines=lines,
redirect_url=redirect_url,
@@ -1123,6 +1120,9 @@ def complete_checkout_pre_payment_part(
redirect_url=redirect_url,
payment=payment,
)
+ except Checkout.DoesNotExist:
+ order = Order.objects.get_by_checkout_token(checkout_info.checkout.token)
+ return order
except ValidationError as exc:
_complete_checkout_fail_handler(checkout_info, manager, payment=payment)
raise exc
@@ -1597,13 +1597,19 @@ def create_order_from_checkout(
"""
code = None
+ checkout_pk = checkout_info.checkout.pk
if voucher := checkout_info.voucher:
with transaction.atomic():
+ checkout = (
+ Checkout.objects.select_for_update().filter(pk=checkout_pk).first()
+ )
+ if not checkout:
+ order = Order.objects.get_by_checkout_token(checkout_pk)
+ return order
code = _increase_voucher_code_usage_value(checkout_info=checkout_info)
with transaction.atomic():
- checkout_pk = checkout_info.checkout.pk
checkout = Checkout.objects.select_for_update().filter(pk=checkout_pk).first()
if not checkout:
order = Order.objects.get_by_checkout_token(checkout_pk)
@@ -1788,6 +1794,9 @@ def complete_checkout_with_transaction(
private_metadata_list=private_metadata_list,
is_automatic_completion=is_automatic_completion,
)
+ except Checkout.DoesNotExist:
+ order = Order.objects.get_by_checkout_token(checkout_info.checkout.token)
+ return order
except NotApplicable as e:
raise ValidationError(
{
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index d8e6ad788a..26422ff3ad 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -9,7 +9,7 @@ from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.indexes import BTreeIndex
from django.core.validators import MinValueValidator
-from django.db import models
+from django.db import models, transaction
from django.utils import timezone
from django.utils.encoding import smart_str
from django_countries.fields import Country, CountryField
@@ -249,6 +249,31 @@ class Checkout(models.Model):
def __iter__(self):
return iter(self.lines.all())
+ def safe_update(self, update_fields: list[str]) -> None:
+ """Safely update the checkout instance.
+
+ This method locks the checkout row in the database to prevent concurrent updates.
+ In case the checkout does not exist, it raises a CheckoutDoesNotExist exception.
+
+ It prevents the DatabaseError that occurs in case save with update_fields is
+ called on a deleted checkout instance.
+ """
+ from ..core.db.connection import allow_writer
+
+ with allow_writer():
+ with transaction.atomic():
+ checkout = (
+ Checkout.objects.select_for_update()
+ .filter(pk=self.pk)
+ .only("pk")
+ .first()
+ )
+ if not checkout:
+ raise Checkout.DoesNotExist(
+ "Checkout does not exist. Unable to update."
+ )
+ self.save(update_fields=update_fields)
+
def get_customer_email(self) -> str | None:
if self.email:
return self.email
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
index 005f07711d..da716b85bd 100644
--- a/saleor/checkout/tests/test_calculations.py
+++ b/saleor/checkout/tests/test_calculations.py
@@ -1496,3 +1496,38 @@ def test_fetch_checkout_data_checkout_updated_during_price_recalculation(
assert checkout.email == expected_email
for old_line, new_line in zip(lines, checkout.lines.all(), strict=True):
assert old_line.quantity + 1 == new_line.quantity
+
+
+def test_fetch_checkout_data_checkout_deleted_during_discount_recalculation(
+ checkout_with_item_and_order_discount,
+):
+ # given
+ checkout = checkout_with_item_and_order_discount
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
+
+ manager = get_plugins_manager(allow_replica=False)
+ lines_info, _ = fetch_checkout_lines(checkout)
+ fetch_kwargs = {
+ "checkout_info": fetch_checkout_info(checkout, lines_info, manager),
+ "manager": manager,
+ "lines": lines_info,
+ }
+
+ # when
+ def delete_checkout(*args, **kwargs):
+ Checkout.objects.filter(pk=checkout.pk).delete()
+
+ with patch(
+ "saleor.checkout.calculations.recalculate_discounts",
+ side_effect=delete_checkout,
+ ):
+ result_checkout_info, result_lines_info = fetch_checkout_data(**fetch_kwargs)
+
+ # then
+ # Check if checkout was deleted.
+ with pytest.raises(Checkout.DoesNotExist):
+ checkout.refresh_from_db()
+
+ assert result_checkout_info.checkout.total is not None
+ assert result_lines_info
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 9743bdecbd..1938fa3b22 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1062,7 +1062,7 @@ def clear_delivery_method(
if updated_fields:
updated_fields.append("last_change")
if save:
- checkout.save(update_fields=updated_fields)
+ checkout.safe_update(updated_fields)
return updated_fields
diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.py
index aa5d4db705..ca294acdf9 100644
--- a/saleor/graphql/checkout/mutations/checkout_complete.py
+++ b/saleor/graphql/checkout/mutations/checkout_complete.py
@@ -1,7 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
-from ....checkout import AddressType
+from ....checkout import AddressType, models
from ....checkout.checkout_cleaner import (
clean_checkout_shipping,
validate_checkout_email,
@@ -312,7 +312,26 @@ class CheckoutComplete(BaseMutation, I18nMixin):
)
checkout_info = fetch_checkout_info(checkout, lines, manager)
- cls.validate_checkout_addresses(checkout_info, lines)
+ try:
+ cls.validate_checkout_addresses(checkout_info, lines)
+ except models.Checkout.DoesNotExist as e:
+ order = order_models.Order.objects.get_by_checkout_token(
+ checkout_info.checkout.token
+ )
+ if order:
+ return CheckoutComplete(
+ order=SyncWebhookControlContext(order),
+ confirmation_needed=False,
+ confirmation_data={},
+ )
+ raise ValidationError(
+ {
+ "checkout": ValidationError(
+ "Checkout does not exist anymore.",
+ code=CheckoutErrorCode.NOT_FOUND.value,
+ )
+ }
+ ) from e
requestor = get_user_or_app_from_context(info.context)
if requestor and requestor.has_perm(AccountPermissions.IMPERSONATE_USER):
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index d1ee3587a7..98b5e03521 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(87):
+ with django_assert_num_queries(90):
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(87):
+ with django_assert_num_queries(90):
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(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(93):
+ with django_assert_num_queries(96):
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(109):
+ with django_assert_num_queries(112):
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(109):
+ with django_assert_num_queries(112):
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(106):
+ with django_assert_num_queries(109):
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(106):
+ with django_assert_num_queries(109):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1167,7 +1167,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(97):
+ with django_assert_num_queries(100):
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(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(97):
+ with django_assert_num_queries(100):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1289,7 +1289,7 @@ def test_add_checkout_lines_order_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(103):
+ with django_assert_num_queries(106):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1324,7 +1324,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(135):
+ with django_assert_num_queries(138):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index a2c1f7d44d..961d065614 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -741,3 +741,93 @@ def test_checkout_complete_builtin_shipping_method_metadata_denormalization(
assert not Checkout.objects.filter(pk=checkout.pk).exists(), (
"Checkout should have been deleted"
)
+
+
+ "saleor.graphql.checkout.mutations.checkout_complete.CheckoutComplete.validate_checkout_addresses"
+)
+def test_checkout_complete_validate_checkout_addresses_raises_does_not_exist_error(
+ validate_addresses_mock,
+ user_api_client,
+ checkout_with_item,
+ shipping_method,
+ address,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.save_shipping_address = False
+ checkout.save_billing_address = False
+ checkout.shipping_method = shipping_method
+ checkout.save(
+ update_fields=[
+ "billing_address",
+ "shipping_address",
+ "save_shipping_address",
+ "save_billing_address",
+ "shipping_method",
+ ]
+ )
+ validate_addresses_mock.side_effect = Checkout.DoesNotExist()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name
+
+
+ "saleor.graphql.checkout.mutations.checkout_complete.CheckoutComplete.validate_checkout_addresses"
+)
+def test_checkout_complete_validate_checkout_addresses_raises_does_not_exist_error_order_returned(
+ validate_addresses_mock,
+ user_api_client,
+ checkout_with_item,
+ order,
+ shipping_method,
+ address,
+):
+ # given
+ checkout = checkout_with_item
+ checkout.billing_address = address
+ checkout.shipping_address = address
+ checkout.save_shipping_address = False
+ checkout.save_billing_address = False
+ checkout.shipping_method = shipping_method
+ checkout.save(
+ update_fields=[
+ "billing_address",
+ "shipping_address",
+ "save_shipping_address",
+ "save_billing_address",
+ "shipping_method",
+ ]
+ )
+ validate_addresses_mock.side_effect = Checkout.DoesNotExist()
+ order.checkout_token = checkout.pk
+ order.save(update_fields=["checkout_token"])
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert not data["errors"]
+ assert data["order"]
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
index fdafede437..81f505b969 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py
@@ -5671,3 +5671,44 @@ def test_checkout_complete_sets_product_type_id_for_all_order_lines(
assert (
line.product_type_id == variant_id_to_product_type_id_map[line.variant_id]
)
+
+
+def test_checkout_complete_race_condition_on_preparing_checkout(
+ user_api_client,
+ checkout_with_item,
+ address,
+ shipping_method,
+ transaction_events_generator,
+ transaction_item_generator,
+ order,
+):
+ # given
+ checkout = prepare_checkout_for_test(
+ checkout_with_item,
+ address,
+ address,
+ shipping_method,
+ transaction_item_generator,
+ transaction_events_generator,
+ )
+ order.checkout_token = checkout.token
+ order.save(update_fields=["checkout_token"])
+
+ redirect_url = "https://www.example.com/new"
+ variables = {"id": to_global_id_or_none(checkout), "redirectUrl": redirect_url}
+
+ def delete_checkout(*args, **kwargs):
+ checkout.delete()
+
+ # when
+ with race_condition.RunAfter(
+ "saleor.checkout.complete_checkout.clean_checkout_shipping", delete_checkout
+ ):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+
+ assert not data["errors"]
+ assert data["order"]