Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add allow_writer usages in tasks (#16054)
Marcin Gębala751afe0ac495
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 9085b2f8bb..d81d6df5a7 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -17,6 +17,7 @@ from requests import HTTPError, Responsefrom .. import schema_versionfrom ..app.headers import AppHeaders, DeprecatedAppHeadersfrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom ..core.http_client import HTTPClientfrom ..core.utils import build_absolute_uri, get_domainfrom ..permission.enums import get_permission_names@@ -150,6 +151,7 @@ def _set_brand_data(brand_obj: Optional[Union[App, AppInstallation]], logo: File@app.task(bind=True, retry_backoff=2700, retry_kwargs={"max_retries": 5})+@allow_writer()def fetch_brand_data_task(self, brand_data: dict, *, app_installation_id=None, app_id=None):diff --git a/saleor/app/tasks.py b/saleor/app/tasks.pyindex 77b56c27fe..7ae0578753 100644--- a/saleor/app/tasks.py+++ b/saleor/app/tasks.py@@ -8,6 +8,7 @@ from requests import HTTPError, RequestExceptionfrom .. import celeryconffrom ..core import JobStatus+from ..core.db.connection import allow_writerfrom ..core.models import EventDelivery, EventDeliveryAttempt, EventPayloadfrom ..webhook.models import Webhookfrom .installation_utils import AppInstallationError, install_app@@ -17,6 +18,7 @@ logger = logging.getLogger(__name__)@celeryconf.app.task+@allow_writer()def install_app_task(job_id, activate=False):try:app_installation = AppInstallation.objects.get(id=job_id)@@ -76,6 +78,7 @@ def _raw_remove_deliveries(deliveries_ids):@celeryconf.app.task+@allow_writer()def remove_apps_task():app_delete_period = timezone.now() - settings.DELETE_APP_TTLapps = App.objects.filter(removed_at__lte=app_delete_period)@@ -106,9 +109,6 @@ def remove_apps_task():_raw_remove_deliveries(deliveries_ids)webhooks.delete()-AppToken.objects.filter(app_id=app.id).delete()-AppExtension.objects.filter(app_id=app.id).delete()-app.delete()diff --git a/saleor/celeryconf.py b/saleor/celeryconf.pyindex 796bb47112..7e83024081 100644--- a/saleor/celeryconf.py+++ b/saleor/celeryconf.py@@ -23,7 +23,7 @@ def setup_celery_logging(loglevel=None, **kwargs):os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings")-app = Celery("saleor")+app = Celery("saleor", task_cls="saleor.core.tasks:RestrictWriterDBTask")app.config_from_object("django.conf:settings", namespace="CELERY")app.autodiscover_tasks()diff --git a/saleor/checkout/migrations/tasks/saleor3_14.py b/saleor/checkout/migrations/tasks/saleor3_14.pyindex 1874a54c45..8f4ee10713 100644--- a/saleor/checkout/migrations/tasks/saleor3_14.py+++ b/saleor/checkout/migrations/tasks/saleor3_14.py@@ -2,6 +2,7 @@ from django.db import transactionfrom django.db.models.expressions import Exists, OuterRef, Qfrom ....celeryconf import app+from ....core.db.connection import allow_writerfrom ....payment.models import TransactionItemfrom ...models import Checkout@@ -11,6 +12,7 @@ BATCH_SIZE = 2000@app.task+@allow_writer()def update_transaction_modified_at_in_checkouts():checkouts_without_modified_at = Checkout.objects.filter(Exists(TransactionItem.objects.filter(checkout_id=OuterRef("pk"))),@@ -41,6 +43,7 @@ def update_transaction_modified_at_in_checkouts():@app.task+@allow_writer()def update_checkout_refundable():with_transactions = TransactionItem.objects.filter(Q(checkout_id=OuterRef("pk"))diff --git a/saleor/checkout/tasks.py b/saleor/checkout/tasks.pyindex df9aef7de0..2c125e2425 100644--- a/saleor/checkout/tasks.py+++ b/saleor/checkout/tasks.py@@ -7,6 +7,7 @@ from django.db.models import Exists, OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezonefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom ..payment.models import TransactionItemfrom .models import Checkout, CheckoutLine@@ -77,7 +78,9 @@ def delete_expired_checkouts())- qs: QuerySet[Checkout] = Checkout.objects.filter(+ qs: QuerySet[Checkout] = Checkout.objects.using(+ settings.DATABASE_CONNECTION_REPLICA_NAME+ ).filter((empty_checkouts | expired_anonymous_checkouts | expired_user_checkout)& ~Q(Exists(with_transactions)))@@ -86,7 +89,9 @@ def delete_expired_checkouts(total_deleted: int = 0has_more: bool = Truefor batch_number in range(batch_count):- deleted_count, _ = Checkout.objects.filter(pk__in=qs.values_list("pk")).delete()+ ids = list(qs.values_list("pk", flat=True))+ with allow_writer():+ deleted_count, _ = Checkout.objects.filter(pk__in=ids).delete()total_deleted += deleted_count# Stop deleting inactive checkouts if there was no match.diff --git a/saleor/core/db/connection.py b/saleor/core/db/connection.pyindex 3b29eebd37..2ea1db12fb 100644--- a/saleor/core/db/connection.py+++ b/saleor/core/db/connection.py@@ -25,15 +25,7 @@ UNSAFE_WRITER_ACCESS_MSG = ()-class UnsafeDBUsageError(Exception):- pass---class UnsafeWriterAccessError(UnsafeDBUsageError):- pass---class UnsafeReplicaUsageError(UnsafeDBUsageError):+class UnsafeWriterAccessError(Exception):pass@@ -87,14 +79,14 @@ def restrict_writer_middleware(get_response):"""def middleware(request):- with connections[writer].execute_wrapper(_restrict_writer):- with connections[replica].execute_wrapper(_restrict_writer):+ with connections[writer].execute_wrapper(restrict_writer):+ with connections[replica].execute_wrapper(restrict_writer):return get_response(request)return middleware-def _restrict_writer(execute, sql, params, many, context):+def restrict_writer(execute, sql, params, many, context):conn: BaseDatabaseWrapper = context["connection"]allow_writer = getattr(conn, "_allow_writer", False)if conn.alias == writer and not allow_writer:@@ -111,13 +103,13 @@ def log_writer_usage_middleware(get_response):"""def middleware(request):- with connections[writer].execute_wrapper(_log_writer_usage):+ with connections[writer].execute_wrapper(log_writer_usage):return get_response(request)return middleware-def _log_writer_usage(execute, sql, params, many, context):+def log_writer_usage(execute, sql, params, many, context):conn: BaseDatabaseWrapper = context["connection"]allow_writer = getattr(conn, "_allow_writer", False)if conn.alias == writer and not allow_writer:diff --git a/saleor/core/db/tests/test_connection.py b/saleor/core/db/tests/test_connection.pyindex 6137d3af64..916db89be3 100644--- a/saleor/core/db/tests/test_connection.py+++ b/saleor/core/db/tests/test_connection.py@@ -7,10 +7,10 @@ from ....graphql.context import SaleorContextfrom ....tests.models import Bookfrom ..connection import (UnsafeWriterAccessError,- _log_writer_usage,- _restrict_writer,allow_writer,allow_writer_in_context,+ log_writer_usage,+ restrict_writer,)@@ -65,14 +65,14 @@ def test_restrict_writer_raises_error(settings):connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]with pytest.raises(UnsafeWriterAccessError):- with connection.execute_wrapper(_restrict_writer):+ with connection.execute_wrapper(restrict_writer):Book.objects.first()def test_restrict_writer_in_allow_writer(settings):connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]- with connection.execute_wrapper(_restrict_writer):+ with connection.execute_wrapper(restrict_writer):with allow_writer():Book.objects.first()@@ -80,7 +80,7 @@ def test_restrict_writer_in_allow_writer(settings):def test_log_writer_usage(settings, caplog):connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]- with connection.execute_wrapper(_log_writer_usage):+ with connection.execute_wrapper(log_writer_usage):Book.objects.first()assert caplog.recordsdiff --git a/saleor/core/search_tasks.py b/saleor/core/search_tasks.pyindex 295b260cd6..6880c3cd66 100644--- a/saleor/core/search_tasks.py+++ b/saleor/core/search_tasks.py@@ -1,8 +1,10 @@from celery.utils.log import get_task_logger+from django.conf import settingsfrom ..account.models import Userfrom ..account.search import prepare_user_search_document_valuefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom ..order.models import Orderfrom ..order.search import prepare_order_search_vector_valuefrom ..product.models import Product@@ -24,7 +26,8 @@ BATCH_SIZE = 500@app.taskdef set_user_search_document_values(updated_count: int = 0) -> None:users = list(- User.objects.filter(search_document="")+ User.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(search_document="").prefetch_related("addresses").order_by("-id")[:BATCH_SIZE])@@ -33,9 +36,10 @@ def set_user_search_document_values(updated_count: int = 0) -> None:task_logger.info("No users to update.")return- updated_count += set_search_document_values(- users, prepare_user_search_document_value- )+ with allow_writer():+ updated_count += set_search_document_values(+ users, prepare_user_search_document_value+ )task_logger.info("Updated %d users", updated_count)@@ -51,7 +55,8 @@ def set_user_search_document_values(updated_count: int = 0) -> None:@app.taskdef set_order_search_document_values(updated_count: int = 0) -> None:orders = list(- Order.objects.filter(search_vector=None)+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(search_vector=None).prefetch_related("user","billing_address",@@ -67,7 +72,10 @@ def set_order_search_document_values(updated_count: int = 0) -> None:task_logger.info("No orders to update.")return- updated_count += set_search_vector_values(orders, prepare_order_search_vector_value)+ with allow_writer():+ updated_count += set_search_vector_values(+ orders, prepare_order_search_vector_value+ )task_logger.info("Updated %d orders", updated_count)@@ -83,7 +91,8 @@ def set_order_search_document_values(updated_count: int = 0) -> None:@app.taskdef set_product_search_document_values(updated_count: int = 0) -> None:products = list(- Product.objects.filter(search_vector=None)+ Product.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(search_vector=None).prefetch_related(*PRODUCT_FIELDS_TO_PREFETCH).order_by("-id")[:BATCH_SIZE])@@ -92,10 +101,11 @@ def set_product_search_document_values(updated_count: int = 0) -> None:task_logger.info("No products to update.")return- updated_count += set_search_vector_values(- products,- prepare_product_search_vector_value,- )+ with allow_writer():+ updated_count += set_search_vector_values(+ products,+ prepare_product_search_vector_value,+ )task_logger.info("Updated %d products", updated_count)diff --git a/saleor/core/tasks.py b/saleor/core/tasks.pyindex 7a323681c6..7a0736d9e8 100644--- a/saleor/core/tasks.py+++ b/saleor/core/tasks.py@@ -1,16 +1,55 @@import logging+from celery import Taskfrom celery.utils.log import get_task_loggerfrom django.conf import settingsfrom django.core.files.storage import default_storage+from django.db import connectionsfrom django.db.models import Exists, OuterReffrom django.utils import timezonefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom .models import EventDelivery, EventPayloadtask_logger: logging.Logger = get_task_logger(__name__)++class RestrictWriterDBTask(Task):+ """Celery task that checks usage of unrestricted queries to the writer database.++ A base class for Celery tasks that protects from inexplicit usages of DB queries+ to the writer DB. Depending on the `CELERY_RESTRICT_WRITER_METHOD` setting, the task+ will either log a warning (suitable for production) or raise an exception (suitable+ for tests).++ The `CELERY_RESTRICT_WRITER_METHOD` setting should point to one of the following:+ - `saleor.core.db.connection.log_writer_usage` - logs a warning+ - `saleor.core.db.connection.restrict_writer` - raises an exception+ """++ def __call__(self, *args, **kwargs):+ from django.utils.module_loading import import_string++ func_path = settings.CELERY_RESTRICT_WRITER_METHOD+ if not func_path:+ return++ try:+ wrapper_fun = import_string(func_path)+ except ImportError:+ task_logger.error(+ f"Could not import the function {func_path}. "+ f"Check if the path is correct."+ )+ return super().__call__(*args, **kwargs)++ with connections[settings.DATABASE_CONNECTION_DEFAULT_NAME].execute_wrapper(+ wrapper_fun+ ):+ return super().__call__(*args, **kwargs)++# Batch size was tested on db with 1mln payloads and deliveries, each delivery# had multiple attempts. One task took less than 0,5 second, memory usage didn't raise# more than 100 MB.@@ -30,14 +69,16 @@ def delete_event_payloads_task(expiration_date=None):)delete_period = timezone.now() - settings.EVENT_PAYLOAD_DELETE_PERIODvalid_deliveries = EventDelivery.objects.filter(created_at__gt=delete_period)- payloads_to_delete = EventPayload.objects.filter(- ~Exists(valid_deliveries.filter(payload_id=OuterRef("id")))- ).order_by("-pk")- ids = payloads_to_delete.values_list("pk", flat=True)[:BATCH_SIZE]- qs = EventPayload.objects.filter(pk__in=ids)+ payloads_to_delete = (+ EventPayload.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(~Exists(valid_deliveries.filter(payload_id=OuterRef("id"))))+ .order_by("-pk")+ )+ ids = list(payloads_to_delete.values_list("pk", flat=True)[:BATCH_SIZE])if ids:if expiration_date > timezone.now():- qs.delete()+ with allow_writer():+ EventPayload.objects.filter(pk__in=ids).delete()delete_event_payloads_task.delay(expiration_date)else:task_logger.error("Task invocation time limit reached, aborting task")diff --git a/saleor/csv/events.py b/saleor/csv/events.pyindex f866fd7557..524fdc770a 100644--- a/saleor/csv/events.py+++ b/saleor/csv/events.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Optional+from ..core.db.connection import allow_writerfrom . import ExportEventsfrom .models import ExportEvent@@ -9,6 +10,7 @@ if TYPE_CHECKING:from .models import ExportFile+@allow_writer()def export_started_event(*,export_file: "ExportFile",@@ -20,6 +22,7 @@ def export_started_event()+@allow_writer()def export_success_event(*,export_file: "ExportFile",@@ -31,6 +34,7 @@ def export_success_event()+@allow_writer()def export_failed_event(*,export_file: "ExportFile",@@ -48,6 +52,7 @@ def export_failed_event()+@allow_writer()def export_deleted_event(*,export_file: "ExportFile",@@ -59,6 +64,7 @@ def export_deleted_event()+@allow_writer()def export_file_sent_event(*, export_file_id: int, user_id: int) -> None:ExportEvent.objects.create(export_file_id=export_file_id,@@ -67,6 +73,7 @@ def export_file_sent_event(*, export_file_id: int, user_id: int) -> None:)+@allow_writer()def export_failed_info_sent_event(*, export_file_id: int, user_id: int) -> None:ExportEvent.objects.create(export_file_id=export_file_id,diff --git a/saleor/csv/tasks.py b/saleor/csv/tasks.pyindex 058867d228..0f48c39b12 100644--- a/saleor/csv/tasks.py+++ b/saleor/csv/tasks.py@@ -1,6 +1,5 @@from typing import Optional, Union-import celeryfrom celery.utils.log import get_task_loggerfrom django.conf import settingsfrom django.core.files.storage import default_storage@@ -10,6 +9,8 @@ from django.utils import timezonefrom ..celeryconf import appfrom ..core import JobStatus+from ..core.db.connection import allow_writer+from ..core.tasks import RestrictWriterDBTaskfrom . import eventsfrom .models import ExportEvent, ExportFilefrom .notifications import send_export_failed_info@@ -18,7 +19,7 @@ from .utils.export import export_gift_cards, export_products, export_voucher_codtask_logger = get_task_logger(__name__)-class ExportTask(celery.Task):+class ExportTask(RestrictWriterDBTask):# should be updated when new export task is addedTASK_NAME_TO_DATA_TYPE_MAPPING = {"export-products": "products",@@ -66,7 +67,12 @@ def export_products_task(file_type: str,delimiter: str = ",",):- export_file = ExportFile.objects.get(pk=export_file_id)+ with allow_writer():+ # Read the ExportFile instance from the writer instead of replica as it might+ # not be replicated yet.+ export_file = ExportFile.objects.select_related("app", "user").get(+ pk=export_file_id+ )export_products(export_file, scope, export_info, file_type, delimiter)@@ -77,7 +83,12 @@ def export_gift_cards_task(file_type: str,delimiter: str = ",",):- export_file = ExportFile.objects.get(pk=export_file_id)+ with allow_writer():+ # Read the ExportFile instance from the writer instead of replica as it might+ # not be replicated yet.+ export_file = ExportFile.objects.select_related("app", "user").get(+ pk=export_file_id+ )export_gift_cards(export_file, scope, file_type, delimiter)@@ -88,11 +99,17 @@ def export_voucher_codes_task(voucher_id: Optional[int],ids: list[int],):- export_file = ExportFile.objects.get(pk=export_file_id)+ with allow_writer():+ # Read the ExportFile instance from the writer instead of replica as it might+ # not be replicated yet.+ export_file = ExportFile.objects.select_related("app", "user").get(+ pk=export_file_id+ )export_voucher_codes(export_file, file_type, voucher_id, ids)@app.task+@allow_writer()def delete_old_export_files():now = timezone.now()diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 9591fb4ca5..ca303d552d 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -7,6 +7,7 @@ import petl as etlfrom django.conf import settingsfrom django.utils import timezone+from ...core.db.connection import allow_writerfrom ...discount.models import VoucherCodefrom ...giftcard.models import GiftCardfrom ...product.models import Product@@ -56,7 +57,6 @@ def export_products(save_csv_file_in_export_file(export_file, temporary_file, file_name)temporary_file.close()-send_export_download_link_notification(export_file, "products")@@ -87,7 +87,6 @@ def export_gift_cards(save_csv_file_in_export_file(export_file, temporary_file, file_name)temporary_file.close()-send_export_download_link_notification(export_file, "gift cards")@@ -291,6 +290,7 @@ def append_to_file(etl.io.xlsx.appendxlsx(table, temporary_file.name)+@allow_writer()def save_csv_file_in_export_file(export_file: "ExportFile", temporary_file: IO[bytes], file_name: str):diff --git a/saleor/discount/tasks.py b/saleor/discount/tasks.pyindex 41cef0b09a..1a6fcdeef1 100644--- a/saleor/discount/tasks.py+++ b/saleor/discount/tasks.py@@ -9,6 +9,7 @@ from django.conf import settingsfrom django.db.models import Exists, F, OuterRef, Q, QuerySetfrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom ..graphql.discount.utils import get_variants_for_catalogue_predicatefrom ..order import OrderStatusfrom ..order.models import Order, OrderLine@@ -45,6 +46,7 @@ PROMOTION_TOGGLE_BATCH_SIZE = 100@app.task+@allow_writer()def handle_promotion_toggle():"""Send the notification about promotion toggle and recalculate discounted prices.@@ -188,6 +190,7 @@ def fetch_promotion_variants_and_product_ids(promotions: "QuerySet[Promotion]"):@app.task+@allow_writer()def clear_promotion_rule_variants_task():"""Clear all promotion rule variants."""promotions = Promotion.objects.using(@@ -211,16 +214,23 @@ def clear_promotion_rule_variants_task():def decrease_voucher_code_usage_of_draft_orders(channel_id: int):- codes = Order.objects.filter(- channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False- ).values_list("voucher_code", flat=True)- voucher_code_ids = VoucherCode.objects.filter(code__in=codes).values_list(- "pk", flat=True+ codes = (+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(+ channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False+ )+ .values_list("voucher_code", flat=True)+ )+ voucher_code_ids = (+ VoucherCode.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(code__in=codes)+ .values_list("pk", flat=True))decrease_voucher_codes_usage_task.delay(list(voucher_code_ids))@app.task+@allow_writer()def decrease_voucher_codes_usage_task(voucher_code_ids):# Batch of size 1000 takes ~1sec and consumes ~20mb at peakBATCH_SIZE = 1000@@ -241,13 +251,18 @@ def decrease_voucher_codes_usage_task(voucher_code_ids):def disconnect_voucher_codes_from_draft_orders(channel_id: int):- order_ids = Order.objects.filter(- channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False- ).values_list("pk", flat=True)+ order_ids = (+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(+ channel_id=channel_id, status=OrderStatus.DRAFT, voucher_code__isnull=False+ )+ .values_list("pk", flat=True)+ )disconnect_voucher_codes_from_draft_orders_task.delay(list(order_ids))@app.task+@allow_writer()def disconnect_voucher_codes_from_draft_orders_task(order_ids):# Batch of size 1000 takes ~1sec and consumes ~20mb at peakBATCH_SIZE = 1000@@ -272,6 +287,7 @@ def disconnect_voucher_codes_from_draft_orders_task(order_ids):@app.task(name="saleor.discount.migrations.tasks.saleor3_17.update_discounted_prices_task")+@allow_writer()def update_discounted_prices_task():"""Recalculate discounted prices during sale to promotion migration."""# WARNING: this function is run during `0047_migrate_sales_to_promotions` migration,@@ -308,6 +324,7 @@ def update_discounted_prices_task():@app.task(name="saleor.discount.migrations.tasks.saleor3_17.set_promotion_rule_variants")+@allow_writer()def set_promotion_rule_variants_task(start_id=None):# WARNING: this function is run during `0067_fulfill_promotionrule_variants`# migration, be careful while updating.diff --git a/saleor/giftcard/search.py b/saleor/giftcard/search.pyindex 21bf3b13e9..b1c64974bd 100644--- a/saleor/giftcard/search.py+++ b/saleor/giftcard/search.py@@ -4,6 +4,7 @@ from django.contrib.postgres.search import SearchQueryfrom django.db.models import Q, QuerySet, Value, prefetch_related_objectsfrom ..account.models import User+from ..core.db.connection import allow_writerfrom ..core.postgres import FlatConcatSearchVector, NoValidationSearchVectorfrom .models import GiftCard@@ -50,6 +51,7 @@ def mark_gift_cards_search_index_as_dirty_by_users(users: list[User]):mark_gift_cards_search_index_as_dirty(gift_cards)+@allow_writer()def update_gift_cards_search_vector(gift_cards: list[GiftCard]):prefetch_related_objects(gift_cards, *GIFTCARD_FIELDS_TO_PREFETCH)for gift_card in gift_cards:diff --git a/saleor/giftcard/tasks.py b/saleor/giftcard/tasks.pyindex 59b9b1e7b2..e7b1a424e6 100644--- a/saleor/giftcard/tasks.py+++ b/saleor/giftcard/tasks.py@@ -3,6 +3,7 @@ from django.conf import settingsfrom django.utils import timezonefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom .events import gift_cards_deactivated_eventfrom .models import GiftCardfrom .search import update_gift_cards_search_vector@@ -12,6 +13,7 @@ GIFT_CARD_BATCH_SIZE = 300@app.task+@allow_writer()def deactivate_expired_cards_task():today = timezone.now().date()gift_cards = GiftCard.objects.filter(expiry_date__lt=today, is_active=True)diff --git a/saleor/giftcard/tests/test_tasks.py b/saleor/giftcard/tests/test_tasks.pyindex f18edbfc29..10b7188985 100644--- a/saleor/giftcard/tests/test_tasks.py+++ b/saleor/giftcard/tests/test_tasks.py@@ -5,7 +5,20 @@ from django.utils import timezonefrom .. import GiftCardEventsfrom ..models import GiftCard-from ..tasks import deactivate_expired_cards_task+from ..tasks import deactivate_expired_cards_task, update_gift_cards_search_vector_task+++def test_update_gift_cards_search_vector_task(gift_card):+ # given+ gift_card.search_index_dirty = True+ gift_card.save(update_fields=["search_index_dirty"])++ # when+ update_gift_cards_search_vector_task.delay()++ # then+ gift_card.refresh_from_db()+ assert not gift_card.search_index_dirtydef test_deactivate_expired_cards_task(diff --git a/saleor/order/tasks.py b/saleor/order/tasks.pyindex 4ee229c227..fc96a80908 100644--- a/saleor/order/tasks.py+++ b/saleor/order/tasks.py@@ -8,6 +8,7 @@ from django.utils import timezonefrom ..celeryconf import appfrom ..channel.models import Channel+from ..core.db.connection import allow_writerfrom ..core.tracing import traced_atomic_transactionfrom ..core.utils.events import call_eventfrom ..discount.models import Voucher, VoucherCode, VoucherCustomer@@ -31,6 +32,7 @@ DELETE_EXPIRED_ORDER_BATCH_SIZE = 5000@app.task+@allow_writer()def recalculate_orders_task(order_ids: list[int]):orders = Order.objects.filter(id__in=order_ids)@@ -41,6 +43,7 @@ def recalculate_orders_task(order_ids: list[int]):@app.task+@allow_writer()def send_order_updated(order_ids):manager = get_plugins_manager(allow_replica=True)for order in Order.objects.filter(id__in=order_ids):@@ -108,6 +111,7 @@ def _order_expired_events(order_ids):)+@allow_writer()def _expire_orders(manager, now):time_diff_func_in_minutes = (Func(Value("day"), now - OuterRef("created_at"), function="DATE_PART") * 24@@ -179,5 +183,7 @@ def delete_expired_orders_task():# the writer DB. This avoids mixing querysets from different DBs.ids_batch = list(ids_batch)- Order.objects.filter(id__in=ids_batch).delete()+ with allow_writer():+ Order.objects.filter(id__in=ids_batch).delete()+delete_expired_orders_task.delay()diff --git a/saleor/payment/migrations/tasks/saleor3_19.py b/saleor/payment/migrations/tasks/saleor3_19.pyindex 336618aaeb..fa7bb2f00b 100644--- a/saleor/payment/migrations/tasks/saleor3_19.py+++ b/saleor/payment/migrations/tasks/saleor3_19.py@@ -2,6 +2,7 @@ from django.db import transactionfrom django.db.models import Exists, OuterReffrom ....celeryconf import app+from ....core.db.connection import allow_writerfrom ... import ChargeStatusfrom ...models import Payment@@ -10,6 +11,7 @@ PAYMENT_BATCH_SIZE = 3000@app.task+@allow_writer()def fix_invalid_atobarai_payments_task():"""Fix the invalid payemnts for atobarai gateway.diff --git a/saleor/payment/tasks.py b/saleor/payment/tasks.pyindex 57e47524bd..6d665e9e2a 100644--- a/saleor/payment/tasks.py+++ b/saleor/payment/tasks.py@@ -10,6 +10,7 @@ from ..celeryconf import appfrom ..channel.models import Channelfrom ..checkout import CheckoutAuthorizeStatus, CheckoutChargeStatusfrom ..checkout.models import Checkout+from ..core.db.connection import allow_writerfrom ..payment.models import TransactionEvent, TransactionItemfrom ..plugins.manager import get_plugins_managerfrom . import PaymentError, TransactionAction, TransactionEventType@@ -43,6 +44,7 @@ def checkouts_with_funds_to_release():@app.task+@allow_writer()def transaction_release_funds_for_checkout_task():CHECKOUT_BATCH_SIZE = int(settings.CHECKOUT_BATCH_FOR_RELEASING_FUNDS)TRANSACTION_BATCH_SIZE = int(settings.TRANSACTION_BATCH_FOR_RELEASING_FUNDS)diff --git a/saleor/plugins/admin_email/tasks.py b/saleor/plugins/admin_email/tasks.pyindex d1d15b0d2b..af482b2bb5 100644--- a/saleor/plugins/admin_email/tasks.py+++ b/saleor/plugins/admin_email/tasks.py@@ -1,4 +1,5 @@from ...celeryconf import app+from ...core.db.connection import allow_writerfrom ...csv.events import export_failed_info_sent_event, export_file_sent_eventfrom ...graphql.core.utils import from_global_id_or_nonefrom ..email_common import EmailConfig, send_email@@ -30,10 +31,11 @@ def send_email_with_link_to_download_file_task(template_str=template,context=payload,)- export_file_sent_event(- export_file_id=from_global_id_or_none(payload["export"]["id"]),- user_id=from_global_id_or_none(payload["export"].get("user_id")),- )+ with allow_writer():+ export_file_sent_event(+ export_file_id=from_global_id_or_none(payload["export"]["id"]),+ user_id=from_global_id_or_none(payload["export"].get("user_id")),+ )@app.task(compression="zlib")@@ -48,10 +50,11 @@ def send_export_failed_email_task(template_str=template,context=payload,)- export_failed_info_sent_event(- export_file_id=from_global_id_or_none(payload["export"]["id"]),- user_id=from_global_id_or_none(payload["export"].get("user_id")),- )+ with allow_writer():+ export_failed_info_sent_event(+ export_file_id=from_global_id_or_none(payload["export"]["id"]),+ user_id=from_global_id_or_none(payload["export"].get("user_id")),+ )@app.task(compression="zlib")diff --git a/saleor/plugins/avatax/tasks.py b/saleor/plugins/avatax/tasks.pyindex 0228dc314f..c2c6e9729a 100644--- a/saleor/plugins/avatax/tasks.py+++ b/saleor/plugins/avatax/tasks.py@@ -1,8 +1,10 @@import opentracingimport opentracing.tagsfrom celery.utils.log import get_task_logger+from django.conf import settingsfrom ...celeryconf import app+from ...core.db.connection import allow_writerfrom ...core.taxes import TaxErrorfrom ...order.events import external_notification_eventfrom ...order.models import Order@@ -16,9 +18,14 @@ task_logger = get_task_logger(__name__)retry_backoff=60,retry_kwargs={"max_retries": 5},)+@allow_writer()def api_post_request_task(transaction_url, data, config, order_id):config = AvataxConfiguration(**config)- order = Order.objects.filter(id=order_id).first()+ order = (+ Order.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)+ .filter(id=order_id)+ .first()+ )if not order:task_logger.error("Unable to send the order %s to Avatax. Order doesn't exist.", order_iddiff --git a/saleor/plugins/sendgrid/tasks.py b/saleor/plugins/sendgrid/tasks.pyindex bc91e7fb54..21f1363e8f 100644--- a/saleor/plugins/sendgrid/tasks.py+++ b/saleor/plugins/sendgrid/tasks.py@@ -6,6 +6,7 @@ from sendgrid.helpers.mail import Mailfrom ...account import events as account_eventsfrom ...celeryconf import app+from ...core.db.connection import allow_writerfrom ...giftcard import events as gift_card_eventsfrom ...graphql.core.utils import from_global_id_or_nonefrom ...invoice import events as invoice_events@@ -62,7 +63,8 @@ def send_password_reset_email_task(payload: dict, configuration: dict):template_id=configuration.account_password_reset_template_id,payload=payload,)- account_events.customer_password_reset_link_sent_event(user_id=user_id)+ with allow_writer():+ account_events.customer_password_reset_link_sent_event(user_id=user_id)@app.task(@@ -79,13 +81,14 @@ def send_request_email_change_email_task(payload: dict, configuration: dict):template_id=configuration.account_change_email_request_template_id,payload=payload,)- account_events.customer_email_change_request_event(- user_id=from_global_id_or_none(user_id),- parameters={- "old_email": payload.get("old_email"),- "new_email": payload["recipient_email"],- },- )+ with allow_writer():+ account_events.customer_email_change_request_event(+ user_id=from_global_id_or_none(user_id),+ parameters={+ "old_email": payload.get("old_email"),+ "new_email": payload["recipient_email"],+ },+ )@app.task(@@ -106,10 +109,10 @@ def send_user_change_email_notification_task(payload: dict, configuration: dict)"old_email": payload["old_email"],"new_email": payload["new_email"],}-- account_events.customer_email_changed_event(- user_id=from_global_id_or_none(user_id), parameters=event_parameters- )+ with allow_writer():+ account_events.customer_email_changed_event(+ user_id=from_global_id_or_none(user_id), parameters=event_parameters+ )@app.task(@@ -156,18 +159,19 @@ def send_invoice_email_task(payload: dict, configuration: dict):template_id=configuration.invoice_ready_template_id,payload=payload,)- invoice_events.notification_invoice_sent_event(- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- invoice_id=from_global_id_or_none(payload["invoice"]["id"]),- customer_email=payload["recipient_email"],- )- order_events.event_invoice_sent_notification(- order_id=from_global_id_or_none(payload["invoice"]["order_id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- email=payload["recipient_email"],- )+ with allow_writer():+ invoice_events.notification_invoice_sent_event(+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ invoice_id=from_global_id_or_none(payload["invoice"]["id"]),+ customer_email=payload["recipient_email"],+ )+ order_events.event_invoice_sent_notification(+ order_id=from_global_id_or_none(payload["invoice"]["order_id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ email=payload["recipient_email"],+ )@app.task(@@ -184,11 +188,12 @@ def send_order_confirmation_email_task(payload: dict, configuration: dict):template_id=configuration.order_confirmation_template_id,payload=payload,)- order_events.event_order_confirmation_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["order"].get("user_id")),- customer_email=payload["recipient_email"],- )+ with allow_writer():+ order_events.event_order_confirmation_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["order"].get("user_id")),+ customer_email=payload["recipient_email"],+ )@app.task(@@ -204,21 +209,22 @@ def send_fulfillment_confirmation_email_task(payload: dict, configuration: dict)template_id=configuration.order_fulfillment_confirmation_template_id,payload=payload,)- order_events.event_fulfillment_confirmed_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=payload["recipient_email"],- )-- if payload.get("digital_lines"):- order_events.event_fulfillment_digital_links_notification(+ with allow_writer():+ order_events.event_fulfillment_confirmed_notification(order_id=from_global_id_or_none(payload["order"]["id"]),user_id=from_global_id_or_none(payload["requester_user_id"]),app_id=from_global_id_or_none(payload["requester_app_id"]),customer_email=payload["recipient_email"],)+ if payload.get("digital_lines"):+ order_events.event_fulfillment_digital_links_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=payload["recipient_email"],+ )+@app.task(autoretry_for=(SendGridException,),@@ -248,11 +254,12 @@ def send_payment_confirmation_email_task(payload: dict, configuration: dict):template_id=configuration.order_payment_confirmation_template_id,payload=payload,)- order_events.event_payment_confirmed_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["order"].get("user_id")),- customer_email=payload["recipient_email"],- )+ with allow_writer():+ order_events.event_payment_confirmed_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["order"].get("user_id")),+ customer_email=payload["recipient_email"],+ )@app.task(@@ -268,12 +275,13 @@ def send_order_canceled_email_task(payload: dict, configuration: dict):template_id=configuration.order_canceled_template_id,payload=payload,)- order_events.event_order_cancelled_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=payload["recipient_email"],- )+ with allow_writer():+ order_events.event_order_cancelled_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=payload["recipient_email"],+ )@app.task(@@ -289,12 +297,13 @@ def send_order_refund_email_task(payload: dict, configuration: dict):template_id=configuration.order_refund_confirmation_template_id,payload=payload,)- order_events.event_order_refunded_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=payload["recipient_email"],- )+ with allow_writer():+ order_events.event_order_refunded_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=payload["recipient_email"],+ )@app.task(@@ -316,10 +325,11 @@ def send_gift_card_email_task(payload: dict, configuration: dict):"app_id": from_global_id_or_none(payload["requester_app_id"]),"email": payload["recipient_email"],}- if payload["resending"] is True:- gift_card_events.gift_card_resent_event(**email_data)- else:- gift_card_events.gift_card_sent_event(**email_data)+ with allow_writer():+ if payload["resending"] is True:+ gift_card_events.gift_card_resent_event(**email_data)+ else:+ gift_card_events.gift_card_sent_event(**email_data)@app.task(@@ -335,12 +345,13 @@ def send_order_confirmed_email_task(payload: dict, configuration: dict):template_id=configuration.order_confirmed_template_id,payload=payload,)- order_events.event_order_confirmed_notification(- order_id=from_global_id_or_none(payload.get("order", {}).get("id")),- user_id=from_global_id_or_none(payload.get("requester_user_id")),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=payload["recipient_email"],- )+ with allow_writer():+ order_events.event_order_confirmed_notification(+ order_id=from_global_id_or_none(payload.get("order", {}).get("id")),+ user_id=from_global_id_or_none(payload.get("requester_user_id")),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=payload["recipient_email"],+ )@app.task(diff --git a/saleor/plugins/user_email/tasks.py b/saleor/plugins/user_email/tasks.pyindex 161906991d..b081351baa 100644--- a/saleor/plugins/user_email/tasks.py+++ b/saleor/plugins/user_email/tasks.py@@ -1,5 +1,6 @@from ...account import events as account_eventsfrom ...celeryconf import app+from ...core.db.connection import allow_writerfrom ...giftcard import events as gift_card_eventsfrom ...graphql.core.utils import from_global_id_or_nonefrom ...invoice import events as invoice_events@@ -34,9 +35,10 @@ def send_password_reset_email_task(recipient_email, payload, config, subject, tesubject=subject,template_str=template,)- account_events.customer_password_reset_link_sent_event(- user_id=from_global_id_or_none(user_id)- )+ with allow_writer():+ account_events.customer_password_reset_link_sent_event(+ user_id=from_global_id_or_none(user_id)+ )@app.task(compression="zlib")@@ -53,13 +55,14 @@ def send_request_email_change_email_task(subject=subject,template_str=template,)- account_events.customer_email_change_request_event(- user_id=from_global_id_or_none(user_id),- parameters={- "old_email": payload.get("old_email"),- "new_email": recipient_email,- },- )+ with allow_writer():+ account_events.customer_email_change_request_event(+ user_id=from_global_id_or_none(user_id),+ parameters={+ "old_email": payload.get("old_email"),+ "new_email": recipient_email,+ },+ )@app.task(compression="zlib")@@ -80,10 +83,10 @@ def send_user_change_email_notification_task("old_email": payload.get("old_email"),"new_email": payload.get("new_email"),}-- account_events.customer_email_changed_event(- user_id=from_global_id_or_none(user_id), parameters=event_parameters- )+ with allow_writer():+ account_events.customer_email_changed_event(+ user_id=from_global_id_or_none(user_id), parameters=event_parameters+ )@app.task(compression="zlib")@@ -91,7 +94,6 @@ def send_account_delete_confirmation_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -106,7 +108,6 @@ def send_set_user_password_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -119,7 +120,6 @@ def send_set_user_password_email_task(@app.task(compression="zlib")def send_gift_card_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -133,17 +133,17 @@ def send_gift_card_email_task(recipient_email, payload, config, subject, templat"app_id": from_global_id_or_none(payload["requester_app_id"]),"email": payload["recipient_email"],}- if payload["resending"] is True:- gift_card_events.gift_card_resent_event(**email_data)- else:- gift_card_events.gift_card_sent_event(**email_data)+ with allow_writer():+ if payload["resending"] is True:+ gift_card_events.gift_card_resent_event(**email_data)+ else:+ gift_card_events.gift_card_sent_event(**email_data)@app.task(compression="zlib")def send_invoice_email_task(recipient_email, payload, config, subject, template):"""Send an invoice to user of related order with URL to download it."""email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -151,18 +151,19 @@ def send_invoice_email_task(recipient_email, payload, config, subject, template)subject=subject,template_str=template,)- invoice_events.notification_invoice_sent_event(- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- invoice_id=from_global_id_or_none(payload["invoice"]["id"]),- customer_email=payload["recipient_email"],- )- order_events.event_invoice_sent_notification(- order_id=from_global_id_or_none(payload["invoice"]["order_id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- email=payload["recipient_email"],- )+ with allow_writer():+ invoice_events.notification_invoice_sent_event(+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ invoice_id=from_global_id_or_none(payload["invoice"]["id"]),+ customer_email=payload["recipient_email"],+ )+ order_events.event_invoice_sent_notification(+ order_id=from_global_id_or_none(payload["invoice"]["order_id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ email=payload["recipient_email"],+ )@app.task(compression="zlib")@@ -171,7 +172,6 @@ def send_order_confirmation_email_task():"""Send order confirmation email."""email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -179,11 +179,12 @@ def send_order_confirmation_email_task(subject=subject,template_str=template,)- order_events.event_order_confirmation_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["order"].get("user_id")),- customer_email=recipient_email,- )+ with allow_writer():+ order_events.event_order_confirmation_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["order"].get("user_id")),+ customer_email=recipient_email,+ )@app.task(compression="zlib")@@ -191,7 +192,6 @@ def send_fulfillment_confirmation_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -199,28 +199,28 @@ def send_fulfillment_confirmation_email_task(subject=subject,template_str=template,)- order_events.event_fulfillment_confirmed_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=recipient_email,- )-- if payload.get("digital_lines"):- order_events.event_fulfillment_digital_links_notification(+ with allow_writer():+ order_events.event_fulfillment_confirmed_notification(order_id=from_global_id_or_none(payload["order"]["id"]),user_id=from_global_id_or_none(payload["requester_user_id"]),app_id=from_global_id_or_none(payload["requester_app_id"]),customer_email=recipient_email,)+ if payload.get("digital_lines"):+ order_events.event_fulfillment_digital_links_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=recipient_email,+ )+@app.task(compression="zlib")def send_fulfillment_update_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -235,7 +235,6 @@ def send_payment_confirmation_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -243,17 +242,17 @@ def send_payment_confirmation_email_task(subject=subject,template_str=template,)- order_events.event_payment_confirmed_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["order"].get("user_id")),- customer_email=recipient_email,- )+ with allow_writer():+ order_events.event_payment_confirmed_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["order"].get("user_id")),+ customer_email=recipient_email,+ )@app.task(compression="zlib")def send_order_canceled_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -261,18 +260,18 @@ def send_order_canceled_email_task(recipient_email, payload, config, subject, tesubject=subject,template_str=template,)- order_events.event_order_cancelled_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=recipient_email,- )+ with allow_writer():+ order_events.event_order_cancelled_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=recipient_email,+ )@app.task(compression="zlib")def send_order_refund_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -280,12 +279,13 @@ def send_order_refund_email_task(recipient_email, payload, config, subject, tempsubject=subject,template_str=template,)- order_events.event_order_refunded_notification(- order_id=from_global_id_or_none(payload["order"]["id"]),- user_id=from_global_id_or_none(payload["requester_user_id"]),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=recipient_email,- )+ with allow_writer():+ order_events.event_order_refunded_notification(+ order_id=from_global_id_or_none(payload["order"]["id"]),+ user_id=from_global_id_or_none(payload["requester_user_id"]),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=recipient_email,+ )@app.task(compression="zlib")@@ -293,7 +293,6 @@ def send_order_confirmed_email_task(recipient_email, payload, config, subject, template):email_config = EmailConfig(**config)-send_email(config=email_config,recipient_list=[recipient_email],@@ -301,9 +300,10 @@ def send_order_confirmed_email_task(subject=subject,template_str=template,)- order_events.event_order_confirmed_notification(- order_id=from_global_id_or_none(payload.get("order", {}).get("id")),- user_id=from_global_id_or_none(payload.get("requester_user_id")),- app_id=from_global_id_or_none(payload["requester_app_id"]),- customer_email=recipient_email,- )+ with allow_writer():+ order_events.event_order_confirmed_notification(+ order_id=from_global_id_or_none(payload.get("order", {}).get("id")),+ user_id=from_global_id_or_none(payload.get("requester_user_id")),+ app_id=from_global_id_or_none(payload["requester_app_id"]),+ customer_email=recipient_email,+ )diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 42f38dd0c2..d8cf8c4824 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -13,6 +13,7 @@ from django.utils import timezonefrom ..attribute.models import Attributefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom ..core.exceptions import PreorderAllocationErrorfrom ..discount import PromotionTypefrom ..discount.models import Promotion, PromotionRule@@ -94,10 +95,12 @@ def update_variants_names(product_type_pk: int, saved_attributes_ids: list[int])saved_attributes = Attribute.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME).filter(pk__in=saved_attributes_ids)- _update_variants_names(instance, saved_attributes)+ with allow_writer():+ _update_variants_names(instance, saved_attributes)@app.task+@allow_writer()def update_products_discounted_prices_of_promotion_task(promotion_pk: UUID):# FIXME: Should be removed in Saleor 3.21@@ -160,6 +163,7 @@ def _get_existing_rule_variant_list(rules: QuerySet[PromotionRule]):@app.task+@allow_writer()def update_variant_relations_for_active_promotion_rules_task():promotions = (Promotion.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)@@ -210,6 +214,7 @@ def update_variant_relations_for_active_promotion_rules_task():@app.task+@allow_writer()def update_products_discounted_prices_for_promotion_task(product_ids: Iterable[int],start_id: Optional[UUID] = None,@@ -224,6 +229,7 @@ def update_products_discounted_prices_for_promotion_task(@app.task+@allow_writer()def recalculate_discounted_price_for_products_task():"""Recalculate discounted price for products."""listings = (@@ -256,6 +262,7 @@ def recalculate_discounted_price_for_products_task():@app.task+@allow_writer()def update_discounted_prices_task(product_ids: Iterable[int]):# FIXME: Should be removed in Saleor 3.21@@ -267,6 +274,7 @@ def update_discounted_prices_task(product_ids: Iterable[int]):@app.task+@allow_writer()def deactivate_preorder_for_variants_task():variants_to_clean = _get_preorder_variants_to_clean()@@ -294,10 +302,12 @@ def update_products_search_vector_task():.order_by("updated_at")[:PRODUCTS_BATCH_SIZE].values_list("id", flat=True))- update_products_search_vector(products)+ with allow_writer():+ update_products_search_vector(products)@app.task(queue=settings.COLLECTION_PRODUCT_UPDATED_QUEUE_NAME)+@allow_writer()def collection_product_updated_task(product_ids):manager = get_plugins_manager(allow_replica=True)products = list(diff --git a/saleor/settings.py b/saleor/settings.pyindex f0608c22db..201940222f 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -251,6 +251,9 @@ ENABLE_RESTRICT_WRITER_MIDDLEWARE = get_bool_from_env(if ENABLE_RESTRICT_WRITER_MIDDLEWARE:MIDDLEWARE = ["saleor.core.db.connection.log_writer_usage_middleware"] + MIDDLEWARE+# Restrict inexplicit writer DB usage in Celery tasks+CELERY_RESTRICT_WRITER_METHOD = "saleor.core.db.connection.log_writer_usage"+INSTALLED_APPS = [# External apps that need to go before django's"storages",diff --git a/saleor/shipping/tasks.py b/saleor/shipping/tasks.pyindex 6c4a7dcbb0..127b7b1ad0 100644--- a/saleor/shipping/tasks.py+++ b/saleor/shipping/tasks.py@@ -5,11 +5,13 @@ from django.utils import timezonefrom ..celeryconf import appfrom ..checkout.models import Checkout+from ..core.db.connection import allow_writerfrom ..order import ORDER_EDITABLE_STATUSfrom ..order.models import Order@app.task+@allow_writer()def drop_invalid_shipping_methods_relations_for_given_channels(shipping_method_ids: Iterable[Union[str, int]],channel_ids: Iterable[Union[str, int]],diff --git a/saleor/tests/settings.py b/saleor/tests/settings.pyindex 71e2cbcedc..99a07d5b0c 100644--- a/saleor/tests/settings.py+++ b/saleor/tests/settings.py@@ -100,3 +100,7 @@ MIDDLEWARE.insert(0, "saleor.core.db.connection.restrict_writer_middleware") #CHECKOUT_WEBHOOK_EVENTS_CELERY_QUEUE_NAME = "checkout_events_queue"ORDER_WEBHOOK_EVENTS_CELERY_QUEUE_NAME = "order_events_queue"++# Raise error when using writer DB in Celery tasks, without explicit "allow_writer"+# context manager.+CELERY_RESTRICT_WRITER_METHOD = "saleor.core.db.connection.restrict_writer"diff --git a/saleor/warehouse/tasks.py b/saleor/warehouse/tasks.pyindex bb38dee674..d7dd27b9cf 100644--- a/saleor/warehouse/tasks.py+++ b/saleor/warehouse/tasks.py@@ -4,12 +4,14 @@ from django.db.models.functions import Coalescefrom django.utils import timezonefrom ..celeryconf import app+from ..core.db.connection import allow_writerfrom .models import Allocation, PreorderReservation, Reservation, Stocktask_logger = get_task_logger(__name__)@app.task+@allow_writer()def delete_empty_allocations_task():count, _ = Allocation.objects.filter(quantity_allocated=0).delete()if count:@@ -17,6 +19,7 @@ def delete_empty_allocations_task():@app.task+@allow_writer()def delete_expired_reservations_task():stock_reservations, _ = Reservation.objects.filter(reserved_until__lt=timezone.now()@@ -34,6 +37,7 @@ def delete_expired_reservations_task():@app.task+@allow_writer()def update_stocks_quantity_allocated_task():stocks_to_update = []for mismatched_stock in Stock.objects.annotate(diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 680a0c11e1..d9ca71982f 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -235,6 +235,7 @@ def trigger_webhooks_async(retry_backoff=10,retry_kwargs={"max_retries": 5},)+@allow_writer()def send_webhook_request_async(self, event_delivery_id):delivery = get_delivery_for_webhook(event_delivery_id)if not delivery:@@ -341,6 +342,7 @@ def send_observability_events(webhooks: list[WebhookData], events: list[bytes]):@app.task(queue=OBSERVABILITY_QUEUE_NAME)+@allow_writer()def observability_send_events():with observability.opentracing_trace("send_events_task", "task"):if webhooks := observability.get_webhooks():@@ -352,6 +354,7 @@ def observability_send_events():@app.task(queue=OBSERVABILITY_QUEUE_NAME)+@allow_writer()def observability_reporter_task():with observability.opentracing_trace("reporter_task", "task"):if webhooks := observability.get_webhooks():diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex ca0293d5c7..b683616656 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -55,6 +55,7 @@ logger = logging.getLogger(__name__)retry_backoff=10,retry_kwargs={"max_retries": 5},)+@allow_writer()def handle_transaction_request_task(self, delivery_id, request_event_id):request_event = TransactionEvent.objects.filter(id=request_event_id).first()if not request_event: