Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix race condition for order calculations (#18641)
Iga Karbowiak70957dcb61b9
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex bb12c8542c..a69f514750 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -108,7 +108,7 @@ class OrderLineUpdate() from einvalidate_order_prices(order)recalculate_order_weight(order)- order.save(update_fields=["should_refresh_prices", "weight"])+ order.save(update_fields=["should_refresh_prices", "weight", "updated_at"])call_event_by_order_status(order, manager)diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 9deb60ec38..f80c2940b2 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -47,6 +47,7 @@ from .fetch import (reattach_apply_once_per_order_voucher_info,)from .interface import OrderTaxedPricesData+from .lock_objects import order_qs_select_for_updatefrom .models import Order, OrderLinefrom .utils import (calculate_draft_order_line_price_expiration_date,@@ -111,38 +112,51 @@ def fetch_order_prices_if_expired()order.should_refresh_prices = False- with transaction.atomic(savepoint=False):- with allow_writer():- order.save(- update_fields=[- "subtotal_net_amount",- "subtotal_gross_amount",- "total_net_amount",- "total_gross_amount",- "undiscounted_total_net_amount",- "undiscounted_total_gross_amount",- "shipping_price_net_amount",- "shipping_price_gross_amount",- "base_shipping_price_amount",- "shipping_tax_rate",- "should_refresh_prices",- "tax_error",- ]- )- order.lines.bulk_update(- lines,- [- "unit_price_net_amount",- "unit_price_gross_amount",- "undiscounted_unit_price_net_amount",- "undiscounted_unit_price_gross_amount",- "total_price_net_amount",- "total_price_gross_amount",- "undiscounted_total_price_net_amount",- "undiscounted_total_price_gross_amount",- "tax_rate",- ],- )+ with allow_writer():+ with transaction.atomic(savepoint=False):+ try:+ locked_order = (+ order_qs_select_for_update().only("updated_at").get(id=order.id)+ )+ except Order.DoesNotExist:+ # Order was removed. Return data without saving.+ return order, lines++ # Check whether the order has been modified during the recalculation process by another process.+ # If so, we should skip saving. The same applies if the order has been removed. This is important+ # to avoid overwriting changes made by the other requests. Skipping the save function does not affect+ # the query response because it returns the adjusted order and line info objects.+ if locked_order.updated_at == order.updated_at:+ order.save(+ update_fields=[+ "subtotal_net_amount",+ "subtotal_gross_amount",+ "total_net_amount",+ "total_gross_amount",+ "undiscounted_total_net_amount",+ "undiscounted_total_gross_amount",+ "shipping_price_net_amount",+ "shipping_price_gross_amount",+ "base_shipping_price_amount",+ "shipping_tax_rate",+ "should_refresh_prices",+ "tax_error",+ ]+ )+ order.lines.bulk_update(+ lines,+ [+ "unit_price_net_amount",+ "unit_price_gross_amount",+ "undiscounted_unit_price_net_amount",+ "undiscounted_unit_price_gross_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ "undiscounted_total_price_net_amount",+ "undiscounted_total_price_gross_amount",+ "tax_rate",+ ],+ )return order, linesdiff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.pyindex cc87cb94bb..fa942ff1c7 100644--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py@@ -18,5 +18,5 @@ def test_fetch_order_prices(order.status = OrderStatus.UNCONFIRMED# when & then- with django_assert_num_queries(29):+ with django_assert_num_queries(30):fetch_order_prices_if_expired(order, plugins_manager, None, True)diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.pyindex 7b30cbd6ff..e238dfd842 100644--- a/saleor/order/tests/test_calculations.py+++ b/saleor/order/tests/test_calculations.py@@ -26,9 +26,11 @@ from ...plugins.tests.sample_plugins import PluginSamplefrom ...tax import TaxCalculationStrategyfrom ...tax.calculations.order import update_order_prices_with_flat_ratesfrom ...tax.utils import get_tax_calculation_strategy_for_order+from ...tests import race_conditionfrom .. import OrderStatus, calculationsfrom ..calculations import loggerfrom ..interface import OrderTaxedPricesData+from ..models import Order@pytest.fixture@@ -1859,3 +1861,104 @@ def test_fetch_order_prices_flat_rates_with_weighted_shipping_tax(assert order.shipping_tax_rate == expected_tax_rateassert order.shipping_tax_rate != shipping_rate / 100+++def test_fetch_order_prices_if_expired_order_removed_before_save(+ order_with_lines,+):+ # given+ order = order_with_lines+ currency = order.currency+ order.should_refresh_prices = True+ order.save(update_fields=["should_refresh_prices"])+ lines = list(order.lines.all())++ manager = get_plugins_manager(allow_replica=False)+ fetch_kwargs = {+ "order": order,+ "manager": manager,+ "lines": lines,+ "force_update": True,+ }++ # when+ def delete_order(*args, **kwargs):+ # Simulate order deletion during price calculation+ Order.objects.filter(pk=order.pk).delete()++ with race_condition.RunAfter(+ "saleor.order.calculations.calculate_taxes", delete_order+ ):+ result_order, result_lines = calculations.fetch_order_prices_if_expired(+ **fetch_kwargs+ )++ # then+ # Check if order was deleted+ with pytest.raises(Order.DoesNotExist):+ order.refresh_from_db()++ # Check if prices are recalculated and returned in objects+ # The function should still return valid price data even if save was skipped+ assert result_order.total is not None+ assert result_order.total > zero_taxed_money(currency)++ assert result_lines is not None+ for result_line in result_lines:+ assert result_line.total_price is not None+ assert result_line.total_price > zero_taxed_money(currency)+++def test_fetch_order_prices_if_expired_order_updated_during_price_recalculation(+ order_with_lines,+):+ # given+ order = order_with_lines+ currency = order.currency+ order.should_refresh_prices = True+ order.save(update_fields=["should_refresh_prices", "updated_at"])++ updated_at_before_recalculation = order.updated_at+ lines = list(order.lines.all())++ manager = get_plugins_manager(allow_replica=False)+ fetch_kwargs = {+ "order": order,+ "manager": manager,+ "lines": lines,+ "force_update": True,+ }+ expected_note = "Updated by another process"++ # when+ def modify_order(*args, **kwargs):+ order_to_modify = Order.objects.get(pk=order.pk)+ order_to_modify.customer_note = expected_note+ order_to_modify.save(update_fields=["customer_note", "updated_at"])++ with race_condition.RunAfter(+ "saleor.order.calculations.calculate_taxes", modify_order+ ):+ result_order, result_lines = calculations.fetch_order_prices_if_expired(+ **fetch_kwargs+ )++ # then+ # Check if prices are recalculated and returned in objects+ assert result_order.total is not None+ assert result_order.total > zero_taxed_money(currency)++ assert result_lines is not None+ for result_line in result_lines:+ assert result_line.total_price is not None+ assert result_line.total_price > zero_taxed_money(currency)++ # The result_lines should have original quantities since they were passed in before modification+ for line, result_line in zip(lines, result_lines, strict=True):+ assert result_line.quantity == line.quantity++ # Check if database contains updated order by other requests+ order.refresh_from_db()+ assert order.should_refresh_prices is True+ assert order.updated_at > updated_at_before_recalculation+ assert order.customer_note == expected_notediff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 20f4bc8d59..1ea20413ba 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -137,7 +137,7 @@ def invalidate_order_prices(order: Order, *, save: bool = False) -> None:order.should_refresh_prices = Trueif save:- order.save(update_fields=["should_refresh_prices"])+ order.save(update_fields=["should_refresh_prices", "updated_at"])def recalculate_order_weight(order: Order, *, save: bool = False):