Skip to content

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

Add cache to AppByTokenLoader (#17736) (#17817)

Filip Owczarekd9a97ea25cbf
diff --git a/saleor/graphql/app/dataloaders/app.py b/saleor/graphql/app/dataloaders/app.py
index 4ed1cdd8f7..4e6d9cca53 100644
--- a/saleor/graphql/app/dataloaders/app.py
+++ b/saleor/graphql/app/dataloaders/app.py
@@ -1,10 +1,21 @@
+import hashlib
from collections import defaultdict
+from dataclasses import dataclass
from django.contrib.auth.hashers import check_password
+from django.core.cache import cache
from ....app.models import App, AppToken
from ...core.dataloaders import DataLoader
+# Cache timeout for the app token loader
+CACHE_TIMEOUT = 30 * 60 * 60 * 24 # 30 days
+
+
+def create_app_cache_key_from_token(token: str) -> str:
+ """Create a cache key for the app based on the token."""
+ return f"AppByTokenLoader:{hashlib.md5(token.encode('utf-8')).hexdigest()}"
+
class AppByIdLoader(DataLoader[str, App]):
context_key = "app_by_id"
@@ -18,24 +29,79 @@ class AppByIdLoader(DataLoader[str, App]):
return [apps.get(key) for key in keys]
+@dataclass
+class TokenInfo:
+ raw_token: str
+ _cache_key: str | None = None
+
+ @property
+ def last_4(self) -> str:
+ return self.raw_token[-4:]
+
+ @property
+ def cache_key(self) -> str:
+ if self._cache_key is None:
+ self._cache_key = create_app_cache_key_from_token(self.raw_token)
+ return self._cache_key
+ return self._cache_key
+
+
class AppByTokenLoader(DataLoader[str, App]):
context_key = "app_by_token"
+ def get_and_cache_app_id(
+ self, token_info: TokenInfo, token_id: int, auth_token: str, app_id: int
+ ):
+ """Check if the token is valid and return the app ID."""
+ cached_data = cache.get(token_info.cache_key)
+ if cached_data:
+ cached_app_id, cached_token_id = cached_data
+ if token_id == cached_token_id:
+ return cached_app_id
+ elif check_password(token_info.raw_token, auth_token):
+ cache_data = (app_id, token_id)
+ cache.set(token_info.cache_key, cache_data, CACHE_TIMEOUT)
+ return app_id
+ return None
+
+ def remove_not_valid_tokens_from_cache(
+ self, last_4s_to_raw_token_map, tokens_found
+ ):
+ """Remove tokens from the cache that are not valid."""
+ for token_infos in last_4s_to_raw_token_map.values():
+ for token_info in token_infos:
+ if token_info.raw_token not in tokens_found:
+ cache.delete(token_info.cache_key)
+
def batch_load(self, keys):
last_4s_to_raw_token_map = defaultdict(list)
+
for raw_token in keys:
- last_4s_to_raw_token_map[raw_token[-4:]].append(raw_token)
+ token_info = TokenInfo(raw_token=raw_token)
+ last_4s_to_raw_token_map[token_info.last_4].append(token_info)
+ # Fetch tokens for keys that are not in the cache and check if they are valid
+ authed_apps = {}
tokens = (
AppToken.objects.using(self.database_connection_name)
.filter(token_last_4__in=last_4s_to_raw_token_map.keys())
- .values_list("auth_token", "token_last_4", "app_id")
+ .values_list("auth_token", "token_last_4", "app_id", "id")
)
- authed_apps = {}
- for auth_token, token_last_4, app_id in tokens:
- for raw_token in last_4s_to_raw_token_map[token_last_4]:
- if check_password(raw_token, auth_token):
- authed_apps[raw_token] = app_id
+ tokens_found = set()
+ for auth_token, token_last_4, app_id, token_id in tokens:
+ for token_info in last_4s_to_raw_token_map[token_last_4]:
+ if token_info.raw_token in tokens_found:
+ # Skip if we already checked this token
+ continue
+ app_id = self.get_and_cache_app_id(
+ token_info, token_id, auth_token, app_id
+ )
+ if app_id:
+ authed_apps[token_info.raw_token] = app_id
+ tokens_found.add(token_info.raw_token)
+
+ # Remove the cache for tokens that are not valid
+ self.remove_not_valid_tokens_from_cache(last_4s_to_raw_token_map, tokens_found)
apps = (
App.objects.using(self.database_connection_name)
@@ -44,7 +110,6 @@ class AppByTokenLoader(DataLoader[str, App]):
)
.in_bulk()
)
-
return [apps.get(authed_apps.get(key)) for key in keys]
diff --git a/saleor/graphql/app/tests/test_app_by_token_loader_use_cache.py b/saleor/graphql/app/tests/test_app_by_token_loader_use_cache.py
new file mode 100644
index 0000000000..f42457767e
--- /dev/null
+++ b/saleor/graphql/app/tests/test_app_by_token_loader_use_cache.py
@@ -0,0 +1,301 @@
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from ....app.models import App, AppToken
+from ...context import SaleorContext
+from ..dataloaders.app import AppByTokenLoader, create_app_cache_key_from_token
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_cache_token_calculation(
+ mocked_cache, app, setup_mock_for_cache
+):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ cached_app_id, token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == token_id
+ assert fetched_app.id == app.id == cached_app_id
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_invalid_token(mocked_cache, app, setup_mock_for_cache):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ cached_data = mocked_cache.get(expected_cache_key)
+ assert fetched_app is None
+ assert cached_data is None
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_use_cached_app(mocked_cache, app, setup_mock_for_cache):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (app.id, token.id), 123)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ cached_app_id, cached_token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == cached_token_id
+ assert fetched_app.id == app.id == cached_app_id
+ # Check that the cache was set only once during given test section
+ mocked_cache.set.assert_called_once_with(
+ expected_cache_key, (app.id, token.id), 123
+ )
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_cached_app_not_active(
+ mocked_cache, app, setup_mock_for_cache
+):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ app.is_active = False
+ app.save(update_fields=["is_active"])
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (app.id, token.id), 123)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ cached_app_id, cached_token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == cached_token_id
+ assert app.id == cached_app_id
+ # Check that the app was not fetched from the database
+ assert fetched_app is None
+ # Check that the cache was set only once during given test section
+ mocked_cache.set.assert_called_once_with(
+ expected_cache_key, (app.id, token.id), 123
+ )
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_cached_app_marked_as_removed(
+ mocked_cache, app, setup_mock_for_cache
+):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ app.removed_at = timezone.now()
+ app.save(update_fields=["removed_at"])
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (app.id, token.id), 123)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ cached_app_id, cached_token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == cached_token_id
+ assert app.id == cached_app_id
+ # Check that the app was not fetched from the database
+ assert fetched_app is None
+ # Check that the cache was set only once during given test section
+ mocked_cache.set.assert_called_once_with(
+ expected_cache_key, (app.id, token.id), 123
+ )
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_missing_app(mocked_cache, app, setup_mock_for_cache):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ deleted_app_id = app.id
+ app.delete()
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (deleted_app_id, token.id), 123)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ # Check that the app was removed from the database
+ assert not App.objects.exists()
+ # Check that the app was not fetched from the database
+ assert fetched_app is None
+ # Check that the cache was set only once during given test section
+ mocked_cache.set.assert_called_once_with(
+ expected_cache_key, (deleted_app_id, token.id), 123
+ )
+ # Check if the token was removed from the cache
+ assert mocked_cache.get(expected_cache_key) is None
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_removed_token(mocked_cache, app, setup_mock_for_cache):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ token_id = token.id
+ token.delete()
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (app.id, token_id), 123)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token])
+ fetched_app = loaded_apps[0]
+
+ # then
+ # Check that the token was removed from the database
+ assert not AppToken.objects.exists()
+ # Check that the app was not fetched from the database
+ assert fetched_app is None
+ # Check that the cache was set only once during given test section
+ mocked_cache.set.assert_called_once_with(
+ expected_cache_key, (app.id, token_id), 123
+ )
+ # Check if the token was removed from the cache
+ assert mocked_cache.get(expected_cache_key) is None
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_one_of_tokens_in_cache(
+ mocked_cache, app, setup_mock_for_cache
+):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+ mocked_cache.set(expected_cache_key, (app.id, token.id), 123)
+
+ raw_token2 = "test_token2"
+ token2, _ = app.tokens.create(
+ name="test_token2",
+ auth_token=raw_token2,
+ )
+ expected_cache_key2 = create_app_cache_key_from_token(raw_token2)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token, raw_token2])
+ fetched_app = loaded_apps[0]
+ fetched_app2 = loaded_apps[1]
+
+ # then
+ cached_app_id, cached_token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == cached_token_id
+ assert fetched_app.id == app.id == cached_app_id
+ cached_app_id2, cached_token_id2 = mocked_cache.get(expected_cache_key2)
+ assert token2.id == cached_token_id2
+ assert fetched_app2.id == app.id == cached_app_id2
+ # Check that the cache was set once during given test section and second time inside dataloader
+ assert mocked_cache.set.call_count == 2
+
+
+@patch("saleor.graphql.app.dataloaders.app.cache")
+def test_app_by_token_loader_tokens_with_same_last_4(
+ mocked_cache, app, app_with_token, setup_mock_for_cache
+):
+ # given
+ dummy_cache = {}
+ setup_mock_for_cache(dummy_cache, mocked_cache)
+ raw_token = "test_token1234"
+ token, _ = app.tokens.create(
+ name="test_token",
+ auth_token=raw_token,
+ )
+ expected_cache_key = create_app_cache_key_from_token(raw_token)
+
+ app2 = app_with_token
+ raw_token2 = "test2_token1234"
+ token2, _ = app2.tokens.create(
+ name="test_token2",
+ auth_token=raw_token2,
+ )
+ expected_cache_key2 = create_app_cache_key_from_token(raw_token2)
+
+ # when
+ context = SaleorContext()
+ app_by_token_loader = AppByTokenLoader(context)
+ loaded_apps = app_by_token_loader.batch_load([raw_token, raw_token2])
+ fetched_app = loaded_apps[0]
+ fetched_app2 = loaded_apps[1]
+
+ # then
+ assert token.token_last_4 == token2.token_last_4
+ cached_app_id, cached_token_id = mocked_cache.get(expected_cache_key)
+ assert token.id == cached_token_id
+ assert fetched_app.id == app.id == cached_app_id
+ cached_app_id2, cached_token_id2 = mocked_cache.get(expected_cache_key2)
+ assert token2.id == cached_token_id2
+ assert fetched_app2.id == app2.id == cached_app_id2
+ # Check that the cache was set once during given test section and second time inside dataloader
+ assert mocked_cache.set.call_count == 2