Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Optimize writer/replica usages in Celery tasks (#16038)
Marcin Gębala1c7bf861542d
diff --git a/saleor/attribute/tasks.py b/saleor/attribute/tasks.pydeleted file mode 100644index 6cd2781927..0000000000--- a/saleor/attribute/tasks.py+++ /dev/null@@ -1,31 +0,0 @@-from celery.utils.log import get_task_logger-from django.db.models import Exists, OuterRef, Q--from ..attribute.models import AttributeValue-from ..celeryconf import app-from ..product.models import Product, ProductVariant--task_logger = get_task_logger(__name__)---def update_associated_products_search_vector(attribute_value_pk: int):- try:- instance = AttributeValue.objects.get(pk=attribute_value_pk)- except AttributeValue.DoesNotExist:- task_logger.warning(- (- "Could not perform search_vector update on associated products as "- 'AttributeValue with pk "%s" does not exists.'- ),- attribute_value_pk,- )- return-- variants = ProductVariant.objects.filter(- Exists(instance.variantassignments.filter(variant_id=OuterRef("id")))- )- Product.objects.filter(- Q(Exists(instance.productvalueassignment.filter(product_id=OuterRef("id"))))- | Q(Exists(variants.filter(product_id=OuterRef("id"))))- ).update(search_index_dirty=True)diff --git a/saleor/core/db/connection.py b/saleor/core/db/connection.pyindex e359caa687..3b29eebd37 100644--- a/saleor/core/db/connection.py+++ b/saleor/core/db/connection.py@@ -127,5 +127,5 @@ def _log_writer_usage(execute, sql, params, many, context):f"{error_msg} SQL: {sql} \n"f"Traceback: \n{''.join(traceback.format_list(stack_trace))}")- logger.error(log_msg)+ logger.warning(log_msg)return execute(sql, params, many, context)diff --git a/saleor/core/tasks.py b/saleor/core/tasks.pyindex 16d60a842b..7a323681c6 100644--- a/saleor/core/tasks.py+++ b/saleor/core/tasks.py@@ -1,6 +1,5 @@import logging-from botocore.exceptions import ClientErrorfrom celery.utils.log import get_task_loggerfrom django.conf import settingsfrom django.core.files.storage import default_storage@@ -44,16 +43,6 @@ def delete_event_payloads_task(expiration_date=None):task_logger.error("Task invocation time limit reached, aborting task")- autoretry_for=(ClientError,),- retry_backoff=10,- retry_kwargs={"max_retries": 5},-)-def delete_product_media_task(media_id):- # TODO: to delete- pass--@app.taskdef delete_files_from_storage_task(paths):for path in paths:diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 3c8e93ef2d..9591fb4ca5 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -4,6 +4,7 @@ from tempfile import NamedTemporaryFilefrom typing import IO, TYPE_CHECKING, Any, Optional, Unionimport petl as etl+from django.conf import settingsfrom django.utils import timezonefrom ...discount.models import VoucherCode@@ -99,11 +100,15 @@ def export_voucher_codes():file_name = get_filename("voucher_code", file_type)- qs = VoucherCode.objects.all()+ qs = VoucherCode.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).all()if voucher_id:- qs = VoucherCode.objects.filter(voucher_id=voucher_id)+ qs = VoucherCode.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(voucher_id=voucher_id)if ids:- qs = VoucherCode.objects.filter(id__in=ids)+ qs = VoucherCode.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(id__in=ids)export_fields = ["code"]temporary_file = create_file_with_headers(export_fields, delimiter, file_type)@@ -129,9 +134,11 @@ def get_filename(model_name: str, file_type: str) -> str:def get_queryset(model, filter, scope: dict[str, Union[str, dict]]) -> "QuerySet":- queryset = model.objects.all()+ queryset = model.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).all()if "ids" in scope:- queryset = model.objects.filter(pk__in=scope["ids"])+ queryset = model.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(pk__in=scope["ids"])elif "filter" in scope:queryset = filter(data=parse_input(scope["filter"]), queryset=queryset).qs@@ -196,13 +203,17 @@ def export_products_in_batches(channels = export_info.get("channels")for batch_pks in queryset_in_batches(queryset):- product_batch = Product.objects.filter(pk__in=batch_pks).prefetch_related(- "attributevalues",- "variants",- "collections",- "media",- "product_type",- "category",+ product_batch = (+ Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(pk__in=batch_pks)+ .prefetch_related(+ "attributevalues",+ "variants",+ "collections",+ "media",+ "product_type",+ "category",+ ))export_data = get_products_data(@@ -220,7 +231,9 @@ def export_gift_cards_in_batches(file_type: str,):for batch_pks in queryset_in_batches(queryset):- gift_card_batch = GiftCard.objects.filter(pk__in=batch_pks)+ gift_card_batch = GiftCard.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(pk__in=batch_pks)export_data = list(gift_card_batch.values(*export_fields))@@ -235,7 +248,9 @@ def export_voucher_codes_in_batches(file_type: str,):for batch_pks in queryset_in_batches(queryset):- voucher_codes_batch = VoucherCode.objects.filter(pk__in=batch_pks)+ voucher_codes_batch = VoucherCode.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(pk__in=batch_pks)export_data = list(voucher_codes_batch.values(*export_fields))diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.pyindex 77592f0147..b97e380406 100644--- a/saleor/csv/utils/product_headers.py+++ b/saleor/csv/utils/product_headers.py@@ -1,5 +1,6 @@from collections import ChainMap+from django.conf import settingsfrom django.db.models import Value as Vfrom django.db.models.functions import Concat@@ -70,17 +71,23 @@ def get_attributes_headers(export_info: dict[str, list]) -> list[str]:if not attribute_ids:return []- attributes = Attribute.objects.filter(pk__in=attribute_ids).order_by("slug")+ attributes = (+ Attribute.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(pk__in=attribute_ids)+ .order_by("slug")+ )products_headers = (- attributes.filter(product_types__isnull=False)+ attributes.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(product_types__isnull=False).distinct().annotate(header=Concat("slug", V(" (product attribute)"))).values_list("header", flat=True))variant_headers = (- attributes.filter(product_variant_types__isnull=False)+ attributes.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(product_variant_types__isnull=False).distinct().annotate(header=Concat("slug", V(" (variant attribute)"))).values_list("header", flat=True)@@ -99,7 +106,8 @@ def get_warehouses_headers(export_info: dict[str, list]) -> list[str]:return []warehouses_headers = (- Warehouse.objects.filter(pk__in=warehouse_ids)+ Warehouse.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(pk__in=warehouse_ids).order_by("slug").annotate(header=Concat("slug", V(" (warehouse quantity)"))).values_list("header", flat=True)@@ -124,7 +132,8 @@ def get_channels_headers(export_info: dict[str, list]) -> list[str]:return []channels_slugs = (- Channel.objects.filter(pk__in=channel_ids)+ Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(pk__in=channel_ids).order_by("slug").values_list("slug", flat=True))diff --git a/saleor/giftcard/tasks.py b/saleor/giftcard/tasks.pyindex 7d52d691c2..59b9b1e7b2 100644--- a/saleor/giftcard/tasks.py+++ b/saleor/giftcard/tasks.py@@ -28,7 +28,9 @@ def deactivate_expired_cards_task():expires=settings.BEAT_UPDATE_SEARCH_EXPIRE_AFTER_SEC,)def update_gift_cards_search_vector_task():- gift_cards = GiftCard.objects.filter(search_index_dirty=True)+ gift_cards = GiftCard.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(search_index_dirty=True)if not gift_cards:returngift_cards_batch = list(gift_cards[:GIFT_CARD_BATCH_SIZE])diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.pyindex 6bac0d3b23..1e0363f54e 100644--- a/saleor/graphql/discount/utils.py+++ b/saleor/graphql/discount/utils.py@@ -4,6 +4,7 @@ from enum import Enumfrom typing import Any, Optional, Union, castimport graphene+from django.conf import settingsfrom django.db.models import Exists, OuterRef, QuerySetfrom graphene.utils.str_converters import to_snake_case@@ -167,12 +168,14 @@ PREDICATE_TO_HANDLE_METHOD = {def get_variants_for_catalogue_predicate(- predicate, queryset: Optional[ProductVariantQueryset] = None+ predicate,+ queryset: Optional[ProductVariantQueryset] = None,+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):if not predicate:return ProductVariant.objects.none()if queryset is None:- queryset = ProductVariant.objects.all()+ queryset = ProductVariant.objects.using(database_connection_name).all()return filter_qs_by_predicate(predicate, queryset, PredicateObjectType.CATALOGUE)diff --git a/saleor/order/tasks.py b/saleor/order/tasks.pyindex 8bb96a70e2..387ad8f40b 100644--- a/saleor/order/tasks.py+++ b/saleor/order/tasks.py@@ -1,6 +1,7 @@import loggingfrom datetime import timedelta+from django.conf import settingsfrom django.db.models import Exists, F, Func, OuterRef, Subquery, Valuefrom django.utils import timezone@@ -12,6 +13,8 @@ from ..discount.models import Voucher, VoucherCode, VoucherCustomerfrom ..payment.models import Payment, TransactionItemfrom ..plugins.manager import get_plugins_managerfrom ..warehouse.management import deallocate_stock_for_orders+from ..webhook.event_types import WebhookEventAsyncType+from ..webhook.utils import get_webhooks_for_eventfrom . import OrderEvents, OrderStatusfrom .models import Order, OrderEventfrom .utils import invalidate_order_prices@@ -71,10 +74,16 @@ def _bulk_release_voucher_usage(order_ids):def _call_expired_order_events(order_ids, manager):- orders = Order.objects.filter(id__in=order_ids)+ orders = (+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(id__in=order_ids)+ .select_related("channel")+ )+ webhooks_order_expired = get_webhooks_for_event(WebhookEventAsyncType.ORDER_EXPIRED)+ webhooks_order_updated = get_webhooks_for_event(WebhookEventAsyncType.ORDER_UPDATED)for order in orders:- call_event(manager.order_expired, order)- call_event(manager.order_updated, order)+ call_event(manager.order_expired, order, webhooks=webhooks_order_expired)+ call_event(manager.order_updated, order, webhooks=webhooks_order_updated)def _order_expired_events(order_ids):@@ -94,20 +103,20 @@ def _expire_orders(manager, now):Func(Value("day"), now - OuterRef("created_at"), function="DATE_PART") * 24+ Func(Value("hour"), now - OuterRef("created_at"), function="DATE_PART") * 60) + Func(Value("minute"), now - OuterRef("created_at"), function="DATE_PART")-- channels = Channel.objects.filter(+ channels = Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(id=OuterRef("channel"),expire_orders_after__isnull=False,expire_orders_after__gt=0,expire_orders_after__lte=time_diff_func_in_minutes,)- qs = Order.objects.filter(+ qs = Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(~Exists(TransactionItem.objects.filter(order=OuterRef("pk"))),~Exists(Payment.objects.filter(order=OuterRef("pk"))),Exists(channels),status=OrderStatus.UNCONFIRMED,)+ids_batch = list(qs.values_list("pk", flat=True)[:EXPIRE_ORDER_BATCH_SIZE])with traced_atomic_transaction():Order.objects.filter(id__in=ids_batch).update(@@ -122,7 +131,7 @@ def _expire_orders(manager, now):@app.taskdef expire_orders_task():now = timezone.now()- manager = get_plugins_manager(allow_replica=False)+ manager = get_plugins_manager(allow_replica=True)_expire_orders(manager, now)@@ -130,24 +139,35 @@ def expire_orders_task():def delete_expired_orders_task():now = timezone.now()- channel_qs = Channel.objects.filter(+ channel_qs = Channel.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(delete_expired_orders_after__gt=timedelta(),id=OuterRef("channel"),)- qs = Order.objects.annotate(- delete_expired_orders_after=Subquery(- channel_qs.values("delete_expired_orders_after")[:1]+ qs = (+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .annotate(+ delete_expired_orders_after=Subquery(+ channel_qs.values("delete_expired_orders_after")[:1]+ )+ )+ .filter(+ ~Exists(TransactionItem.objects.filter(order=OuterRef("pk"))),+ ~Exists(Payment.objects.filter(order=OuterRef("pk"))),+ expired_at__isnull=False,+ status=OrderStatus.EXPIRED,+ expired_at__lte=now - F("delete_expired_orders_after"), # type:ignore)- ).filter(- ~Exists(TransactionItem.objects.filter(order=OuterRef("pk"))),- ~Exists(Payment.objects.filter(order=OuterRef("pk"))),- expired_at__isnull=False,- status=OrderStatus.EXPIRED,- expired_at__lte=now - F("delete_expired_orders_after"), # type:ignore)ids_batch = qs.values_list("pk", flat=True)[:DELETE_EXPIRED_ORDER_BATCH_SIZE]if not ids_batch:return++ # Wrap ids_batch with a list as it comes from the replica DB and delete is done on+ # the writer DB. This avoids mixing querysets from different DBs.+ ids_batch = list(ids_batch)+Order.objects.filter(id__in=ids_batch).delete()delete_expired_orders_task.delay()diff --git a/saleor/payment/tasks.py b/saleor/payment/tasks.pyindex 5da816bec3..57e47524bd 100644--- a/saleor/payment/tasks.py+++ b/saleor/payment/tasks.py@@ -29,7 +29,7 @@ def checkouts_with_funds_to_release():datetime.now(pytz.UTC) - settings.CHECKOUT_TTL_BEFORE_RELEASING_FUNDS)- return Checkout.objects.filter(+ return Checkout.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(Q(automatically_refundable=True,last_change__lt=expired_checkouts_time,@@ -49,10 +49,16 @@ def transaction_release_funds_for_checkout_task():# Fetch checkouts that are ready to release fundscheckouts = checkouts_with_funds_to_release().order_by("last_change")- checkouts_data = checkouts.values_list("pk", "channel_id")[:CHECKOUT_BATCH_SIZE]+ checkouts_data = list(+ checkouts.values_list("pk", "channel_id")[:CHECKOUT_BATCH_SIZE]+ )checkout_pks = [pk for pk, _ in checkouts_data]checkout_channel_ids = [channel_id for _, channel_id in checkouts_data]- channel_map = Channel.objects.filter(id__in=checkout_channel_ids).in_bulk()+ channel_map = (+ Channel.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(id__in=checkout_channel_ids)+ .in_bulk()+ )if checkout_pks:transaction_events = TransactionEvent.objects.filter(transaction_id=OuterRef("pk"),@@ -64,7 +70,8 @@ def transaction_release_funds_for_checkout_task():# Annotate the last event for each transaction to exclude the transactions that# were already processedtransactions = (- TransactionItem.objects.select_related("app")+ TransactionItem.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .select_related("app").annotate(last_event_type=Subquery(transaction_events.values("type")[:1])).annotate(channel_id=Subquery(checkout_subquery.values("channel_id")[:1])).filter(@@ -111,7 +118,7 @@ def transaction_release_funds_for_checkout_task():[event for _tr, event in transactions_with_cancel_request_events]+ [event for _tr, event in transactions_with_charge_request_events])- manager = get_plugins_manager(allow_replica=False)+ manager = get_plugins_manager(allow_replica=True)for transaction, event in transactions_with_cancel_request_events:channel_slug = channel_map[transaction.channel_id].slugtry:diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex dfa8a2f690..94188d5b45 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1098,10 +1098,14 @@ class PluginsManager(PaymentInterface):webhooks=webhooks,)- def order_expired(self, order: "Order"):+ def order_expired(self, order: "Order", webhooks=None):default_value = Nonereturn self.__run_method_on_plugins(- "order_expired", default_value, order, channel_slug=order.channel.slug+ "order_expired",+ default_value,+ order,+ channel_slug=order.channel.slug,+ webhooks=webhooks,)def order_fulfilled(self, order: "Order"):diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 04b6d9c93a..a15a6e5551 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -923,11 +923,11 @@ class WebhookPlugin(BasePlugin):legacy_data_generator=order_data_generator,)- def order_expired(self, order: "Order", previous_value: Any) -> Any:+ def order_expired(self, order: "Order", previous_value: Any, webhooks=None) -> Any:if not self.active:return previous_valueevent_type = WebhookEventAsyncType.ORDER_EXPIRED- if webhooks := get_webhooks_for_event(event_type):+ if webhooks := self._get_webhooks_for_event(event_type, webhooks):order_data_generator = partial(generate_order_payload, order, self.requestor)diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pydeleted file mode 100644index 18a9d81c32..0000000000--- a/saleor/plugins/webhook/tasks.py+++ /dev/null@@ -1,52 +0,0 @@-import logging--from celery.utils.log import get_task_logger-from django.conf import settings--from ...celeryconf import app--logger = logging.getLogger(__name__)-task_logger = get_task_logger(__name__)---# all tasks to be removed in 3.18.-# tasks moved to different direction.--- queue=settings.WEBHOOK_CELERY_QUEUE_NAME,- bind=True,- retry_backoff=10,- retry_kwargs={"max_retries": 5},-)-def send_webhook_request_async(self, event_delivery_id):- from ...webhook.transport.asynchronous.transport import send_webhook_request_async-- send_webhook_request_async(self, event_delivery_id)---def observability_send_events():- from ...webhook.transport.asynchronous.transport import observability_send_events-- observability_send_events()---def observability_reporter_task():- from ...webhook.transport.asynchronous.transport import observability_reporter_task-- observability_reporter_task()--- bind=True,- retry_backoff=10,- retry_kwargs={"max_retries": 5},-)-def handle_transaction_request_task(self, delivery_id, request_event_id):- from ...webhook.transport.synchronous.transport import (- handle_transaction_request_task,- )-- handle_transaction_request_task(self, delivery_id, request_event_id)diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.pyindex ff78d73364..ae282cdf5d 100644--- a/saleor/plugins/webhook/tests/test_tasks.py+++ b/saleor/plugins/webhook/tests/test_tasks.py@@ -170,7 +170,9 @@ def test_trigger_transaction_request_with_webhook_subscription(@freeze_time("2022-06-11 12:50")[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")+ "saleor.webhook.transport.synchronous.transport.handle_transaction_request_task.delay"+)def test_trigger_transaction_request_missing_app_owner_updates_refundable_checkout(mocked_task,transaction_item_created_by_app,@@ -237,7 +239,9 @@ def test_trigger_transaction_request_missing_app_owner_updates_refundable_checko@freeze_time("2022-06-11 12:50")[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")+ "saleor.webhook.transport.synchronous.transport.handle_transaction_request_task.delay"+)def test_trigger_transaction_request_missing_webhook_updates_refundable_checkout(mocked_task,transaction_item_created_by_app,@@ -281,7 +285,9 @@ def test_trigger_transaction_request_missing_webhook_updates_refundable_checkout@freeze_time("2022-06-11 12:50")[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")+ "saleor.webhook.transport.synchronous.transport.handle_transaction_request_task.delay"+)def test_trigger_transaction_request_incorrect_subscription_updates_refundable_checkout(mocked_task,transaction_item_created_by_app,diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 86f6fd3e16..6513a82d2c 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -66,7 +66,9 @@ def _update_variants_names(instance: ProductType, saved_attributes: Iterable):if not attributes_changed:return- variants = ProductVariant.objects.filter(+ variants = ProductVariant.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(name="",product__in=instance.products.all(),product__product_type__variant_attributes__in=attributes_changed,@@ -83,11 +85,15 @@ def _update_variants_names(instance: ProductType, saved_attributes: Iterable):@app.taskdef update_variants_names(product_type_pk: int, saved_attributes_ids: list[int]):try:- instance = ProductType.objects.get(pk=product_type_pk)+ instance = ProductType.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).get(pk=product_type_pk)except ObjectDoesNotExist:logging.warning(f"Cannot find product type with id: {product_type_pk}.")return- saved_attributes = Attribute.objects.filter(pk__in=saved_attributes_ids)+ saved_attributes = Attribute.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter(pk__in=saved_attributes_ids)_update_variants_names(instance, saved_attributes)@@ -139,9 +145,8 @@ def _get_channel_to_products_map(rule_to_variant_list):def _get_existing_rule_variant_list(rules: QuerySet[PromotionRule]):PromotionRuleVariant = PromotionRule.variants.throughexisting_rules_variants = (- PromotionRuleVariant.objects.filter(- Exists(rules.filter(pk=OuterRef("promotionrule_id")))- )+ PromotionRuleVariant.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(Exists(rules.filter(pk=OuterRef("promotionrule_id")))).all().values_list("promotionrule_id",@@ -182,7 +187,10 @@ def update_variant_relations_for_active_promotion_rules_task():# in the promotion as dirtyexisting_variant_relation = _get_existing_rule_variant_list(rules)- new_rule_to_variant_list = fetch_variants_for_promotion_rules(rules=rules)+ new_rule_to_variant_list = fetch_variants_for_promotion_rules(+ rules=rules,+ database_connection_name=settings.DATABASE_CONNECTION_REPLICA_NAME,+ )channel_to_product_map = _get_channel_to_products_map(existing_variant_relation + new_rule_to_variant_list)@@ -252,7 +260,7 @@ def update_discounted_prices_task(product_ids: Iterable[int]):# FIXME: Should be removed in Saleor 3.21# in case triggering the task by old server worker, we will just mark the products- # as dirty. The recalculation will happen in the backgorund+ # as dirty. The recalculation will happen in the background.ProductChannelListing.objects.filter(product_id__in=product_ids).update(discounted_price_dirty=True)diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.pyindex c3e850b44a..f3d0f45d54 100644--- a/saleor/product/utils/variants.py+++ b/saleor/product/utils/variants.py@@ -1,6 +1,7 @@from collections.abc import Iterablefrom typing import TYPE_CHECKING, Optional+from django.conf import settingsfrom django.db.models import QuerySetfrom ...attribute import AttributeType@@ -54,13 +55,17 @@ def get_variant_selection_attributes(def fetch_variants_for_promotion_rules(rules: QuerySet[PromotionRule],+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):from ...graphql.discount.utils import get_variants_for_catalogue_predicatePromotionRuleVariant = PromotionRule.variants.throughnew_rules_variants = []for rule in rules.iterator():- variants = get_variants_for_catalogue_predicate(rule.catalogue_predicate)+ variants = get_variants_for_catalogue_predicate(+ rule.catalogue_predicate,+ database_connection_name=settings.DATABASE_CONNECTION_REPLICA_NAME,+ )new_rules_variants.extend([PromotionRuleVariant(