Skip to content

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

Rebuild the lock for checkout. Reduce amount of queries

Maciej Korycinski53f3089e4907
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index fde8370ba9..7c1ccdb86f 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -18,10 +18,9 @@ from ..payment.utils import store_customer_id
from . import models
from .checkout_cleaner import clean_checkout_payment, clean_checkout_shipping
from .error_codes import CheckoutErrorCode
-from .utils import abort_order_data, create_order, get_order, prepare_order_data
+from .utils import abort_order_data, create_order, prepare_order_data
def prepare_checkout(
checkout: models.Checkout, discounts, tracking_code, redirect_url, payment
):
@@ -54,7 +53,6 @@ def prepare_checkout(
checkout.save(update_fields=to_update)
def convert_checkout_to_order(
checkout: models.Checkout, order_data: dict, user: Optional[User]
) -> order_models.Order:
@@ -121,12 +119,11 @@ def complete_checkout(
tracking_code=None,
redirect_url=None,
) -> Tuple[Optional[Order], bool, dict]:
- action_required = False
- action_data = {} # type: ignore
- order = get_order(checkout.token)
- if order:
- return order, action_required, action_data
+ """Logic required to finalize the checkout and convert it to order.
+ Should be used with transaction_with_commit_on_errors. As there is a possibility
+ for thread race.
+ """
payment = checkout.get_last_active_payment()
prepare_checkout(
checkout=checkout,
@@ -155,24 +152,15 @@ def complete_checkout(
action_required = txn.action_required
action_data = txn.action_required_data if action_required else {}
+ order = None
if not action_required:
try:
- with transaction.atomic():
- order = get_order(checkout.token)
- if order:
- # Order was created asynchronously, we can release the lock made
- # on order_data
- abort_order_data(order_data)
- else:
- order = convert_checkout_to_order(
- checkout=checkout, order_data=order_data, user=user
- )
+ order = convert_checkout_to_order(
+ checkout=checkout, order_data=order_data, user=user
+ )
except InsufficientStock as e:
abort_order_data(order_data)
gateway.payment_refund_or_void(payment)
raise ValidationError(f"Insufficient product stock: {e.item}", code=e.code)
- if not order:
- abort_order_data(order_data)
-
return order, action_required, action_data
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 21c85065e6..de374f034f 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -2,7 +2,6 @@
from datetime import date
from decimal import Decimal
from typing import Iterable, List, Optional, Tuple
-from uuid import UUID
from django.core.exceptions import ValidationError
from django.db import transaction
@@ -696,11 +695,6 @@ def abort_order_data(order_data: dict):
remove_voucher_usage_by_customer(voucher, order_data["user_email"])
-def get_order(checkout_token: UUID) -> Optional[Order]:
- """Get order based on checkout token."""
- return Order.objects.confirmed().filter(checkout_token=checkout_token).first()
-
-
@transaction.atomic
def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
"""Create an order from the checkout.
@@ -724,7 +718,9 @@ def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
order_lines = order_data.pop("lines")
order = Order.objects.create(**order_data, checkout_token=checkout.token)
- order.lines.set(order_lines, bulk=False)
+ for line in order_lines:
+ line.order_id = order.pk
+ order_lines = OrderLine.objects.bulk_create(order_lines)
# allocate stocks from the lines
for line in order_lines: # type: OrderLine
diff --git a/saleor/core/transactions.py b/saleor/core/transactions.py
new file mode 100644
index 0000000000..7f961b2891
--- /dev/null
+++ b/saleor/core/transactions.py
@@ -0,0 +1,18 @@
+from contextlib import contextmanager
+
+from django.db import DatabaseError, IntegrityError, transaction
+
+
+@contextmanager
+def transaction_with_commit_on_errors():
+ """Perform transaction and raise an error in any occurred."""
+ error = None
+ with transaction.atomic():
+ try:
+ yield
+ except (DatabaseError, IntegrityError):
+ raise
+ except Exception as e:
+ error = e
+ if error:
+ raise error
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 82f517492d..1fbff94c85 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -14,7 +14,6 @@ from ...checkout.utils import (
add_variant_to_checkout,
change_billing_address_in_checkout,
change_shipping_address_in_checkout,
- get_order,
get_user_checkout,
get_valid_shipping_methods_for_checkout,
recalculate_checkout_discount,
@@ -23,6 +22,8 @@ from ...checkout.utils import (
from ...core import analytics
from ...core.exceptions import InsufficientStock, PermissionDenied, ProductNotPublished
from ...core.permissions import OrderPermissions
+from ...core.transactions import transaction_with_commit_on_errors
+from ...order import models as order_models
from ...payment import models as payment_models
from ...product import models as product_models
from ...warehouse.availability import check_stock_quantity, get_available_quantity
@@ -767,46 +768,55 @@ class CheckoutComplete(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, checkout_id, store_source, **data):
- checkout_token = from_global_id_strict_type(
- checkout_id, Checkout, field="checkout_id"
- )
- order = get_order(checkout_token)
- if order:
- # The order is already created. We return it as a success checkoutComplete
- # response. Order is anonymized for not logged in user
- return CheckoutComplete(
- order=order, confirmation_needed=False, confirmation_data={}
- )
-
- with transaction.atomic():
- checkout = cls.get_node_or_error(
- info,
- checkout_id,
- only_type=Checkout,
- field="checkout_id",
- qs=models.Checkout.objects.select_for_update(of=("self",))
- .prefetch_related(
- "gift_cards",
- "lines",
- Prefetch(
- "payments",
- queryset=payment_models.Payment.objects.prefetch_related(
- "order", "order__lines"
+ tracking_code = analytics.get_client_id(info.context)
+ with transaction_with_commit_on_errors():
+ try:
+ checkout = cls.get_node_or_error(
+ info,
+ checkout_id,
+ only_type=Checkout,
+ field="checkout_id",
+ qs=models.Checkout.objects.select_for_update(of=("self",))
+ .prefetch_related(
+ "gift_cards",
+ "lines__variant__product",
+ Prefetch(
+ "payments",
+ queryset=payment_models.Payment.objects.prefetch_related(
+ "order__lines"
+ ),
),
- ),
+ )
+ .select_related("shipping_method__shipping_zone"),
+ )
+ except ValidationError as e:
+ checkout_token = from_global_id_strict_type(
+ checkout_id, Checkout, field="checkout_id"
)
- .select_related("shipping_method", "shipping_method__shipping_zone"),
+
+ order = (
+ order_models.Order.objects.confirmed()
+ .filter(checkout_token=checkout_token)
+ .first()
+ )
+ if order:
+ # The order is already created. We return it as a success
+ # checkoutComplete response. Order is anonymized for not logged in
+ # user
+ return CheckoutComplete(
+ order=order, confirmation_needed=False, confirmation_data={}
+ )
+ raise e
+
+ order, action_required, action_data = complete_checkout(
+ checkout=checkout,
+ payment_data=data.get("payment_data", {}),
+ store_source=store_source,
+ discounts=info.context.discounts,
+ user=info.context.user,
+ tracking_code=tracking_code,
+ redirect_url=data.get("redirect_url"),
)
- tracking_code = analytics.get_client_id(info.context)
- order, action_required, action_data = complete_checkout(
- checkout=checkout,
- payment_data=data.get("payment_data", {}),
- store_source=store_source,
- discounts=info.context.discounts,
- user=info.context.user,
- tracking_code=tracking_code,
- redirect_url=data.get("redirect_url"),
- )
# If gateway returns information that additional steps are required we need
# to inform the frontend and pass all required data
return CheckoutComplete(
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 973b557011..d77fb5bb9e 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -68,6 +68,7 @@ def test_checkout_complete_order_already_exists(
order_with_lines.save()
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}
+ checkout.delete()
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
content = get_graphql_content(response)
diff --git a/saleor/order/emails.py b/saleor/order/emails.py
index fc2e592a9c..dd30ff64a7 100644
--- a/saleor/order/emails.py
+++ b/saleor/order/emails.py
@@ -14,7 +14,7 @@ from .models import Fulfillment, Order
if TYPE_CHECKING:
from decimal import Decimal
- from ..account.models import User
+ from ..account.models import User # noqa: F401
CONFIRM_ORDER_TEMPLATE = "order/confirm_order"
STAFF_CONFIRM_ORDER_TEMPLATE = "order/staff_confirm_order"
@@ -43,7 +43,9 @@ def collect_data_for_email(
order_pk: int, template: str, redirect_url: str = ""
) -> dict:
"""Collect the required data for sending emails."""
- order = Order.objects.get(pk=order_pk)
+ order = Order.objects.prefetch_related("lines__variant__product__images").get(
+ pk=order_pk
+ )
recipient_email = order.get_customer_email()
send_kwargs, email_context = get_email_context()
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 954605e720..1af33b20d5 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -12,7 +12,6 @@ from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.handlers.wsgi import WSGIRequest
-from django.db import transaction as django_transaction
from django.http import (
HttpResponse,
HttpResponseBadRequest,
@@ -25,6 +24,7 @@ from graphql_relay import from_global_id
from ....checkout.complete_checkout import complete_checkout
from ....checkout.models import Checkout
+from ....core.transactions import transaction_with_commit_on_errors
from ....core.utils.url import prepare_url
from ....discount.utils import fetch_active_discounts
from ....order.actions import cancel_order, order_captured, order_refunded
@@ -59,8 +59,8 @@ def get_checkout(payment: Payment) -> Optional[Checkout]:
# Lock checkout in the same way as in checkoutComplete
return (
Checkout.objects.select_for_update(of=("self",))
- .prefetch_related("gift_cards", "lines",)
- .select_related("shipping_method", "shipping_method__shipping_zone")
+ .prefetch_related("gift_cards", "lines__variant__product",)
+ .select_related("shipping_method__shipping_zone")
.filter(pk=payment.checkout.pk)
.first()
)
@@ -114,7 +114,7 @@ def create_payment_notification_for_order(
)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_authorization(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
@@ -175,7 +175,7 @@ def handle_authorization(notification: Dict[str, Any], _gateway_config: GatewayC
create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/cancel#cancellation-notifciation
payment = get_payment(notification.get("merchantReference"))
@@ -215,7 +215,7 @@ def handle_cancel_or_refund(
handle_cancellation(notification, gateway_config)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#capture-notification
payment = get_payment(notification.get("merchantReference"))
@@ -280,7 +280,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
create_payment_notification_for_order(payment, success_msg, failed_msg, is_success)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/capture#failed-capture
payment = get_payment(notification.get("merchantReference"))
@@ -307,7 +307,7 @@ def handle_failed_capture(notification: Dict[str, Any], _gateway_config: Gateway
create_payment_notification_for_order(payment, msg, None, True)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/development-resources/webhooks/understand-notifications#
# event-codes"
@@ -331,7 +331,7 @@ def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#refund-notification
payment = get_payment(notification.get("merchantReference"))
@@ -364,7 +364,7 @@ def _get_kind(transaction: Optional[Transaction]) -> str:
return TransactionKind.CAPTURE
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayConfig):
# https://docs.adyen.com/checkout/refund#failed-refund
payment = get_payment(notification.get("merchantReference"))
@@ -428,7 +428,7 @@ def handle_failed_refund(notification: Dict[str, Any], gateway_config: GatewayCo
gateway_postprocess(new_transaction, payment)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def handle_reversed_refund(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
@@ -465,7 +465,7 @@ def handle_refund_with_data(
handle_refund(notification, gateway_config)
-@django_transaction.atomic
+@transaction_with_commit_on_errors()
def webhook_not_implemented(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
diff --git a/saleor/seo/schema/email.py b/saleor/seo/schema/email.py
index efbc6ea644..49add1f945 100644
--- a/saleor/seo/schema/email.py
+++ b/saleor/seo/schema/email.py
@@ -59,8 +59,7 @@ def get_order_confirmation_markup(order: "Order") -> str:
"orderDate": order.created,
}
- lines = order.lines.prefetch_related("variant")
- for line in lines:
+ for line in order.lines.all():
product_data = get_product_data(line=line, organization=organization)
data["acceptedOffer"].append(product_data)
return json.dumps(data, cls=HTMLSafeJSON)