Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add allow_writer context manager (#15651)
Marcin Gębalaa6693fdc3b17
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 3493f023af..92b1070af1 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -7,6 +7,7 @@ from django.utils import timezonefrom prices import Money, TaxedMoneyfrom ..checkout import base_calculations+from ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, TaxEmptyData, zero_money, zero_taxed_moneyfrom ..discount.utils import (@@ -325,18 +326,19 @@ def _fetch_checkout_prices_if_expired(checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL- checkout.save(- update_fields=checkout_update_fields,- using=settings.DATABASE_CONNECTION_DEFAULT_NAME,- )- checkout.lines.bulk_update(- [line_info.line for line_info in lines],- [- "total_price_net_amount",- "total_price_gross_amount",- "tax_rate",- ],- )+ with allow_writer():+ checkout.save(+ update_fields=checkout_update_fields,+ using=settings.DATABASE_CONNECTION_DEFAULT_NAME,+ )+ checkout.lines.bulk_update(+ [line_info.line for line_info in lines],+ [+ "total_price_net_amount",+ "total_price_gross_amount",+ "tax_rate",+ ],+ )return checkout_info, linesdiff --git a/saleor/checkout/payment_utils.py b/saleor/checkout/payment_utils.pyindex 0b2a6a9694..48d0043b9d 100644--- a/saleor/checkout/payment_utils.py+++ b/saleor/checkout/payment_utils.py@@ -7,6 +7,7 @@ from django.conf import settingsfrom django.db.models import Exists, Qfrom prices import Money+from ..core.db.connection import allow_writerfrom ..core.taxes import zero_moneyfrom ..payment.models import TransactionItemfrom . import CheckoutAuthorizeStatus, CheckoutChargeStatus@@ -115,7 +116,8 @@ def update_checkout_payment_statuses(fields_to_update.append("charge_status")if fields_to_update:fields_to_update.append("last_change")- checkout.save(update_fields=fields_to_update)+ with allow_writer():+ checkout.save(update_fields=fields_to_update)def update_refundable_for_checkout(checkout_pk):diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex be07aab2b7..9d8f97082c 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -13,6 +13,7 @@ from django.utils import timezonefrom prices import Moneyfrom ..account.models import User+from ..core.db.connection import allow_writerfrom ..core.exceptions import ProductNotPublishedfrom ..core.taxes import zero_taxed_moneyfrom ..core.utils.promo_code import (@@ -960,9 +961,7 @@ def cancel_active_payments(checkout: Checkout):def is_shipping_required(lines: Iterable["CheckoutLineInfo"]):"""Check if shipping is required for given checkout lines."""- return any(- line_info.product.product_type.is_shipping_required for line_info in lines- )+ return any(line_info.product_type.is_shipping_required for line_info in lines)def validate_variants_in_checkout_lines(lines: Iterable["CheckoutLineInfo"]):@@ -1012,6 +1011,7 @@ def delete_external_shipping_id(checkout: Checkout, save: bool = False):metadata.save(update_fields=["private_metadata"])+@allow_writer()def get_or_create_checkout_metadata(checkout: "Checkout") -> CheckoutMetadata:if hasattr(checkout, "metadata_storage"):return checkout.metadata_storagediff --git a/saleor/core/db/connection.py b/saleor/core/db/connection.pynew file mode 100644index 0000000000..e359caa687--- /dev/null+++ b/saleor/core/db/connection.py@@ -0,0 +1,131 @@+import logging+import traceback+from contextlib import contextmanager++from django.conf import settings+from django.core.management.color import color_style+from django.db import connections+from django.db.backends.base.base import BaseDatabaseWrapper++from ...graphql.core.context import SaleorContext, get_database_connection_name++logger = logging.getLogger(__name__)++writer = settings.DATABASE_CONNECTION_DEFAULT_NAME+replica = settings.DATABASE_CONNECTION_REPLICA_NAME++# Limit the number of frames in the traceback in `log_writer_usage_middleware` to avoid+# excessive log size.+TRACEBACK_LIMIT = 20++UNSAFE_WRITER_ACCESS_MSG = (+ "Unsafe access to the writer DB detected. Call `using()` on the `QuerySet` "+ "to utilize a replica DB, or employ the `allow_writer` context manager to "+ "explicitly permit access to the writer."+)+++class UnsafeDBUsageError(Exception):+ pass+++class UnsafeWriterAccessError(UnsafeDBUsageError):+ pass+++class UnsafeReplicaUsageError(UnsafeDBUsageError):+ pass+++@contextmanager+def allow_writer():+ """Context manager that allows write access to the default database connection.++ This context manager works in conjunction with the `restrict_writer_middleware` and+ `log_writer_usage_middleware` middlewares. If any of these middlewares are enabled,+ use the `allow_writer` context manager to allow write access to the default+ database. Otherwise an error will be raised or a log message will be emitted.+ """++ default_connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]++ # Check if we are already in an allow_writer block. If so we don't need to do+ # anything and we don't have to close access to the writer at the end.+ in_allow_writer_block = getattr(default_connection, "_allow_writer", False)+ if not in_allow_writer_block:+ setattr(default_connection, "_allow_writer", True)+ try:+ yield+ finally:+ if not in_allow_writer_block:+ # Close writer access when exiting the outermost allow_writer block.+ setattr(default_connection, "_allow_writer", False)+++@contextmanager+def allow_writer_in_context(context: SaleorContext):+ """Context manager that allows write access to the default database connection in a context (SaleorContext).++ This is a helper context manager that conditionally allows write access based on the+ database connection name in the given context.+ """+ conn_name = get_database_connection_name(context)+ if conn_name == settings.DATABASE_CONNECTION_DEFAULT_NAME:+ with allow_writer():+ yield+ else:+ yield+++def restrict_writer_middleware(get_response):+ """Middleware that restricts write access to the default database connection.++ This middleware will raise an error if a write operation is attempted on the default+ database connection. To allow writes, use the `allow_writer` context manager. Make+ sure that writer is not used accidentally and always use the `using` queryset method+ with proper database connection name.+ """++ def middleware(request):+ 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):+ conn: BaseDatabaseWrapper = context["connection"]+ allow_writer = getattr(conn, "_allow_writer", False)+ if conn.alias == writer and not allow_writer:+ raise UnsafeWriterAccessError(f"{UNSAFE_WRITER_ACCESS_MSG} SQL: {sql}")+ return execute(sql, params, many, context)+++def log_writer_usage_middleware(get_response):+ """Middleware that logs write access to the default database connection.++ This is similar to the `restrict_writer_middleware` middleware, but instead of+ raising an error, it logs a message when a write operation is attempted on the+ default database connection.+ """++ def middleware(request):+ with connections[writer].execute_wrapper(_log_writer_usage):+ return get_response(request)++ return middleware+++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:+ stack_trace = traceback.extract_stack(limit=TRACEBACK_LIMIT)+ error_msg = color_style().NOTICE(UNSAFE_WRITER_ACCESS_MSG)+ log_msg = (+ f"{error_msg} SQL: {sql} \n"+ f"Traceback: \n{''.join(traceback.format_list(stack_trace))}"+ )+ logger.error(log_msg)+ return execute(sql, params, many, context)diff --git a/saleor/core/db/tests/__init__.py b/saleor/core/db/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/db/tests/test_connection.py b/saleor/core/db/tests/test_connection.pynew file mode 100644index 0000000000..6137d3af64--- /dev/null+++ b/saleor/core/db/tests/test_connection.py@@ -0,0 +1,88 @@+from unittest.mock import patch++import pytest+from django.db import connections++from ....graphql.context import SaleorContext+from ....tests.models import Book+from ..connection import (+ UnsafeWriterAccessError,+ _log_writer_usage,+ _restrict_writer,+ allow_writer,+ allow_writer_in_context,+)+++def test_allow_writer(settings):+ default_connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]+ assert not getattr(default_connection, "_allow_writer", False)++ with allow_writer():+ assert hasattr(default_connection, "_allow_writer")+ assert default_connection._allow_writer+++def test_allow_writer_yield_exception(settings):+ default_connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]++ def example_function():+ raise Exception()++ try:+ with allow_writer():+ example_function()+ except Exception:+ pass++ assert hasattr(default_connection, "_allow_writer")+ assert not default_connection._allow_writer+++def test_allow_writer_in_context_writer(settings):+ context = SaleorContext()+ context.allow_replica = False++ with allow_writer_in_context(context):+ connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]+ assert hasattr(connection, "_allow_writer")+ assert connection._allow_writer+++@patch("saleor.core.db.connection.get_database_connection_name")+def test_allow_writer_in_context_replica(mocked_get_database_connection_name, settings):+ mocked_get_database_connection_name.return_value = "replica"++ context = SaleorContext()+ context.allow_replica = True++ with allow_writer_in_context(context):+ connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]+ assert not getattr(connection, "_allow_writer")+++def test_restrict_writer_raises_error(settings):+ connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]++ with pytest.raises(UnsafeWriterAccessError):+ 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 allow_writer():+ Book.objects.first()+++def test_log_writer_usage(settings, caplog):+ connection = connections[settings.DATABASE_CONNECTION_DEFAULT_NAME]++ with connection.execute_wrapper(_log_writer_usage):+ Book.objects.first()++ assert caplog.records+ msg = caplog.records[0].getMessage()+ assert "Unsafe access to the writer DB detected" in msgdiff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex cf27fb685f..4c21523cfd 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -21,6 +21,7 @@ from ..checkout.base_calculations import ()from ..checkout.fetch import CheckoutLineInfo, find_checkout_line_infofrom ..checkout.models import Checkout, CheckoutLine+from ..core.db.connection import allow_writerfrom ..core.exceptions import InsufficientStockfrom ..core.taxes import zero_moneyfrom ..core.utils.promo_code import InvalidPromoCode@@ -431,14 +432,17 @@ def create_discount_objects_for_catalogue_promotions(line_discounts_to_update.append(discount_to_update)- if line_discounts_to_create:- CheckoutLineDiscount.objects.bulk_create(line_discounts_to_create)- if line_discounts_to_update and updated_fields:- CheckoutLineDiscount.objects.bulk_update(- line_discounts_to_update, updated_fields- )- if line_discount_ids_to_remove:- CheckoutLineDiscount.objects.filter(id__in=line_discount_ids_to_remove).delete()+ with allow_writer():+ if line_discounts_to_create:+ CheckoutLineDiscount.objects.bulk_create(line_discounts_to_create)+ if line_discounts_to_update and updated_fields:+ CheckoutLineDiscount.objects.bulk_update(+ line_discounts_to_update, updated_fields+ )+ if line_discount_ids_to_remove:+ CheckoutLineDiscount.objects.filter(+ id__in=line_discount_ids_to_remove+ ).delete()def _get_discount_amount(@@ -640,7 +644,8 @@ def _set_checkout_base_prices(checkout_info, lines_info):if is_update_needed:checkout.base_subtotal = subtotalcheckout.base_total = total- checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])+ with allow_writer():+ checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])def _clear_checkout_discount(@@ -833,6 +838,7 @@ def _create_or_update_checkout_discount()+@allow_writer()def _handle_order_promotion(checkout: "Checkout",checkout_info: "CheckoutInfo",@@ -882,6 +888,7 @@ def delete_gift_line(checkout: "Checkout", lines_info: Iterable["CheckoutLineInflines_info.remove(gift_line_info) # type: ignore[attr-defined]+@allow_writer()def _handle_gift_reward(checkout: "Checkout",checkout_info: "CheckoutInfo",diff --git a/saleor/graphql/account/mutations/authentication/set_password.py b/saleor/graphql/account/mutations/authentication/set_password.pyindex c319421f0e..2ef7414ce8 100644--- a/saleor/graphql/account/mutations/authentication/set_password.py+++ b/saleor/graphql/account/mutations/authentication/set_password.py@@ -6,6 +6,7 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom .....account import events as account_eventsfrom .....account import modelsfrom .....account.error_codes import AccountErrorCode+from .....core.db.connection import allow_writerfrom .....order.utils import match_orders_with_new_userfrom ....core import ResolveInfofrom ....core.context import disallow_replica_in_context@@ -35,6 +36,7 @@ class SetPassword(CreateToken):error_type_field = "account_errors"@classmethod+ @allow_writer()def mutate( # type: ignore[override]cls, root, info: ResolveInfo, /, *, email, password, token):diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 7dc79c2d0e..d112bbcf12 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -562,7 +562,7 @@ def test_create_checkout_with_order_promotion(}# when- with django_assert_num_queries(89):+ with django_assert_num_queries(88):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# thendiff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.pyindex d109f74948..d50b1f020c 100644--- a/saleor/graphql/core/connection.py+++ b/saleor/graphql/core/connection.py@@ -345,13 +345,16 @@ def create_connection_slice()args["sort_by"] = sort_by- slice = connection_from_queryset_slice(- queryset,- args,- connection_type,- edge_type or connection_type.Edge,- pageinfo_type or graphene.relay.PageInfo,- )+ from ...core.db.connection import allow_writer_in_context++ with allow_writer_in_context(info.context):+ slice = connection_from_queryset_slice(+ queryset,+ args,+ connection_type,+ edge_type or connection_type.Edge,+ pageinfo_type or graphene.relay.PageInfo,+ )if isinstance(iterable, ChannelQsContext):edges_with_context = []diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.pyindex 48b464f87e..329470986c 100644--- a/saleor/graphql/core/dataloaders.py+++ b/saleor/graphql/core/dataloaders.py@@ -7,6 +7,7 @@ import opentracing.tagsfrom promise import Promisefrom promise.dataloader import DataLoader as BaseLoader+from ...core.db.connection import allow_writer_in_contextfrom ...thumbnail.models import Thumbnailfrom ...thumbnail.utils import get_thumbnail_formatfrom . import SaleorContext@@ -47,7 +48,10 @@ class DataLoader(BaseLoader, Generic[K, R]):) as scope:span = scope.spanspan.set_tag(opentracing.tags.COMPONENT, "dataloaders")- results = self.batch_load(keys)++ with allow_writer_in_context(self.context):+ results = self.batch_load(keys)+if not isinstance(results, Promise):return Promise.resolve(results)return resultsdiff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 023e65772e..5e5e3f4674 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -27,6 +27,7 @@ from graphene import ObjectTypefrom graphene.types.mutation import MutationOptionsfrom graphql.error import GraphQLError+from ...core.db.connection import allow_writerfrom ...core.error_codes import MetadataErrorCodefrom ...core.exceptions import PermissionDeniedfrom ...core.utils.events import call_event@@ -511,6 +512,7 @@ class BaseMutation(graphene.Mutation):return one_of_permissions_or_auth_filter_required(context, all_permissions)@classmethod+ @allow_writer()def mutate(cls, root, info: ResolveInfo, **data):disallow_replica_in_context(info.context)setup_context_user(info.context)@@ -1043,6 +1045,7 @@ class BaseBulkMutation(BaseMutation):return count, errors@classmethod+ @allow_writer()def mutate(cls, root, info: ResolveInfo, **data):disallow_replica_in_context(info.context)setup_context_user(info.context)diff --git a/saleor/graphql/meta/mutations/base.py b/saleor/graphql/meta/mutations/base.pyindex 0ecd4926a4..e125f013d3 100644--- a/saleor/graphql/meta/mutations/base.py+++ b/saleor/graphql/meta/mutations/base.py@@ -5,6 +5,7 @@ from graphql.error.base import GraphQLErrorfrom ....checkout import models as checkout_modelsfrom ....checkout.models import Checkoutfrom ....core import models+from ....core.db.connection import allow_writerfrom ....core.error_codes import MetadataErrorCodefrom ....core.exceptions import PermissionDeniedfrom ....discount import models as discount_models@@ -168,6 +169,7 @@ class BaseMetadataMutation(BaseMutation):return super().check_permissions(context, permissions)@classmethod+ @allow_writer()def mutate(cls, root, info: ResolveInfo, **data):try:type_name, object_pk = cls.get_object_type_name_and_pk(data)diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.pyindex d599332f5f..6053cd93ea 100644--- a/saleor/graphql/product/dataloaders/products.py+++ b/saleor/graphql/product/dataloaders/products.py@@ -4,6 +4,7 @@ from typing import Optionalfrom django.db.models import F+from ....core.db.connection import allow_writer_in_contextfrom ....product import ProductMediaTypesfrom ....product.models import (Category,@@ -19,7 +20,10 @@ from ....product.models import (VariantChannelListingPromotionRule,VariantMedia,)-from ...core.dataloaders import BaseThumbnailBySizeAndFormatLoader, DataLoader+from ...core.dataloaders import (+ BaseThumbnailBySizeAndFormatLoader,+ DataLoader,+)ProductIdAndChannelSlug = tuple[int, str]VariantIdAndChannelSlug = tuple[int, str]@@ -556,6 +560,7 @@ class ProductTypeByProductIdLoader(DataLoader):context_key = "producttype_by_product_id"def batch_load(self, keys):+ @allow_writer_in_context(self.context)def with_products(products):product_ids = {p.id for p in products}product_types_map = (diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.pyindex f4e1414579..b114de2032 100644--- a/saleor/graphql/product/mutations/digital_contents.py+++ b/saleor/graphql/product/mutations/digital_contents.py@@ -1,6 +1,7 @@import graphenefrom django.core.exceptions import ValidationError+from ....core.db.connection import allow_writerfrom ....core.exceptions import PermissionDeniedfrom ....permission.enums import ProductPermissionsfrom ....product import models@@ -172,6 +173,7 @@ class DigitalContentDelete(BaseMutation):permissions = (ProductPermissions.MANAGE_PRODUCTS,)@classmethod+ @allow_writer()def mutate( # type: ignore[override]cls, root, info: ResolveInfo, /, *, variant_id: str):diff --git a/saleor/order/calculations.py b/saleor/order/calculations.pyindex 8d649bd324..bc23505a2d 100644--- a/saleor/order/calculations.py+++ b/saleor/order/calculations.py@@ -7,6 +7,7 @@ from django.db import transactionfrom django.db.models import prefetch_related_objectsfrom prices import Money, TaxedMoney+from ..core.db.connection import allow_writerfrom ..core.prices import quantize_pricefrom ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_moneyfrom ..discount import DiscountType@@ -61,40 +62,44 @@ def fetch_order_prices_if_expired(_update_order_discount_for_voucher(order)_recalculate_prices(- order, manager, lines, database_connection_name=database_connection_name+ order,+ manager,+ lines,+ database_connection_name=database_connection_name,)order.subtotal = get_subtotal(lines, order.currency)with transaction.atomic(savepoint=False):- 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",- "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():+ 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",+ "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, lines@@ -102,7 +107,8 @@ def fetch_order_prices_if_expired(def _update_order_discount_for_voucher(order: Order):"""Create or delete OrderDiscount instances."""if not order.voucher_id:- order.discounts.filter(type=DiscountType.VOUCHER).delete()+ with allow_writer():+ order.discounts.filter(type=DiscountType.VOUCHER).delete()elif (order.voucher_iddiff --git a/saleor/settings.py b/saleor/settings.pyindex 77ed50553e..3c70df8960 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -231,6 +231,12 @@ MIDDLEWARE = ["saleor.core.middleware.jwt_refresh_token_middleware",]+ENABLE_RESTRICT_WRITER_MIDDLEWARE = get_bool_from_env(+ "ENABLE_RESTRICT_WRITER_MIDDLEWARE", False+)+if ENABLE_RESTRICT_WRITER_MIDDLEWARE:+ MIDDLEWARE = ["saleor.core.db.connection.log_writer_usage_middleware"] + MIDDLEWARE+INSTALLED_APPS = [# External apps that need to go before django's"storages",