Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add cache for SHIPPING_LIST_METHODS_FOR_CHECKOUT event (#12716) (#12736)
Iga Karbowiak1abda1e0d36e
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex e78894cab6..1f97240856 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -865,11 +865,11 @@ def test_add_checkout_lines_with_external_shipping(api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables))assert not response["data"]["checkoutLinesAdd"]["errors"]- # Three api calls:+ # Two api calls :# - post-mutate() logic used to validate currently selected method- # - fetch_checkout_data - calculating all prices for checkout- # - in check_stock_quantity_bulk to check if the shipping method is set- assert mock_send_request.call_count == 3+ # - fetch_checkout_prices_if_expired - calculating all prices for checkout+ # - (cached) in check_stock_quantity_bulk to check if the shipping method is set+ assert mock_send_request.call_count == 2@pytest.mark.django_dbdiff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex fefeb1dbb3..3d99adca85 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -1,9 +1,10 @@import jsonimport loggingfrom decimal import Decimal-from typing import TYPE_CHECKING, Any, DefaultDict, List, Optional, Set, Union+from typing import TYPE_CHECKING, Any, DefaultDict, Final, List, Optional, Set, Unionimport graphene+from django.core.cache import cachefrom ...app.models import Appfrom ...checkout.models import Checkout@@ -58,7 +59,11 @@ from ...webhook.payloads import (from ...webhook.utils import get_webhooks_for_eventfrom ..base_plugin import BasePlugin, ExcludedShippingMethodfrom .const import CACHE_EXCLUDED_SHIPPING_KEY-from .shipping import get_excluded_shipping_data, parse_list_shipping_methods_response+from .shipping import (+ generate_cache_key_for_shipping_list_methods_for_checkout,+ get_excluded_shipping_data,+ parse_list_shipping_methods_response,+)from .tasks import (send_webhook_request_async,trigger_all_webhooks_sync,@@ -104,6 +109,10 @@ if TYPE_CHECKING:from ...warehouse.models import Stock, Warehousefrom ...webhook.models import Webhook++CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT: Final[int] = 5 * 60 # 5 minutes++logger = logging.getLogger(__name__)@@ -1606,7 +1615,7 @@ class WebhookPlugin(BasePlugin):subscribable_object = (source_object, gateway_data, amount)response_data = trigger_webhook_sync(event_type=WebhookEventSyncType.PAYMENT_GATEWAY_INITIALIZE_SESSION,- data=json.dumps(payload, cls=CustomJsonEncoder),+ payload=json.dumps(payload, cls=CustomJsonEncoder),webhook=webhook,subscribable_object=subscribable_object,request=request,@@ -1691,7 +1700,7 @@ class WebhookPlugin(BasePlugin):response_data = trigger_webhook_sync(event_type=webhook_event,- data=payload,+ payload=payload,webhook=webhook,subscribable_object=transaction_session_data,)@@ -1742,7 +1751,7 @@ class WebhookPlugin(BasePlugin):response_data = trigger_webhook_sync(event_type=event_type,- data=generate_list_gateways_payload(currency, checkout),+ payload=generate_list_gateways_payload(currency, checkout),webhook=webhook,subscribable_object=checkout,)@@ -1892,12 +1901,26 @@ class WebhookPlugin(BasePlugin):raise PaymentError(f"No payment webhook found for event: {event_type}.")- response_data = trigger_webhook_sync(- event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,- data=payload,- webhook=webhook,- subscribable_object=checkout,++ cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(+ payload, webhook.target_url)+ response_data = cache.get(cache_key)++ if response_data is None:+ response_data = trigger_webhook_sync(+ event_type=WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ payload=payload,+ webhook=webhook,+ subscribable_object=checkout,+ )+ if response_data is not None:+ cache.set(+ cache_key,+ response_data,+ CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT,+ )+if response_data:shipping_methods = parse_list_shipping_methods_response(response_data, webhook.appdiff --git a/saleor/plugins/webhook/shipping.py b/saleor/plugins/webhook/shipping.pyindex 273104221c..380cf35324 100644--- a/saleor/plugins/webhook/shipping.py+++ b/saleor/plugins/webhook/shipping.py@@ -1,4 +1,5 @@import base64+import hashlibimport jsonimport loggingfrom collections import defaultdict@@ -203,3 +204,18 @@ def parse_excluded_shipping_methods())return excluded_methods_map+++def generate_cache_key_for_shipping_list_methods_for_checkout(+ payload: str, target_url: str+) -> str:+ 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]["meta"].pop("issued_at")++ # make cache key+ key = json.dumps(key_data)+ key = f"{target_url}-{hashlib.sha256(key.encode('utf-8')).hexdigest()}"+ return keydiff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.pyindex 61096e4377..1eef953674 100644--- a/saleor/plugins/webhook/tasks.py+++ b/saleor/plugins/webhook/tasks.py@@ -226,13 +226,16 @@ def group_webhooks_by_subscription(webhooks):def trigger_webhook_sync(event_type: str,- data: str,+ payload: str,webhook: "Webhook",subscribable_object=None,timeout=None,request=None,) -> Optional[Dict[Any, Any]]:"""Send a synchronous webhook request."""+ if not webhook:+ raise PaymentError(f"No payment webhook found for event: {event_type}.")+if webhook.subscription_query:delivery = create_delivery_for_subscription_sync_event(event_type=event_type,@@ -243,16 +246,18 @@ def trigger_webhook_sync(if not delivery:return Noneelse:- event_payload = EventPayload.objects.create(payload=data)+ event_payload = EventPayload.objects.create(payload=payload)delivery = EventDelivery.objects.create(status=EventDeliveryStatus.PENDING,event_type=event_type,payload=event_payload,webhook=webhook,)+kwargs = {}if timeout:kwargs = {"timeout": timeout}+return send_webhook_request_sync(webhook.app.name, delivery, **kwargs)diff --git a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.pynew file mode 100644index 0000000000..8825a13d4f--- /dev/null+++ b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py@@ -0,0 +1,173 @@+import json+from datetime import timedelta+from decimal import Decimal+from unittest import mock++from django.utils import timezone++from ....webhook.payloads import generate_checkout_payload+from ..shipping import generate_cache_key_for_shipping_list_methods_for_checkout++[email protected]("saleor.plugins.webhook.plugin.cache.set")[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_methods_for_checkout_set_cache(+ mocked_webhook,+ mocked_cache_set,+ webhook_plugin,+ checkout_with_item,+ shipping_app,+):+ # given+ mocked_webhook.return_value = [+ {+ "id": "method-1",+ "name": "Standard Shipping",+ "amount": Decimal("5.5"),+ "currency": "GBP",+ }+ ]+ plugin = webhook_plugin()++ # when+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)++ # then+ assert mocked_webhook.called+ assert mocked_cache_set.called++[email protected]("saleor.plugins.webhook.plugin.cache.set")[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_methods_no_webhook_response_does_not_set_cache(+ mocked_webhook,+ mocked_cache_set,+ webhook_plugin,+ checkout_with_item,+ shipping_app,+):+ # given+ mocked_webhook.return_value = None+ plugin = webhook_plugin()++ # when+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)++ # then+ assert mocked_webhook.called+ assert not mocked_cache_set.called++[email protected]("saleor.plugins.webhook.plugin.cache.get")[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_methods_for_checkout_use_cache(+ mocked_webhook,+ mocked_cache_get,+ webhook_plugin,+ checkout_with_item,+ shipping_app,+):+ # given+ mocked_cache_get.return_value = [+ {+ "id": "method-1",+ "name": "Standard Shipping",+ "amount": Decimal("5.5"),+ "currency": "GBP",+ }+ ]+ plugin = webhook_plugin()++ # when+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)++ # then+ assert not mocked_webhook.called+ assert mocked_cache_get.called++[email protected]("saleor.plugins.webhook.plugin.cache.get")[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")+def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(+ mocked_webhook,+ mocked_cache_get,+ webhook_plugin,+ checkout_with_item,+ shipping_app,+):+ # given+ mocked_cache_get.return_value = []+ plugin = webhook_plugin()++ # when+ plugin.get_shipping_methods_for_checkout(checkout_with_item, None)++ # then+ assert not mocked_webhook.called+ assert mocked_cache_get.called+++def test_checkout_change_invalidates_cache_key(checkout_with_item, shipping_app):+ # given+ payload = generate_checkout_payload(checkout_with_item)+ target_url = shipping_app.webhooks.first().target_url+ cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(+ payload, target_url+ )++ # when+ checkout_with_item.email = "[email protected]"+ checkout_with_item.save(update_fields=["email"])+ new_payload = generate_checkout_payload(checkout_with_item)+ new_cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(+ new_payload, target_url+ )++ # then+ assert cache_key != new_cache_key+++def test_ignore_selected_fields_on_generating_cache_key(+ checkout_with_item, shipping_app+):+ # given+ target_url = shipping_app.webhooks.first().target_url++ payload = generate_checkout_payload(checkout_with_item)+ cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(+ payload, target_url+ )++ # when+ checkout_with_item.last_change = timezone.now() + timedelta(seconds=30)+ checkout_with_item.save(update_fields=["last_change"])++ new_payload = generate_checkout_payload(checkout_with_item)+ new_payload_data = json.loads(new_payload)+ new_payload_data[0]["meta"]["issued_at"] = timezone.now().isoformat()+ new_payload = json.dumps(new_payload_data)+ new_cache_key = generate_cache_key_for_shipping_list_methods_for_checkout(+ new_payload, target_url+ )++ # then+ assert cache_key == new_cache_key+++def test_different_target_urls_produce_different_cache_key(checkout_with_item):+ # given+ target_url_1 = "http://example.com/1"+ target_url_2 = "http://example.com/2"++ payload = generate_checkout_payload(checkout_with_item)++ # when+ cache_key_1 = generate_cache_key_for_shipping_list_methods_for_checkout(+ payload, target_url_1+ )+ cache_key_2 = generate_cache_key_for_shipping_list_methods_for_checkout(+ payload, target_url_2+ )++ # then+ assert cache_key_1 != cache_key_2