Skip to content

Commit f3d7f11

Browse files
authored
fix: Make cachetools caches thread-safe (#155)
1 parent 1475bd9 commit f3d7f11

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/viur/shop/modules/discount.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import io
2+
import threading
23
import typing as t # noqa
34

45
import cachetools
@@ -15,6 +16,9 @@
1516

1617
logger = SHOP_LOGGER.getChild(__name__)
1718

19+
lock_current_automatically_discounts = threading.Lock()
20+
"""Lock to make the current_automatically_discounts cache thread-safe"""
21+
1822

1923
class Discount(ShopModuleAbstract, List):
2024
moduleName = "discount"
@@ -236,7 +240,7 @@ def can_apply(
236240
return dv.is_fulfilled, dv
237241

238242
@property
239-
@cachetools.cached(cache=cachetools.TTLCache(maxsize=1024, ttl=3600))
243+
@cachetools.cached(cache=cachetools.TTLCache(maxsize=1024, ttl=3600), lock=lock_current_automatically_discounts)
240244
def current_automatically_discounts(self) -> list[SkeletonInstance_T[DiscountSkel]]:
241245
query = self.viewSkel().all().filter("activate_automatically =", True)
242246
discounts = []

src/viur/shop/modules/discount_condition.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import random
22
import string
3+
import threading
34
import typing as t
45

56
import cachetools
@@ -22,6 +23,9 @@
2223
CODE_LENGTH = 8
2324
SUFFIX_LENGTH = 6
2425

26+
lock_get_skel = threading.Lock()
27+
"""Lock to make the get_skel cache thread-safe"""
28+
2529

2630
class DiscountCondition(ShopModuleAbstract, List):
2731
moduleName = "discount_condition"
@@ -158,7 +162,7 @@ def generate_subcodes(self, parent_key: db.Key, prefix: str, amount: int):
158162
# --- Helpers ------------------------------------------------------------
159163

160164
@classmethod
161-
@cachetools.cached(cache=cachetools.TTLCache(maxsize=1024, ttl=3600))
165+
@cachetools.cached(cache=cachetools.TTLCache(maxsize=1024, ttl=3600), lock=lock_get_skel)
162166
def get_skel(cls, key: db.Key) -> SkeletonInstance_T["DiscountConditionSkel"] | None:
163167
# logger.debug(f"get_skel({key=})")
164168
skel = SHOP_INSTANCE.get().discount_condition.viewSkel()

0 commit comments

Comments
 (0)