Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop caching flow for checkout webhooks (#18874)
Maciej Korycinski668e160644b7
diff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping.py b/saleor/checkout/tests/webhooks/test_exclude_shipping.pyindex ba9fb4a5e7..3c0e51c0b4 100644--- a/saleor/checkout/tests/webhooks/test_exclude_shipping.py+++ b/saleor/checkout/tests/webhooks/test_exclude_shipping.py@@ -2,7 +2,6 @@ import jsonimport uuidfrom decimal import Decimalfrom unittest import mock-from unittest.mock import callimport grapheneimport pytest@@ -14,13 +13,9 @@ from ....graphql.core.utils import to_global_id_or_nonefrom ....graphql.tests.utils import get_graphql_contentfrom ....shipping.interface import ExcludedShippingMethod, ShippingMethodDatafrom ....shipping.models import ShippingMethod-from ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIMEfrom ....webhook.event_types import WebhookEventSyncTypefrom ....webhook.models import Webhook-from ....webhook.transport.utils import generate_cache_key_for_webhookfrom ...webhooks.exclude_shipping import (- _generate_excluded_shipping_methods_for_checkout_payload,- _get_cache_data_for_exclude_shipping_methods,excluded_shipping_methods_for_checkout,)@@ -173,26 +168,7 @@ def test_checkout_deliveries_webhook_called_once(assert mocked_webhook.called-def test_get_cache_data_for_exclude_shipping_methods(checkout_with_items):- # given- payload_str = _generate_excluded_shipping_methods_for_checkout_payload(- checkout_with_items, []- )- assert "last_change" in payload_str- assert "meta" in payload_str-- # when- cache_data = _get_cache_data_for_exclude_shipping_methods(payload_str)-- # then- assert "last_change" not in cache_data- assert "meta" not in cache_data--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)[email protected]("saleor.shipping.webhooks.shared.trigger_webhook_sync_promise")@mock.patch("saleor.checkout.webhooks.exclude_shipping.""_generate_excluded_shipping_methods_for_checkout_payload"@@ -200,7 +176,6 @@ def test_get_cache_data_for_exclude_shipping_methods(checkout_with_items):def test_excluded_shipping_methods_for_checkout_webhook_with_subscription(mocked_static_payload,mocked_webhook,- mocked_cache_set,checkout_with_items,available_shipping_methods,exclude_shipping_app_with_subscription,@@ -240,33 +215,17 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription(assert webhook_reason in em.reasonmocked_webhook.assert_called_once_with(- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- shipping_webhook,- False,+ event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,+ webhook=shipping_webhook,+ allow_replica=False,static_payload=payload,subscribable_object=(checkout_with_items, available_shipping_methods),timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,requestor=None,)- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- shipping_app.id,- )-- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)[email protected]("saleor.shipping.webhooks.shared.trigger_webhook_sync_promise")@mock.patch("saleor.checkout.webhooks.exclude_shipping.""_generate_excluded_shipping_methods_for_checkout_payload"@@ -274,7 +233,6 @@ def test_excluded_shipping_methods_for_checkout_webhook_with_subscription(def test_multiple_app_with_excluded_shipping_methods_for_checkout(mocked_payload,mocked_webhook,- mocked_cache_set,checkout_with_items,available_shipping_methods,app_exclude_shipping_for_checkout,@@ -337,59 +295,27 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(assert webhook_second_reason in em.reasonevent_type = WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODSmocked_webhook.assert_any_call(- event_type,- shipping_webhook,- False,+ event_type=event_type,+ webhook=shipping_webhook,+ allow_replica=False,static_payload=payload,subscribable_object=(checkout_with_items, available_shipping_methods),timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,requestor=None,)mocked_webhook.assert_any_call(- event_type,- second_shipping_webhook,- False,+ event_type=event_type,+ webhook=second_shipping_webhook,+ allow_replica=False,static_payload=payload,subscribable_object=(checkout_with_items, available_shipping_methods),timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,requestor=None,)assert mocked_webhook.call_count == 2- expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(- payload_dict, shipping_webhook.target_url, event_type, shipping_app.id- )- expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(- payload_dict,- second_shipping_webhook.target_url,- event_type,- second_shipping_app.id,- )- assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key-- mocked_cache_set.assert_has_calls(- [- call(- expected_cache_for_first_webhook_key,- first_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- call(- expected_cache_for_second_webhook_key,- second_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- ]- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)[email protected]("saleor.shipping.webhooks.shared.trigger_webhook_sync_promise")@mock.patch("saleor.checkout.webhooks.exclude_shipping.""_generate_excluded_shipping_methods_for_checkout_payload"@@ -397,7 +323,6 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_checkout(mocked_payload,mocked_webhook,- mocked_cache_set,checkout_with_items,available_shipping_methods,app_exclude_shipping_for_checkout,@@ -468,50 +393,25 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_chassert webhook_second_reason in em.reasonmocked_webhook.assert_any_call(- event_type,- first_webhook,- False,+ event_type=event_type,+ webhook=first_webhook,+ allow_replica=False,static_payload=payload,subscribable_object=(checkout_with_items, available_shipping_methods),timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,requestor=None,)mocked_webhook.assert_any_call(- event_type,- second_webhook,- False,+ event_type=event_type,+ webhook=second_webhook,+ allow_replica=False,static_payload=payload,subscribable_object=(checkout_with_items, available_shipping_methods),timeout=settings.WEBHOOK_SYNC_TIMEOUT,- request=None,requestor=None,)assert mocked_webhook.call_count == 2- expected_cache_for_first_webhook_key = generate_cache_key_for_webhook(- payload_dict, first_webhook.target_url, event_type, shipping_app.id- )- expected_cache_for_second_webhook_key = generate_cache_key_for_webhook(- payload_dict, second_webhook.target_url, event_type, shipping_app.id- )- assert expected_cache_for_first_webhook_key != expected_cache_for_second_webhook_key-- mocked_cache_set.assert_has_calls(- [- call(- expected_cache_for_first_webhook_key,- first_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- call(- expected_cache_for_second_webhook_key,- second_webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- ),- ]- )-@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")def test_excluded_shipping_methods_for_checkout(diff --git a/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py b/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.pydeleted file mode 100644index 45dc29738d..0000000000--- a/saleor/checkout/tests/webhooks/test_exclude_shipping_cache.py+++ /dev/null@@ -1,208 +0,0 @@-import json-import uuid-from decimal import Decimal-from unittest import mock--import graphene-import pytest-from measurement.measures import Weight-from prices import Money--from ....shipping.interface import ShippingMethodData-from ....shipping.webhooks.shared import CACHE_EXCLUDED_SHIPPING_TIME-from ....webhook.event_types import WebhookEventSyncType-from ....webhook.transport.utils import generate_cache_key_for_webhook-from ...webhooks.exclude_shipping import (- excluded_shipping_methods_for_checkout,-)---def available_shipping_methods():- methods = []- for i in range(2):- methods.append(- ShippingMethodData(- id=str(i),- price=Money(Decimal(10), "usd"),- name=uuid.uuid4().hex,- maximum_order_weight=Weight(kg=0),- minimum_order_weight=Weight(kg=0),- maximum_delivery_days=0,- minimum_delivery_days=5,- )- )- return methods--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.checkout.webhooks.exclude_shipping."- "_generate_excluded_shipping_methods_for_checkout_payload"-)-def test_excluded_shipping_methods_for_checkout_use_cache(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- checkout_with_items,- available_shipping_methods,- app_exclude_shipping_for_checkout,-):- # given- webhook_reason = "Order contains dangerous products."-- mocked_webhook.return_value = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- payload = json.dumps({"checkout": {"id": 1, "some_field": "12"}})- mocked_payload.return_value = payload-- mocked_cache_get.return_value = (payload, [{"id": "1", "reason": webhook_reason}])-- # when- excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- allow_replica=True,- requestor=None,- )-- # then- assert not mocked_webhook.called-- assert not mocked_cache_set.called--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.checkout.webhooks.exclude_shipping."- "_generate_excluded_shipping_methods_for_checkout_payload"-)-def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- checkout_with_items,- available_shipping_methods,- app_exclude_shipping_for_checkout,-):- # given- shipping_webhook = app_exclude_shipping_for_checkout.webhooks.get()-- webhook_reason = "Order contains dangerous products."-- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }- mocked_webhook.return_value = webhook_response-- payload_dict = {"checkout": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload-- mocked_cache_get.return_value = None-- # when- excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- allow_replica=True,- requestor=None,- )-- # then- assert mocked_webhook.called-- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- app_exclude_shipping_for_checkout.id,- )-- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.checkout.webhooks.exclude_shipping."- "_generate_excluded_shipping_methods_for_checkout_payload"-)-def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_different(- mocked_payload,- mocked_webhook,- mocked_cache_set,- mocked_cache_get,- checkout_with_items,- available_shipping_methods,- app_exclude_shipping_for_checkout,-):- # given-- shipping_webhook = app_exclude_shipping_for_checkout.webhooks.get()-- webhook_reason = "Order contains dangerous products."-- webhook_response = {- "excluded_methods": [- {- "id": graphene.Node.to_global_id("ShippingMethod", "1"),- "reason": webhook_reason,- }- ]- }-- mocked_webhook.return_value = webhook_response-- payload_dict = {"checkout": {"id": 1, "some_field": "12"}}- payload = json.dumps(payload_dict)- mocked_payload.return_value = payload-- mocked_cache_get.return_value = None-- # when- excluded_shipping_methods_for_checkout(- checkout_with_items,- available_shipping_methods=available_shipping_methods,- allow_replica=True,- requestor=None,- )- # then- assert mocked_webhook.called-- expected_cache_key = generate_cache_key_for_webhook(- payload_dict,- shipping_webhook.target_url,- WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,- app_exclude_shipping_for_checkout.id,- )- mocked_cache_get.assert_called_once_with(expected_cache_key)-- mocked_cache_set.assert_called_once_with(- expected_cache_key,- webhook_response,- timeout=CACHE_EXCLUDED_SHIPPING_TIME,- )diff --git a/saleor/checkout/tests/webhooks/test_list_shipping_methods.py b/saleor/checkout/tests/webhooks/test_list_shipping_methods.pyindex 9f8cfcf023..60d320777a 100644--- a/saleor/checkout/tests/webhooks/test_list_shipping_methods.py+++ b/saleor/checkout/tests/webhooks/test_list_shipping_methods.py@@ -1,18 +1,7 @@-import datetime-from decimal import Decimalfrom unittest import mock-from django.utils import timezone--from ....webhook import const-from ....webhook.event_types import WebhookEventSyncType-from ....webhook.payloads import generate_checkout_payloadfrom ....webhook.response_schemas.utils.annotations import logger as annotations_logger-from ....webhook.transport.utils import generate_cache_key_for_webhook-from ...utils import get_or_create_checkout_metadatafrom ...webhooks.list_shipping_methods import (- CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,- _get_cache_data_for_shipping_list_methods_for_checkout,_parse_list_shipping_methods_response,list_shipping_methods_for_checkout,)@@ -40,232 +29,6 @@ def test_list_shipping_methods_for_checkout_webhook_response_none(assert not response[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_list_shipping_methods_for_checkout_set_cache(- mocked_webhook,- mocked_cache_set,- checkout_with_item,- shipping_app,-):- # given- mocked_webhook.return_value = [- {- "id": "method-1",- "name": "Standard Shipping",- "amount": Decimal("5.5"),- "currency": "GBP",- }- ]-- # when- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert mocked_webhook.called- assert mocked_cache_set.called--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_list_shipping_methods_no_webhook_response_sets_short_term_cache(- mocked_webhook,- mocked_cache_set,- checkout_with_item,- shipping_app,-):- # given- mocked_webhook.return_value = None-- payload = generate_checkout_payload(checkout_with_item)- key_data = _get_cache_data_for_shipping_list_methods_for_checkout(payload)- target_url = shipping_app.webhooks.first().target_url- cache_key = generate_cache_key_for_webhook(- key_data,- target_url,- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- shipping_app.id,- )-- # when- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert mocked_webhook.called- mocked_cache_set.assert_called_once_with(- cache_key,- const.SYNC_WEBHOOK_FAILURE_SENTINEL,- timeout=const.SYNC_WEBHOOK_FAILURE_CACHE_TTL,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_list_shipping_methods_for_checkout_use_cache(- mocked_webhook,- mocked_cache_get,- checkout_with_item,- shipping_app,-):- # given- mocked_cache_get.return_value = [- {- "id": "method-1",- "name": "Standard Shipping",- "amount": Decimal("5.5"),- "currency": "GBP",- }- ]-- # when- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert not mocked_webhook.called- assert mocked_cache_get.called--[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_list_shipping_methods_for_checkout_use_cache_for_empty_list(- mocked_webhook,- mocked_cache_get,- checkout_with_item,- shipping_app,-):- # given- mocked_cache_get.return_value = []-- # when- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert not mocked_webhook.called- assert mocked_cache_get.called--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_checkout_change_invalidates_cache_key(- mocked_webhook,- mocked_cache_get,- mocked_cache_set,- checkout_with_item,- shipping_app,-):- # given- mocked_webhook_response = [- {- "id": "method-1",- "name": "Standard Shipping",- "amount": Decimal("5.5"),- "currency": "GBP",- }- ]- mocked_webhook.return_value = mocked_webhook_response- mocked_cache_get.return_value = None-- payload = generate_checkout_payload(checkout_with_item)- key_data = _get_cache_data_for_shipping_list_methods_for_checkout(payload)- target_url = shipping_app.webhooks.first().target_url- cache_key = generate_cache_key_for_webhook(- key_data,- target_url,- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- shipping_app.id,- )-- # when- checkout_with_item.email = "[email protected]"- checkout_with_item.save(update_fields=["email"])- new_payload = generate_checkout_payload(checkout_with_item)- new_key_data = _get_cache_data_for_shipping_list_methods_for_checkout(new_payload)- new_cache_key = generate_cache_key_for_webhook(- new_key_data,- target_url,- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- shipping_app.id,- )- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert cache_key != new_cache_key- mocked_cache_get.assert_called_once_with(new_cache_key)- mocked_cache_set.assert_called_once_with(- new_cache_key,- mocked_webhook_response,- timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,- )--[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")-def test_ignore_selected_fields_on_generating_cache_key(- mocked_webhook,- mocked_cache_get,- mocked_cache_set,- checkout_with_item,- shipping_app,-):- # given- mocked_webhook_response = [- {- "id": "method-1",- "name": "Standard Shipping",- "amount": Decimal("5.5"),- "currency": "GBP",- }- ]- mocked_webhook.return_value = mocked_webhook_response- mocked_cache_get.return_value = None-- payload = generate_checkout_payload(checkout_with_item)- key_data = _get_cache_data_for_shipping_list_methods_for_checkout(payload)- target_url = shipping_app.webhooks.first().target_url- cache_key = generate_cache_key_for_webhook(- key_data,- target_url,- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- shipping_app.id,- )-- # when- checkout_with_item.last_change = timezone.now() + datetime.timedelta(seconds=30)- checkout_with_item.save(update_fields=["last_change"])- new_payload = generate_checkout_payload(checkout_with_item)- new_key_data = _get_cache_data_for_shipping_list_methods_for_checkout(new_payload)- new_cache_key = generate_cache_key_for_webhook(- new_key_data,- target_url,- WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- shipping_app.id,- )- list_shipping_methods_for_checkout(- checkout_with_item, [], allow_replica=False, requestor=None- ).get()-- # then- assert cache_key == new_cache_key- mocked_cache_get.assert_called_once_with(new_cache_key)- mocked_cache_set.assert_called_once_with(- new_cache_key,- mocked_webhook_response,- timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,- )--@mock.patch.object(annotations_logger, "warning")def test_parse_list_shipping_methods_response_response_incorrect_format(mocked_logger, app@@ -379,22 +142,3 @@ def test_parse_list_shipping_methods_metadata_is_none(app):# thenassert response[0].metadata == {}---def test_get_cache_data_for_shipping_list_methods_for_checkout(checkout_with_items):- # given- metadata = get_or_create_checkout_metadata(checkout_with_items)- metadata.store_value_in_private_metadata({"external_app_shipping_id": "something"})- metadata.save()- payload_str = generate_checkout_payload(checkout_with_items)- assert "last_change" in payload_str- assert "meta" in payload_str- assert "external_app_shipping_id" in payload_str-- # when- cache_data = _get_cache_data_for_shipping_list_methods_for_checkout(payload_str)-- # then- assert "last_change" not in cache_data[0]- assert "meta" not in cache_data[0]- assert "external_app_shipping_id" not in cache_data[0]["private_metadata"]diff --git a/saleor/checkout/webhooks/exclude_shipping.py b/saleor/checkout/webhooks/exclude_shipping.pyindex 7b0f14ce54..1831fe15e9 100644--- a/saleor/checkout/webhooks/exclude_shipping.py+++ b/saleor/checkout/webhooks/exclude_shipping.py@@ -45,7 +45,6 @@ def excluded_shipping_methods_for_checkout(checkout,available_shipping_methods,)- cache_data = _get_cache_data_for_exclude_shipping_methods(static_payload)return get_excluded_shipping_data(webhooks=webhooks,event_type=WebhookEventSyncType.CHECKOUT_FILTER_SHIPPING_METHODS,@@ -53,7 +52,10 @@ def excluded_shipping_methods_for_checkout(subscribable_object=(checkout, available_shipping_methods),allow_replica=allow_replica,requestor=requestor,- cache_data=cache_data,+ # Set cache to None as Checkout doesn't use cache flow anymore+ # This field will be fully dropped after moving Order to new+ # flow.+ cache_data=None,)@@ -72,14 +74,3 @@ def _generate_excluded_shipping_methods_for_checkout_payload(],}return json.dumps(payload, cls=CustomJsonEncoder)---def _get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:- payload_dict = json.loads(payload)- source_object = payload_dict.get("checkout", payload_dict.get("order", {}))-- # drop fields that change between requests but are not relevant for cache key- source_object.pop("last_change", None)- source_object.pop("meta", None)- source_object.pop("shipping_method", None)- return payload_dictdiff --git a/saleor/checkout/webhooks/list_shipping_methods.py b/saleor/checkout/webhooks/list_shipping_methods.pyindex 70fb0f5784..1f13392333 100644--- a/saleor/checkout/webhooks/list_shipping_methods.py+++ b/saleor/checkout/webhooks/list_shipping_methods.py@@ -1,4 +1,3 @@-import jsonimport loggingfrom typing import TYPE_CHECKING, Any, Union@@ -10,9 +9,7 @@ from ...shipping.interface import ShippingMethodDatafrom ...webhook.event_types import WebhookEventSyncTypefrom ...webhook.payloads import generate_checkout_payloadfrom ...webhook.response_schemas.shipping import ListShippingMethodsSchema-from ...webhook.transport.synchronous.transport import (- trigger_webhook_sync_promise_if_not_cached,-)+from ...webhook.transport.synchronous.transport import trigger_webhook_sync_promisefrom ...webhook.utils import get_webhooks_for_eventfrom ..models import Checkout@@ -22,8 +19,6 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT = 3600 * 12-def list_shipping_methods_for_checkout(checkout: "Checkout",@@ -39,18 +34,15 @@ def list_shipping_methods_for_checkout(promised_responses = []payload = generate_checkout_payload(checkout, requestor)- cache_data = _get_cache_data_for_shipping_list_methods_for_checkout(payload)for webhook in webhooks:promised_responses.append(- trigger_webhook_sync_promise_if_not_cached(+ trigger_webhook_sync_promise(event_type=event_type,static_payload=payload,webhook=webhook,- cache_data=cache_data,allow_replica=allow_replica,subscribable_object=(checkout, built_in_shipping_methods),- request_timeout=settings.WEBHOOK_SYNC_TIMEOUT,- cache_timeout=CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,requestor=requestor,))@@ -97,16 +89,3 @@ def _parse_list_shipping_methods_response()for shipping_method in list_shipping_method_model.root]---def _get_cache_data_for_shipping_list_methods_for_checkout(payload: str) -> dict:- key_data = json.loads(payload)-- # drop fields that change between requests but are not relevant for cache key- key_data[0].pop("last_change")- key_data[0].pop("meta")- # Drop the external_app_shipping_id from the cache key as it should not have an- # impact on cache invalidation- if "external_app_shipping_id" in key_data[0].get("private_metadata", {}):- del key_data[0]["private_metadata"]["external_app_shipping_id"]- return key_datadiff --git a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.pyindex 2307a00987..743d241c7e 100644--- a/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py+++ b/saleor/graphql/webhook/tests/pregenerated_subscription/test_checkout_resolvers.py@@ -3,9 +3,7 @@ from unittest import mockfrom django.test import override_settingsfrom django.utils import timezone-from promise import Promise-from .....shipping.models import ShippingMethodfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content@@ -404,245 +402,6 @@ def test_checkout_line_total_price_use_pregenerated_payload(mock_request.assert_called_once()-@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)- "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"-)-def test_shipping_methods_use_pregenerated_payload(- mock_generate_payload,- mock_request,- checkout_with_shipping_address,- shipping_method,- api_client,- exclude_shipping_app_with_subscription,-):- # given- checkout = checkout_with_shipping_address- checkout_global_id = to_global_id_or_none(checkout)- shipping_methods = ShippingMethod.objects.order_by("id").all()- shipping_method_global_ids = [- to_global_id_or_none(shipping_method) for shipping_method in shipping_methods- ]- exclude_msg = "Shipping method is excluded via metadata by external app."- checkout_shipping_query = """- query getCheckout($id: ID!) {- checkout(id: $id) {- id- shippingMethods {- id- name- active- message- }- }- }- """- variables = {"id": checkout_global_id}-- mock_request.return_value = Promise.resolve(- {- "excluded_methods": [- {- "id": shipping_method_global_ids[1],- "reason": exclude_msg,- },- ]- }- )-- # when- response = api_client.post_graphql(checkout_shipping_query, variables)- content = get_graphql_content(response)-- # then- assert content["data"]["checkout"]["id"] == checkout_global_id-- shipping_methods = content["data"]["checkout"]["shippingMethods"]- first_expected_shipping_method = {- "id": shipping_method_global_ids[0],- "name": "DHL",- "active": True,- "message": "",- }- second_expected_shipping_method = {- "id": shipping_method_global_ids[1],- "name": "DHL",- "active": False,- "message": exclude_msg,- }- assert len(shipping_methods) == 2- assert first_expected_shipping_method in shipping_methods- assert second_expected_shipping_method in shipping_methods-- mock_request.assert_called_once()- mock_generate_payload.assert_not_called()---@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)- "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"-)-def test_available_shipping_methods_use_pregenerated_payload(- mock_generate_payload,- mock_request,- checkout_with_shipping_address,- shipping_method,- api_client,- exclude_shipping_app_with_subscription,-):- # given- checkout = checkout_with_shipping_address- checkout_global_id = to_global_id_or_none(checkout)- shipping_methods = ShippingMethod.objects.order_by("id").all()- shipping_method_global_ids = [- to_global_id_or_none(shipping_method) for shipping_method in shipping_methods- ]- exclude_msg = "Shipping method is excluded via metadata by external app."- checkout_shipping_query = """- query getCheckout($id: ID!) {- checkout(id: $id) {- id- availableShippingMethods {- id- name- active- message- }- }- }- """- variables = {"id": checkout_global_id}-- mock_request.return_value = Promise.resolve(- {- "excluded_methods": [- {- "id": shipping_method_global_ids[1],- "reason": exclude_msg,- },- ]- }- )-- # when- response = api_client.post_graphql(checkout_shipping_query, variables)- content = get_graphql_content(response)-- # then- assert content["data"]["checkout"]["id"] == checkout_global_id- assert content["data"]["checkout"]["availableShippingMethods"] == [- {- "id": shipping_method_global_ids[0],- "name": "DHL",- "active": True,- "message": "",- }- ]- mock_request.assert_called_once()- mock_generate_payload.assert_not_called()---@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")- "saleor.webhook.transport.synchronous.transport.trigger_webhook_sync_promise"-)- "saleor.webhook.transport.synchronous.transport.generate_payload_promise_from_subscription"-)-def test_shipping_methods_and_taxes_use_pregenerated_payload(- mock_generate_payload,- mock_shipping_request,- mock_tax_request,- checkout_with_shipping_address,- shipping_method,- api_client,- exclude_shipping_app_with_subscription,- tax_data_response,- tax_app,-):- # given- checkout = checkout_with_shipping_address- checkout.price_expiration = timezone.now() - datetime.timedelta(days=1)- checkout.save()- checkout_global_id = to_global_id_or_none(checkout)- shipping_methods = ShippingMethod.objects.order_by("id").all()- shipping_method_global_ids = [- to_global_id_or_none(shipping_method) for shipping_method in shipping_methods- ]- exclude_msg = "Shipping method is excluded via metadata by external app."- checkout_shipping_query = """- query getCheckout($id: ID!) {- checkout(id: $id) {- id- totalPrice {- net {- amount- }- gross {- amount- }- }- shippingMethods {- id- name- active- message- }- }- }- """- variables = {"id": checkout_global_id}-- mock_shipping_request.return_value = Promise.resolve(- {- "excluded_methods": [- {- "id": shipping_method_global_ids[1],- "reason": exclude_msg,- },- ]- }- )- mock_tax_request.return_value = TAX_DATA_RESPONSE-- # when- response = api_client.post_graphql(checkout_shipping_query, variables)- content = get_graphql_content(response)-- # then- assert content["data"]["checkout"]["id"] == checkout_global_id-- shipping_methods = content["data"]["checkout"]["shippingMethods"]- first_expected_shipping_method = {- "id": shipping_method_global_ids[0],- "name": "DHL",- "active": True,- "message": "",- }- second_expected_shipping_method = {- "id": shipping_method_global_ids[1],- "name": "DHL",- "active": False,- "message": exclude_msg,- }- assert len(shipping_methods) == 2- assert first_expected_shipping_method in shipping_methods- assert second_expected_shipping_method in shipping_methods-- assert content["data"]["checkout"]["totalPrice"]["net"]["amount"] == 16- assert content["data"]["checkout"]["totalPrice"]["gross"]["amount"] == 20- mock_tax_request.assert_called_once()- mock_shipping_request.assert_called_once()- mock_generate_payload.assert_not_called()--CHECKOUTS_QUERY = """query CheckoutsQuery {checkouts(first: 1) {diff --git a/saleor/shipping/webhooks/shared.py b/saleor/shipping/webhooks/shared.pyindex 92058b55ee..08d3c7631b 100644--- a/saleor/shipping/webhooks/shared.py+++ b/saleor/shipping/webhooks/shared.py@@ -13,6 +13,7 @@ from ...webhook.response_schemas.shipping import (FilterShippingMethodsSchema,)from ...webhook.transport.synchronous.transport import (+ trigger_webhook_sync_promise,trigger_webhook_sync_promise_if_not_cached,)from ..interface import ExcludedShippingMethod, ShippingMethodData@@ -85,17 +86,24 @@ def _get_excluded_shipping_methods_or_fetch(subscribable_object: "tuple[Order | Checkout, list[ShippingMethodData]]",allow_replica: bool,requestor: Union["App", "User", None],- cache_data: dict,+ cache_data: dict | None,) -> Promise[dict[str, list[ExcludedShippingMethod]]]:"""Return data of all excluded shipping methods.- The data will be fetched from the cache. If missing it will fetch it from all- defined webhooks by calling a request to each of them one by one.+ The data will be fetched from the cache if present and cache_data was provided.+ If missing it will fetch it from all defined webhooks by calling a request to+ each of them one by one."""promised_responses = []for webhook in webhooks:- promised_responses.append(- trigger_webhook_sync_promise_if_not_cached(+ # The approach for Order and Checkout is the same, except that+ # Checkout does not need a cache anymore as all deliveries and their+ # data are denormalized. The same flow will be introduced for the Order+ # but for now we use cache_data as a indicator to decide if we want to+ # use the cache approach. This will be fully dropped after introducing+ # denormalized deliveries for Order.+ if cache_data is not None:+ response_promise = trigger_webhook_sync_promise_if_not_cached(event_type=event_type,static_payload=static_payload,webhook=webhook,@@ -106,7 +114,17 @@ def _get_excluded_shipping_methods_or_fetch(cache_timeout=CACHE_EXCLUDED_SHIPPING_TIME,requestor=requestor,)- )+ else:+ response_promise = trigger_webhook_sync_promise(+ event_type=event_type,+ static_payload=static_payload,+ webhook=webhook,+ allow_replica=allow_replica,+ subscribable_object=subscribable_object,+ requestor=requestor,+ timeout=settings.WEBHOOK_SYNC_TIMEOUT,+ )+ promised_responses.append(response_promise)def process_responses(responses: list[Any],@@ -129,13 +147,13 @@ def get_excluded_shipping_data(subscribable_object: "tuple[Order | Checkout, list[ShippingMethodData]]",allow_replica: bool,requestor: Union["App", "User", None],- cache_data: dict,+ cache_data: dict | None,) -> Promise[list[ExcludedShippingMethod]]:"""Exclude not allowed shipping methods by sync webhook.Fetch excluded shipping methods from sync webhooks and return them as a list ofexcluded shipping methods.- The function uses a cache_key to reduce the number of+ When cache_data is provided, the function uses it to built cache and reduce the number ofrequests which we call to the external APIs. In case when we have the same payloadin a cache as we're going to send now, we will skip an additional request and usethe response fetched from cache.