Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Move webhook plugin tasks and utils to dedicated directories (#14010)

Artur69764fe5ddf7
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index f6d023eba0..fc0a3a293f 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -474,7 +474,7 @@ def update_checkout_info_delivery_method_info(
The attribute is lazy-evaluated avoid external API calls unless accessed.
"""
- from ..plugins.webhook.shipping import convert_to_app_id_with_identifier
+ from ..webhook.transport.shipping import convert_to_app_id_with_identifier
from .utils import get_external_shipping_id
delivery_method: Optional[Union[ShippingMethodData, Warehouse, Callable]] = None
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 9b7b211636..7c7b988c2c 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -76,7 +76,7 @@ def test_is_valid_delivery_method(checkout_with_item, address, shipping_zone):
assert not delivery_method_info.is_method_in_valid_methods(checkout_info)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_is_valid_delivery_method_external_method(
mock_send_request, checkout_with_item, address, settings, shipping_app
):
@@ -113,7 +113,7 @@ def test_is_valid_delivery_method_external_method(
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_is_valid_delivery_method_external_method_shipping_app_id_with_identifier(
mock_send_request, checkout_with_item, address, settings, shipping_app
):
@@ -153,7 +153,7 @@ def test_is_valid_delivery_method_external_method_shipping_app_id_with_identifie
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_is_valid_delivery_method_external_method_old_shipping_app_id(
mock_send_request, checkout_with_item, address, settings, shipping_app
):
@@ -193,7 +193,7 @@ def test_is_valid_delivery_method_external_method_old_shipping_app_id(
assert delivery_method_info.is_method_in_valid_methods(checkout_info)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_is_valid_delivery_method_external_method_no_longer_available(
mock_send_request, checkout_with_item, address, settings, shipping_app
):
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
index 83ae7cb8f7..e87d884cd9 100644
--- a/saleor/core/tests/test_taxes.py
+++ b/saleor/core/tests/test_taxes.py
@@ -6,9 +6,9 @@ from ...permission.enums import (
OrderPermissions,
get_permissions_from_codenames,
)
-from ...plugins.webhook.utils import get_current_tax_app
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.models import Webhook, WebhookEvent
+from ...webhook.transport.utils import get_current_tax_app
@pytest.fixture
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index aa9585a801..60fa1bd96a 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -17,11 +17,11 @@ from ....checkout.utils import (
is_shipping_required,
set_external_shipping_id,
)
-from ....plugins.webhook.utils import APP_ID_PREFIX
from ....shipping import interface as shipping_interface
from ....shipping import models as shipping_models
from ....shipping.utils import convert_to_shipping_method_data
from ....warehouse import models as warehouse_models
+from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_31, ADDED_IN_34, DEPRECATED_IN_3X_INPUT
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index 3c00d80eb5..72740fc3f3 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -12,10 +12,10 @@ from ....checkout.utils import (
is_shipping_required,
set_external_shipping_id,
)
-from ....plugins.webhook.utils import APP_ID_PREFIX
from ....shipping import interface as shipping_interface
from ....shipping import models as shipping_models
from ....shipping.utils import convert_to_shipping_method_data
+from ....webhook.const import APP_ID_PREFIX
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 8ee2e56d3e..00fda60737 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -736,7 +736,7 @@ MUTATION_CHECKOUT_LINES_ADD = (
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_add_checkout_lines(
mock_send_request,
api_client,
@@ -809,7 +809,7 @@ def test_add_checkout_lines(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_add_checkout_lines_with_external_shipping(
mock_send_request,
api_client,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index 14d6b39b09..15c7dd6639 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -4,7 +4,7 @@ import pytest
from django.utils import timezone
from .....checkout.utils import set_external_shipping_id
-from .....plugins.webhook.shipping import to_shipping_app_id
+from .....webhook.transport.shipping import to_shipping_app_id
from ....tests.utils import get_graphql_content
@@ -146,7 +146,7 @@ def test_user_checkout_details(user_api_client, customer_checkout, count_queries
get_graphql_content(user_api_client.post_graphql(query))
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_user_checkout_details_with_external_shipping_method(
mock_send_request,
app,
@@ -200,7 +200,7 @@ def test_user_checkout_details_with_external_shipping_method(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_user_checkout_details_with_tax_app(
mock_send_request,
user_api_client,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 3d8634ffea..9b31d77efb 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -157,7 +157,7 @@ def test_checkout_add_already_applied_voucher_for_entire_order(
assert checkout_data["discount"]["amount"] == net.amount
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_add_voucher_code_by_token_with_external_shipment(
mock_send_request,
api_client,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index bab605d811..26852b4a3c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -194,7 +194,7 @@ def test_checkout_delivery_method_update_no_checkout_metadata(
@pytest.mark.parametrize("is_valid_delivery_method", (True, False))
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@patch(
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
"clean_delivery_method"
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index fc14c1fc20..e640648a40 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -103,7 +103,7 @@ def test_checkout_shipping_method_update(
assert checkout.last_change == previous_last_change
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_shipping_method_update_external_shipping_method(
mock_send_request,
staff_api_client,
@@ -147,7 +147,7 @@ def test_checkout_shipping_method_update_external_shipping_method(
assert PRIVATE_META_APP_SHIPPING_ID in checkout.metadata_storage.private_metadata
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_shipping_method_update_external_shipping_method_with_tax_plugin(
mock_send_request,
staff_api_client,
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 7a261d4334..300fff7e6f 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -763,7 +763,7 @@ def test_checkout_available_shipping_methods_excluded_postal_codes(
assert data["availableShippingMethods"] == []
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_checkout_available_shipping_methods_with_price_displayed(
send_webhook_request_sync,
monkeypatch,
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py b/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py
index 6f2ef4e951..a18603ab69 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_method_initialize_tokenization.py
@@ -9,7 +9,7 @@ from .....payment.interface import (
PaymentMethodTokenizationResult,
)
from .....plugins.manager import PluginsManager
-from .....plugins.webhook.utils import to_payment_app_id
+from .....webhook.transport.utils import to_payment_app_id
from ....core.enums import PaymentMethodInitializeTokenizationErrorCode
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import PaymentMethodTokenizationResultEnum, TokenizedPaymentFlowEnum
diff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.py
index d1b36541b5..84de7f9846 100644
--- a/saleor/graphql/webhook/mutations/webhook_trigger.py
+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py
@@ -112,7 +112,7 @@ class WebhookTrigger(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
- from ....plugins.webhook.tasks import (
+ from ....webhook.transport.asynchronous.transport import (
create_deliveries_for_subscriptions,
send_webhook_request_async,
)
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
index 84aac775a0..f46a27b197 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py
@@ -28,7 +28,9 @@ WEBHOOK_TRIGGER_MUTATION = """
"""
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_webhook_trigger_success(
mock_send_webhook_using_scheme_method,
async_subscription_webhooks_with_root_objects,
@@ -68,7 +70,7 @@ def test_webhook_trigger_success(
assert not data["delivery"]["payload"]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
[email protected]("saleor.webhook.transport.utils.send_webhook_using_scheme_method")
def test_webhook_trigger_type_not_supported(
mock_send_webhook_using_scheme_method,
async_subscription_webhooks_with_root_objects,
@@ -116,7 +118,9 @@ def test_webhook_trigger_type_not_supported(
]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_webhook_trigger_fail(
mock_send_webhook_using_scheme_method,
staff_api_client,
@@ -150,7 +154,9 @@ def test_webhook_trigger_fail(
assert payload["order"]["id"] == order_id
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_missing_user_permission(
mocked_send_webhook_request,
staff_api_client,
@@ -179,7 +185,9 @@ def test_webhook_trigger_missing_user_permission(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_staff_user_not_authorized(
mocked_send_webhook_request,
user_api_client,
@@ -204,7 +212,9 @@ def test_webhook_trigger_staff_user_not_authorized(
assert_no_permission(response)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_missing_subscription_query(
mocked_send_webhook_request,
staff_api_client,
@@ -236,7 +246,9 @@ def test_webhook_trigger_missing_subscription_query(
assert error["message"] == "Missing subscription query for given webhook."
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_invalid_subscription_query(
mocked_send_webhook_request,
staff_api_client,
@@ -270,7 +282,9 @@ def test_webhook_trigger_invalid_subscription_query(
assert 'Unknown type "UndefinedEvent"' in error["message"]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_event_not_supported(
mocked_send_webhook_request,
staff_api_client,
@@ -303,7 +317,9 @@ def test_webhook_trigger_event_not_supported(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
def test_webhook_trigger_object_id_does_not_match_event(
mocked_send_webhook_request,
staff_api_client,
diff --git a/saleor/plugins/webhook/__init__.py b/saleor/plugins/webhook/__init__.py
index 52b14e76c3..e69de29bb2 100644
--- a/saleor/plugins/webhook/__init__.py
+++ b/saleor/plugins/webhook/__init__.py
@@ -1,12 +0,0 @@
-import hashlib
-import hmac
-from typing import Optional
-
-from ...core.jwt_manager import get_jwt_manager
-
-
-def signature_for_payload(body: bytes, secret_key: Optional[str]):
- if not secret_key:
- return get_jwt_manager().jws_encode(body)
- hash = hmac.new(bytes(secret_key, "utf-8"), body, hashlib.sha256)
- return hash.hexdigest()
diff --git a/saleor/plugins/webhook/list_stored_payment_methods.py b/saleor/plugins/webhook/list_stored_payment_methods.py
deleted file mode 100644
index a3685d76df..0000000000
--- a/saleor/plugins/webhook/list_stored_payment_methods.py
+++ /dev/null
@@ -1,139 +0,0 @@
-import logging
-from typing import Optional, cast
-
-from ...app.models import App
-from ...payment import TokenizedPaymentFlow
-from ...payment.interface import (
- PaymentGateway,
- PaymentMethodCreditCardInfo,
- PaymentMethodData,
-)
-from .utils import to_payment_app_id
-
-logger = logging.getLogger(__name__)
-
-
-def get_credit_card_info(
- app: App, credit_card_info: dict
-) -> Optional[PaymentMethodCreditCardInfo]:
- required_fields = [
- "brand",
- "lastDigits",
- "expYear",
- "expMonth",
- ]
- brand = credit_card_info.get("brand")
- last_digits = credit_card_info.get("lastDigits")
- exp_year = credit_card_info.get("expYear")
- exp_month = credit_card_info.get("expMonth")
- first_digits = credit_card_info.get("firstDigits")
- if not all(field in credit_card_info for field in required_fields):
- logger.warning(
- "Skipping stored payment method. Missing required fields for credit card "
- "info. Required fields: %s, received fields: %s from app %s.",
- required_fields,
- credit_card_info.keys(),
- app.id,
- )
- return None
- if not all([brand, last_digits, exp_year, exp_month]):
- logger.warning("Skipping stored credit card info without required fields")
- return None
- if not isinstance(exp_year, int):
- if isinstance(exp_year, str) and exp_year.isdigit():
- exp_year = int(exp_year)
- else:
- logger.warning(
- "Skipping stored payment method with invalid expYear, "
- "received from app %s",
- app.id,
- )
- return None
-
- if not isinstance(exp_month, int):
- if isinstance(exp_month, str) and exp_month.isdigit():
- exp_month = int(exp_month)
- else:
- logger.warning(
- "Skipping stored payment method with invalid expMonth, "
- "received from app %s",
- app.id,
- )
- return None
-
- return PaymentMethodCreditCardInfo(
- brand=str(brand),
- last_digits=str(last_digits),
- exp_year=exp_year,
- exp_month=exp_month,
- first_digits=str(first_digits) if first_digits else None,
- )
-
-
-def get_payment_method_from_response(
- app: "App", payment_method: dict, currency: str
-) -> Optional[PaymentMethodData]:
- payment_method_external_id = payment_method.get("id")
- if not payment_method_external_id:
- logger.warning(
- "Skipping stored payment method without id, received from app %s", app.id
- )
- return None
- payment_method_type = payment_method.get("type")
- if not payment_method_type:
- logger.warning(
- "Skipping stored payment method without type, received from app %s",
- app.id,
- )
- return None
-
- supported_payment_flows = payment_method.get("supportedPaymentFlows")
- if not supported_payment_flows or not isinstance(supported_payment_flows, list):
- logger.warning(
- "Skipping stored payment method with incorrect `supportedPaymentFlows`, "
- "received from app %s",
- app.id,
- )
- return None
- payment_flow_choices = {
- flow[0].upper(): flow[0] for flow in TokenizedPaymentFlow.CHOICES
- }
- if set(supported_payment_flows).difference(payment_flow_choices.keys()):
- logger.warning(
- "Skipping stored payment method with unsupported payment flows, "
- "received from app %s",
- app.id,
- )
- return None
- app_identifier = cast(str, app.identifier)
- credit_card_info = payment_method.get("creditCardInfo")
- name = payment_method.get("name")
- return PaymentMethodData(
- id=to_payment_app_id(app, payment_method_external_id),
- external_id=payment_method_external_id,
- supported_payment_flows=[
- payment_flow_choices[flow] for flow in supported_payment_flows
- ],
- type=payment_method_type,
- credit_card_info=get_credit_card_info(app, credit_card_info)
- if credit_card_info
- else None,
- name=name if name else None,
- data=payment_method.get("data"),
- gateway=PaymentGateway(
- id=app_identifier, name=app.name, currencies=[currency], config=[]
- ),
- )
-
-
-def get_list_stored_payment_methods_from_response(
- app: "App", response_data: dict, currency: str
-) -> list["PaymentMethodData"]:
- payment_methods_response = response_data.get("paymentMethods", [])
- payment_methods = []
- for payment_method in payment_methods_response:
- if parsed_payment_method := get_payment_method_from_response(
- app, payment_method, currency
- ):
- payment_methods.append(parsed_payment_method)
- return payment_methods
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 41ac31a4b3..d94ae3948e 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -52,6 +52,7 @@ from ...payment.interface import (
from ...payment.models import Payment, TransactionItem
from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...thumbnail.models import Thumbnail
+from ...webhook.const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.payloads import (
generate_checkout_payload,
@@ -81,15 +82,11 @@ from ...webhook.payloads import (
generate_transaction_session_payload,
generate_translation_payload,
)
-from ...webhook.utils import get_webhooks_for_event
-from ..base_plugin import BasePlugin, ExcludedShippingMethod
-from .const import CACHE_EXCLUDED_SHIPPING_KEY, WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from .shipping import (
- get_cache_data_for_shipping_list_methods_for_checkout,
- get_excluded_shipping_data,
- parse_list_shipping_methods_response,
+from ...webhook.transport.asynchronous.transport import (
+ send_webhook_request_async,
+ trigger_webhooks_async,
)
-from .stored_payment_methods import (
+from ...webhook.transport.list_stored_payment_methods import (
get_list_stored_payment_methods_data_dict,
get_list_stored_payment_methods_from_response,
get_response_for_payment_gateway_initialize_tokenization,
@@ -97,15 +94,17 @@ from .stored_payment_methods import (
get_response_for_stored_payment_method_request_delete,
invalidate_cache_for_stored_payment_methods,
)
-from .tasks import (
- send_webhook_request_async,
+from ...webhook.transport.shipping import (
+ get_cache_data_for_shipping_list_methods_for_checkout,
+ get_excluded_shipping_data,
+ parse_list_shipping_methods_response,
+)
+from ...webhook.transport.synchronous.transport import (
trigger_all_webhooks_sync,
- trigger_transaction_request,
trigger_webhook_sync,
trigger_webhook_sync_if_not_cached,
- trigger_webhooks_async,
)
-from .utils import (
+from ...webhook.transport.utils import (
DEFAULT_TAX_CODE,
DEFAULT_TAX_DESCRIPTION,
delivery_update,
@@ -116,7 +115,10 @@ from .utils import (
parse_list_payment_gateways_response,
parse_payment_action_response,
parse_tax_data,
+ trigger_transaction_request,
)
+from ...webhook.utils import get_webhooks_for_event
+from ..base_plugin import BasePlugin, ExcludedShippingMethod
if TYPE_CHECKING:
from ...account.models import Address, Group, User
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index d48296db18..18a9d81c32 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -1,601 +1,16 @@
-import json
import logging
-from dataclasses import dataclass
-from enum import Enum
-from json import JSONDecodeError
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, TypeVar
-from urllib.parse import unquote, urlparse, urlunparse
-import boto3
-from botocore.exceptions import ClientError
-from celery import group
-from celery.exceptions import MaxRetriesExceededError, Retry
from celery.utils.log import get_task_logger
from django.conf import settings
-from django.core.cache import cache
-from django.urls import reverse
-from google.cloud import pubsub_v1
-from requests.exceptions import RequestException
-from requests_hardened.ip_filter import InvalidIPAddress
-from ...app.headers import AppHeaders, DeprecatedAppHeaders
from ...celeryconf import app
-from ...core import EventDeliveryStatus
-from ...core.http_client import HTTPClient
-from ...core.models import EventDelivery, EventPayload
-from ...core.tracing import webhooks_opentracing_trace
-from ...core.utils import build_absolute_uri
-from ...core.utils.events import call_event
-from ...graphql.webhook.subscription_payload import (
- generate_payload_from_subscription,
- initialize_request,
-)
-from ...graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
-from ...payment import PaymentError
-from ...payment.interface import TransactionActionData
-from ...payment.models import TransactionEvent
-from ...payment.utils import (
- create_failed_transaction_event,
- create_transaction_event_from_request_and_webhook_response,
-)
-from ...site.models import Site
-from ...webhook import observability
-from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from ...webhook.observability import WebhookData
-from ...webhook.payloads import generate_transaction_action_request_payload
-from ...webhook.utils import get_webhooks_for_event
-from . import signature_for_payload
-from .const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from .utils import (
- attempt_update,
- catch_duration_time,
- clear_successful_delivery,
- create_attempt,
- create_event_delivery_list_for_webhooks,
- delivery_update,
- generate_cache_key_for_webhook,
- get_delivery_for_webhook,
-)
-
-if TYPE_CHECKING:
- from ...webhook.models import Webhook
logger = logging.getLogger(__name__)
task_logger = get_task_logger(__name__)
-class WebhookSchemes(str, Enum):
- HTTP = "http"
- HTTPS = "https"
- AWS_SQS = "awssqs"
- GOOGLE_CLOUD_PUBSUB = "gcpubsub"
-
-
-@dataclass
-class WebhookResponse:
- content: str
- request_headers: Optional[Dict] = None
- response_headers: Optional[Dict] = None
- response_status_code: Optional[int] = None
- status: str = EventDeliveryStatus.SUCCESS
- duration: float = 0.0
-
-
-def create_deliveries_for_subscriptions(
- event_type, subscribable_object, webhooks, requestor=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.
- """
- if event_type not in WEBHOOK_TYPES_MAP:
- logger.info(
- "Skipping subscription webhook. Event %s is not subscribable.", event_type
- )
- return []
-
- event_payloads = []
- event_deliveries = []
- for webhook in webhooks:
- data = generate_payload_from_subscription(
- event_type=event_type,
- subscribable_object=subscribable_object,
- subscription_query=webhook.subscription_query,
- request=initialize_request(
- requestor,
- event_type in WebhookEventSyncType.ALL,
- event_type=event_type,
- ),
- app=webhook.app,
- )
- if not data:
- logger.info(
- "No payload was generated with subscription for event: %s" % event_type
- )
- continue
- event_payload = EventPayload(payload=json.dumps({**data}))
- event_payloads.append(event_payload)
- event_deliveries.append(
- EventDelivery(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
- )
-
- EventPayload.objects.bulk_create(event_payloads)
- return EventDelivery.objects.bulk_create(event_deliveries)
-
-
-def create_delivery_for_subscription_sync_event(
- event_type, subscribable_object, webhook, requestor=None, request=None
-) -> Optional[EventDelivery]:
- """Generate webhook payload based on subscription query and create delivery object.
-
- It uses a defined 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 webhook: webhook object for which delivery will be created.
- :param requestor: used in subscription webhooks to generate meta data for payload.
- :param request: used to share context between sync event calls
- :return: List of event deliveries to send via webhook tasks.
- """
- if event_type not in WEBHOOK_TYPES_MAP:
- logger.info(
- "Skipping subscription webhook. Event %s is not subscribable.", event_type
- )
- return None
-
- if not request:
- request = initialize_request(
- requestor, event_type in WebhookEventSyncType.ALL, event_type=event_type
- )
-
- data = generate_payload_from_subscription(
- event_type=event_type,
- subscribable_object=subscribable_object,
- subscription_query=webhook.subscription_query,
- request=request,
- app=webhook.app,
- )
- if not data:
- # PaymentError is a temporary exception type. New type will be implemented
- # in separate PR to ensure proper handling for all sync events.
- # It was implemented when sync webhooks were handling payment events only.
- raise PaymentError(
- f"No payload was generated with subscription for event: {event_type}"
- )
- event_payload = EventPayload.objects.create(payload=json.dumps({**data}))
- event_delivery = EventDelivery.objects.create(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
- return event_delivery
-
-
-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,
-):
- """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 meta data for payload.
- :param legacy_data_generator: used to generate payload for regular webhooks.
- """
- 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.")
-
- payload = EventPayload.objects.create(payload=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(
- event_type=event_type,
- subscribable_object=subscribable_object,
- webhooks=subscription_webhooks,
- requestor=requestor,
- )
- )
-
- for delivery in deliveries:
- send_webhook_request_async.delay(delivery.id)
-
-
-def group_webhooks_by_subscription(webhooks):
- subscription = [webhook for webhook in webhooks if webhook.subscription_query]
- regular = [webhook for webhook in webhooks if not webhook.subscription_query]
-
- return regular, subscription
-
-
-def trigger_webhook_sync_if_not_cached(
- event_type: str,
- payload: str,
- webhook: "Webhook",
- cache_data: dict,
- subscribable_object=None,
- request_timeout=None,
- cache_timeout=None,
- request=None,
-) -> Optional[dict]:
- """Get response for synchronous webhook.
-
- - Send a synchronous webhook request if cache is expired.
- - Fetch response from cache if it is still valid.
- """
-
- cache_key = generate_cache_key_for_webhook(
- cache_data, webhook.target_url, event_type, webhook.app_id
- )
- response_data = cache.get(cache_key)
- if response_data is None:
- response_data = trigger_webhook_sync(
- event_type,
- payload,
- webhook,
- subscribable_object=subscribable_object,
- timeout=request_timeout,
- request=request,
- )
- if response_data is not None:
- cache.set(
- cache_key,
- response_data,
- timeout=cache_timeout or WEBHOOK_CACHE_DEFAULT_TIMEOUT,
- )
- return response_data
-
-
-def trigger_webhook_sync(
- event_type: str,
- payload: str,
- webhook: "Webhook",
- subscribable_object=None,
- timeout=None,
- request=None,
-) -> Optional[Dict[Any, Any]]:
- """Send a synchronous webhook request."""
- if webhook.subscription_query:
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=subscribable_object,
- webhook=webhook,
- request=request,
- )
- if not delivery:
- return None
- else:
- 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(delivery, **kwargs)
-
-
-R = TypeVar("R")
-
-
-def trigger_all_webhooks_sync(
- event_type: str,
- generate_payload: Callable,
- parse_response: Callable[[Any], Optional[R]],
- subscribable_object=None,
- requestor=None,
- allow_replica=True,
-) -> Optional[R]:
- """Send all synchronous webhook request for given event type.
-
- Requests are send sequentially.
- If the current webhook does not return expected response,
- the next one is send.
- If no webhook responds with expected response,
- this function returns None.
- """
- webhooks = get_webhooks_for_event(event_type)
- request_context = None
- event_payload = None
- for webhook in webhooks:
- if webhook.subscription_query:
- if request_context is None:
- request_context = initialize_request(
- requestor,
- event_type in WebhookEventSyncType.ALL,
- allow_replica,
- event_type=event_type,
- )
-
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=subscribable_object,
- webhook=webhook,
- request=request_context,
- requestor=requestor,
- )
- if not delivery:
- return None
- else:
- if event_payload is None:
- event_payload = EventPayload.objects.create(payload=generate_payload())
- delivery = EventDelivery.objects.create(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
-
- response_data = send_webhook_request_sync(delivery)
- if parsed_response := parse_response(response_data):
- return parsed_response
- return None
-
-
-def send_webhook_using_http(
- target_url,
- message,
- domain,
- signature,
- event_type,
- timeout=settings.WEBHOOK_TIMEOUT,
- custom_headers: Optional[Dict[str, str]] = None,
-) -> WebhookResponse:
- """Send a webhook request using http / https protocol.
-
- :param target_url: Target URL request will be sent to.
- :param message: Payload that will be used.
- :param domain: Current site domain.
- :param signature: Webhook secret key checksum.
- :param event_type: Webhook event type.
- :param timeout: Request timeout.
- :param custom_headers: Custom headers which will be added to request headers.
-
- :return: WebhookResponse object.
- """
- headers = {
- "Content-Type": "application/json",
- # X- headers will be deprecated in Saleor 4.0, proper headers are without X-
- DeprecatedAppHeaders.EVENT_TYPE: event_type,
- DeprecatedAppHeaders.DOMAIN: domain,
- DeprecatedAppHeaders.SIGNATURE: signature,
- AppHeaders.EVENT_TYPE: event_type,
- AppHeaders.DOMAIN: domain,
- AppHeaders.SIGNATURE: signature,
- AppHeaders.API_URL: build_absolute_uri(reverse("api"), domain),
- }
-
- if custom_headers:
- headers.update(custom_headers)
-
- try:
- response = HTTPClient.send_request(
- "POST",
- target_url,
- data=message,
- headers=headers,
- timeout=timeout,
- allow_redirects=False,
- )
- except RequestException as e:
- if e.response:
- return WebhookResponse(
- content=e.response.text,
- status=EventDeliveryStatus.FAILED,
- request_headers=headers,
- response_headers=dict(e.response.headers),
- response_status_code=e.response.status_code,
- )
-
- if isinstance(e, InvalidIPAddress):
- message = "Invalid IP address"
- else:
- message = str(e)
- result = WebhookResponse(
- content=message,
- status=EventDeliveryStatus.FAILED,
- request_headers=headers,
- )
- return result
-
- return WebhookResponse(
- content=response.text,
- request_headers=headers,
- response_headers=dict(response.headers),
- response_status_code=response.status_code,
- duration=response.elapsed.total_seconds(),
- status=(
- EventDeliveryStatus.SUCCESS if response.ok else EventDeliveryStatus.FAILED
- ),
- )
-
-
-def send_webhook_using_aws_sqs(
- target_url, message, domain, signature, event_type, **kwargs
-):
- parts = urlparse(target_url)
- region = "us-east-1"
- hostname_parts = parts.hostname.split(".")
- if len(hostname_parts) == 4 and hostname_parts[0] == "sqs":
- region = hostname_parts[1]
- client = boto3.client(
- "sqs",
- region_name=region,
- aws_access_key_id=parts.username,
- aws_secret_access_key=(
- unquote(parts.password) if parts.password else parts.password
- ),
- )
- queue_url = urlunparse(
- (
- "https",
- parts.hostname,
- parts.path,
- parts.params,
- parts.query,
- parts.fragment,
- )
- )
- is_fifo = parts.path.endswith(".fifo")
-
- msg_attributes = {
- "SaleorDomain": {"DataType": "String", "StringValue": domain},
- "SaleorApiUrl": {
- "DataType": "String",
- "StringValue": build_absolute_uri(reverse("api"), domain),
- },
- "EventType": {"DataType": "String", "StringValue": event_type},
- }
- if signature:
- msg_attributes["Signature"] = {
- "DataType": "String",
- "StringValue": signature,
- }
-
- message_kwargs = {
- "QueueUrl": queue_url,
- "MessageAttributes": msg_attributes,
- "MessageBody": message.decode("utf-8"),
- }
- if is_fifo:
- message_kwargs["MessageGroupId"] = domain
- with catch_duration_time() as duration:
- try:
- response = client.send_message(**message_kwargs)
- except (ClientError,) as e:
- return WebhookResponse(
- content=str(e), status=EventDeliveryStatus.FAILED, duration=duration()
- )
- return WebhookResponse(content=response, duration=duration())
-
-
-def send_webhook_using_google_cloud_pubsub(
- target_url, message, domain, signature, event_type, **kwargs
-):
- parts = urlparse(target_url)
- client = pubsub_v1.PublisherClient()
- topic_name = parts.path[1:] # drop the leading slash
- with catch_duration_time() as duration:
- try:
- future = client.publish(
- topic_name,
- message,
- saleorDomain=domain,
- saleorApiUrl=build_absolute_uri(reverse("api"), domain),
- eventType=event_type,
- signature=signature,
- )
- except (pubsub_v1.publisher.exceptions.MessageTooLargeError, RuntimeError) as e:
- return WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)
- response_duration = duration()
- response = future.result()
- return WebhookResponse(content=response, duration=response_duration)
-
-
-def send_webhook_using_scheme_method(
- target_url,
- domain,
- secret,
- event_type,
- data,
- custom_headers=None,
-) -> WebhookResponse:
- parts = urlparse(target_url)
- message = data.encode("utf-8")
- signature = signature_for_payload(message, secret)
- scheme_matrix: Dict[WebhookSchemes, Callable] = {
- WebhookSchemes.HTTP: send_webhook_using_http,
- WebhookSchemes.HTTPS: send_webhook_using_http,
- WebhookSchemes.AWS_SQS: send_webhook_using_aws_sqs,
- WebhookSchemes.GOOGLE_CLOUD_PUBSUB: send_webhook_using_google_cloud_pubsub,
- }
-
- if send_method := scheme_matrix.get(parts.scheme.lower()):
- # try:
- return send_method(
- target_url,
- message,
- domain,
- signature,
- event_type,
- custom_headers=custom_headers,
- )
- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
-
-
-def handle_webhook_retry(
- celery_task, webhook, response_content, delivery, delivery_attempt
-) -> bool:
- """Handle celery retry for webhook requests.
-
- Calls retry to re-run the celery_task by raising Retry exception.
- When MaxRetriesExceededError is raised the function will end without exception.
- """
- is_success = True
- task_logger.info(
- "[Webhook ID: %r] Failed request to %r: %r for event: %r."
- " Delivery attempt id: %r",
- webhook.id,
- webhook.target_url,
- response_content,
- delivery.event_type,
- delivery_attempt.id,
- )
- try:
- countdown = celery_task.retry_backoff * (2**celery_task.request.retries)
- celery_task.retry(countdown=countdown, **celery_task.retry_kwargs)
- except Retry as retry_error:
- next_retry = observability.task_next_retry_date(retry_error)
- observability.report_event_delivery_attempt(delivery_attempt, next_retry)
- raise retry_error
- except MaxRetriesExceededError:
- is_success = False
- task_logger.info(
- "[Webhook ID: %r] Failed request to %r: exceeded retry limit."
- "Delivery id: %r",
- webhook.id,
- webhook.target_url,
- delivery.id,
- )
- return is_success
+# all tasks to be removed in 3.18.
+# tasks moved to different direction.
@app.task(
@@ -605,275 +20,23 @@ def handle_webhook_retry(
retry_kwargs={"max_retries": 5},
)
def send_webhook_request_async(self, event_delivery_id):
- delivery = get_delivery_for_webhook(event_delivery_id)
- if not delivery:
- return None
-
- webhook = delivery.webhook
- domain = Site.objects.get_current().domain
- attempt = create_attempt(delivery, self.request.id)
- delivery_status = EventDeliveryStatus.SUCCESS
- try:
- if not delivery.payload:
- raise ValueError(
- "Event delivery id: %r has no payload." % event_delivery_id
- )
- data = delivery.payload.payload
- with webhooks_opentracing_trace(delivery.event_type, domain, app=webhook.app):
- response = send_webhook_using_scheme_method(
- webhook.target_url,
- domain,
- webhook.secret_key,
- delivery.event_type,
- data,
- webhook.custom_headers,
- )
-
- attempt_update(attempt, response)
- if response.status == EventDeliveryStatus.FAILED:
- handle_webhook_retry(self, webhook, response.content, delivery, attempt)
- delivery_status = EventDeliveryStatus.FAILED
- elif response.status == EventDeliveryStatus.SUCCESS:
- task_logger.info(
- "[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",
- webhook.id,
- webhook.target_url,
- delivery.event_type,
- delivery.id,
- )
- delivery_update(delivery, delivery_status)
- except ValueError as e:
- response = WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)
- attempt_update(attempt, response)
- delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
- observability.report_event_delivery_attempt(attempt)
- clear_successful_delivery(delivery)
-
-
-def _send_webhook_request_sync(
- delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT, attempt=None
-) -> Tuple[WebhookResponse, Optional[Dict[Any, Any]]]:
- event_payload = delivery.payload
- data = event_payload.payload
- webhook = delivery.webhook
- parts = urlparse(webhook.target_url)
- domain = Site.objects.get_current().domain
- message = data.encode("utf-8")
- signature = signature_for_payload(message, webhook.secret_key)
-
- if parts.scheme.lower() not in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:
- delivery_update(delivery, EventDeliveryStatus.FAILED)
- raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
-
- logger.debug(
- "[Webhook] Sending payload to %r for event %r.",
- webhook.target_url,
- delivery.event_type,
- )
- if attempt is None:
- attempt = create_attempt(delivery=delivery, task_id=None)
- response = WebhookResponse(content="")
- response_data = None
-
- try:
- with webhooks_opentracing_trace(
- delivery.event_type, domain, sync=True, app=webhook.app
- ):
- response = send_webhook_using_http(
- webhook.target_url,
- message,
- domain,
- signature,
- delivery.event_type,
- timeout=timeout,
- custom_headers=webhook.custom_headers,
- )
- response_data = json.loads(response.content)
-
- except JSONDecodeError as e:
- logger.info(
- "[Webhook] Failed parsing JSON response from %r: %r."
- "ID of failed DeliveryAttempt: %r . ",
- webhook.target_url,
- e,
- attempt.id,
- )
- response.status = EventDeliveryStatus.FAILED
- else:
- if response.status == EventDeliveryStatus.FAILED:
- logger.info(
- "[Webhook] Failed request to %r: %r. "
- "ID of failed DeliveryAttempt: %r . ",
- webhook.target_url,
- response.content,
- attempt.id,
- )
- if response.status == EventDeliveryStatus.SUCCESS:
- logger.debug(
- "[Webhook] Success response from %r."
- "Successful DeliveryAttempt id: %r",
- webhook.target_url,
- attempt.id,
- )
+ from ...webhook.transport.asynchronous.transport import send_webhook_request_async
- attempt_update(attempt, response)
- delivery_update(delivery, response.status)
- observability.report_event_delivery_attempt(attempt)
- clear_successful_delivery(delivery)
- return response, response_data
-
-
-def send_webhook_request_sync(
- delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT
-) -> Optional[Dict[Any, Any]]:
- response, response_data = _send_webhook_request_sync(delivery, timeout)
- return response_data if response.status == EventDeliveryStatus.SUCCESS else None
-
-
-def send_observability_events(webhooks: List[WebhookData], events: List[Any]):
- event_type = WebhookEventAsyncType.OBSERVABILITY
- for webhook in webhooks:
- scheme = urlparse(webhook.target_url).scheme.lower()
- failed = 0
- extra = {
- "webhook_id": webhook.id,
- "webhook_target_url": webhook.target_url,
- "events_count": len(events),
- }
- try:
- if scheme in [WebhookSchemes.AWS_SQS, WebhookSchemes.GOOGLE_CLOUD_PUBSUB]:
- for event in events:
- response = send_webhook_using_scheme_method(
- webhook.target_url,
- webhook.saleor_domain,
- webhook.secret_key,
- event_type,
- observability.dump_payload(event),
- )
- if response.status == EventDeliveryStatus.FAILED:
- failed += 1
- else:
- response = send_webhook_using_scheme_method(
- webhook.target_url,
- webhook.saleor_domain,
- webhook.secret_key,
- event_type,
- observability.dump_payload(events),
- )
- if response.status == EventDeliveryStatus.FAILED:
- failed = len(events)
- except ValueError:
- logger.error(
- "Webhook ID: %r unknown webhook scheme: %r.",
- webhook.id,
- scheme,
- extra={**extra, "dropped_events_count": len(events)},
- )
- continue
- if failed:
- logger.info(
- "Webhook ID: %r failed request to %r (%s/%s events dropped): %r.",
- webhook.id,
- webhook.target_url,
- failed,
- len(events),
- response.content,
- extra={**extra, "dropped_events_count": failed},
- )
- continue
- logger.debug(
- "Successful delivered %s events to %r.",
- len(events),
- webhook.target_url,
- extra={**extra, "dropped_events_count": 0},
- )
+ send_webhook_request_async(self, event_delivery_id)
@app.task
def observability_send_events():
- with observability.opentracing_trace("send_events_task", "task"):
- if webhooks := observability.get_webhooks():
- with observability.opentracing_trace("pop_events", "buffer"):
- events, _ = observability.pop_events_with_remaining_size()
- if events:
- with observability.opentracing_trace("send_events", "webhooks"):
- send_observability_events(webhooks, events)
+ from ...webhook.transport.asynchronous.transport import observability_send_events
+
+ observability_send_events()
@app.task
def observability_reporter_task():
- with observability.opentracing_trace("reporter_task", "task"):
- if webhooks := observability.get_webhooks():
- with observability.opentracing_trace("pop_events", "buffer"):
- events, batch_count = observability.pop_events_with_remaining_size()
- if batch_count > 0:
- tasks = [observability_send_events.s() for _ in range(batch_count)]
- expiration = settings.OBSERVABILITY_REPORT_PERIOD.total_seconds()
- group(tasks).apply_async(expires=expiration)
- if events:
- with observability.opentracing_trace("send_events", "webhooks"):
- send_observability_events(webhooks, events)
+ from ...webhook.transport.asynchronous.transport import observability_reporter_task
-
-def trigger_transaction_request(
- transaction_data: "TransactionActionData", event_type: str, requestor
-):
- if not transaction_data.event:
- logger.warning(
- "The transaction request for transaction: %s doesn't have a "
- "proper REQUEST event.",
- transaction_data.transaction.id,
- )
- return None
- if not transaction_data.transaction_app_owner:
- create_failed_transaction_event(
- transaction_data.event,
- cause=(
- "Cannot process the action as the given transaction is not "
- "attached to any app."
- ),
- )
- return None
- webhook = get_webhooks_for_event(
- event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
- ).first()
- if not webhook:
- create_failed_transaction_event(
- transaction_data.event,
- cause="Cannot find a webhook that can process the action.",
- )
- return None
-
- if webhook.subscription_query:
- delivery = create_delivery_for_subscription_sync_event(
- event_type=event_type,
- subscribable_object=transaction_data,
- webhook=webhook,
- )
- if not delivery:
- create_failed_transaction_event(
- transaction_data.event,
- cause="Cannot generate a payload for the action.",
- )
- return None
- else:
- payload = generate_transaction_action_request_payload(
- transaction_data, requestor
- )
- event_payload = EventPayload.objects.create(payload=payload)
- delivery = EventDelivery.objects.create(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
-
- call_event(
- handle_transaction_request_task.delay,
- delivery.id,
- transaction_data.event.id,
- )
- return None
+ observability_reporter_task()
@app.task(
@@ -882,29 +45,8 @@ def trigger_transaction_request(
retry_kwargs={"max_retries": 5},
)
def handle_transaction_request_task(self, delivery_id, request_event_id):
- delivery = get_delivery_for_webhook(delivery_id)
- if not delivery:
- logger.error(
- f"Cannot find the delivery with id: {delivery_id} "
- f"for transaction-request webhook."
- )
- return None
- request_event = TransactionEvent.objects.filter(id=request_event_id).first()
- if not request_event:
- logger.error(
- f"Cannot find the request event with id: {request_event_id} "
- f"for transaction-request webhook."
- )
- return None
- attempt = create_attempt(delivery, self.request.id)
- response, response_data = _send_webhook_request_sync(delivery, attempt=attempt)
- if response.response_status_code and response.response_status_code >= 500:
- handle_webhook_retry(
- self, delivery.webhook, response.content, delivery, attempt
- )
- response_data = None
- create_transaction_event_from_request_and_webhook_response(
- request_event,
- delivery.webhook.app,
- response_data,
+ from ...webhook.transport.synchronous.transport import (
+ handle_transaction_request_task,
)
+
+ handle_transaction_request_task(self, delivery_id, request_event_id)
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
index 1a8da41671..7cbf5a75f6 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_list_payment_methods.py
@@ -4,7 +4,9 @@ import graphene
from .....payment.interface import ListStoredPaymentMethodsRequestData
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
LIST_STORED_PAYMENT_METHODS = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
index d5176c9291..39f018a413 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_session.py
@@ -5,7 +5,9 @@ import graphene
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
PAYMENT_GATEWAY_INITIALIZE_SESSION = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
index 24c9cdeba2..af1711fc4e 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_gateway_initialize_tokenization_session.py
@@ -4,7 +4,9 @@ import graphene
from .....payment.interface import PaymentGatewayInitializeTokenizationRequestData
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
PAYMENT_GATEWAY_INITIALIZE_TOKENIZATION = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
index eda5fe40a6..dc58bed5b3 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_initialize_tokenization.py
@@ -5,7 +5,9 @@ import graphene
from .....payment import TokenizedPaymentFlow
from .....payment.interface import PaymentMethodInitializeTokenizationRequestData
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION = """
subscription{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
index 39ef54f96d..94a8926963 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_process_tokenization.py
@@ -4,7 +4,9 @@ import graphene
from .....payment.interface import PaymentMethodProcessTokenizationRequestData
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = """
subscription{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
index e4ffbedc32..9a3ffaba86 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py
@@ -4,7 +4,9 @@ import graphene
from .....payment.interface import StoredPaymentMethodRequestDeleteData
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
STORED_PAYMENT_METHOD_DELETE_REQUESTED = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 0eea04c966..1c0d638769 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -14,7 +14,10 @@ from .....product.models import Category
from .....shipping.models import ShippingMethod, ShippingZone
from .....site.models import SiteSettings
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions, logger
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+ logger,
+)
from . import subscription_queries
from .payloads import (
generate_account_events_payload,
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscriptions_payments.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscriptions_payments.py
index 907228981a..ca1f42e4b5 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscriptions_payments.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscriptions_payments.py
@@ -3,7 +3,9 @@ import json
import graphene
from .....webhook.event_types import WebhookEventSyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
from .payloads import generate_payment_payload
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index 7a67e9b020..a20f24572a 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -14,7 +14,9 @@ from .....order.models import Order
from .....tests.fixtures import recalculate_order
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_delivery_for_subscription_sync_event
+from .....webhook.transport.synchronous.transport import (
+ create_delivery_for_subscription_sync_event,
+)
TAXES_SUBSCRIPTION_QUERY = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
index f94296af8c..501f5ea3eb 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_cancelation_requested.py
@@ -11,7 +11,9 @@ from .....payment.interface import TransactionActionData
from .....payment.models import TransactionItem
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
TRANSACTION_CANCELATION_REQUESTED_SUBSCRIPTION = (
fragments.TRANSACTION_ITEM_DETAILS
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
index 13436c2d81..9f818802a2 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_charge_requested.py
@@ -11,7 +11,9 @@ from .....payment.interface import TransactionActionData
from .....payment.models import TransactionItem
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
TRANSACTION_CHARGE_REQUESTED_SUBSCRIPTION = (
fragments.TRANSACTION_ITEM_DETAILS
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
index cbf2b5ed66..a28e804ded 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py
@@ -11,7 +11,9 @@ from .....payment.interface import (
)
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
TRANSACTION_INITIALIZE_SESSION = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
index 81eed57945..327b907dd2 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_process_session.py
@@ -11,7 +11,9 @@ from .....payment.interface import (
)
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
TRANSACTION_PROCESS_SESSION = """
subscription {
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
index c83841f87b..69da3130d3 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_refund_requested.py
@@ -11,7 +11,9 @@ from .....payment.interface import TransactionActionData
from .....payment.models import TransactionItem
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
TRANSACTION_REFUND_REQUESTED_SUBSCRIPTION = (
fragments.TRANSACTION_ITEM_DETAILS
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
index 59610e61ed..6f08e97ff2 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_translation_subscription.py
@@ -3,7 +3,9 @@ import json
import graphene
from .....webhook.event_types import WebhookEventAsyncType
-from ...tasks import create_deliveries_for_subscriptions
+from .....webhook.transport.asynchronous.transport import (
+ create_deliveries_for_subscriptions,
+)
def test_translation_created_product(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
index d4a94f87b1..557bd42bf3 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_webhook.py
@@ -13,7 +13,8 @@ from .....graphql.product.tests.mutations.test_product_create import (
)
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from .....webhook.models import Webhook
-from ...tasks import trigger_webhook_sync, trigger_webhooks_async
+from .....webhook.transport.asynchronous.transport import trigger_webhooks_async
+from .....webhook.transport.synchronous.transport import trigger_webhook_sync
from .payloads import generate_payment_payload
TEST_ID = "test_id"
@@ -24,7 +25,9 @@ class FakeDelivery:
id = TEST_ID
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.delay"
+)
def test_trigger_webhooks_async(
mocked_send_webhook_request,
webhook,
@@ -44,8 +47,12 @@ def test_trigger_webhooks_async(
assert mocked_send_webhook_request.mock_calls == calls
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
[email protected]("saleor.plugins.webhook.tasks.create_deliveries_for_subscriptions")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.delay"
+)
+ "saleor.webhook.transport.asynchronous.transport.create_deliveries_for_subscriptions"
+)
def test_trigger_webhooks_async_no_subscription_webhooks(
mocked_create_deliveries_for_subscriptions,
mocked_send_webhook_request,
@@ -59,7 +66,7 @@ def test_trigger_webhooks_async_no_subscription_webhooks(
mocked_create_deliveries_for_subscriptions.assert_not_called()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_webhook_sync_with_subscription(
mock_request, payment_app_with_subscription_webhooks, payment
):
@@ -81,9 +88,11 @@ def test_trigger_webhook_sync_with_subscription(
mock_request.assert_called_once_with(event_delivery)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.plugins.webhook.tasks.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.tasks.generate_payload_from_subscription")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.get_webhooks_for_event")
+ "saleor.webhook.transport.synchronous.transport.generate_payload_from_subscription"
+)
def test_trigger_webhook_sync_with_subscription_within_mutation_use_default_db(
mocked_generate_payload,
mocked_get_webhooks_for_event,
@@ -115,9 +124,13 @@ def test_trigger_webhook_sync_with_subscription_within_mutation_use_default_db(
assert not mocked_generate_payload.call_args[1]["request"].allow_replica
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async")
[email protected]("saleor.plugins.webhook.tasks.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.tasks.generate_payload_from_subscription")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async"
+)
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+ "saleor.webhook.transport.asynchronous.transport.generate_payload_from_subscription"
+)
def test_trigger_webhook_async_with_subscription_use_replica_db(
mocked_generate_payload,
mocked_get_webhooks_for_event,
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.py
index 79660ed56a..ef8f4f8971 100644
--- a/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
+++ b/saleor/plugins/webhook/tests/test_list_shipping_methods_for_checkout.py
@@ -6,13 +6,15 @@ from django.utils import timezone
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.payloads import generate_checkout_payload
+from ....webhook.transport.shipping import (
+ get_cache_data_for_shipping_list_methods_for_checkout,
+)
+from ....webhook.transport.utils import generate_cache_key_for_webhook
from ..plugin import CACHE_TIME_SHIPPING_LIST_METHODS_FOR_CHECKOUT
-from ..shipping import get_cache_data_for_shipping_list_methods_for_checkout
-from ..utils import generate_cache_key_for_webhook
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_set_cache(
mocked_webhook,
mocked_cache_set,
@@ -39,8 +41,8 @@ def test_get_shipping_methods_for_checkout_set_cache(
assert mocked_cache_set.called
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_shipping_methods_no_webhook_response_does_not_set_cache(
mocked_webhook,
mocked_cache_set,
@@ -60,8 +62,8 @@ def test_get_shipping_methods_no_webhook_response_does_not_set_cache(
assert not mocked_cache_set.called
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_use_cache(
mocked_webhook,
mocked_cache_get,
@@ -88,8 +90,8 @@ def test_get_shipping_methods_for_checkout_use_cache(
assert mocked_cache_get.called
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.get")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(
mocked_webhook,
mocked_cache_get,
@@ -109,9 +111,9 @@ def test_get_shipping_methods_for_checkout_use_cache_for_empty_list(
assert mocked_cache_get.called
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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,
@@ -166,9 +168,9 @@ def test_checkout_change_invalidates_cache_key(
)
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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,
diff --git a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
index 576addd6ab..12a940e39f 100644
--- a/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
+++ b/saleor/plugins/webhook/tests/test_list_stored_payment_methods_webhook.py
@@ -4,10 +4,12 @@ import mock
from ....core.models import EventDelivery
from ....payment.interface import ListStoredPaymentMethodsRequestData
from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ....webhook.event_types import WebhookEventSyncType
-from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from ..stored_payment_methods import get_list_stored_payment_methods_from_response
-from ..utils import generate_cache_key_for_webhook
+from ....webhook.transport.list_stored_payment_methods import (
+ get_list_stored_payment_methods_from_response,
+)
+from ....webhook.transport.utils import generate_cache_key_for_webhook
LIST_STORED_PAYMENT_METHODS = """
subscription {
@@ -25,9 +27,9 @@ subscription {
"""
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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_list_stored_payment_methods_with_static_payload(
mock_request,
mocked_cache_get,
@@ -82,9 +84,9 @@ def test_list_stored_payment_methods_with_static_payload(
)
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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_list_stored_payment_methods_with_subscription_payload(
mock_request,
mocked_cache_get,
@@ -142,9 +144,9 @@ def test_list_stored_payment_methods_with_subscription_payload(
)
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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_list_stored_payment_methods_uses_cache_if_available(
mock_request,
mocked_cache_get,
@@ -196,9 +198,9 @@ def test_list_stored_payment_methods_uses_cache_if_available(
)
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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_list_stored_payment_methods_app_returns_incorrect_response(
mock_request,
mocked_cache_get,
diff --git a/saleor/plugins/webhook/tests/test_observability.py b/saleor/plugins/webhook/tests/test_observability.py
index b34049e113..c29241ef3a 100644
--- a/saleor/plugins/webhook/tests/test_observability.py
+++ b/saleor/plugins/webhook/tests/test_observability.py
@@ -5,17 +5,17 @@ from celery.canvas import Signature
from ....core import EventDeliveryStatus
from ....webhook.event_types import WebhookEventAsyncType
from ....webhook.observability import dump_payload
-from ..tasks import (
+from ....webhook.transport.asynchronous.transport import (
observability_reporter_task,
observability_send_events,
send_observability_events,
)
-@patch("saleor.plugins.webhook.tasks.group")
-@patch("saleor.plugins.webhook.tasks.send_observability_events")
-@patch("saleor.plugins.webhook.tasks.observability.get_webhooks")
-@patch("saleor.plugins.webhook.tasks.observability.pop_events_with_remaining_size")
+@patch("saleor.webhook.transport.asynchronous.transport.group")
+@patch("saleor.webhook.transport.asynchronous.transport.send_observability_events")
+@patch("saleor.webhook.observability.get_webhooks")
+@patch("saleor.webhook.observability.pop_events_with_remaining_size")
def test_observability_reporter_task(
mock_pop_events_with_remaining_size,
mock_get_webhooks,
@@ -41,9 +41,9 @@ def test_observability_reporter_task(
mock_send_observability_events.assert_called_once_with(webhooks, events)
-@patch("saleor.plugins.webhook.tasks.send_observability_events")
-@patch("saleor.plugins.webhook.tasks.observability.get_webhooks")
-@patch("saleor.plugins.webhook.tasks.observability.pop_events_with_remaining_size")
+@patch("saleor.webhook.transport.asynchronous.transport.send_observability_events")
+@patch("saleor.webhook.observability.get_webhooks")
+@patch("saleor.webhook.observability.pop_events_with_remaining_size")
def test_observability_send_events(
mock_pop_events_with_remaining_size,
mock_get_webhooks,
@@ -60,7 +60,9 @@ def test_observability_send_events(
mock_send_observability_events.assert_called_once_with(webhooks, events)
-@patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_observability_events(
mock_send_webhook_using_scheme_method, observability_webhook_data
):
@@ -77,7 +79,9 @@ def test_send_observability_events(
)
-@patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_observability_events_when_reposnse_failed(
mock_send_webhook_using_scheme_method, observability_webhook_data
):
@@ -90,7 +94,9 @@ def test_send_observability_events_when_reposnse_failed(
mock_send_webhook_using_scheme_method.assert_called_once()
-@patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_observability_events_to_google_pub_sub(
mock_send_webhook_using_scheme_method, observability_webhook_data
):
@@ -112,7 +118,9 @@ def test_send_observability_events_to_google_pub_sub(
)
-@patch("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+@patch(
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_observability_events_to_google_pub_sub_when_reposnse_failed(
mock_send_webhook_using_scheme_method, observability_webhook_data
):
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
index 780f2ba5d3..39430ac34b 100644
--- a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
@@ -89,7 +89,7 @@ def _assert_fields(payload, webhook, expected_data, response, mock_request):
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_checkout_without_request_data_and_static_payload(
mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
):
@@ -123,7 +123,7 @@ def test_gateway_initialize_checkout_without_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_checkout_with_request_data_and_static_payload(
mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
):
@@ -161,7 +161,7 @@ def test_gateway_initialize_checkout_with_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_checkout_without_request_data(
mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
):
@@ -197,7 +197,7 @@ def test_gateway_initialize_checkout_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_checkout_with_request_data(
mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
):
@@ -236,7 +236,7 @@ def test_gateway_initialize_checkout_with_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_session_skips_app_without_identifier(
mock_request, webhook_plugin, webhook_app, checkout, permission_manage_payments
):
@@ -268,7 +268,7 @@ def test_gateway_initialize_session_skips_app_without_identifier(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_order_without_request_data_static_payload(
mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
):
@@ -302,7 +302,7 @@ def test_gateway_initialize_order_without_request_data_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_order_with_request_data_static_payload(
mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
):
@@ -340,7 +340,7 @@ def test_gateway_initialize_order_with_request_data_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_session_for_order_without_request_data(
mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
):
@@ -377,7 +377,7 @@ def test_gateway_initialize_session_for_order_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_gateway_initialize_session_for_order_with_request_data(
mock_request, webhook_plugin, webhook_app, order, permission_manage_payments
):
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
index df8469ad56..beacb7dc9a 100644
--- a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_tokenization.py
@@ -39,7 +39,7 @@ def webhook_payment_gateway_initialize_tokenization_response():
}
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_gateway_initialize_tokenization_with_static_payload(
mock_request,
customer_user,
@@ -88,7 +88,7 @@ def test_payment_gateway_initialize_tokenization_with_static_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_gateway_initialize_tokenization_with_subscription_payload(
mock_request,
customer_user,
@@ -142,7 +142,7 @@ def test_payment_gateway_initialize_tokenization_with_subscription_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_gateway_initialize_tokenization_missing_correct_response_from_webhook(
mock_request,
customer_user,
@@ -191,7 +191,7 @@ def test_payment_gateway_initialize_tokenization_missing_correct_response_from_w
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_gateway_initialize_tokenization_failure_from_app(
mock_request,
customer_user,
diff --git a/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
index 5f7964ed7d..49c33ea907 100644
--- a/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_method_initialize_tokenization.py
@@ -13,10 +13,13 @@ from ....payment.interface import (
PaymentMethodTokenizationResult,
)
from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
-from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+from ....webhook.transport.utils import (
+ generate_cache_key_for_webhook,
+ to_payment_app_id,
+)
PAYMENT_METHOD_INITIALIZE_TOKENIZATION_SESSION = """
subscription{
@@ -45,7 +48,7 @@ def webhook_payment_method_initialize_tokenization_response():
}
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_with_static_payload(
mock_request,
customer_user,
@@ -100,7 +103,7 @@ def test_payment_method_initialize_tokenization_with_static_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_with_subscription_payload(
mock_request,
customer_user,
@@ -160,7 +163,7 @@ def test_payment_method_initialize_tokenization_with_subscription_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_missing_correct_response_from_webhook(
mock_request,
customer_user,
@@ -211,7 +214,7 @@ def test_payment_method_initialize_tokenization_missing_correct_response_from_we
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_failure_from_app(
mock_request,
customer_user,
@@ -267,7 +270,7 @@ def test_payment_method_initialize_tokenization_failure_from_app(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_additional_action_required(
mock_request,
customer_user,
@@ -333,7 +336,7 @@ def test_payment_method_initialize_tokenization_additional_action_required(
PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
],
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_initialize_tokenization_missing_required_id(
mock_request,
result,
@@ -396,10 +399,10 @@ def test_payment_method_initialize_tokenization_missing_required_id(
PaymentMethodTokenizationResult.PENDING,
],
)
[email protected]("saleor.plugins.webhook.tasks.cache.delete")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.delete")
[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_expected_result_invalidates_cache_for_app(
mocked_request,
mocked_cache_get,
diff --git a/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
index c049750f6a..b7b0687657 100644
--- a/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
+++ b/saleor/plugins/webhook/tests/test_payment_method_process_tokenization.py
@@ -12,10 +12,13 @@ from ....payment.interface import (
PaymentMethodTokenizationResult,
)
from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
-from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+from ....webhook.transport.utils import (
+ generate_cache_key_for_webhook,
+ to_payment_app_id,
+)
PAYMENT_METHOD_PROCESS_TOKENIZATION_SESSION = """
subscription{
@@ -44,7 +47,7 @@ def webhook_payment_method_process_tokenization_response():
}
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_with_static_payload(
mock_request,
customer_user,
@@ -102,7 +105,7 @@ def test_payment_method_process_tokenization_with_static_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_with_subscription_payload(
mock_request,
customer_user,
@@ -165,7 +168,7 @@ def test_payment_method_process_tokenization_with_subscription_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_missing_correct_response_from_webhook(
mock_request,
customer_user,
@@ -217,7 +220,7 @@ def test_payment_method_process_tokenization_missing_correct_response_from_webho
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_failure_from_app(
mock_request,
customer_user,
@@ -276,7 +279,7 @@ def test_payment_method_process_tokenization_failure_from_app(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_additional_action_required(
mock_request,
customer_user,
@@ -344,7 +347,7 @@ def test_payment_method_process_tokenization_additional_action_required(
PaymentMethodTokenizationResult.ADDITIONAL_ACTION_REQUIRED.name,
],
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_payment_method_process_tokenization_missing_required_id(
mock_request,
result,
@@ -409,10 +412,10 @@ def test_payment_method_process_tokenization_missing_required_id(
PaymentMethodTokenizationResult.PENDING,
],
)
[email protected]("saleor.plugins.webhook.tasks.cache.delete")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.delete")
[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_expected_result_invalidates_cache_for_app(
mocked_request,
mocked_cache_get,
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 5db6d899c9..d02b4e2cf7 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -17,9 +17,12 @@ from ....payment.interface import PaymentGateway
from ....payment.utils import create_payment_information
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
-from .. import signature_for_payload
-from ..tasks import send_webhook_request_sync, trigger_webhook_sync
-from ..utils import (
+from ....webhook.transport import signature_for_payload
+from ....webhook.transport.synchronous.transport import (
+ send_webhook_request_sync,
+ trigger_webhook_sync,
+)
+from ....webhook.transport.utils import (
parse_list_payment_gateways_response,
parse_payment_action_response,
to_payment_app_id,
@@ -49,7 +52,7 @@ def webhook_data():
return WebhookTestData(secret, event_type, data, message)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_webhook_sync(mock_request, payment_app):
data = '{"key": "value"}'
trigger_webhook_sync(
@@ -59,8 +62,10 @@ def test_trigger_webhook_sync(mock_request, payment_app):
mock_request.assert_called_once_with(event_delivery)
[email protected]("saleor.plugins.webhook.tasks.create_delivery_for_subscription_sync_event")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+ "saleor.webhook.transport.synchronous.transport.create_delivery_for_subscription_sync_event"
+)
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_webhook_sync_with_subscription(
mock_request,
mock_delivery_create,
@@ -80,7 +85,9 @@ def test_trigger_webhook_sync_with_subscription(
mock_request.assert_called_once_with(fake_delivery)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
+ "saleor.webhook.transport.synchronous.transport.observability.report_event_delivery_attempt"
+)
@mock.patch.object(HTTPSession, "request")
def test_send_webhook_request_sync_failed_attempt(
mock_post, mock_observability, app, event_delivery
@@ -112,9 +119,9 @@ def test_send_webhook_request_sync_failed_attempt(
mock_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.webhook.observability.report_event_delivery_attempt")
@mock.patch.object(HTTPSession, "request")
[email protected]("saleor.plugins.webhook.tasks.clear_successful_delivery")
[email protected]("saleor.webhook.transport.synchronous.transport.clear_successful_delivery")
def test_send_webhook_request_sync_successful_attempt(
mock_clear_delivery, mock_post, mock_observability, app, event_delivery
):
@@ -147,7 +154,7 @@ def test_send_webhook_request_sync_successful_attempt(
mock_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.webhook.observability.report_event_delivery_attempt")
@mock.patch.object(HTTPSession, "request", side_effect=RequestException)
def test_send_webhook_request_sync_request_exception(
mock_post, mock_observability, app, event_delivery
@@ -179,7 +186,7 @@ def test_send_webhook_request_sync_request_exception(
mock_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.webhook.observability.report_event_delivery_attempt")
@mock.patch.object(HTTPSession, "request")
def test_send_webhook_request_sync_when_exception_with_response(
mock_post, mock_observability, app, event_delivery
@@ -200,7 +207,7 @@ def test_send_webhook_request_sync_when_exception_with_response(
mock_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.webhook.observability.report_event_delivery_attempt")
@mock.patch.object(HTTPSession, "request")
def test_send_webhook_request_sync_json_parsing_error(
mock_post, mock_observability, app, event_delivery
@@ -257,7 +264,7 @@ def test_send_webhook_request_sync_invalid_scheme(webhook, app):
send_webhook_request_sync(delivery)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_payment_gateways(
mock_send_request, payment_app, permission_manage_payments, webhook_plugin
):
@@ -299,7 +306,7 @@ def test_get_payment_gateways(
assert response_data[1] == expected_response_2[0]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_payment_gateways_with_transactions(
mock_send_request, permission_manage_payments, webhook_plugin
):
@@ -330,7 +337,7 @@ def test_get_payment_gateways_with_transactions(
assert not mock_send_request.called
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_payment_gateways_with_transactions_and_app_without_identifier(
mock_send_request, permission_manage_payments, webhook_plugin
):
@@ -357,7 +364,7 @@ def test_get_payment_gateways_with_transactions_and_app_without_identifier(
assert len(response_data) == 0
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_payment_gateways_multiple_webhooks_in_the_same_app(
mock_send_request, payment_app, permission_manage_payments, webhook_plugin
):
@@ -401,7 +408,7 @@ def test_get_payment_gateways_multiple_webhooks_in_the_same_app(
assert response_data[1] == expected_response_2[0]
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_payment_gateways_filters_out_unsupported_currencies(
mock_send_request, payment_app, webhook_plugin
):
@@ -419,7 +426,7 @@ def test_get_payment_gateways_filters_out_unsupported_currencies(
assert response_data == []
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
@mock.patch("saleor.plugins.webhook.plugin.generate_list_gateways_payload")
def test_get_payment_gateways_for_checkout(
mock_generate_payload, mock_send_request, checkout_info, payment_app, webhook_plugin
@@ -450,7 +457,7 @@ def test_get_payment_gateways_for_checkout(
(TransactionKind.CAPTURE, "process_payment"),
),
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_run_payment_webhook(
mock_send_request,
txn_kind,
@@ -512,7 +519,7 @@ def test_run_payment_webhook_inactive_plugin(payment, webhook_plugin):
assert response == dummy_previous_value
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_run_payment_webhook_no_response(mock_send_request, payment, webhook_plugin):
# Should raise and error when response data is None.
mock_send_request.return_value = None
@@ -527,7 +534,7 @@ def test_run_payment_webhook_no_response(mock_send_request, payment, webhook_plu
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_run_payment_webhook_empty_response(mock_send_request, payment, webhook_plugin):
# Empty JSON response "{}"" is accepted; check that it doesn't fail.
mock_send_request.return_value = {}
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
index 72a2a00864..8b92917c3e 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
@@ -3,8 +3,8 @@ import pytest
from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventPayload
from ....payment import TransactionKind
-from ..utils import (
- APP_ID_PREFIX,
+from ....webhook.const import APP_ID_PREFIX
+from ....webhook.transport.utils import (
clear_successful_delivery,
from_payment_app_id,
parse_list_payment_gateways_response,
diff --git a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
index 0a03117c55..164eca4481 100644
--- a/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
+++ b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
@@ -3,13 +3,17 @@ from unittest import mock
import graphene
+from saleor.webhook.const import (
+ CACHE_EXCLUDED_SHIPPING_KEY,
+ CACHE_EXCLUDED_SHIPPING_TIME,
+)
+
from ...base_plugin import ExcludedShippingMethod
-from ..const import CACHE_EXCLUDED_SHIPPING_KEY, CACHE_EXCLUDED_SHIPPING_TIME
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -60,9 +64,9 @@ def test_excluded_shipping_methods_for_order_use_cache(
assert not mocked_cache_set.called
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -121,9 +125,9 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_empty(
)
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -185,9 +189,9 @@ def test_excluded_shipping_methods_for_order_stores_in_cache_when_payload_is_dif
)
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -241,9 +245,9 @@ def test_excluded_shipping_methods_for_checkout_use_cache(
assert not mocked_cache_set.called
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -305,9 +309,9 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
)
[email protected]("saleor.plugins.webhook.shipping.cache.get")
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[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")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 05ff2b7412..74b58f4411 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -6,16 +6,19 @@ import pytest
from ....core.models import EventDelivery
from ....graphql.tests.utils import get_graphql_content
+from ....webhook.const import CACHE_EXCLUDED_SHIPPING_KEY, CACHE_EXCLUDED_SHIPPING_TIME
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
from ....webhook.payloads import (
generate_excluded_shipping_methods_for_checkout_payload,
generate_excluded_shipping_methods_for_order_payload,
)
+from ....webhook.transport.shipping import (
+ get_excluded_shipping_methods_from_response,
+ to_shipping_app_id,
+)
+from ....webhook.transport.synchronous.transport import trigger_webhook_sync
from ...base_plugin import ExcludedShippingMethod
-from ..const import CACHE_EXCLUDED_SHIPPING_KEY, CACHE_EXCLUDED_SHIPPING_TIME
-from ..shipping import get_excluded_shipping_methods_from_response, to_shipping_app_id
-from ..tasks import trigger_webhook_sync
ORDER_QUERY_SHIPPING_METHOD = """
query OrdersQuery {
@@ -62,8 +65,8 @@ CHECKOUT_QUERY_SHIPPING_METHOD = """
"""
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -81,7 +84,6 @@ def test_excluded_shipping_methods_for_order(
shipping_app = shipping_app_factory()
webhook_reason = "Order contains dangerous products."
other_reason = "Shipping is not applicable for this order."
-
mocked_webhook.return_value = {
"excluded_methods": [
{
@@ -130,8 +132,8 @@ def test_excluded_shipping_methods_for_order(
)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -223,8 +225,8 @@ def test_multiple_app_with_excluded_shipping_methods_for_order(
)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin.generate_excluded_shipping_methods_for_order_payload"
)
@@ -509,7 +511,7 @@ def test_checkout_shipping_methods_webhook_called_once(
assert len(checkout_data["shippingMethods"]) == 2
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_webhook_sync(mock_request, shipping_app):
data = '{"key": "value"}'
webhook = shipping_app.webhooks.first()
@@ -520,8 +522,8 @@ def test_trigger_webhook_sync(mock_request, shipping_app):
mock_request.assert_called_once_with(event_delivery)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -589,7 +591,7 @@ def test_excluded_shipping_methods_for_checkout_webhook(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_excluded_shipping_methods_for_checkout(
mocked_webhook,
webhook_plugin,
@@ -634,8 +636,8 @@ def test_excluded_shipping_methods_for_checkout(
mocked_webhook.assert_called_once()
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
@@ -728,8 +730,8 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
)
[email protected]("saleor.plugins.webhook.shipping.cache.set")
[email protected]("saleor.plugins.webhook.shipping.trigger_webhook_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.set")
[email protected]("saleor.webhook.transport.shipping.trigger_webhook_sync")
@mock.patch(
"saleor.plugins.webhook.plugin."
"generate_excluded_shipping_methods_for_checkout_payload"
diff --git a/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
index d95dac1503..cbdc43e87a 100644
--- a/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
+++ b/saleor/plugins/webhook/tests/test_stored_payment_method_request_delete.py
@@ -12,10 +12,13 @@ from ....payment.interface import (
StoredPaymentMethodRequestDeleteResult,
)
from ....settings import WEBHOOK_SYNC_TIMEOUT
+from ....webhook.const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
-from ..const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
-from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+from ....webhook.transport.utils import (
+ generate_cache_key_for_webhook,
+ to_payment_app_id,
+)
STORED_PAYMENT_METHOD_DELETE_REQUESTED = """
subscription {
@@ -41,7 +44,7 @@ def webhook_stored_payment_method_request_delete_response():
}
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_with_static_payload(
mock_request,
customer_user,
@@ -91,7 +94,7 @@ def test_stored_payment_method_request_delete_with_static_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_with_subscription_payload(
mock_request,
customer_user,
@@ -145,7 +148,7 @@ def test_stored_payment_method_request_delete_with_subscription_payload(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_failure_from_app(
mock_request,
customer_user,
@@ -200,7 +203,7 @@ def test_stored_payment_method_request_delete_failure_from_app(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_missing_response_from_webhook(
mock_request,
customer_user,
@@ -249,7 +252,7 @@ def test_stored_payment_method_request_delete_missing_response_from_webhook(
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_incorrect_result_response_from_webhook(
mock_request,
customer_user,
@@ -298,7 +301,7 @@ def test_stored_payment_method_request_delete_incorrect_result_response_from_web
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_stored_payment_method_request_delete_missing_result_in_response_from_webhook(
mock_request,
customer_user,
@@ -347,10 +350,10 @@ def test_stored_payment_method_request_delete_missing_result_in_response_from_we
)
[email protected]("saleor.plugins.webhook.tasks.cache.delete")
[email protected]("saleor.plugins.webhook.tasks.cache.set")
[email protected]("saleor.plugins.webhook.tasks.cache.get")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.cache.delete")
[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_stored_payment_method_request_delete_invalidates_cache_for_app(
mocked_request,
mocked_cache_get,
diff --git a/saleor/plugins/webhook/tests/test_tasks.py b/saleor/plugins/webhook/tests/test_tasks.py
index c9aec7df42..cd9bbbb013 100644
--- a/saleor/plugins/webhook/tests/test_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tasks.py
@@ -17,7 +17,8 @@ from ....payment.transaction_item_calculations import recalculate_transaction_am
from ....tests.utils import flush_post_commit_hooks
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.payloads import generate_transaction_action_request_payload
-from ..tasks import handle_transaction_request_task, trigger_transaction_request
+from ....webhook.transport.synchronous.transport import handle_transaction_request_task
+from ....webhook.transport.utils import trigger_transaction_request
@pytest.fixture
@@ -33,7 +34,10 @@ def mocked_webhook_response():
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+ "saleor.webhook.transport.synchronous."
+ "transport.handle_transaction_request_task.delay"
+)
def test_trigger_transaction_request(
mocked_task,
transaction_item_created_by_app,
@@ -85,7 +89,10 @@ def test_trigger_transaction_request(
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_transaction_request_task.delay")
+ "saleor.webhook.transport.synchronous."
+ "transport.handle_transaction_request_task.delay"
+)
def test_trigger_transaction_request_with_webhook_subscription(
mocked_task,
transaction_item_created_by_app,
@@ -229,7 +236,7 @@ def test_handle_transaction_request_task_with_only_psp_reference(
@pytest.mark.parametrize("status_code", [500, 501, 510])
@freeze_time("2022-06-11 12:50")
[email protected]("saleor.plugins.webhook.tasks.handle_webhook_retry")
[email protected]("saleor.webhook.transport.synchronous.transport.handle_webhook_retry")
@mock.patch.object(HTTPSession, "request")
def test_handle_transaction_request_task_with_server_error(
mocked_post_request,
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index 10a25a29b7..df8b6b857b 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -12,11 +12,15 @@ from ....core.taxes import TaxType
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook
from ....webhook.payloads import generate_order_payload_for_tax_calculation
+from ....webhook.transport.utils import (
+ DEFAULT_TAX_CODE,
+ DEFAULT_TAX_DESCRIPTION,
+ parse_tax_data,
+)
from ...manager import get_plugins_manager
-from ..utils import DEFAULT_TAX_CODE, DEFAULT_TAX_DESCRIPTION, parse_tax_data
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_taxes_for_checkout_no_permission(
mock_request,
webhook_plugin,
@@ -37,7 +41,7 @@ def test_get_taxes_for_checkout_no_permission(
@freeze_time()
@mock.patch("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_taxes_for_order(
mock_request,
mock_fetch,
@@ -68,7 +72,7 @@ def test_get_taxes_for_order(
assert tax_data == parse_tax_data(tax_data_response)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_taxes_for_order_no_permission(
mock_request,
webhook_plugin,
@@ -148,7 +152,7 @@ def test_get_tax_code_from_object_meta_default_code(
@freeze_time()
@mock.patch("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_taxes_for_order_with_sync_subscription(
mock_request,
mock_fetch,
@@ -188,7 +192,7 @@ def test_get_taxes_for_order_with_sync_subscription(
@freeze_time()
@mock.patch("saleor.checkout.calculations.fetch_checkout_data")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_get_taxes_for_checkout_with_sync_subscription(
mock_request,
mock_fetch,
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py b/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py
index fb2e5c80f1..aa988c405e 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py
@@ -6,8 +6,8 @@ from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventPayload
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
-from ..tasks import trigger_all_webhooks_sync
-from ..utils import parse_tax_data
+from ....webhook.transport.synchronous.transport import trigger_all_webhooks_sync
+from ....webhook.transport.utils import parse_tax_data
@pytest.fixture
@@ -36,7 +36,7 @@ def tax_checkout_webhooks(tax_app):
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_tax_webhook_sync(
mock_request,
tax_checkout_webhook,
@@ -62,7 +62,7 @@ def test_trigger_tax_webhook_sync(
assert tax_data == parse_tax_data(tax_data_response)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_tax_webhook_sync_multiple_webhooks_first(
mock_request,
tax_checkout_webhooks,
@@ -90,7 +90,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_first(
assert tax_data == parse_tax_data(tax_data_response)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_tax_webhook_sync_multiple_webhooks_last(
mock_request,
tax_checkout_webhooks,
@@ -122,7 +122,7 @@ def test_trigger_tax_webhook_sync_multiple_webhooks_last(
assert tax_data == parse_tax_data(tax_data_response)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_trigger_tax_webhook_sync_invalid_webhooks(
mock_request,
tax_checkout_webhooks,
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook_utils.py b/saleor/plugins/webhook/tests/test_tax_webhook_utils.py
index 49a324872d..8a34a87cd1 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook_utils.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook_utils.py
@@ -3,7 +3,11 @@ import decimal
import pytest
from ....core.taxes import TaxData
-from ..utils import _unsafe_parse_tax_data, _unsafe_parse_tax_line_data, parse_tax_data
+from ....webhook.transport.utils import (
+ _unsafe_parse_tax_data,
+ _unsafe_parse_tax_line_data,
+ parse_tax_data,
+)
def test_unsafe_parse_tax_line_data_success(tax_line_data_response):
diff --git a/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py
index 99cbcc5210..e6daeb2a78 100644
--- a/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py
+++ b/saleor/plugins/webhook/tests/test_transaction_initialize_session_webhook.py
@@ -118,7 +118,7 @@ def _assert_fields(payload, webhook, expected_response, response, mock_request):
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_checkout_without_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -186,7 +186,7 @@ def test_transaction_initialize_checkout_without_request_data_and_static_payload
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_checkout_with_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -255,7 +255,7 @@ def test_transaction_initialize_checkout_with_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_checkout_without_request_data(
mock_request,
webhook_plugin,
@@ -324,7 +324,7 @@ def test_transaction_initialize_checkout_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_checkout_with_request_data(
mock_request,
webhook_plugin,
@@ -394,7 +394,7 @@ def test_transaction_initialize_checkout_with_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_session_skips_app_without_identifier(
mock_request,
webhook_plugin,
@@ -459,7 +459,7 @@ def test_transaction_initialize_session_skips_app_without_identifier(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_order_without_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -527,7 +527,7 @@ def test_transaction_initialize_order_without_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_order_with_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -596,7 +596,7 @@ def test_transaction_initialize_order_with_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_order_without_request_data(
mock_request,
webhook_plugin,
@@ -665,7 +665,7 @@ def test_transaction_initialize_order_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_initialize_order_with_request_data(
mock_request,
webhook_plugin,
diff --git a/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py
index a84a38aa42..d5ef49fc07 100644
--- a/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py
+++ b/saleor/plugins/webhook/tests/test_transaction_process_session_webhook.py
@@ -118,7 +118,7 @@ def _assert_fields(payload, webhook, expected_response, response, mock_request):
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_checkout_without_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -186,7 +186,7 @@ def test_transaction_process_checkout_without_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_checkout_with_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -255,7 +255,7 @@ def test_transaction_process_checkout_with_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_checkout_without_request_data(
mock_request,
webhook_plugin,
@@ -324,7 +324,7 @@ def test_transaction_process_checkout_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_checkout_with_request_data(
mock_request,
webhook_plugin,
@@ -394,7 +394,7 @@ def test_transaction_process_checkout_with_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_session_skips_app_without_identifier(
mock_request,
webhook_plugin,
@@ -459,7 +459,7 @@ def test_transaction_process_session_skips_app_without_identifier(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_order_without_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -527,7 +527,7 @@ def test_transaction_process_order_without_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_order_with_request_data_and_static_payload(
mock_request,
webhook_plugin,
@@ -596,7 +596,7 @@ def test_transaction_process_order_with_request_data_and_static_payload(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_order_without_request_data(
mock_request,
webhook_plugin,
@@ -665,7 +665,7 @@ def test_transaction_process_order_without_request_data(
@freeze_time()
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
def test_transaction_process_order_with_request_data(
mock_request,
webhook_plugin,
diff --git a/saleor/plugins/webhook/tests/test_utils.py b/saleor/plugins/webhook/tests/test_utils.py
index ee9d3cce73..b4142c31b0 100644
--- a/saleor/plugins/webhook/tests/test_utils.py
+++ b/saleor/plugins/webhook/tests/test_utils.py
@@ -4,12 +4,15 @@ import pytest
from ....payment.interface import PaymentGateway
from ....webhook.event_types import WebhookEventSyncType
-from ..stored_payment_methods import (
+from ....webhook.transport.list_stored_payment_methods import (
get_credit_card_info,
get_list_stored_payment_methods_from_response,
get_payment_method_from_response,
)
-from ..utils import generate_cache_key_for_webhook, to_payment_app_id
+from ....webhook.transport.utils import (
+ generate_cache_key_for_webhook,
+ to_payment_app_id,
+)
@pytest.fixture()
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index b2b2c8f5ce..c58526fcaf 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -46,10 +46,13 @@ from ....webhook.payloads import (
generate_checkout_payload,
generate_product_deleted_payload,
)
+from ....webhook.transport import signature_for_payload
+from ....webhook.transport.asynchronous.transport import (
+ send_webhook_request_async,
+ trigger_webhooks_async,
+)
from ....webhook.utils import get_webhooks_for_event
from ...manager import get_plugins_manager
-from .. import signature_for_payload
-from ..tasks import send_webhook_request_async, trigger_webhooks_async
from .utils import generate_request_headers
first_url = "http://www.example.com/first/"
@@ -69,7 +72,9 @@ third_url = "http://www.example.com/third/"
(WebhookEventAsyncType.CUSTOMER_CREATED, 0, set()),
],
)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.delay")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.delay"
+)
def test_trigger_webhooks_for_event_calls_expected_events(
mock_request,
event_name,
@@ -1557,7 +1562,7 @@ def test_create_event_payload_reference_with_error(
mocked_client_constructor = MagicMock(spec=boto3.client, return_value=mocked_client)
monkeypatch.setattr(
- "saleor.plugins.webhook.tasks.boto3.client",
+ "saleor.webhook.transport.utils.boto3.client",
mocked_client_constructor,
)
@@ -1720,9 +1725,13 @@ def test_event_delivery_retry(mocked_webhook_send, event_delivery, settings):
mocked_webhook_send.assert_called_once_with(event_delivery.pk)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.clear_successful_delivery")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.observability.report_event_delivery_attempt"
+)
[email protected]("saleor.webhook.transport.asynchronous.transport.clear_successful_delivery")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_webhook_request_async(
mocked_send_response,
mocked_clear_delivery,
@@ -1757,7 +1766,9 @@ def test_send_webhook_request_async(
mocked_observability.assert_called_once_with(attempt)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_webhook_request_async_with_custom_headers(
mocked_send_response,
event_delivery,
@@ -1777,8 +1788,8 @@ def test_send_webhook_request_async_with_custom_headers(
assert custom_headers in mocked_send_response.call_args[0]
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.clear_successful_delivery")
[email protected]("saleor.webhook.observability.utils.report_event_delivery_attempt")
[email protected]("saleor.webhook.transport.utils.clear_successful_delivery")
def test_send_webhook_request_async_when_webhook_is_disabled(
mocked_clear_delivery, mocked_observability, event_delivery
):
@@ -1956,8 +1967,12 @@ def test_transaction_cancelation_requested(
)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.observability.report_event_delivery_attempt"
+)
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_webhook_request_async_when_delivery_attempt_failed(
mocked_send_response,
mocked_observability,
@@ -1978,7 +1993,9 @@ def test_send_webhook_request_async_when_delivery_attempt_failed(
@mock.patch.object(HTTPSession, "request", side_effect=RequestException)
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
+ "saleor.webhook.transport.asynchronous.transport.observability.report_event_delivery_attempt"
+)
def test_send_webhook_request_async_with_request_exception(
mocked_observability, mocked_post, event_delivery, webhook_response_failed
):
@@ -2006,9 +2023,15 @@ def test_send_webhook_request_async_with_request_exception(
mocked_observability.assert_called_once_with(attempt, None)
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_async.retry")
[email protected]("saleor.plugins.webhook.tasks.observability.report_event_delivery_attempt")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_using_scheme_method")
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.retry"
+)
+ "saleor.webhook.transport.asynchronous.transport.observability.report_event_delivery_attempt"
+)
+ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"
+)
def test_send_webhook_request_async_when_max_retries_exceeded(
mocked_send_response,
mocked_observability,
diff --git a/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py b/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py
index e9948a20bb..58b21d57be 100644
--- a/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py
+++ b/saleor/plugins/webhook/tests/test_webhook_ip_filtering.py
@@ -1,6 +1,6 @@
from ....core.http_client import HTTPClient
from ....core.models import EventDeliveryAttempt
-from ..tasks import trigger_webhooks_async
+from ....webhook.transport.asynchronous.transport import trigger_webhooks_async
def test_rejects_private_ips(webhook, monkeypatch):
diff --git a/saleor/plugins/webhook/tests/test_webhook_protocols.py b/saleor/plugins/webhook/tests/test_webhook_protocols.py
index 85b379ee18..094f054ae2 100644
--- a/saleor/plugins/webhook/tests/test_webhook_protocols.py
+++ b/saleor/plugins/webhook/tests/test_webhook_protocols.py
@@ -9,8 +9,8 @@ from google.cloud.pubsub_v1 import PublisherClient
from requests_hardened import HTTPSession
from ....webhook.event_types import WebhookEventAsyncType
-from ...webhook import signature_for_payload
-from ...webhook.tasks import trigger_webhooks_async
+from ....webhook.transport import signature_for_payload
+from ....webhook.transport.asynchronous.transport import trigger_webhooks_async
@pytest.mark.parametrize(
@@ -32,7 +32,7 @@ def test_trigger_webhooks_with_aws_sqs(
mocked_client_constructor = MagicMock(spec=boto3.client, return_value=mocked_client)
monkeypatch.setattr(
- "saleor.plugins.webhook.tasks.boto3.client",
+ "saleor.webhook.transport.utils.boto3.client",
mocked_client_constructor,
)
@@ -98,7 +98,7 @@ def test_trigger_webhooks_with_aws_sqs_and_secret_key(
mocked_client_constructor = MagicMock(spec=boto3.client, return_value=mocked_client)
monkeypatch.setattr(
- "saleor.plugins.webhook.tasks.boto3.client",
+ "saleor.webhook.transport.utils.boto3.client",
mocked_client_constructor,
)
@@ -154,7 +154,7 @@ def test_trigger_webhooks_with_google_pub_sub(
mocked_publisher = MagicMock(spec=PublisherClient)
mocked_publisher.publish.return_value.result.return_value = "message_id"
monkeypatch.setattr(
- "saleor.plugins.webhook.tasks.pubsub_v1.PublisherClient",
+ "saleor.webhook.transport.utils.pubsub_v1.PublisherClient",
lambda: mocked_publisher,
)
webhook.app.permissions.add(permission_manage_orders)
@@ -187,7 +187,7 @@ def test_trigger_webhooks_with_google_pub_sub_and_secret_key(
mocked_publisher = MagicMock(spec=PublisherClient)
mocked_publisher.publish.return_value.result.return_value = "message_id"
monkeypatch.setattr(
- "saleor.plugins.webhook.tasks.pubsub_v1.PublisherClient",
+ "saleor.webhook.transport.utils.pubsub_v1.PublisherClient",
lambda: mocked_publisher,
)
webhook.app.permissions.add(permission_manage_orders)
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
deleted file mode 100644
index 728298d114..0000000000
--- a/saleor/plugins/webhook/utils.py
+++ /dev/null
@@ -1,309 +0,0 @@
-import decimal
-import hashlib
-import json
-import logging
-from contextlib import contextmanager
-from dataclasses import dataclass
-from time import time
-from typing import TYPE_CHECKING, Any, List, Optional, Sequence
-
-from ...app.models import App
-from ...core.models import (
- EventDelivery,
- EventDeliveryAttempt,
- EventDeliveryStatus,
- EventPayload,
-)
-from ...core.taxes import TaxData, TaxLineData
-from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo
-from ...webhook.event_types import WebhookEventSyncType
-from ..const import APP_ID_PREFIX
-
-if TYPE_CHECKING:
- from ...payment.interface import PaymentData
- from ...webhook.models import Webhook
- from .tasks import WebhookResponse
-
-
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class PaymentAppData:
- app_pk: Optional[int]
- app_identifier: Optional[str]
- name: str
-
-
-def to_payment_app_id(app: "App", external_id: str) -> "str":
- app_identifier = app.identifier or app.id
- return f"{APP_ID_PREFIX}:{app_identifier}:{external_id}"
-
-
-def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
- splitted_id = app_gateway_id.split(":", maxsplit=2)
- if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):
- try:
- app_pk = int(splitted_id[1])
- except (TypeError, ValueError):
- return PaymentAppData(
- app_identifier=splitted_id[1], app_pk=None, name=splitted_id[2]
- )
- else:
- return PaymentAppData(
- app_pk=app_pk, app_identifier=None, name=splitted_id[2]
- )
- return None
-
-
-def parse_list_payment_gateways_response(
- response_data: Any, app: "App"
-) -> List["PaymentGateway"]:
- gateways: List[PaymentGateway] = []
- if not isinstance(response_data, list):
- return gateways
-
- for gateway_data in response_data:
- gateway_id = gateway_data.get("id")
- gateway_name = gateway_data.get("name")
- gateway_currencies = gateway_data.get("currencies")
- gateway_config = gateway_data.get("config")
-
- if gateway_id:
- gateways.append(
- PaymentGateway(
- id=to_payment_app_id(app, gateway_id),
- name=gateway_name,
- currencies=gateway_currencies,
- config=gateway_config,
- )
- )
- return gateways
-
-
-def parse_payment_action_response(
- payment_information: "PaymentData",
- response_data: Any,
- transaction_kind: "str",
-) -> "GatewayResponse":
- error = response_data.get("error")
- is_success = not error
-
- payment_method_info = None
- payment_method_data = response_data.get("payment_method")
- if payment_method_data:
- payment_method_info = PaymentMethodInfo(
- brand=payment_method_data.get("brand"),
- exp_month=payment_method_data.get("exp_month"),
- exp_year=payment_method_data.get("exp_year"),
- last_4=payment_method_data.get("last_4"),
- name=payment_method_data.get("name"),
- type=payment_method_data.get("type"),
- )
-
- amount = payment_information.amount
- if "amount" in response_data:
- try:
- amount = decimal.Decimal(response_data["amount"])
- except decimal.DecimalException:
- pass
-
- return GatewayResponse(
- action_required=response_data.get("action_required", False),
- action_required_data=response_data.get("action_required_data"),
- amount=amount,
- currency=payment_information.currency,
- customer_id=response_data.get("customer_id"),
- error=error,
- is_success=is_success,
- kind=response_data.get("kind", transaction_kind),
- payment_method_info=payment_method_info,
- raw_response=response_data,
- psp_reference=response_data.get("psp_reference"),
- transaction_id=response_data.get("transaction_id", ""),
- transaction_already_processed=response_data.get(
- "transaction_already_processed", False
- ),
- )
-
-
-def _unsafe_parse_tax_line_data(
- tax_line_data_response: Any,
-) -> TaxLineData:
- """Unsafe TaxLineData parser.
-
- Raises KeyError or DecimalException on invalid data.
- """
- total_gross_amount = decimal.Decimal(tax_line_data_response["total_gross_amount"])
- total_net_amount = decimal.Decimal(tax_line_data_response["total_net_amount"])
- tax_rate = decimal.Decimal(tax_line_data_response["tax_rate"])
-
- return TaxLineData(
- total_gross_amount=total_gross_amount,
- total_net_amount=total_net_amount,
- tax_rate=tax_rate,
- )
-
-
-def _unsafe_parse_tax_data(
- tax_data_response: Any,
-) -> TaxData:
- """Unsafe TaxData parser.
-
- Raises KeyError or DecimalException on invalid data.
- """
- shipping_price_gross_amount = decimal.Decimal(
- tax_data_response["shipping_price_gross_amount"]
- )
- shipping_price_net_amount = decimal.Decimal(
- tax_data_response["shipping_price_net_amount"]
- )
- shipping_tax_rate = decimal.Decimal(tax_data_response["shipping_tax_rate"])
- lines = [_unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]]
-
- return TaxData(
- shipping_price_gross_amount=shipping_price_gross_amount,
- shipping_price_net_amount=shipping_price_net_amount,
- shipping_tax_rate=shipping_tax_rate,
- lines=lines,
- )
-
-
-def parse_tax_data(
- response_data: Any,
-) -> Optional[TaxData]:
- try:
- return _unsafe_parse_tax_data(response_data)
- except (TypeError, KeyError, decimal.DecimalException):
- return None
-
-
-def get_delivery_for_webhook(event_delivery_id) -> Optional["EventDelivery"]:
- try:
- delivery = EventDelivery.objects.select_related("payload", "webhook__app").get(
- id=event_delivery_id
- )
- except EventDelivery.DoesNotExist:
- logger.error("Event delivery id: %r not found", event_delivery_id)
- return None
-
- if not delivery.webhook.is_active:
- delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
- logger.info("Event delivery id: %r webhook is disabled.", event_delivery_id)
- return None
- return delivery
-
-
-@contextmanager
-def catch_duration_time():
- start = time()
- yield lambda: time() - start
-
-
-def create_event_delivery_list_for_webhooks(
- webhooks: Sequence["Webhook"],
- event_payload: "EventPayload",
- event_type: str,
-) -> List[EventDelivery]:
- event_deliveries = EventDelivery.objects.bulk_create(
- [
- EventDelivery(
- status=EventDeliveryStatus.PENDING,
- event_type=event_type,
- payload=event_payload,
- webhook=webhook,
- )
- for webhook in webhooks
- ]
- )
- return event_deliveries
-
-
-def create_attempt(
- delivery: "EventDelivery",
- task_id: Optional[str] = None,
-):
- attempt = EventDeliveryAttempt.objects.create(
- delivery=delivery,
- task_id=task_id,
- duration=None,
- response=None,
- request_headers=None,
- response_headers=None,
- status=EventDeliveryStatus.PENDING,
- )
- return attempt
-
-
-def attempt_update(
- attempt: "EventDeliveryAttempt",
- webhook_response: "WebhookResponse",
-):
- attempt.duration = webhook_response.duration
- attempt.response = webhook_response.content
- attempt.response_headers = json.dumps(webhook_response.response_headers)
- attempt.response_status_code = webhook_response.response_status_code
- attempt.request_headers = json.dumps(webhook_response.request_headers)
- attempt.status = webhook_response.status
- attempt.save(
- update_fields=[
- "duration",
- "response",
- "response_headers",
- "response_status_code",
- "request_headers",
- "status",
- ]
- )
-
-
-def delivery_update(delivery: "EventDelivery", status: str):
- delivery.status = status
- delivery.save(update_fields=["status"])
-
-
-def clear_successful_delivery(delivery: "EventDelivery"):
- if delivery.status == EventDeliveryStatus.SUCCESS:
- payload_id = delivery.payload_id
- delivery.delete()
- if payload_id:
- EventPayload.objects.filter(pk=payload_id, deliveries__isnull=True).delete()
-
-
-DEFAULT_TAX_CODE = "UNMAPPED"
-DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"
-
-
-def get_current_tax_app() -> Optional[App]:
- """Return currently used tax app or None, if there aren't any."""
- return (
- App.objects.order_by("pk")
- .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
- .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
- .last()
- )
-
-
-def get_meta_code_key(app: App) -> str:
- return f"{app.identifier}.code"
-
-
-def get_meta_description_key(app: App) -> str:
- return f"{app.identifier}.description"
-
-
-def generate_cache_key_for_webhook(
- key_data: dict, webhook_url: str, event: str, app_id: int
-) -> str:
- """Generate cache key for webhook.
-
- Cache key takes into account the webhook url, event type, and app id.
- The response from webhook_url can be different for different events.
- Apps can have assigned different permissions, so the response can vary for
- different apps.
- """
- key = json.dumps(key_data)
- return (
- f"{app_id}-{webhook_url}-{event}-"
- f"{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
- )
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1c7f13b450..0cdc8be47a 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -93,9 +93,7 @@ from ..payment.utils import create_manual_adjustment_events
from ..permission.enums import get_permissions
from ..permission.models import Permission
from ..plugins.manager import get_plugins_manager
-from ..plugins.webhook.tasks import WebhookResponse
from ..plugins.webhook.tests.subscription_webhooks import subscription_queries
-from ..plugins.webhook.utils import to_payment_app_id
from ..product import ProductMediaTypes, ProductTypeKind
from ..product.models import (
Category,
@@ -140,6 +138,7 @@ from ..warehouse.models import (
from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..webhook.models import Webhook, WebhookEvent
from ..webhook.observability import WebhookData
+from ..webhook.transport.utils import WebhookResponse, to_payment_app_id
from .utils import dummy_editorjs
diff --git a/saleor/plugins/webhook/const.py b/saleor/webhook/const.py
similarity index 87%
rename from saleor/plugins/webhook/const.py
rename to saleor/webhook/const.py
index 116becde28..dbabdd0496 100644
--- a/saleor/plugins/webhook/const.py
+++ b/saleor/webhook/const.py
@@ -1,3 +1,4 @@
CACHE_EXCLUDED_SHIPPING_KEY = "webhook_exclude_shipping_id_"
CACHE_EXCLUDED_SHIPPING_TIME = 60 * 3
WEBHOOK_CACHE_DEFAULT_TIMEOUT: int = 5 * 60 # 5 minutes
+APP_ID_PREFIX = "app"
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index afb92652c9..c37b30c392 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -41,7 +41,6 @@ from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ..order.utils import get_order_country
from ..page.models import Page
from ..payment import ChargeStatus
-from ..plugins.webhook.utils import from_payment_app_id
from ..product import ProductMediaTypes
from ..product.models import Collection, Product, ProductMedia
from ..shipping.interface import ShippingMethodData
@@ -1043,6 +1042,8 @@ def _generate_refund_data_payload(data):
def generate_payment_payload(
payment_data: "PaymentData", requestor: Optional["RequestorOrLazyObject"] = None
):
+ from .transport.utils import from_payment_app_id
+
data = asdict(payment_data)
if refund_data := data.get("refund_data"):
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 19acb9f296..4db714e970 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -30,7 +30,6 @@ from ...payment import TransactionAction, TransactionEventType
from ...payment.interface import RefundData, TransactionActionData, TransactionData
from ...payment.models import TransactionItem
from ...plugins.manager import get_plugins_manager
-from ...plugins.webhook.utils import from_payment_app_id
from ...product.models import ProductVariant
from ...shipping.interface import ShippingMethodData
from ...warehouse import WarehouseClickAndCollectOption
@@ -64,6 +63,7 @@ from ..payloads import (
generate_translation_payload,
)
from ..serializers import serialize_checkout_lines
+from ..transport.utils import from_payment_app_id
def parse_django_datetime(date):
diff --git a/saleor/webhook/transport/__init__.py b/saleor/webhook/transport/__init__.py
new file mode 100644
index 0000000000..52b14e76c3
--- /dev/null
+++ b/saleor/webhook/transport/__init__.py
@@ -0,0 +1,12 @@
+import hashlib
+import hmac
+from typing import Optional
+
+from ...core.jwt_manager import get_jwt_manager
+
+
+def signature_for_payload(body: bytes, secret_key: Optional[str]):
+ if not secret_key:
+ return get_jwt_manager().jws_encode(body)
+ hash = hmac.new(bytes(secret_key, "utf-8"), body, hashlib.sha256)
+ return hash.hexdigest()
diff --git a/saleor/webhook/transport/asynchronous/__init__.py b/saleor/webhook/transport/asynchronous/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.py
new file mode 100644
index 0000000000..f98e6dd3b1
--- /dev/null
+++ b/saleor/webhook/transport/asynchronous/transport.py
@@ -0,0 +1,306 @@
+import json
+import logging
+from typing import TYPE_CHECKING, Any, List, Sequence
+from urllib.parse import urlparse
+
+from celery import group
+from celery.utils.log import get_task_logger
+from django.conf import settings
+from django.contrib.sites.models import Site
+
+from ....celeryconf import app
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....core.tracing import webhooks_opentracing_trace
+from ....graphql.webhook.subscription_payload import (
+ generate_payload_from_subscription,
+ initialize_request,
+)
+from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
+from ... import observability
+from ...event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...observability import WebhookData
+from ..utils import (
+ WebhookResponse,
+ WebhookSchemes,
+ attempt_update,
+ clear_successful_delivery,
+ create_attempt,
+ delivery_update,
+ get_delivery_for_webhook,
+ handle_webhook_retry,
+ send_webhook_using_scheme_method,
+)
+
+if TYPE_CHECKING:
+ from ....webhook.models import Webhook
+
+
+logger = logging.getLogger(__name__)
+task_logger = get_task_logger(__name__)
+
+
+def create_deliveries_for_subscriptions(
+ event_type, subscribable_object, webhooks, requestor=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.
+ """
+ if event_type not in WEBHOOK_TYPES_MAP:
+ logger.info(
+ "Skipping subscription webhook. Event %s is not subscribable.", event_type
+ )
+ return []
+
+ event_payloads = []
+ event_deliveries = []
+ for webhook in webhooks:
+ data = generate_payload_from_subscription(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ subscription_query=webhook.subscription_query,
+ request=initialize_request(
+ requestor,
+ event_type in WebhookEventSyncType.ALL,
+ event_type=event_type,
+ ),
+ app=webhook.app,
+ )
+ if not data:
+ logger.info(
+ "No payload was generated with subscription for event: %s" % event_type
+ )
+ continue
+ event_payload = EventPayload(payload=json.dumps({**data}))
+ event_payloads.append(event_payload)
+ event_deliveries.append(
+ EventDelivery(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ )
+
+ EventPayload.objects.bulk_create(event_payloads)
+ return EventDelivery.objects.bulk_create(event_deliveries)
+
+
+def group_webhooks_by_subscription(webhooks):
+ subscription = [webhook for webhook in webhooks if webhook.subscription_query]
+ regular = [webhook for webhook in webhooks if not webhook.subscription_query]
+
+ return regular, subscription
+
+
+def create_event_delivery_list_for_webhooks(
+ webhooks: Sequence["Webhook"],
+ event_payload: "EventPayload",
+ event_type: str,
+) -> List[EventDelivery]:
+ event_deliveries = EventDelivery.objects.bulk_create(
+ [
+ EventDelivery(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ for webhook in webhooks
+ ]
+ )
+ return event_deliveries
+
+
+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,
+):
+ """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 meta data for payload.
+ :param legacy_data_generator: used to generate payload for regular webhooks.
+ """
+ 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.")
+
+ payload = EventPayload.objects.create(payload=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(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ webhooks=subscription_webhooks,
+ requestor=requestor,
+ )
+ )
+
+ for delivery in deliveries:
+ send_webhook_request_async.delay(delivery.id)
+
+
+ queue=settings.WEBHOOK_CELERY_QUEUE_NAME,
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+)
+def send_webhook_request_async(self, event_delivery_id):
+ delivery = get_delivery_for_webhook(event_delivery_id)
+ if not delivery:
+ return None
+
+ webhook = delivery.webhook
+ domain = Site.objects.get_current().domain
+ attempt = create_attempt(delivery, self.request.id)
+ delivery_status = EventDeliveryStatus.SUCCESS
+ try:
+ if not delivery.payload:
+ raise ValueError(
+ "Event delivery id: %r has no payload." % event_delivery_id
+ )
+ data = delivery.payload.payload
+ with webhooks_opentracing_trace(delivery.event_type, domain, app=webhook.app):
+ response = send_webhook_using_scheme_method(
+ webhook.target_url,
+ domain,
+ webhook.secret_key,
+ delivery.event_type,
+ data,
+ webhook.custom_headers,
+ )
+
+ attempt_update(attempt, response)
+ if response.status == EventDeliveryStatus.FAILED:
+ handle_webhook_retry(self, webhook, response.content, delivery, attempt)
+ delivery_status = EventDeliveryStatus.FAILED
+ elif response.status == EventDeliveryStatus.SUCCESS:
+ task_logger.info(
+ "[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",
+ webhook.id,
+ webhook.target_url,
+ delivery.event_type,
+ delivery.id,
+ )
+ delivery_update(delivery, delivery_status)
+ except ValueError as e:
+ response = WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)
+ attempt_update(attempt, response)
+ delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
+ observability.report_event_delivery_attempt(attempt)
+ clear_successful_delivery(delivery)
+
+
+def send_observability_events(webhooks: List[WebhookData], events: List[Any]):
+ event_type = WebhookEventAsyncType.OBSERVABILITY
+ for webhook in webhooks:
+ scheme = urlparse(webhook.target_url).scheme.lower()
+ failed = 0
+ extra = {
+ "webhook_id": webhook.id,
+ "webhook_target_url": webhook.target_url,
+ "events_count": len(events),
+ }
+ try:
+ if scheme in [WebhookSchemes.AWS_SQS, WebhookSchemes.GOOGLE_CLOUD_PUBSUB]:
+ for event in events:
+ response = send_webhook_using_scheme_method(
+ webhook.target_url,
+ webhook.saleor_domain,
+ webhook.secret_key,
+ event_type,
+ observability.dump_payload(event),
+ )
+ if response.status == EventDeliveryStatus.FAILED:
+ failed += 1
+ else:
+ response = send_webhook_using_scheme_method(
+ webhook.target_url,
+ webhook.saleor_domain,
+ webhook.secret_key,
+ event_type,
+ observability.dump_payload(events),
+ )
+ if response.status == EventDeliveryStatus.FAILED:
+ failed = len(events)
+ except ValueError:
+ logger.error(
+ "Webhook ID: %r unknown webhook scheme: %r.",
+ webhook.id,
+ scheme,
+ extra={**extra, "dropped_events_count": len(events)},
+ )
+ continue
+ if failed:
+ logger.info(
+ "Webhook ID: %r failed request to %r (%s/%s events dropped): %r.",
+ webhook.id,
+ webhook.target_url,
+ failed,
+ len(events),
+ response.content,
+ extra={**extra, "dropped_events_count": failed},
+ )
+ continue
+ logger.debug(
+ "Successful delivered %s events to %r.",
+ len(events),
+ webhook.target_url,
+ extra={**extra, "dropped_events_count": 0},
+ )
+
+
+def observability_send_events():
+ with observability.opentracing_trace("send_events_task", "task"):
+ if webhooks := observability.get_webhooks():
+ with observability.opentracing_trace("pop_events", "buffer"):
+ events, _ = observability.pop_events_with_remaining_size()
+ if events:
+ with observability.opentracing_trace("send_events", "webhooks"):
+ send_observability_events(webhooks, events)
+
+
+def observability_reporter_task():
+ with observability.opentracing_trace("reporter_task", "task"):
+ if webhooks := observability.get_webhooks():
+ with observability.opentracing_trace("pop_events", "buffer"):
+ events, batch_count = observability.pop_events_with_remaining_size()
+ if batch_count > 0:
+ tasks = [observability_send_events.s() for _ in range(batch_count)]
+ expiration = settings.OBSERVABILITY_REPORT_PERIOD.total_seconds()
+ group(tasks).apply_async(expires=expiration)
+ if events:
+ with observability.opentracing_trace("send_events", "webhooks"):
+ send_observability_events(webhooks, events)
diff --git a/saleor/plugins/webhook/stored_payment_methods.py b/saleor/webhook/transport/list_stored_payment_methods.py
similarity index 100%
rename from saleor/plugins/webhook/stored_payment_methods.py
rename to saleor/webhook/transport/list_stored_payment_methods.py
diff --git a/saleor/plugins/webhook/shipping.py b/saleor/webhook/transport/shipping.py
similarity index 97%
rename from saleor/plugins/webhook/shipping.py
rename to saleor/webhook/transport/shipping.py
index 64adc68e58..fa256eb68d 100644
--- a/saleor/plugins/webhook/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -15,12 +15,11 @@ from ...checkout.models import Checkout
from ...graphql.core.utils import from_global_id_or_error
from ...graphql.shipping.types import ShippingMethod
from ...order.models import Order
+from ...plugins.base_plugin import ExcludedShippingMethod
from ...shipping.interface import ShippingMethodData
from ...webhook.utils import get_webhooks_for_event
-from ..base_plugin import ExcludedShippingMethod
-from ..const import APP_ID_PREFIX
-from .const import CACHE_EXCLUDED_SHIPPING_TIME
-from .tasks import trigger_webhook_sync
+from ..const import APP_ID_PREFIX, CACHE_EXCLUDED_SHIPPING_TIME
+from .synchronous.transport import trigger_webhook_sync
logger = logging.getLogger(__name__)
diff --git a/saleor/webhook/transport/synchronous/__init__.py b/saleor/webhook/transport/synchronous/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.py
new file mode 100644
index 0000000000..0df6fc8735
--- /dev/null
+++ b/saleor/webhook/transport/synchronous/transport.py
@@ -0,0 +1,338 @@
+import json
+import logging
+from json import JSONDecodeError
+from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, TypeVar
+from urllib.parse import urlparse
+
+from celery.utils.log import get_task_logger
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.core.cache import cache
+
+from ....celeryconf import app
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....core.tracing import webhooks_opentracing_trace
+from ....graphql.webhook.subscription_payload import (
+ generate_payload_from_subscription,
+ initialize_request,
+)
+from ....graphql.webhook.subscription_types import WEBHOOK_TYPES_MAP
+from ....payment import PaymentError
+from ....payment.models import TransactionEvent
+from ....payment.utils import create_transaction_event_from_request_and_webhook_response
+from ... import observability
+from ...const import WEBHOOK_CACHE_DEFAULT_TIMEOUT
+from ...event_types import WebhookEventSyncType
+from ...utils import get_webhooks_for_event
+from .. import signature_for_payload
+from ..utils import (
+ WebhookResponse,
+ WebhookSchemes,
+ attempt_update,
+ clear_successful_delivery,
+ create_attempt,
+ delivery_update,
+ generate_cache_key_for_webhook,
+ get_delivery_for_webhook,
+ handle_webhook_retry,
+ send_webhook_using_http,
+)
+
+if TYPE_CHECKING:
+ from ....webhook.models import Webhook
+
+R = TypeVar("R")
+
+
+logger = logging.getLogger(__name__)
+task_logger = get_task_logger(__name__)
+
+
+ bind=True,
+ retry_backoff=10,
+ retry_kwargs={"max_retries": 5},
+)
+def handle_transaction_request_task(self, delivery_id, request_event_id):
+ delivery = get_delivery_for_webhook(delivery_id)
+ if not delivery:
+ logger.error(
+ f"Cannot find the delivery with id: {delivery_id} "
+ f"for transaction-request webhook."
+ )
+ return None
+ request_event = TransactionEvent.objects.filter(id=request_event_id).first()
+ if not request_event:
+ logger.error(
+ f"Cannot find the request event with id: {request_event_id} "
+ f"for transaction-request webhook."
+ )
+ return None
+ attempt = create_attempt(delivery, self.request.id)
+ response, response_data = _send_webhook_request_sync(delivery, attempt=attempt)
+ if response.response_status_code and response.response_status_code >= 500:
+ handle_webhook_retry(
+ self, delivery.webhook, response.content, delivery, attempt
+ )
+ response_data = None
+ create_transaction_event_from_request_and_webhook_response(
+ request_event,
+ delivery.webhook.app,
+ response_data,
+ )
+
+
+def _send_webhook_request_sync(
+ delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT, attempt=None
+) -> Tuple[WebhookResponse, Optional[Dict[Any, Any]]]:
+ event_payload = delivery.payload
+ data = event_payload.payload
+ webhook = delivery.webhook
+ parts = urlparse(webhook.target_url)
+ domain = Site.objects.get_current().domain
+ message = data.encode("utf-8")
+ signature = signature_for_payload(message, webhook.secret_key)
+
+ if parts.scheme.lower() not in [WebhookSchemes.HTTP, WebhookSchemes.HTTPS]:
+ delivery_update(delivery, EventDeliveryStatus.FAILED)
+ raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+
+ logger.debug(
+ "[Webhook] Sending payload to %r for event %r.",
+ webhook.target_url,
+ delivery.event_type,
+ )
+ if attempt is None:
+ attempt = create_attempt(delivery=delivery, task_id=None)
+ response = WebhookResponse(content="")
+ response_data = None
+
+ try:
+ with webhooks_opentracing_trace(
+ delivery.event_type, domain, sync=True, app=webhook.app
+ ):
+ response = send_webhook_using_http(
+ webhook.target_url,
+ message,
+ domain,
+ signature,
+ delivery.event_type,
+ timeout=timeout,
+ custom_headers=webhook.custom_headers,
+ )
+ response_data = json.loads(response.content)
+
+ except JSONDecodeError as e:
+ logger.info(
+ "[Webhook] Failed parsing JSON response from %r: %r."
+ "ID of failed DeliveryAttempt: %r . ",
+ webhook.target_url,
+ e,
+ attempt.id,
+ )
+ response.status = EventDeliveryStatus.FAILED
+ else:
+ if response.status == EventDeliveryStatus.FAILED:
+ logger.info(
+ "[Webhook] Failed request to %r: %r. "
+ "ID of failed DeliveryAttempt: %r . ",
+ webhook.target_url,
+ response.content,
+ attempt.id,
+ )
+ if response.status == EventDeliveryStatus.SUCCESS:
+ logger.debug(
+ "[Webhook] Success response from %r."
+ "Successful DeliveryAttempt id: %r",
+ webhook.target_url,
+ attempt.id,
+ )
+
+ attempt_update(attempt, response)
+ delivery_update(delivery, response.status)
+ observability.report_event_delivery_attempt(attempt)
+ clear_successful_delivery(delivery)
+ return response, response_data
+
+
+def send_webhook_request_sync(
+ delivery, timeout=settings.WEBHOOK_SYNC_TIMEOUT
+) -> Optional[Dict[Any, Any]]:
+ response, response_data = _send_webhook_request_sync(delivery, timeout)
+ return response_data if response.status == EventDeliveryStatus.SUCCESS else None
+
+
+def trigger_webhook_sync_if_not_cached(
+ event_type: str,
+ payload: str,
+ webhook: "Webhook",
+ cache_data: dict,
+ subscribable_object=None,
+ request_timeout=None,
+ cache_timeout=None,
+ request=None,
+) -> Optional[dict]:
+ """Get response for synchronous webhook.
+
+ - Send a synchronous webhook request if cache is expired.
+ - Fetch response from cache if it is still valid.
+ """
+
+ cache_key = generate_cache_key_for_webhook(
+ cache_data, webhook.target_url, event_type, webhook.app_id
+ )
+ response_data = cache.get(cache_key)
+ if response_data is None:
+ response_data = trigger_webhook_sync(
+ event_type,
+ payload,
+ webhook,
+ subscribable_object=subscribable_object,
+ timeout=request_timeout,
+ request=request,
+ )
+ if response_data is not None:
+ cache.set(
+ cache_key,
+ response_data,
+ timeout=cache_timeout or WEBHOOK_CACHE_DEFAULT_TIMEOUT,
+ )
+ return response_data
+
+
+def create_delivery_for_subscription_sync_event(
+ event_type, subscribable_object, webhook, requestor=None, request=None
+) -> Optional[EventDelivery]:
+ """Generate webhook payload based on subscription query and create delivery object.
+
+ It uses a defined 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 webhook: webhook object for which delivery will be created.
+ :param requestor: used in subscription webhooks to generate meta data for payload.
+ :param request: used to share context between sync event calls
+ :return: List of event deliveries to send via webhook tasks.
+ """
+ if event_type not in WEBHOOK_TYPES_MAP:
+ logger.info(
+ "Skipping subscription webhook. Event %s is not subscribable.", event_type
+ )
+ return None
+
+ if not request:
+ request = initialize_request(
+ requestor, event_type in WebhookEventSyncType.ALL, event_type=event_type
+ )
+ data = generate_payload_from_subscription(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ subscription_query=webhook.subscription_query,
+ request=request,
+ app=webhook.app,
+ )
+ if not data:
+ # PaymentError is a temporary exception type. New type will be implemented
+ # in separate PR to ensure proper handling for all sync events.
+ # It was implemented when sync webhooks were handling payment events only.
+ raise PaymentError(
+ f"No payload was generated with subscription for event: {event_type}"
+ )
+ event_payload = EventPayload.objects.create(payload=json.dumps({**data}))
+ event_delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ return event_delivery
+
+
+def trigger_webhook_sync(
+ event_type: str,
+ payload: str,
+ webhook: "Webhook",
+ subscribable_object=None,
+ timeout=None,
+ request=None,
+) -> Optional[Dict[Any, Any]]:
+ """Send a synchronous webhook request."""
+ if webhook.subscription_query:
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ webhook=webhook,
+ request=request,
+ )
+ if not delivery:
+ return None
+ else:
+ 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(delivery, **kwargs)
+
+
+def trigger_all_webhooks_sync(
+ event_type: str,
+ generate_payload: Callable,
+ parse_response: Callable[[Any], Optional[R]],
+ subscribable_object=None,
+ requestor=None,
+ allow_replica=True,
+) -> Optional[R]:
+ """Send all synchronous webhook request for given event type.
+
+ Requests are send sequentially.
+ If the current webhook does not return expected response,
+ the next one is send.
+ If no webhook responds with expected response,
+ this function returns None.
+ """
+ webhooks = get_webhooks_for_event(event_type)
+ request_context = None
+ event_payload = None
+ for webhook in webhooks:
+ if webhook.subscription_query:
+ if request_context is None:
+ request_context = initialize_request(
+ requestor,
+ event_type in WebhookEventSyncType.ALL,
+ allow_replica,
+ event_type=event_type,
+ )
+
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ webhook=webhook,
+ request=request_context,
+ requestor=requestor,
+ )
+ if not delivery:
+ return None
+ else:
+ if event_payload is None:
+ event_payload = EventPayload.objects.create(payload=generate_payload())
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+
+ response_data = send_webhook_request_sync(delivery)
+ if parsed_response := parse_response(response_data):
+ return parsed_response
+ return None
diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.py
new file mode 100644
index 0000000000..b2fb6f761d
--- /dev/null
+++ b/saleor/webhook/transport/utils.py
@@ -0,0 +1,622 @@
+import decimal
+import hashlib
+import json
+import logging
+from contextlib import contextmanager
+from dataclasses import dataclass
+from enum import Enum
+from time import time
+from typing import Any, Callable, Dict, List, Optional
+from urllib.parse import unquote, urlparse, urlunparse
+
+import boto3
+from botocore.exceptions import ClientError
+from celery.exceptions import MaxRetriesExceededError, Retry
+from celery.utils.log import get_task_logger
+from django.conf import settings
+from django.urls import reverse
+from google.cloud import pubsub_v1
+from requests import RequestException
+from requests_hardened.ip_filter import InvalidIPAddress
+
+from ...app.headers import AppHeaders, DeprecatedAppHeaders
+from ...app.models import App
+from ...core.http_client import HTTPClient
+from ...core.models import (
+ EventDelivery,
+ EventDeliveryAttempt,
+ EventDeliveryStatus,
+ EventPayload,
+)
+from ...core.taxes import TaxData, TaxLineData
+from ...core.utils import build_absolute_uri
+from ...core.utils.events import call_event
+from ...payment.interface import (
+ GatewayResponse,
+ PaymentData,
+ PaymentGateway,
+ PaymentMethodInfo,
+ TransactionActionData,
+)
+from ...payment.utils import create_failed_transaction_event
+from ...webhook.utils import get_webhooks_for_event
+from .. import observability
+from ..const import APP_ID_PREFIX
+from ..event_types import WebhookEventSyncType
+from . import signature_for_payload
+
+logger = logging.getLogger(__name__)
+task_logger = get_task_logger(__name__)
+
+
+DEFAULT_TAX_CODE = "UNMAPPED"
+DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"
+
+
+class WebhookSchemes(str, Enum):
+ HTTP = "http"
+ HTTPS = "https"
+ AWS_SQS = "awssqs"
+ GOOGLE_CLOUD_PUBSUB = "gcpubsub"
+
+
+@dataclass
+class PaymentAppData:
+ app_pk: Optional[int]
+ app_identifier: Optional[str]
+ name: str
+
+
+@dataclass
+class WebhookResponse:
+ content: str
+ request_headers: Optional[Dict] = None
+ response_headers: Optional[Dict] = None
+ response_status_code: Optional[int] = None
+ status: str = EventDeliveryStatus.SUCCESS
+ duration: float = 0.0
+
+
+def generate_cache_key_for_webhook(
+ key_data: dict, webhook_url: str, event: str, app_id: int
+) -> str:
+ """Generate cache key for webhook.
+
+ Cache key takes into account the webhook url, event type, and app id.
+ The response from webhook_url can be different for different events.
+ Apps can have assigned different permissions, so the response can vary for
+ different apps.
+ """
+ key = json.dumps(key_data)
+ return (
+ f"{app_id}-{webhook_url}-{event}-"
+ f"{hashlib.sha256(key.encode('utf-8')).hexdigest()}"
+ )
+
+
+def send_webhook_using_http(
+ target_url,
+ message,
+ domain,
+ signature,
+ event_type,
+ timeout=settings.WEBHOOK_TIMEOUT,
+ custom_headers: Optional[Dict[str, str]] = None,
+) -> WebhookResponse:
+ """Send a webhook request using http / https protocol.
+
+ :param target_url: Target URL request will be sent to.
+ :param message: Payload that will be used.
+ :param domain: Current site domain.
+ :param signature: Webhook secret key checksum.
+ :param event_type: Webhook event type.
+ :param timeout: Request timeout.
+ :param custom_headers: Custom headers which will be added to request headers.
+
+ :return: WebhookResponse object.
+ """
+ headers = {
+ "Content-Type": "application/json",
+ # X- headers will be deprecated in Saleor 4.0, proper headers are without X-
+ DeprecatedAppHeaders.EVENT_TYPE: event_type,
+ DeprecatedAppHeaders.DOMAIN: domain,
+ DeprecatedAppHeaders.SIGNATURE: signature,
+ AppHeaders.EVENT_TYPE: event_type,
+ AppHeaders.DOMAIN: domain,
+ AppHeaders.SIGNATURE: signature,
+ AppHeaders.API_URL: build_absolute_uri(reverse("api"), domain),
+ }
+
+ if custom_headers:
+ headers.update(custom_headers)
+
+ try:
+ response = HTTPClient.send_request(
+ "POST",
+ target_url,
+ data=message,
+ headers=headers,
+ timeout=timeout,
+ allow_redirects=False,
+ )
+ except RequestException as e:
+ if e.response:
+ return WebhookResponse(
+ content=e.response.text,
+ status=EventDeliveryStatus.FAILED,
+ request_headers=headers,
+ response_headers=dict(e.response.headers),
+ response_status_code=e.response.status_code,
+ )
+
+ if isinstance(e, InvalidIPAddress):
+ message = "Invalid IP address"
+ else:
+ message = str(e)
+ result = WebhookResponse(
+ content=message,
+ status=EventDeliveryStatus.FAILED,
+ request_headers=headers,
+ )
+ return result
+
+ return WebhookResponse(
+ content=response.text,
+ request_headers=headers,
+ response_headers=dict(response.headers),
+ response_status_code=response.status_code,
+ duration=response.elapsed.total_seconds(),
+ status=(
+ EventDeliveryStatus.SUCCESS if response.ok else EventDeliveryStatus.FAILED
+ ),
+ )
+
+
+def send_webhook_using_aws_sqs(
+ target_url, message, domain, signature, event_type, **kwargs
+):
+ parts = urlparse(target_url)
+ region = "us-east-1"
+ hostname_parts = parts.hostname.split(".")
+ if len(hostname_parts) == 4 and hostname_parts[0] == "sqs":
+ region = hostname_parts[1]
+ client = boto3.client(
+ "sqs",
+ region_name=region,
+ aws_access_key_id=parts.username,
+ aws_secret_access_key=(
+ unquote(parts.password) if parts.password else parts.password
+ ),
+ )
+ queue_url = urlunparse(
+ (
+ "https",
+ parts.hostname,
+ parts.path,
+ parts.params,
+ parts.query,
+ parts.fragment,
+ )
+ )
+ is_fifo = parts.path.endswith(".fifo")
+
+ msg_attributes = {
+ "SaleorDomain": {"DataType": "String", "StringValue": domain},
+ "SaleorApiUrl": {
+ "DataType": "String",
+ "StringValue": build_absolute_uri(reverse("api"), domain),
+ },
+ "EventType": {"DataType": "String", "StringValue": event_type},
+ }
+ if signature:
+ msg_attributes["Signature"] = {
+ "DataType": "String",
+ "StringValue": signature,
+ }
+
+ message_kwargs = {
+ "QueueUrl": queue_url,
+ "MessageAttributes": msg_attributes,
+ "MessageBody": message.decode("utf-8"),
+ }
+ if is_fifo:
+ message_kwargs["MessageGroupId"] = domain
+ with catch_duration_time() as duration:
+ try:
+ response = client.send_message(**message_kwargs)
+ except (ClientError,) as e:
+ return WebhookResponse(
+ content=str(e), status=EventDeliveryStatus.FAILED, duration=duration()
+ )
+ return WebhookResponse(content=response, duration=duration())
+
+
+def send_webhook_using_google_cloud_pubsub(
+ target_url, message, domain, signature, event_type, **kwargs
+):
+ parts = urlparse(target_url)
+ client = pubsub_v1.PublisherClient()
+ topic_name = parts.path[1:] # drop the leading slash
+ with catch_duration_time() as duration:
+ try:
+ future = client.publish(
+ topic_name,
+ message,
+ saleorDomain=domain,
+ saleorApiUrl=build_absolute_uri(reverse("api"), domain),
+ eventType=event_type,
+ signature=signature,
+ )
+ except (pubsub_v1.publisher.exceptions.MessageTooLargeError, RuntimeError) as e:
+ return WebhookResponse(content=str(e), status=EventDeliveryStatus.FAILED)
+ response_duration = duration()
+ response = future.result()
+ return WebhookResponse(content=response, duration=response_duration)
+
+
+def send_webhook_using_scheme_method(
+ target_url,
+ domain,
+ secret,
+ event_type,
+ data,
+ custom_headers=None,
+) -> WebhookResponse:
+ parts = urlparse(target_url)
+ message = data.encode("utf-8")
+ signature = signature_for_payload(message, secret)
+ scheme_matrix: Dict[WebhookSchemes, Callable] = {
+ WebhookSchemes.HTTP: send_webhook_using_http,
+ WebhookSchemes.HTTPS: send_webhook_using_http,
+ WebhookSchemes.AWS_SQS: send_webhook_using_aws_sqs,
+ WebhookSchemes.GOOGLE_CLOUD_PUBSUB: send_webhook_using_google_cloud_pubsub,
+ }
+
+ if send_method := scheme_matrix.get(parts.scheme.lower()):
+ # try:
+ return send_method(
+ target_url,
+ message,
+ domain,
+ signature,
+ event_type,
+ custom_headers=custom_headers,
+ )
+ raise ValueError("Unknown webhook scheme: %r" % (parts.scheme,))
+
+
+def handle_webhook_retry(
+ celery_task, webhook, response_content, delivery, delivery_attempt
+) -> bool:
+ """Handle celery retry for webhook requests.
+
+ Calls retry to re-run the celery_task by raising Retry exception.
+ When MaxRetriesExceededError is raised the function will end without exception.
+ """
+ is_success = True
+ task_logger.info(
+ "[Webhook ID: %r] Failed request to %r: %r for event: %r."
+ " Delivery attempt id: %r",
+ webhook.id,
+ webhook.target_url,
+ response_content,
+ delivery.event_type,
+ delivery_attempt.id,
+ )
+ try:
+ countdown = celery_task.retry_backoff * (2**celery_task.request.retries)
+ celery_task.retry(countdown=countdown, **celery_task.retry_kwargs)
+ except Retry as retry_error:
+ next_retry = observability.task_next_retry_date(retry_error)
+ observability.report_event_delivery_attempt(delivery_attempt, next_retry)
+ raise retry_error
+ except MaxRetriesExceededError:
+ is_success = False
+ task_logger.info(
+ "[Webhook ID: %r] Failed request to %r: exceeded retry limit."
+ "Delivery id: %r",
+ webhook.id,
+ webhook.target_url,
+ delivery.id,
+ )
+ return is_success
+
+
+def get_delivery_for_webhook(event_delivery_id) -> Optional["EventDelivery"]:
+ try:
+ delivery = EventDelivery.objects.select_related("payload", "webhook__app").get(
+ id=event_delivery_id
+ )
+ except EventDelivery.DoesNotExist:
+ logger.error("Event delivery id: %r not found", event_delivery_id)
+ return None
+
+ if not delivery.webhook.is_active:
+ delivery_update(delivery=delivery, status=EventDeliveryStatus.FAILED)
+ logger.info("Event delivery id: %r webhook is disabled.", event_delivery_id)
+ return None
+ return delivery
+
+
+@contextmanager
+def catch_duration_time():
+ start = time()
+ yield lambda: time() - start
+
+
+def create_attempt(
+ delivery: "EventDelivery",
+ task_id: Optional[str] = None,
+):
+ attempt = EventDeliveryAttempt.objects.create(
+ delivery=delivery,
+ task_id=task_id,
+ duration=None,
+ response=None,
+ request_headers=None,
+ response_headers=None,
+ status=EventDeliveryStatus.PENDING,
+ )
+ return attempt
+
+
+def attempt_update(
+ attempt: "EventDeliveryAttempt",
+ webhook_response: "WebhookResponse",
+):
+ attempt.duration = webhook_response.duration
+ attempt.response = webhook_response.content
+ attempt.response_headers = json.dumps(webhook_response.response_headers)
+ attempt.response_status_code = webhook_response.response_status_code
+ attempt.request_headers = json.dumps(webhook_response.request_headers)
+ attempt.status = webhook_response.status
+ attempt.save(
+ update_fields=[
+ "duration",
+ "response",
+ "response_headers",
+ "response_status_code",
+ "request_headers",
+ "status",
+ ]
+ )
+
+
+def clear_successful_delivery(delivery: "EventDelivery"):
+ if delivery.status == EventDeliveryStatus.SUCCESS:
+ payload_id = delivery.payload_id
+ delivery.delete()
+ if payload_id:
+ EventPayload.objects.filter(pk=payload_id, deliveries__isnull=True).delete()
+
+
+def delivery_update(delivery: "EventDelivery", status: str):
+ delivery.status = status
+ delivery.save(update_fields=["status"])
+
+
+def trigger_transaction_request(
+ transaction_data: "TransactionActionData", event_type: str, requestor
+):
+ from ..payloads import generate_transaction_action_request_payload
+ from .synchronous.transport import (
+ create_delivery_for_subscription_sync_event,
+ handle_transaction_request_task,
+ )
+
+ if not transaction_data.event:
+ logger.warning(
+ "The transaction request for transaction: %s doesn't have a "
+ "proper REQUEST event.",
+ transaction_data.transaction.id,
+ )
+ return None
+ if not transaction_data.transaction_app_owner:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause=(
+ "Cannot process the action as the given transaction is not "
+ "attached to any app."
+ ),
+ )
+ return None
+ webhook = get_webhooks_for_event(
+ event_type, apps_ids=[transaction_data.transaction_app_owner.pk]
+ ).first()
+ if not webhook:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot find a webhook that can process the action.",
+ )
+ return None
+
+ if webhook.subscription_query:
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=transaction_data,
+ webhook=webhook,
+ )
+ if not delivery:
+ create_failed_transaction_event(
+ transaction_data.event,
+ cause="Cannot generate a payload for the action.",
+ )
+ return None
+ else:
+ payload = generate_transaction_action_request_payload(
+ transaction_data, requestor
+ )
+ event_payload = EventPayload.objects.create(payload=payload)
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ call_event(
+ handle_transaction_request_task.delay,
+ delivery.id,
+ transaction_data.event.id,
+ )
+ return None
+
+
+def parse_tax_data(
+ response_data: Any,
+) -> Optional[TaxData]:
+ try:
+ return _unsafe_parse_tax_data(response_data)
+ except (TypeError, KeyError, decimal.DecimalException):
+ return None
+
+
+def parse_payment_action_response(
+ payment_information: "PaymentData",
+ response_data: Any,
+ transaction_kind: "str",
+) -> "GatewayResponse":
+ error = response_data.get("error")
+ is_success = not error
+
+ payment_method_info = None
+ payment_method_data = response_data.get("payment_method")
+ if payment_method_data:
+ payment_method_info = PaymentMethodInfo(
+ brand=payment_method_data.get("brand"),
+ exp_month=payment_method_data.get("exp_month"),
+ exp_year=payment_method_data.get("exp_year"),
+ last_4=payment_method_data.get("last_4"),
+ name=payment_method_data.get("name"),
+ type=payment_method_data.get("type"),
+ )
+
+ amount = payment_information.amount
+ if "amount" in response_data:
+ try:
+ amount = decimal.Decimal(response_data["amount"])
+ except decimal.DecimalException:
+ pass
+
+ return GatewayResponse(
+ action_required=response_data.get("action_required", False),
+ action_required_data=response_data.get("action_required_data"),
+ amount=amount,
+ currency=payment_information.currency,
+ customer_id=response_data.get("customer_id"),
+ error=error,
+ is_success=is_success,
+ kind=response_data.get("kind", transaction_kind),
+ payment_method_info=payment_method_info,
+ raw_response=response_data,
+ psp_reference=response_data.get("psp_reference"),
+ transaction_id=response_data.get("transaction_id", ""),
+ transaction_already_processed=response_data.get(
+ "transaction_already_processed", False
+ ),
+ )
+
+
+def _unsafe_parse_tax_line_data(
+ tax_line_data_response: Any,
+) -> TaxLineData:
+ """Unsafe TaxLineData parser.
+
+ Raises KeyError or DecimalException on invalid data.
+ """
+ total_gross_amount = decimal.Decimal(tax_line_data_response["total_gross_amount"])
+ total_net_amount = decimal.Decimal(tax_line_data_response["total_net_amount"])
+ tax_rate = decimal.Decimal(tax_line_data_response["tax_rate"])
+
+ return TaxLineData(
+ total_gross_amount=total_gross_amount,
+ total_net_amount=total_net_amount,
+ tax_rate=tax_rate,
+ )
+
+
+def _unsafe_parse_tax_data(
+ tax_data_response: Any,
+) -> TaxData:
+ """Unsafe TaxData parser.
+
+ Raises KeyError or DecimalException on invalid data.
+ """
+ shipping_price_gross_amount = decimal.Decimal(
+ tax_data_response["shipping_price_gross_amount"]
+ )
+ shipping_price_net_amount = decimal.Decimal(
+ tax_data_response["shipping_price_net_amount"]
+ )
+ shipping_tax_rate = decimal.Decimal(tax_data_response["shipping_tax_rate"])
+ lines = [_unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]]
+
+ return TaxData(
+ shipping_price_gross_amount=shipping_price_gross_amount,
+ shipping_price_net_amount=shipping_price_net_amount,
+ shipping_tax_rate=shipping_tax_rate,
+ lines=lines,
+ )
+
+
+def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
+ splitted_id = app_gateway_id.split(":", maxsplit=2)
+ if len(splitted_id) == 3 and splitted_id[0] == APP_ID_PREFIX and all(splitted_id):
+ try:
+ app_pk = int(splitted_id[1])
+ except (TypeError, ValueError):
+ return PaymentAppData(
+ app_identifier=splitted_id[1], app_pk=None, name=splitted_id[2]
+ )
+ else:
+ return PaymentAppData(
+ app_pk=app_pk, app_identifier=None, name=splitted_id[2]
+ )
+ return None
+
+
+def get_current_tax_app() -> Optional[App]:
+ """Return currently used tax app or None, if there aren't any."""
+ return (
+ App.objects.order_by("pk")
+ .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+ .last()
+ )
+
+
+def get_meta_code_key(app: App) -> str:
+ return f"{app.identifier}.code"
+
+
+def get_meta_description_key(app: App) -> str:
+ return f"{app.identifier}.description"
+
+
+def to_payment_app_id(app: "App", external_id: str) -> "str":
+ app_identifier = app.identifier or app.id
+ return f"{APP_ID_PREFIX}:{app_identifier}:{external_id}"
+
+
+def parse_list_payment_gateways_response(
+ response_data: Any, app: "App"
+) -> List["PaymentGateway"]:
+ gateways: List[PaymentGateway] = []
+ if not isinstance(response_data, list):
+ return gateways
+
+ for gateway_data in response_data:
+ gateway_id = gateway_data.get("id")
+ gateway_name = gateway_data.get("name")
+ gateway_currencies = gateway_data.get("currencies")
+ gateway_config = gateway_data.get("config")
+
+ if gateway_id:
+ gateways.append(
+ PaymentGateway(
+ id=to_payment_app_id(app, gateway_id),
+ name=gateway_name,
+ currencies=gateway_currencies,
+ config=gateway_config,
+ )
+ )
+ return gateways