Skip to content

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

Fix promises not successfully handling exceptions (#12597)

Mikailb06f653e10ec
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 842d4d6e69..e6a1742286 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -14,8 +14,7 @@ from typing import (
)
from uuid import UUID
-from django.utils.functional import SimpleLazyObject
-
+from ..core.utils.lazyobjects import lazy_no_retry
from ..discount import DiscountInfo, VoucherType
from ..discount.interface import fetch_voucher_info
from ..discount.utils import fetch_active_discounts
@@ -493,7 +492,7 @@ def update_checkout_info_delivery_method_info(
else:
delivery_method = collection_point
- checkout_info.delivery_method_info = SimpleLazyObject(
+ checkout_info.delivery_method_info = lazy_no_retry(
lambda: get_delivery_method_info(
delivery_method,
checkout_info.shipping_address,
@@ -640,10 +639,10 @@ def update_delivery_method_lists_for_checkout_info(
initialize_shipping_method_active_status(all_methods, excluded_methods)
return all_methods
- checkout_info.all_shipping_methods = SimpleLazyObject(
+ checkout_info.all_shipping_methods = lazy_no_retry(
_resolve_all_shipping_methods
) # type: ignore[assignment] # using lazy object breaks protocol
- checkout_info.valid_pick_up_points = SimpleLazyObject(
+ checkout_info.valid_pick_up_points = lazy_no_retry(
lambda: (get_valid_collection_points_for_checkout_info(lines, checkout_info))
) # type: ignore[assignment] # using lazy object breaks protocol
update_checkout_info_delivery_method_info(
@@ -663,7 +662,7 @@ def get_valid_collection_points_for_checkout_info(
valid_collection_points = get_valid_collection_points_for_checkout(
lines, checkout_info.channel.id, quantity_check=False
)
- return SimpleLazyObject(lambda: list(valid_collection_points))
+ return list(valid_collection_points)
def update_checkout_info_delivery_method(
diff --git a/saleor/core/utils/lazyobjects.py b/saleor/core/utils/lazyobjects.py
new file mode 100644
index 0000000000..a21528dab9
--- /dev/null
+++ b/saleor/core/utils/lazyobjects.py
@@ -0,0 +1,39 @@
+import functools
+from typing import Any, Callable, Optional
+
+from django.utils.functional import LazyObject, SimpleLazyObject, empty
+
+
+def lazy_no_retry(func: Callable) -> SimpleLazyObject:
+ """Wrap SimpleLazyObject while ensuring it is never re-evaluated on failure.
+
+ Wraps a given function into a ``SimpleLazyObject`` class while ensuring
+ if ``func`` fails, then ``func`` is never invoked again.
+
+ This mitigates an issue where an expensive ``func`` can be rerun for
+ each GraphQL resolver instead of flagging it as rejected/failed.
+ """
+ error: Optional[Exception] = None
+
+ @functools.wraps(func)
+ def _wrapper():
+ nonlocal error
+
+ # If it was already evaluated, and it crashed, then do not re-attempt.
+ if error:
+ raise error
+
+ try:
+ return func()
+ except Exception as exc:
+ error = exc
+ raise
+
+ return SimpleLazyObject(_wrapper)
+
+
+def unwrap_lazy(obj: LazyObject) -> Any:
+ """Return the value of a given ``LazyObject``."""
+ if obj._wrapped is empty: # type: ignore[attr-defined] # valid attribute
+ obj._setup() # type: ignore[attr-defined] # valid attribute
+ return obj._wrapped # type: ignore[attr-defined] # valid attribute
diff --git a/saleor/graphql/app/dataloaders.py b/saleor/graphql/app/dataloaders.py
index 562171b6c9..6dda874f5b 100644
--- a/saleor/graphql/app/dataloaders.py
+++ b/saleor/graphql/app/dataloaders.py
@@ -3,10 +3,12 @@ from functools import partial, wraps
from typing import Optional
from django.contrib.auth.hashers import check_password
+from django.utils.functional import LazyObject
from promise import Promise
from ...app.models import App, AppExtension, AppToken
from ...core.auth import get_token_from_request
+from ...core.utils.lazyobjects import unwrap_lazy
from ..core import SaleorContext
from ..core.dataloaders import DataLoader
@@ -96,7 +98,10 @@ def promise_app(context: SaleorContext) -> Promise[Optional[App]]:
def get_app_promise(context: SaleorContext) -> Promise[Optional[App]]:
if hasattr(context, "app"):
- return Promise.resolve(context.app)
+ app = context.app
+ if isinstance(app, LazyObject):
+ app = unwrap_lazy(app)
+ return Promise.resolve(app)
return promise_app(context)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index bb8e9efce1..068c9a5432 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -11,6 +11,7 @@ from ...checkout.base_calculations import (
from ...checkout.calculations import fetch_checkout_data
from ...checkout.utils import get_valid_collection_points_for_checkout
from ...core.taxes import zero_money, zero_taxed_money
+from ...core.utils.lazyobjects import unwrap_lazy
from ...permission.enums import (
AccountPermissions,
CheckoutPermissions,
@@ -581,7 +582,7 @@ class Checkout(ModelObjectType[models.Checkout]):
return (
CheckoutInfoByCheckoutTokenLoader(info.context)
.load(root.token)
- .then(lambda checkout_info: checkout_info.all_shipping_methods)
+ .then(lambda checkout_info: unwrap_lazy(checkout_info.all_shipping_methods))
)
@staticmethod