Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add an LRU cache for GraphQL document parser and validator (#14843)
Patryk Zawadzkiec81e34dd0c0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 377266dcf5..af596493f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,8 @@ All notable, unreleased changes to this project will be documented in this file.- Drop demo - #14835 by @fowczarek- Add JSON serialization immediately after creating observability events to eliminate extra cPickle serialization and deserialization steps - #14992 by @przlada+- Added caching of GraphQL documents for common queries to improve performance - #14843 by @patrys+# 3.18.0### Highlightsdiff --git a/saleor/core/utils/cache.py b/saleor/core/utils/cache.pynew file mode 100644index 0000000000..24a0d70710--- /dev/null+++ b/saleor/core/utils/cache.py@@ -0,0 +1,20 @@+import collections+++class CacheDict(collections.OrderedDict):+ def __init__(self, capacity: int):+ self.capacity = capacity+ super().__init__()++ def __getitem__(self, key):+ value = super().__getitem__(key)+ super().move_to_end(key)+ return value++ def __setitem__(self, key, value):+ super().__setitem__(key, value)+ super().move_to_end(key)++ while len(self) > self.capacity:+ surplus = next(iter(self))+ super().__delitem__(surplus)diff --git a/saleor/core/utils/tests/__init__.py b/saleor/core/utils/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/core/utils/tests/test_cache.py b/saleor/core/utils/tests/test_cache.pynew file mode 100644index 0000000000..31cd7f91e8--- /dev/null+++ b/saleor/core/utils/tests/test_cache.py@@ -0,0 +1,44 @@+from ..cache import CacheDict+++def test_capacity():+ # given+ cache = CacheDict(2)+ cache[1] = "a"+ cache[2] = "b"++ # when+ cache[3] = "c"++ # then+ assert 1 not in cache+ assert 2 in cache+ assert 3 in cache+++def test_persistence():+ # given+ cache = CacheDict(2)+ watchdog = object()++ # when+ cache[1] = watchdog++ # then+ assert cache[1] is watchdog+++def test_eviction_order():+ # given+ cache = CacheDict(2)+ cache[1] = "a"+ cache[2] = "b"++ # when+ cache[1]+ cache[3] = "c"++ # then+ assert 1 in cache+ assert 2 not in cache+ assert 3 in cachediff --git a/saleor/core/tests/test_editorjs.py b/saleor/core/utils/tests/test_editorjs.pysimilarity index 99%rename from saleor/core/tests/test_editorjs.pyrename to saleor/core/utils/tests/test_editorjs.pyindex 02bc14b174..ca4d96277e 100644--- a/saleor/core/tests/test_editorjs.py+++ b/saleor/core/utils/tests/test_editorjs.py@@ -4,7 +4,7 @@ from unittest import mockimport pytestfrom django.utils.html import strip_tags-from ..utils.editorjs import clean_editor_js+from ..editorjs import clean_editor_js@pytest.mark.parametrize(diff --git a/saleor/core/tests/test_serializer.py b/saleor/core/utils/tests/test_serializer.pysimilarity index 89%rename from saleor/core/tests/test_serializer.pyrename to saleor/core/utils/tests/test_serializer.pyindex a85abedbb8..bd3f90ef8f 100644--- a/saleor/core/tests/test_serializer.py+++ b/saleor/core/utils/tests/test_serializer.py@@ -2,8 +2,8 @@ import jsonfrom measurement.measures import Weight-from ..taxes import zero_money-from ..utils.json_serializer import CustomJsonEncoder+from ...taxes import zero_money+from ..json_serializer import CustomJsonEncoderdef test_custom_json_encoder_dumps_money_objects():diff --git a/saleor/core/tests/test_url.py b/saleor/core/utils/tests/test_url.pysimilarity index 92%rename from saleor/core/tests/test_url.pyrename to saleor/core/utils/tests/test_url.pyindex ad9016fc3b..6dd5e3e7ed 100644--- a/saleor/core/tests/test_url.py+++ b/saleor/core/utils/tests/test_url.py@@ -3,7 +3,7 @@ from urllib.parse import urlencodefrom django.conf import settings-from ..utils.url import get_default_storage_root_url, prepare_url+from ..url import get_default_storage_root_url, prepare_urldef test_prepare_url():diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 511a5ed5b3..47d123e519 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -1,8 +1,21 @@+from functools import partial+import graphqlfrom django.urls import reversefrom django.utils.functional import SimpleLazyObject-from graphql import GraphQLScalarType+from graphql import (+ GraphQLCachedBackend,+ GraphQLCoreBackend,+ GraphQLScalarType,+ GraphQLSchema,+ execute,+ parse,+ validate,+)+from graphql.backend.base import GraphQLDocument+from graphql.execution import ExecutionResult+from ..core.utils.cache import CacheDictfrom ..graphql.notifications.schema import ExternalNotificationMutationsfrom .account.schema import AccountMutations, AccountQueriesfrom .app.schema import AppMutations, AppQueries@@ -168,3 +181,35 @@ schema = build_federated_schema(directives=graphql.specified_directives+ [GraphQLDocDirective, GraphQLWebhookEventsInfoDirective],)+++def _fail(errors, **_kwargs) -> ExecutionResult:+ return ExecutionResult(errors=errors, invalid=True)+++class SaleorGraphQLBackend(GraphQLCoreBackend):+ def document_from_string(+ self,+ schema: GraphQLSchema,+ document_string: str, # type: ignore[override]+ ) -> GraphQLDocument:+ # validate eagerly so we can cache the result+ document_ast = parse(document_string)+ validation_errors = validate(schema, document_ast)+ if validation_errors:+ return GraphQLDocument(+ schema=schema,+ document_string=document_string,+ document_ast=document_ast,+ execute=partial(_fail, validation_errors),+ )++ return GraphQLDocument(+ schema=schema,+ document_string=document_string,+ document_ast=document_ast,+ execute=partial(execute, schema, document_ast, **self.execute_params),+ )+++backend = GraphQLCachedBackend(SaleorGraphQLBackend(), cache_map=CacheDict(1000))diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.pyindex a31e83be96..54e0323c50 100644--- a/saleor/graphql/core/fields.py+++ b/saleor/graphql/core/fields.py@@ -5,7 +5,6 @@ from typing import Optionalimport graphenefrom django.conf import settingsfrom graphene.relay import Connection, is_node-from graphql import GraphQLErrorfrom ...permission.utils import message_one_of_permissions_requiredfrom ..decorators import one_of_permissions_required@@ -164,4 +163,4 @@ class JSONString(graphene.JSONString):try:return graphene.JSONString.parse_literal(node)except JSONDecodeError:- raise GraphQLError(f"{str(node.value)[:20]}... is not a valid JSONString")+ return Nonediff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.pyindex 35cfd6c8ad..4de6a1ab75 100644--- a/saleor/graphql/core/scalars.py+++ b/saleor/graphql/core/scalars.py@@ -2,7 +2,6 @@ import decimalimport graphenefrom graphene.types.generic import GenericScalar-from graphql.error import GraphQLErrorfrom graphql.language import astfrom measurement.measures import Weight@@ -47,9 +46,7 @@ class PositiveDecimal(Decimal):def parse_value(value):value = super(PositiveDecimal, PositiveDecimal).parse_value(value)if value and value < 0:- raise GraphQLError(- f"Value cannot be lower than 0. Unsupported value: {value}"- )+ return Nonereturn value@@ -63,7 +60,7 @@ class JSON(GenericScalar):}elif isinstance(node, ast.ListValue):return [GenericScalar.parse_literal(value) for value in node.values]- raise GraphQLError("JSON scalar needs to receive a correct JSON structure.")+ return None@staticmethoddef parse_value(value):@@ -71,7 +68,7 @@ class JSON(GenericScalar):return valueif isinstance(value, list):return [GenericScalar.parse_value(v) for v in value]- raise GraphQLError("JSON scalar needs to receive a correct JSON structure.")+ return Noneclass WeightScalar(graphene.Scalar):@@ -81,8 +78,6 @@ class WeightScalar(graphene.Scalar):weight = Weight(**{value["unit"]: value["value"]})else:weight = WeightScalar.parse_decimal(value)- if weight is None:- raise GraphQLError(f"Unsupported value: {value}")return weight@staticmethod@@ -98,8 +93,6 @@ class WeightScalar(graphene.Scalar):weight = WeightScalar.parse_literal_object(node)else:weight = WeightScalar.parse_decimal(node.value)- if weight is None:- raise GraphQLError(f"Unsupported value: {node.value}")return weight@staticmethod@@ -121,7 +114,7 @@ class WeightScalar(graphene.Scalar):try:value = decimal.Decimal(field.value.value)except decimal.DecimalException:- raise GraphQLError(f"Unsupported value: {field.value.value}")+ return Noneif field.name.value == "unit":unit = field.value.valuereturn Weight(**{unit: value})@@ -136,15 +129,15 @@ class UUID(graphene.UUID):def parse_literal(node):try:return super(UUID, UUID).parse_literal(node)- except ValueError as e:- raise GraphQLError(str(e))+ except ValueError:+ return None@staticmethoddef parse_value(value):try:return super(UUID, UUID).parse_value(value)- except ValueError as e:- raise GraphQLError(str(e))+ except ValueError:+ return None# The custom Date scalar is needed as the currently used graphene 2 version is notdiff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.pyindex 50dead0732..fca7fd88b5 100644--- a/saleor/graphql/core/tests/test_view.py+++ b/saleor/graphql/core/tests/test_view.py@@ -141,7 +141,7 @@ def test_graphql_execution_exception(monkeypatch, api_client):def mocked_execute(*args, **kwargs):raise OSError("Spanish inquisition")- monkeypatch.setattr("graphql.backend.core.execute_and_validate", mocked_execute)+ monkeypatch.setattr("saleor.graphql.api.execute", mocked_execute)response = api_client.post_graphql("{ shop { name }}")assert response.status_code == 400content = get_graphql_content_from_response(response)diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.pyindex 2b2f3423a9..63ff93a10f 100644--- a/saleor/graphql/product/tests/mutations/test_product_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_create.py@@ -1427,7 +1427,7 @@ def test_product_create_with_invalid_json_description(staff_api_client):assert content["errors"]assert len(content["errors"]) == 1assert content["errors"][0]["extensions"]["exception"]["code"] == "GraphQLError"- assert "is not a valid JSONString" in content["errors"][0]["message"]+ assert 'Expected type "JSONString"' in content["errors"][0]["message"]@freeze_time("2020-03-18 12:00:00")diff --git a/saleor/graphql/tests/utils.py b/saleor/graphql/tests/utils.pyindex 57396378ff..7683748474 100644--- a/saleor/graphql/tests/utils.py+++ b/saleor/graphql/tests/utils.py@@ -30,9 +30,9 @@ def assert_no_permission(response):def assert_negative_positive_decimal_value(response):content = get_graphql_content_from_response(response)assert "errors" in content, content- assert "Value cannot be lower than 0." in content["errors"][0]["message"], content[- "errors"- ]+ assert (+ 'Expected type "PositiveDecimal"' in content["errors"][0]["message"]+ ), content["errors"]def assert_graphql_error_with_message(response, message):diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex d29ad9507b..4528fff96d 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -13,7 +13,7 @@ from django.db.backends.postgresql.base import DatabaseWrapperfrom django.http import HttpRequest, HttpResponseNotAllowed, JsonResponsefrom django.shortcuts import renderfrom django.views.generic import View-from graphql import GraphQLDocument, get_default_backend+from graphql import GraphQLBackend, GraphQLDocument, GraphQLSchemafrom graphql.error import GraphQLError, GraphQLSyntaxErrorfrom graphql.execution import ExecutionResultfrom jwt.exceptions import PyJWTError@@ -55,10 +55,11 @@ class GraphQLView(View):# - file upload (https://github.com/lmcgartland/graphene-file-upload)# - query batching- schema = None+ schema: GraphQLSchema = None # type: ignore[assignment]executor = Nonemiddleware = Noneroot_value = None+ backend: GraphQLBackend = None # type: ignore[assignment]HANDLED_EXCEPTIONS = (GraphQLError,@@ -69,15 +70,13 @@ class GraphQLView(View):def __init__(self,- schema=None,+ schema: GraphQLSchema,+ backend: GraphQLBackend,executor=None,middleware: Optional[list[str]] = None,root_value=None,- backend=None,):super().__init__()- if backend is None:- backend = get_default_backend()if middleware is None:middleware = settings.GRAPHQL_MIDDLEWAREif middleware:@@ -85,7 +84,7 @@ class GraphQLView(View):self.import_middleware(middleware_name)for middleware_name in middleware]- self.schema = self.schema or schema+ self.schema = schemaif middleware is not None:self.middleware = list(instantiate_middleware(middleware))self.executor = executordiff --git a/saleor/urls.py b/saleor/urls.pyindex 5ff57b4377..8cf6c64e51 100644--- a/saleor/urls.py+++ b/saleor/urls.py@@ -5,7 +5,7 @@ from django.urls import include, re_pathfrom django.views.decorators.csrf import csrf_exemptfrom .core.views import jwks-from .graphql.api import schema+from .graphql.api import backend, schemafrom .graphql.views import GraphQLViewfrom .plugins.views import (handle_global_plugin_webhook,@@ -16,7 +16,11 @@ from .product.views import digital_productfrom .thumbnail.views import handle_thumbnailurlpatterns = [- re_path(r"^graphql/$", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"),+ re_path(+ r"^graphql/$",+ csrf_exempt(GraphQLView.as_view(backend=backend, schema=schema)),+ name="api",+ ),re_path(r"^digital-download/(?P<token>[0-9A-Za-z_\-]+)/$",digital_product,