Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve the perfromance of StockBulkUpdate mutation (#16952)
Maciej Korycinskidacded922b1f
diff --git a/saleor/core/models.py b/saleor/core/models.pyindex c215d56b08..09c9289dcd 100644--- a/saleor/core/models.py+++ b/saleor/core/models.py@@ -159,7 +159,8 @@ class EventPayloadManager(models.Manager["EventPayload"]):) -> list["EventPayload"]:created_objs = self.bulk_create(objs)for obj, payload_data in zip(created_objs, payloads):- obj.save_payload_file(payload_data)+ obj.save_payload_file(payload_data, save_instance=False)+ self.bulk_update(created_objs, ["payload_file"])return created_objs@@ -181,12 +182,14 @@ class EventPayload(models.Model):return payload_data.decode("utf-8")return self.payload- def save_payload_file(self, payload_data: str):+ def save_payload_file(self, payload_data: str, save_instance=True):payload_bytes = payload_data.encode("utf-8")prefix = get_random_string(length=12)file_name = f"{self.pk}.json"file_path = safe_join(prefix, file_name)- self.payload_file.save(file_path, ContentFile(payload_bytes))+ self.payload_file.save(+ file_path, ContentFile(payload_bytes), save=save_instance+ )def save_as_file(self):payload_data = self.payloaddiff --git a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.pyindex 36ff6f7528..7a610b1dd0 100644--- a/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py+++ b/saleor/graphql/product/bulk_mutations/product_variant_stocks_update.py@@ -123,10 +123,10 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):stock.quantity = stock_data["quantity"]stocks.append(stock)- cls.call_event(- manager.product_variant_stock_updated,- stock,- webhooks=webhooks_stock_update,- )+ cls.call_event(+ manager.product_variant_stocks_updated,+ stocks,+ webhooks=webhooks_stock_update,+ )warehouse_models.Stock.objects.bulk_update(stocks, ["quantity"])diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.pyindex b940dc0504..6bdac516ee 100644--- a/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_variant_stocks_update.py@@ -251,11 +251,11 @@ def test_update_or_create_variant_stocks(variant, warehouses):"saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")def test_update_or_create_variant_stocks_when_stock_out_of_quantity(back_in_stock_webhook_trigger,- stock_updated_webhook_trigger,+ stocks_updated_webhook_trigger,mocked_get_webhooks_for_event,variant,warehouses,@@ -284,7 +284,9 @@ def test_update_or_create_variant_stocks_when_stock_out_of_quantity(data["quantity"] for data in stocks_data}back_in_stock_webhook_trigger.assert_called_once_with(stock, webhooks=[any_webhook])- stock_updated_webhook_trigger.assert_called_once_with(stock, webhooks=[any_webhook])+ stocks_updated_webhook_trigger.assert_called_once_with(+ [stock], webhooks=[any_webhook]+ )assert variant.stocks.all()[0].quantity == 10@@ -310,13 +312,13 @@ def test_update_or_create_variant_stocks_empty_stocks_data(variant, warehouses):"saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,- product_variant_stock_updated_webhook,+ product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,variant,@@ -345,11 +347,12 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success(assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 10+ stock = Stock.objects.all()[1]product_variant_back_in_stock_webhook.assert_called_once_with(- Stock.objects.all()[1], webhooks=[any_webhook]+ stock, webhooks=[any_webhook])- product_variant_stock_updated_webhook.assert_called_once_with(- Stock.objects.all()[1], webhooks=[any_webhook]+ product_variant_stocks_updated_webhook.assert_called_once_with(+ [stock], webhooks=[any_webhook])product_variant_stock_out_of_stock_webhook.assert_not_called()@@ -358,13 +361,13 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_success("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,- product_variant_stock_update_webhook,+ product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,settings,variant,@@ -394,13 +397,14 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed(assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 0+ stock = Stock.objects.all()[1]product_variant_back_in_stock_webhook.assert_not_called()product_variant_stock_out_of_stock_webhook.assert_called_once_with(- Stock.objects.all()[1], webhooks=[any_webhook]+ stock, webhooks=[any_webhook])- assert product_variant_stock_update_webhook.call_count == 1- product_variant_stock_update_webhook.assert_called_with(- Stock.objects.all()[1], webhooks=[any_webhook]+ assert product_variant_stocks_update_webhook.call_count == 1+ product_variant_stocks_update_webhook.assert_called_with(+ [stock], webhooks=[any_webhook])@@ -408,13 +412,13 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_only_failed("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,- product_variant_stock_updated_webhook,+ product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,variant,@@ -446,8 +450,8 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations(product_variant_back_in_stock_webhook.assert_called_once_with(stock, webhooks=[any_webhook])- product_variant_stock_updated_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ product_variant_stocks_updated_webhook.assert_called_once_with(+ [stock], webhooks=[any_webhook])product_variant_stock_out_of_stock_webhook.assert_not_called()@@ -456,13 +460,13 @@ def test_update_or_create_variant_with_back_in_stock_webhooks_with_allocations("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,- product_variant_stock_updated_webhook,+ product_variant_stocks_updated_webhook,mocked_get_webhooks_for_event,settings,variant,@@ -494,8 +498,8 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations(product_variant_stock_out_of_stock_webhook.assert_called_once_with(stock, webhooks=[any_webhook])- product_variant_stock_updated_webhook.assert_called_once_with(- stock, webhooks=[any_webhook]+ product_variant_stocks_updated_webhook.assert_called_once_with(+ [stock], webhooks=[any_webhook])product_variant_back_in_stock_webhook.assert_not_called()@@ -504,13 +508,13 @@ def test_update_or_create_variant_with_out_of_stock_webhooks_with_allocations("saleor.graphql.product.bulk_mutations.""product_variant_stocks_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")@patch("saleor.plugins.manager.PluginsManager.product_variant_back_in_stock")@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(product_variant_stock_out_of_stock_webhook,product_variant_back_in_stock_webhook,- product_variant_stock_update_webhook,+ product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,settings,variant,@@ -543,7 +547,12 @@ def test_update_or_create_variant_stocks_with_out_of_stock_webhook_only(assert variant.stocks.aggregate(Sum("quantity"))["quantity__sum"] == 2assert product_variant_stock_out_of_stock_webhook.call_count == 1- assert product_variant_stock_update_webhook.call_count == 2++ assert product_variant_stocks_update_webhook.call_count == 1+ product_variant_stocks_update_webhook.assert_called_once_with(+ list(variant.stocks.all()), webhooks=[any_webhook]+ )+product_variant_back_in_stock_webhook.assert_not_called()diff --git a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.pyindex 30d49a964f..893040c49b 100644--- a/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py+++ b/saleor/graphql/warehouse/bulk_mutations/stock_bulk_update.py@@ -309,9 +309,14 @@ class StockBulkUpdate(BaseMutation):filter_stock = selectors_stock_map.get(f"{variant_value}_{warehouse_value}")if filter_stock:+ quantity_updated = filter_stock.quantity != cleaned_input["quantity"]filter_stock.quantity = cleaned_input["quantity"]instances_data_and_errors_list.append(- {"instance": filter_stock, "errors": index_error_map[index]}+ {+ "instance": filter_stock,+ "errors": index_error_map[index],+ "quantity_updated": quantity_updated,+ })else:index_error_map[index].append(@@ -355,11 +360,13 @@ class StockBulkUpdate(BaseMutation):else:variant_lookup = Q(product_variant__external_reference__in=variants)- stocks = models.Stock.objects.filter(- warehouse_lookup & variant_lookup- ).annotate(- variant_external_reference=F("product_variant__external_reference"),- warehouse_external_reference=F("warehouse__external_reference"),+ stocks = (+ models.Stock.objects.select_for_update()+ .filter(warehouse_lookup & variant_lookup)+ .annotate(+ variant_external_reference=F("product_variant__external_reference"),+ warehouse_external_reference=F("warehouse__external_reference"),+ ))selectors_stock_map = {@@ -373,9 +380,8 @@ class StockBulkUpdate(BaseMutation):stocks_to_update = [stock_data["instance"]for stock_data in instances_data_with_errors_list- if stock_data["instance"]+ if stock_data["instance"] and stock_data.get("quantity_updated")]-models.Stock.objects.bulk_update(stocks_to_update, fields=["quantity"])return stocks_to_update@@ -383,12 +389,12 @@ class StockBulkUpdate(BaseMutation):@classmethoddef post_save_actions(cls, info, instances):manager = get_plugin_manager_promise(info.context).get()- webhooks = get_webhooks_for_event(- WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED- )- for instance in instances:+ if instances:+ webhooks = get_webhooks_for_event(+ WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED+ )cls.call_event(- manager.product_variant_stock_updated, instance, webhooks=webhooks+ manager.product_variant_stocks_updated, instances, webhooks=webhooks)@classmethod@@ -399,14 +405,15 @@ class StockBulkUpdate(BaseMutation):for data in instances_data_with_errors_list]return [- StockBulkResult(stock=data.get("instance"), errors=data.get("errors"))- if data.get("instance")- else StockBulkResult(stock=None, errors=data.get("errors"))+ (+ StockBulkResult(stock=data.get("instance"), errors=data.get("errors"))+ if data.get("instance")+ else StockBulkResult(stock=None, errors=data.get("errors"))+ )for data in instances_data_with_errors_list]@classmethod- @traced_atomic_transaction()def perform_mutation(cls, _root, info, **data):error_policy = data.get("error_policy", ErrorPolicyEnum.REJECT_EVERYTHING.value)index_error_map: dict = defaultdict(list)@@ -414,25 +421,30 @@ class StockBulkUpdate(BaseMutation):warehouse_selector, variant_selector = cls.get_selectors(cleaned_inputs_map)- instances_data_with_errors_list = cls.update_stocks(- cleaned_inputs_map, warehouse_selector, variant_selector, index_error_map- )+ with traced_atomic_transaction():+ instances_data_with_errors_list = cls.update_stocks(+ cleaned_inputs_map,+ warehouse_selector,+ variant_selector,+ index_error_map,+ )- if any(bool(error) for error in index_error_map.values()):- if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:- results = cls.get_results(instances_data_with_errors_list, True)- return StockBulkUpdate(count=0, results=results)+ if any(bool(error) for error in index_error_map.values()):+ if error_policy == ErrorPolicyEnum.REJECT_EVERYTHING.value:+ results = cls.get_results(instances_data_with_errors_list, True)+ return StockBulkUpdate(count=0, results=results)- if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:- for data in instances_data_with_errors_list:- if data["errors"] and data["instance"]:- data["instance"] = None+ if error_policy == ErrorPolicyEnum.REJECT_FAILED_ROWS.value:+ for data in instances_data_with_errors_list:+ if data["errors"] and data["instance"]:+ data["instance"] = None- updated_stocks = cls.save_stocks(instances_data_with_errors_list)+ updated_stocks = cls.save_stocks(instances_data_with_errors_list)+ cls.post_save_actions(info, updated_stocks)# prepare and return dataresults = cls.get_results(instances_data_with_errors_list)-- cls.post_save_actions(info, updated_stocks)-- return StockBulkUpdate(count=len(updated_stocks), results=results)+ count = len(+ list(filter(lambda item: item["instance"], instances_data_with_errors_list))+ )+ return StockBulkUpdate(count=count, results=results)diff --git a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.pyindex 0f96483e7d..ef0e299a65 100644--- a/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py+++ b/saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py@@ -116,6 +116,7 @@ def test_stocks_bulk_update_queries_count(content = get_graphql_content(response)data = content["data"]["stockBulkUpdate"]+assert data["count"] == 4webhook_queries_count = sum([diff --git a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.pyindex 815092f89e..704d541592 100644--- a/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py+++ b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py@@ -80,9 +80,9 @@ def test_stocks_bulk_update_using_ids("saleor.graphql.warehouse.bulk_mutations.""stock_bulk_update.get_webhooks_for_event")-@patch("saleor.plugins.manager.PluginsManager.product_variant_stock_updated")+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")def test_stocks_bulk_update_send_stock_updated_event(- product_variant_stock_update_webhook,+ product_variant_stocks_update_webhook,mocked_get_webhooks_for_event,staff_api_client,variant_with_many_stocks,@@ -118,7 +118,69 @@ def test_stocks_bulk_update_send_stock_updated_event(# thenassert not data["results"][0]["errors"]assert data["count"] == 1- assert product_variant_stock_update_webhook.call_count == 1+ product_variant_stocks_update_webhook.assert_called_once_with(+ [stock], webhooks=[any_webhook]+ )+++@patch(+ "saleor.graphql.warehouse.bulk_mutations."+ "stock_bulk_update.get_webhooks_for_event"+)+@patch("saleor.plugins.manager.PluginsManager.product_variant_stocks_updated")+def test_stocks_bulk_update_send_stock_updated_event_only_for_changed_stocks(+ product_variant_stocks_update_webhook,+ mocked_get_webhooks_for_event,+ staff_api_client,+ variant_with_many_stocks,+ permission_manage_products,+ any_webhook,+ settings,+):+ # given+ mocked_get_webhooks_for_event.return_value = [any_webhook]+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ stocks = variant.stocks.all()++ modified_stock = stocks[0]+ non_modified_stock = stocks[1]++ first_warehouse_id = graphene.Node.to_global_id(+ "Warehouse", modified_stock.warehouse_id+ )+ seconf_warehouse_id = graphene.Node.to_global_id(+ "Warehouse", non_modified_stock.warehouse_id+ )++ stocks_input = [+ {+ "variantId": variant_id,+ "warehouseId": first_warehouse_id,+ "quantity": modified_stock.quantity + 1,+ },+ {+ "variantId": variant_id,+ "warehouseId": seconf_warehouse_id,+ "quantity": non_modified_stock.quantity,+ },+ ]++ variables = {"stocks": stocks_input}++ # when+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(STOCKS_BULK_UPDATE_MUTATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["stockBulkUpdate"]++ # then+ assert not data["results"][0]["errors"]+ assert data["count"] == 2+ product_variant_stocks_update_webhook.assert_called_once_with(+ [modified_stock], webhooks=[any_webhook]+ )def test_stocks_bulk_update_using_external_refs(diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 9f38f5dfbb..805705a4d9 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -1353,7 +1353,7 @@ class BasePlugin:## Note: This method is deprecated in Saleor 3.20 and will be removed in Saleor 3.21.# Webhook-related functionality will be moved from the plugin to core modules.- product_variant_stock_updated: Callable[["Stock", None, None], Any]+ product_variant_stocks_updated: Callable[[list["Stock"], None, None], Any]# Trigger when a product export is completed.#diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex efb0c8908e..1e5e3d5516 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -908,12 +908,12 @@ class PluginsManager(PaymentInterface):# Note: this method is deprecated in Saleor 3.20 and will be removed in Saleor 3.21.# Webhook-related functionality will be moved from plugin to core modules.- def product_variant_stock_updated(self, stock: "Stock", webhooks=None):+ def product_variant_stocks_updated(self, stocks: list["Stock"], webhooks=None):default_value = Noneself.__run_method_on_plugins(- "product_variant_stock_updated",+ "product_variant_stocks_updated",default_value,- stock,+ stocks,webhooks=webhooks,channel_slug=None,)diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex 4fafd13a91..a6833742f7 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -82,8 +82,10 @@ from ...webhook.payloads import (generate_translation_payload,)from ...webhook.transport.asynchronous.transport import (+ WebhookPayloadData,send_webhook_request_async,trigger_webhooks_async,+ trigger_webhooks_async_for_multiple_objects,)from ...webhook.transport.list_stored_payment_methods import (get_list_stored_payment_methods_data_dict,@@ -1998,23 +2000,30 @@ class WebhookPlugin(BasePlugin):)return previous_value- def product_variant_stock_updated(- self, stock: "Stock", previous_value: None, webhooks=None+ def product_variant_stocks_updated(+ self, stocks: list["Stock"], previous_value: None, webhooks=None) -> None:if not self.active:return previous_valueevent_type = WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATEDif webhooks := self._get_webhooks_for_event(event_type, webhooks):- product_variant_data_generator = partial(- generate_product_variant_with_stock_payload, [stock], self.requestor- )- self.trigger_webhooks_async(- None,+ webhook_payload_details = []+ for stock in stocks:+ product_variant_data_generator = partial(+ generate_product_variant_with_stock_payload, [stock], self.requestor+ )+ webhook_payload_details.append(+ WebhookPayloadData(+ subscribable_object=stock,+ legacy_data_generator=product_variant_data_generator,+ data=None,+ )+ )+ trigger_webhooks_async_for_multiple_objects(event_type,webhooks,- stock,- self.requestor,- legacy_data_generator=product_variant_data_generator,+ webhook_payloads_data=webhook_payload_details,+ requestor=self.requestor,)return previous_valuediff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.pyindex f1482c8ff9..045a32bc75 100644--- a/saleor/plugins/webhook/tests/test_webhook.py+++ b/saleor/plugins/webhook/tests/test_webhook.py@@ -53,6 +53,7 @@ from ....webhook.payloads import ()from ....webhook.transport import signature_for_payloadfrom ....webhook.transport.asynchronous.transport import (+ WebhookPayloadData,send_webhook_request_async,trigger_webhooks_async,)@@ -904,32 +905,41 @@ def test_product_variant_back_in_stock(@freeze_time("2014-06-28 10:50")@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")-def test_product_variant_stock_updated(- mocked_webhook_trigger,[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async_for_multiple_objects")+def test_product_variant_stocks_updated(+ mocked_webhook_trigger_for_multiple_objects,mocked_get_webhooks_for_event,any_webhook,settings,variant_with_many_stocks,):- variant = variant_with_many_stocks.stocks.first()+ stock = variant_with_many_stocks.stocks.first()mocked_get_webhooks_for_event.return_value = [any_webhook]settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]manager = get_plugins_manager(allow_replica=False)- manager.product_variant_stock_updated(variant)+ manager.product_variant_stocks_updated([stock])- mocked_webhook_trigger.assert_called_once_with(- None,+ mocked_webhook_trigger_for_multiple_objects.assert_called_once_with(WebhookEventAsyncType.PRODUCT_VARIANT_STOCK_UPDATED,[any_webhook],- variant,- None,- legacy_data_generator=ANY,- allow_replica=False,+ webhook_payloads_data=[+ WebhookPayloadData(+ subscribable_object=stock, legacy_data_generator=ANY, data=None+ )+ ],+ requestor=None,+ )++ assert callable(+ mocked_webhook_trigger_for_multiple_objects.call_args.kwargs[+ "webhook_payloads_data"+ ][0].legacy_data_generator)- assert callable(mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"])assert isinstance(- mocked_webhook_trigger.call_args.kwargs["legacy_data_generator"], partial+ mocked_webhook_trigger_for_multiple_objects.call_args.kwargs[+ "webhook_payloads_data"+ ][0].legacy_data_generator,+ partial,)diff --git a/saleor/webhook/tests/subscription_webhooks/test_webhook.py b/saleor/webhook/tests/subscription_webhooks/test_webhook.pyindex 9b83129ef1..30b8d202bd 100644--- a/saleor/webhook/tests/subscription_webhooks/test_webhook.py+++ b/saleor/webhook/tests/subscription_webhooks/test_webhook.py@@ -1,10 +1,16 @@import jsonfrom unittest import mock+import graphene+from ....core.models import EventDeliveryfrom ...event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ...models import Webhookfrom ...transport.asynchronous import trigger_webhooks_async+from ...transport.asynchronous.transport import (+ WebhookPayloadData,+ trigger_webhooks_async_for_multiple_objects,+)from ...transport.synchronous import trigger_webhook_syncfrom .payloads import generate_payment_payload@@ -40,6 +46,68 @@ def test_trigger_webhooks_async()+ "saleor.webhook.transport.asynchronous.transport.MAX_WEBHOOK_EVENTS_IN_DB_BULK", 2+)+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+def test_trigger_webhooks_async_for_multiple_objects(+ mocked_send_webhook_request,+ webhook,+ subscription_order_created_webhook,+ order_with_lines,+ order_unconfirmed,+):+ # given+ webhook_type = WebhookEventAsyncType.ORDER_CREATED+ webhooks, payload = Webhook.objects.all(), '{"example": "payload"}'++ # when+ trigger_webhooks_async_for_multiple_objects(+ webhook_type,+ webhooks,+ webhook_payloads_data=[+ WebhookPayloadData(+ data=payload,+ subscribable_object=order_with_lines,+ ),+ WebhookPayloadData(+ data=payload,+ subscribable_object=order_unconfirmed,+ ),+ ],+ )++ # then+ order_ids = [+ graphene.Node.to_global_id("Order", order_unconfirmed.pk),+ graphene.Node.to_global_id("Order", order_with_lines.pk),+ ]+ deliveries = EventDelivery.objects.all()+ assert deliveries.count() == 4+ simple_webhook_deliveries = deliveries.filter(webhook=webhook)+ assert simple_webhook_deliveries.count() == 2+ for delivery in simple_webhook_deliveries:+ assert delivery.payload.get_payload() == payload+ subscription_webhook = deliveries.filter(webhook=subscription_order_created_webhook)+ for delivery in subscription_webhook:+ generated_payload = delivery.payload.get_payload()+ assert any(order_id in generated_payload for order_id in order_ids)++ for delivery in deliveries:+ assert (+ mock.call(+ kwargs={"event_delivery_id": delivery.id},+ queue=None,+ bind=True,+ retry_backoff=10,+ retry_kwargs={"max_retries": 5},+ )+ in mocked_send_webhook_request.mock_calls+ )++@mock.patch("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async")diff --git a/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py b/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.pyindex 81bf4a8b13..bf2b8aafaf 100644--- a/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py+++ b/saleor/webhook/transport/asynchronous/tests/test_create_deliveries_for_subscriptions.py@@ -1,12 +1,17 @@import jsonfrom unittest import mock+import graphenefrom django.test import override_settingsfrom .....graphql.webhook.subscription_payload import generate_payload_from_subscriptionfrom .....webhook.event_types import WebhookEventAsyncTypefrom .....webhook.models import Webhook-from ..transport import create_deliveries_for_subscriptions, get_pre_save_payload_key+from ..transport import (+ create_deliveries_for_multiple_subscription_objects,+ create_deliveries_for_subscriptions,+ get_pre_save_payload_key,+)SUBSCRIPTION_QUERY = """subscription {@@ -154,3 +159,54 @@ def test_create_deliveries_reuse_request_for_webhooks(request_2 = mock_generate_payload_from_subscription.call_args_list[1][1]["request"]assert request_1 is request_2assert request_1.dataloaders is request_2.dataloaders+++def test_create_deliveries_for_multiple_subscription_objects(+ subscription_product_updated_webhook, product_list+):+ # given+ webhooks = [subscription_product_updated_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_UPDATED++ # when+ deliveries = create_deliveries_for_multiple_subscription_objects(+ event_type, product_list, webhooks+ )++ # then+ assert len(deliveries) == len(product_list)+ for index, delivery in enumerate(deliveries):+ assert delivery.webhook == subscription_product_updated_webhook+ assert delivery.event_type == event_type+ assert json.loads(delivery.payload.get_payload()) == {+ "product": {+ "id": graphene.Node.to_global_id("Product", product_list[index].pk)+ }+ }+++ "saleor.webhook.transport.asynchronous.transport.MAX_WEBHOOK_EVENTS_IN_DB_BULK", 2+)+def test_create_deliveries_for_multiple_subscription_objects_when_more_objs_than_bulk(+ subscription_product_updated_webhook, product_list+):+ # given+ webhooks = [subscription_product_updated_webhook]+ event_type = WebhookEventAsyncType.PRODUCT_UPDATED++ # when+ deliveries = create_deliveries_for_multiple_subscription_objects(+ event_type, product_list, webhooks+ )++ # then+ assert len(deliveries) == len(product_list)+ for index, delivery in enumerate(deliveries):+ assert delivery.webhook == subscription_product_updated_webhook+ assert delivery.event_type == event_type+ assert json.loads(delivery.payload.get_payload()) == {+ "product": {+ "id": graphene.Node.to_global_id("Product", product_list[index].pk)+ }+ }diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 3dbd2d8f6b..6addf92fe5 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -2,7 +2,8 @@ import datetimeimport jsonimport loggingfrom collections.abc import Sequence-from typing import TYPE_CHECKING, Optional+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Callable, Optionalfrom urllib.parse import urlparsefrom celery import group@@ -46,24 +47,37 @@ logger = logging.getLogger(__name__)task_logger = get_task_logger(f"{__name__}.celery")OBSERVABILITY_QUEUE_NAME = "observability"+MAX_WEBHOOK_EVENTS_IN_DB_BULK = 100-def create_deliveries_for_subscriptions(+@dataclass+class WebhookPayloadData:+ subscribable_object: Any+ legacy_data_generator: Optional[Callable[[], str]] = None+ data: Optional[str] = (+ None # deprecated, legacy_data_generator should be used instead+ )+++def create_deliveries_for_multiple_subscription_objects(event_type,- subscribable_object,+ subscribable_objects,webhooks,requestor=None,allow_replica=False,pre_save_payloads: Optional[dict] = None,request_time: Optional[datetime.datetime] = None,) -> list[EventDelivery]:- """Create a list of event deliveries with payloads based on subscription query.+ """Create event deliveries with payloads based on multiple subscription objects.++ Trigger webhooks for each object in `subscribable_objects`. EventDeliveries and+ their related objects will be created in bulk.It uses a subscription query, defined for webhook to explicitly determinewhat fields should be included in the payload.:param event_type: event type which should be triggered.- :param subscribable_object: subscribable object to process via subscription query.+ :param subscribable_objects: subscribable objects to process via subscription query.:param webhooks: sequence of async webhooks.:param requestor: used in subscription webhooks to generate meta data for payload.:return: List of event deliveries to send via webhook tasks.@@ -78,63 +92,81 @@ def create_deliveries_for_subscriptions(event_payloads = []event_payloads_data = []event_deliveries = []+ event_deliveries_for_bulk_update = []- # Dataloaders are shared between calls to generate_payload_from_subscription to- # reuse their cache. This avoids unnecessary DB queries when different webhooks- # need to resolve the same data.- dataloaders: dict[str, type[DataLoader]] = {}+ for subscribable_object in subscribable_objects:+ # Dataloaders are shared between calls to generate_payload_from_subscription to+ # reuse their cache. This avoids unnecessary DB queries when different webhooks+ # need to resolve the same data.+ dataloaders: dict[str, type[DataLoader]] = {}- request = initialize_request(- requestor,- event_type in WebhookEventSyncType.ALL,- event_type=event_type,- allow_replica=allow_replica,- request_time=request_time,- dataloaders=dataloaders,- )-- for webhook in webhooks:- data = generate_payload_from_subscription(+ request = initialize_request(+ requestor,+ event_type in WebhookEventSyncType.ALL,event_type=event_type,- subscribable_object=subscribable_object,- subscription_query=webhook.subscription_query,- request=request,- app=webhook.app,+ allow_replica=allow_replica,+ request_time=request_time,+ dataloaders=dataloaders,)- if not data:- logger.info(- "No payload was generated with subscription for event: %s", event_type+ for webhook in webhooks:+ data = generate_payload_from_subscription(+ event_type=event_type,+ subscribable_object=subscribable_object,+ subscription_query=webhook.subscription_query,+ request=request,+ app=webhook.app,)- continue- if (- settings.ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS- and pre_save_payloads- ):- key = get_pre_save_payload_key(webhook, subscribable_object)- pre_save_payload = pre_save_payloads.get(key)- if pre_save_payload and pre_save_payload == data:+ if not data:logger.info(- "[Webhook ID:%r] No data changes for event %r, skip delivery to %r",- webhook.id,+ "No payload was generated with subscription for event: %s",event_type,- webhook.target_url,)continue- payload_data = json.dumps({**data})- event_payloads_data.append(payload_data)- event_payload = EventPayload()- event_payloads.append(event_payload)- event_deliveries.append(- EventDelivery(+ if (+ settings.ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS+ and pre_save_payloads+ ):+ key = get_pre_save_payload_key(webhook, subscribable_object)+ pre_save_payload = pre_save_payloads.get(key)+ if pre_save_payload and pre_save_payload == data:+ logger.info(+ "[Webhook ID:%r] No data changes for event %r, skip delivery to %r",+ webhook.id,+ event_type,+ webhook.target_url,+ )+ continue++ payload_data = json.dumps({**data})+ event_payloads_data.append(payload_data)+ event_payload = EventPayload()+ event_payloads.append(event_payload)+ event_delivery = EventDelivery(status=EventDeliveryStatus.PENDING,event_type=event_type,payload=event_payload,webhook=webhook,)- )+ event_deliveries_for_bulk_update.append(event_delivery)++ if len(event_deliveries_for_bulk_update) > MAX_WEBHOOK_EVENTS_IN_DB_BULK:+ with allow_writer():+ # Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.+ with transaction.atomic():+ EventPayload.objects.bulk_create_with_payload_files(+ event_payloads, event_payloads_data+ )+ event_deliveries.extend(+ EventDelivery.objects.bulk_create(+ event_deliveries_for_bulk_update+ )+ )+ event_payloads = []+ event_payloads_data = []+ event_deliveries_for_bulk_update = []with allow_writer():# Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.@@ -142,7 +174,42 @@ def create_deliveries_for_subscriptions(EventPayload.objects.bulk_create_with_payload_files(event_payloads, event_payloads_data)- return EventDelivery.objects.bulk_create(event_deliveries)+ event_deliveries.extend(+ EventDelivery.objects.bulk_create(event_deliveries_for_bulk_update)+ )+ return event_deliveries+++def create_deliveries_for_subscriptions(+ event_type,+ subscribable_object,+ webhooks,+ requestor=None,+ allow_replica=False,+ pre_save_payloads: Optional[dict] = None,+ request_time: Optional[datetime.datetime] = None,+) -> list[EventDelivery]:+ """Create a list of event deliveries with payloads based on subscription query.++ It uses a subscription query, defined for webhook to explicitly determine+ what fields should be included in the payload.++ :param event_type: event type which should be triggered.+ :param subscribable_object: subscribable object to process via subscription query.+ :param webhooks: sequence of async webhooks.+ :param requestor: used in subscription webhooks to generate meta data for payload.+ :return: List of event deliveries to send via webhook tasks.+ :param allow_replica: use replica database.+ """+ return create_deliveries_for_multiple_subscription_objects(+ event_type,+ [subscribable_object],+ webhooks,+ requestor,+ allow_replica,+ pre_save_payloads,+ request_time,+ )def group_webhooks_by_subscription(webhooks):@@ -182,55 +249,58 @@ def get_queue_name_for_webhook(webhook, default_queue):)-def trigger_webhooks_async(- data, # deprecated, legacy_data_generator should be used instead+def trigger_webhooks_async_for_multiple_objects(event_type,webhooks,- subscribable_object=None,+ webhook_payloads_data: list[WebhookPayloadData],requestor=None,- legacy_data_generator=None,allow_replica=False,pre_save_payloads=None,request_time=None,queue=None,):- """Trigger async webhooks - both regular and subscription.+ """Trigger async webhooks (regular and subscription) for each object in the list.- :param data: used as payload in regular webhooks.- Note: this is a legacy parameter, thus it is optional; if it's not provided,- `legacy_data_generator` function is used to generate the payload when needed.:param event_type: used in both webhook types as event type.:param webhooks: used in both webhook types, queryset of async webhooks.- :param subscribable_object: subscribable object used in subscription webhooks.+ :param webhook_payloads_data: list of webhook payload data, required to generate+ the payload.:param requestor: used in subscription webhooks to generate metadata for payload.- :param legacy_data_generator: used to generate payload for regular webhooks.:param allow_replica: use a replica database.:param queue: defines the queue to which the event should be sent."""regular_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)deliveries = []- if regular_webhooks:- if legacy_data_generator:- data = legacy_data_generator()- elif data is None:- raise NotImplementedError("No payload was provided for regular webhooks.")-- with allow_writer():- # Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.- with transaction.atomic():- payload = EventPayload.objects.create_with_payload_file(data)- deliveries.extend(- create_event_delivery_list_for_webhooks(- webhooks=regular_webhooks,- event_payload=payload,- event_type=event_type,- )+ for webhook_payload_detail in webhook_payloads_data:+ if regular_webhooks:+ data = webhook_payload_detail.data+ if webhook_payload_detail.legacy_data_generator:+ data = webhook_payload_detail.legacy_data_generator()+ elif data is None:+ raise NotImplementedError(+ "No payload was provided for regular webhooks.")++ with allow_writer():+ # Use transaction to ensure EventPayload and EventDelivery are created together, preventing inconsistent DB state.+ with transaction.atomic():+ payload = EventPayload.objects.create_with_payload_file(data)+ deliveries.extend(+ create_event_delivery_list_for_webhooks(+ webhooks=regular_webhooks,+ event_payload=payload,+ event_type=event_type,+ )+ )+if subscription_webhooks:deliveries.extend(- create_deliveries_for_subscriptions(+ create_deliveries_for_multiple_subscription_objects(event_type=event_type,- subscribable_object=subscribable_object,+ subscribable_objects=[+ webhook_payload_data.subscribable_object+ for webhook_payload_data in webhook_payloads_data+ ],webhooks=subscription_webhooks,requestor=requestor,allow_replica=allow_replica,@@ -251,6 +321,49 @@ def trigger_webhooks_async()+def trigger_webhooks_async(+ data, # deprecated, legacy_data_generator should be used instead+ event_type,+ webhooks,+ subscribable_object=None,+ requestor=None,+ legacy_data_generator=None,+ allow_replica=False,+ pre_save_payloads=None,+ request_time=None,+ queue=None,+):+ """Trigger async webhooks - both regular and subscription.++ :param data: used as payload in regular webhooks.+ Note: this is a legacy parameter, thus it is optional; if it's not provided,+ `legacy_data_generator` function is used to generate the payload when needed.+ :param event_type: used in both webhook types as event type.+ :param webhooks: used in both webhook types, queryset of async webhooks.+ :param subscribable_object: subscribable object used in subscription webhooks.+ :param requestor: used in subscription webhooks to generate metadata for payload.+ :param legacy_data_generator: used to generate payload for regular webhooks.+ :param allow_replica: use a replica database.+ :param queue: defines the queue to which the event should be sent.+ """+ trigger_webhooks_async_for_multiple_objects(+ event_type=event_type,+ webhooks=webhooks,+ webhook_payloads_data=[+ WebhookPayloadData(+ subscribable_object=subscribable_object,+ legacy_data_generator=legacy_data_generator,+ data=data,+ )+ ],+ requestor=requestor,+ allow_replica=allow_replica,+ pre_save_payloads=pre_save_payloads,+ request_time=request_time,+ queue=queue,+ )++@app.task(queue=settings.WEBHOOK_CELERY_QUEUE_NAME,bind=True,