Skip to content

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

Fix race condition with checkout complete process and TransactionEventReport mutation. (#17776) (#17789)

Filip Owczarekccd3960acd1d
diff --git a/saleor/checkout/actions.py b/saleor/checkout/actions.py
index c9dd7f8366..2af0e92de2 100644
--- a/saleor/checkout/actions.py
+++ b/saleor/checkout/actions.py
@@ -20,7 +20,10 @@ from .fetch import (
fetch_checkout_lines,
)
from .models import Checkout
-from .payment_utils import update_refundable_for_checkout
+from .payment_utils import (
+ update_checkout_payment_statuses,
+ update_refundable_for_checkout,
+)
if TYPE_CHECKING:
from ..account.models import Address, User
@@ -206,8 +209,6 @@ def transaction_amounts_for_checkout_updated(
user: Optional["User"],
app: Optional["App"],
):
- from .tasks import automatic_checkout_completion_task
-
if not transaction.checkout_id:
return
checkout = cast(Checkout, transaction.checkout)
@@ -216,6 +217,63 @@ def transaction_amounts_for_checkout_updated(
previous_charge_status = checkout_info.checkout.charge_status
previous_authorize_status = checkout_info.checkout.authorize_status
fetch_checkout_data(checkout_info, manager, lines, force_status_update=True)
+ _transaction_amounts_for_checkout_updated(
+ transaction,
+ previous_charge_status,
+ previous_authorize_status,
+ checkout_info,
+ lines,
+ manager,
+ user,
+ app,
+ )
+
+
+def transaction_amounts_for_checkout_updated_without_price_recalculation(
+ transaction: TransactionItem,
+ checkout: Checkout,
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: Optional["App"],
+):
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, manager)
+ previous_charge_status = checkout_info.checkout.charge_status
+ previous_authorize_status = checkout_info.checkout.authorize_status
+
+ current_total_gross = checkout_info.checkout.total.gross
+ update_checkout_payment_statuses(
+ checkout=checkout_info.checkout,
+ checkout_total_gross=current_total_gross,
+ checkout_has_lines=bool(lines),
+ )
+
+ _transaction_amounts_for_checkout_updated(
+ transaction,
+ previous_charge_status,
+ previous_authorize_status,
+ checkout_info,
+ lines,
+ manager,
+ user,
+ app,
+ )
+
+
+def _transaction_amounts_for_checkout_updated(
+ transaction: TransactionItem,
+ previous_charge_status: str,
+ previous_authorize_status: str,
+ checkout_info: CheckoutInfo,
+ lines: list[CheckoutLineInfo],
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: Optional["App"],
+):
+ from .tasks import automatic_checkout_completion_task
+
+ checkout = checkout_info.checkout
+
previous_charge_status_is_fully_paid = previous_charge_status in [
CheckoutChargeStatus.FULL,
CheckoutChargeStatus.OVERCHARGED,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 226ac1d1e7..8c1b09fe50 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
import graphene
@@ -5,7 +6,10 @@ from django.core.exceptions import ValidationError
from django.utils import timezone
from .....app.models import App
-from .....checkout.actions import transaction_amounts_for_checkout_updated
+from .....checkout.actions import (
+ transaction_amounts_for_checkout_updated_without_price_recalculation,
+)
+from .....checkout.models import Checkout
from .....core.exceptions import PermissionDenied
from .....core.prices import quantize_price
from .....core.tracing import traced_atomic_transaction
@@ -49,6 +53,7 @@ from ...utils import check_if_requestor_has_access
from .utils import get_transaction_item
if TYPE_CHECKING:
+ from .....accounts.models import User
from .....plugins.manager import PluginsManager
@@ -272,6 +277,88 @@ class TransactionEventReport(DeprecatedModelMutation):
) from e
return quantize_price(amount, currency)
+ @classmethod
+ def process_order_with_transaction(
+ cls,
+ transaction: payment_models.TransactionItem,
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: App | None,
+ previous_authorized_value: Decimal,
+ previous_charged_value: Decimal,
+ previous_refunded_value: Decimal,
+ related_granted_refund: order_models.OrderGrantedRefund | None,
+ ):
+ order = cast(order_models.Order, transaction.order)
+ with traced_atomic_transaction():
+ order = (
+ order_models.Order.objects.prefetch_related(
+ "payments", "payment_transactions", "granted_refunds"
+ )
+ .select_for_update()
+ .get(pk=order.pk)
+ )
+ transaction = payment_models.TransactionItem.objects.select_for_update(
+ of=("self",)
+ ).get(pk=transaction.pk)
+ updates_amounts_for_order(order)
+ update_order_search_vector(order)
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
+ )
+ if related_granted_refund:
+ calculate_order_granted_refund_status(related_granted_refund)
+
+ @classmethod
+ def process_order_or_checkout_with_transaction(
+ cls,
+ transaction: payment_models.TransactionItem,
+ manager: "PluginsManager",
+ user: Optional["User"],
+ app: App | None,
+ previous_authorized_value: Decimal,
+ previous_charged_value: Decimal,
+ previous_refunded_value: Decimal,
+ related_granted_refund: order_models.OrderGrantedRefund | None,
+ ):
+ checkout_deleted = False
+ if transaction.checkout_id:
+ with traced_atomic_transaction():
+ locked_checkout = (
+ Checkout.objects.select_for_update()
+ .filter(pk=transaction.checkout_id)
+ .first()
+ )
+ transaction = payment_models.TransactionItem.objects.select_for_update(
+ of=("self",)
+ ).get(pk=transaction.pk)
+ if transaction.checkout_id and locked_checkout:
+ transaction_amounts_for_checkout_updated_without_price_recalculation(
+ transaction, locked_checkout, manager, user, app
+ )
+ else:
+ checkout_deleted = True
+ # If the checkout was deleted, we still want to update the order associated with the transaction.
+ if transaction.order_id or checkout_deleted:
+ cls.process_order_with_transaction(
+ transaction,
+ manager,
+ user,
+ app,
+ previous_authorized_value,
+ previous_charged_value,
+ previous_refunded_value,
+ related_granted_refund,
+ )
+
@classmethod
def perform_mutation( # type: ignore[override]
cls,
@@ -418,38 +505,16 @@ class TransactionEventReport(DeprecatedModelMutation):
metadata=transaction_metadata,
private_metadata=transaction_private_metadata,
)
- if transaction.order_id:
- order = cast(order_models.Order, transaction.order)
- update_order_search_vector(order, save=False)
- updates_amounts_for_order(order, save=False)
- order.save(
- update_fields=[
- "total_charged_amount",
- "charge_status",
- "updated_at",
- "total_authorized_amount",
- "authorize_status",
- "search_vector",
- ]
- )
- order_info = fetch_order_info(order)
- order_transaction_updated(
- order_info=order_info,
- transaction_item=transaction,
- manager=manager,
- user=user,
- app=app,
- previous_authorized_value=previous_authorized_value,
- previous_charged_value=previous_charged_value,
- previous_refunded_value=previous_refunded_value,
- )
- if related_granted_refund:
- calculate_order_granted_refund_status(related_granted_refund)
- if transaction.checkout_id:
- manager = get_plugin_manager_promise(info.context).get()
- transaction_amounts_for_checkout_updated(
- transaction, manager, user, app
- )
+ cls.process_order_or_checkout_with_transaction(
+ transaction,
+ manager,
+ user,
+ app,
+ previous_authorized_value,
+ previous_charged_value,
+ previous_refunded_value,
+ related_granted_refund,
+ )
elif available_actions is not None and set(
transaction.available_actions
) != set(available_actions):
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index 1e6dfb43c7..b98babb654 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -5,11 +5,14 @@ from uuid import uuid4
import graphene
import pytest
+from django.db import transaction as database_transaction
from django.utils import timezone
from freezegun import freeze_time
+from psycopg.errors import QueryCanceled
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
+from .....checkout.complete_checkout import create_order_from_checkout
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....order import OrderEvents, OrderGrantedRefundStatus, OrderStatus
@@ -17,6 +20,7 @@ from .....order.models import Order
from .....payment import OPTIONAL_AMOUNT_EVENTS, TransactionEventType
from .....payment.models import TransactionEvent
from .....payment.transaction_item_calculations import recalculate_transaction_amounts
+from .....tests import race_condition
from ....core.enums import TransactionEventReportErrorCode
from ....core.utils import to_global_id_or_none
from ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum
@@ -1237,9 +1241,16 @@ def test_transaction_event_updates_checkout_payment_statuses(
app_api_client,
permission_manage_payments,
checkout_with_items,
+ plugins_manager,
):
# given
checkout = checkout_with_items
+
+ # Fetch checkout lines and info to recalculate checkout total prices
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ fetch_checkout_data(checkout_info, plugins_manager, lines)
+
current_charged_value = Decimal("20")
psp_reference = "111-abc"
amount = Decimal("11.00")
@@ -3304,3 +3315,226 @@ def test_transaction_event_report_empty_message(
assert event.app == app_api_client.app
assert event.user is None
assert event.message == ""
+
+
+# transaction=True is required to ensure that the order is locked without it second context will not
+# be able to trying to acquire a lock on the order.
[email protected]_db(transaction=True)
+def test_lock_order_during_updating_order_amounts(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ psp_reference = "111-abc"
+ amount = order.total.gross.amount
+ transaction = transaction_item_generator(
+ app=app_api_client.app,
+ order_id=order.pk,
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+
+ # when & then
+ def check_if_order_is_locked(*args, **kwargs):
+ # This function will be called when the order amounts are being updated
+ # We will try to acquire a lock on the order row to check if it's locked.
+ cxn = database_transaction.get_connection()
+ new_cxn = cxn.get_new_connection(cxn.get_connection_params())
+ with new_cxn.cursor() as cursor:
+ cursor.execute("SET statement_timeout = 100")
+ with pytest.raises(QueryCanceled):
+ cursor.execute(
+ """
+ SELECT *
+ FROM "order_order"
+ WHERE "order_order"."id" = %s
+ FOR UPDATE
+ """,
+ [order.pk],
+ )
+
+ with race_condition.RunBefore(
+ "saleor.order.utils.update_order_charge_data",
+ check_if_order_is_locked,
+ ):
+ app_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_payments],
+ check_no_permissions=False,
+ )
+
+
+# transaction=True is required to ensure that the order is locked without it second context will not
+# be able to trying to acquire a lock on the order.
[email protected]_db(transaction=True)
+def test_lock_checkout_during_updating_checkout_amounts(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+
+ # when & then
+ def check_if_checkout_is_locked(*args, **kwargs):
+ # This function will be called when the order amounts are being updated
+ # We will try to acquire a lock on the order row to check if it's locked.
+ cxn = database_transaction.get_connection()
+ new_cxn = cxn.get_new_connection(cxn.get_connection_params())
+ with new_cxn.cursor() as cursor:
+ cursor.execute("SET statement_timeout = 100")
+ with pytest.raises(QueryCanceled):
+ cursor.execute(
+ """
+ SELECT *
+ FROM "checkout_checkout"
+ WHERE "checkout_checkout"."token" = %s
+ FOR UPDATE
+ """,
+ [checkout.pk],
+ )
+
+ with race_condition.RunBefore(
+ "saleor.graphql.payment.mutations.transaction."
+ "transaction_event_report.transaction_amounts_for_checkout_updated_without_price_recalculation",
+ check_if_checkout_is_locked,
+ ):
+ app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+
+def test_transaction_event_report_checkout_completed_race_condition(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ checkout_with_items,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_items
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)
+ checkout_info, _ = fetch_checkout_data(checkout_info, plugins_manager, lines)
+
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(
+ app=app_api_client.app, checkout_id=checkout.pk
+ )
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": checkout_info.checkout.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+
+ # when
+ def complete_checkout(*args, **kwargs):
+ create_order_from_checkout(
+ checkout_info, plugins_manager, user=None, app=app_api_client.app
+ )
+
+ with race_condition.RunBefore(
+ "saleor.graphql.payment.mutations.transaction.transaction_event_report.recalculate_transaction_amounts",
+ complete_checkout,
+ ):
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order = Order.objects.get(checkout_token=checkout.pk)
+
+ assert order.status == OrderStatus.UNFULFILLED
+ assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ assert order.total_charged.amount == checkout.total.gross.amount