Skip to content

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

Add an LRU cache for GraphQL document parser and validator (#14843)

Patryk Zawadzkiec81e34dd0c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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
### Highlights
diff --git a/saleor/core/utils/cache.py b/saleor/core/utils/cache.py
new file mode 100644
index 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__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/core/utils/tests/test_cache.py b/saleor/core/utils/tests/test_cache.py
new file mode 100644
index 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 cache
diff --git a/saleor/core/tests/test_editorjs.py b/saleor/core/utils/tests/test_editorjs.py
similarity index 99%
rename from saleor/core/tests/test_editorjs.py
rename to saleor/core/utils/tests/test_editorjs.py
index 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 mock
import pytest
from 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.py
similarity index 89%
rename from saleor/core/tests/test_serializer.py
rename to saleor/core/utils/tests/test_serializer.py
index a85abedbb8..bd3f90ef8f 100644
--- a/saleor/core/tests/test_serializer.py
+++ b/saleor/core/utils/tests/test_serializer.py
@@ -2,8 +2,8 @@ import json
from measurement.measures import Weight
-from ..taxes import zero_money
-from ..utils.json_serializer import CustomJsonEncoder
+from ...taxes import zero_money
+from ..json_serializer import CustomJsonEncoder
def test_custom_json_encoder_dumps_money_objects():
diff --git a/saleor/core/tests/test_url.py b/saleor/core/utils/tests/test_url.py
similarity index 92%
rename from saleor/core/tests/test_url.py
rename to saleor/core/utils/tests/test_url.py
index 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 urlencode
from django.conf import settings
-from ..utils.url import get_default_storage_root_url, prepare_url
+from ..url import get_default_storage_root_url, prepare_url
def test_prepare_url():
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 511a5ed5b3..47d123e519 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -1,8 +1,21 @@
+from functools import partial
+
import graphql
from django.urls import reverse
from 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 CacheDict
from ..graphql.notifications.schema import ExternalNotificationMutations
from .account.schema import AccountMutations, AccountQueries
from .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.py
index a31e83be96..54e0323c50 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -5,7 +5,6 @@ from typing import Optional
import graphene
from django.conf import settings
from graphene.relay import Connection, is_node
-from graphql import GraphQLError
from ...permission.utils import message_one_of_permissions_required
from ..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 None
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index 35cfd6c8ad..4de6a1ab75 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -2,7 +2,6 @@ import decimal
import graphene
from graphene.types.generic import GenericScalar
-from graphql.error import GraphQLError
from graphql.language import ast
from 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 None
return 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
@staticmethod
def parse_value(value):
@@ -71,7 +68,7 @@ class JSON(GenericScalar):
return value
if isinstance(value, list):
return [GenericScalar.parse_value(v) for v in value]
- raise GraphQLError("JSON scalar needs to receive a correct JSON structure.")
+ return None
class 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 None
if field.name.value == "unit":
unit = field.value.value
return 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
@staticmethod
def 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 not
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index 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 == 400
content = 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.py
index 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"]) == 1
assert 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.py
index 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.py
index d29ad9507b..4528fff96d 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -13,7 +13,7 @@ from django.db.backends.postgresql.base import DatabaseWrapper
from django.http import HttpRequest, HttpResponseNotAllowed, JsonResponse
from django.shortcuts import render
from django.views.generic import View
-from graphql import GraphQLDocument, get_default_backend
+from graphql import GraphQLBackend, GraphQLDocument, GraphQLSchema
from graphql.error import GraphQLError, GraphQLSyntaxError
from graphql.execution import ExecutionResult
from 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 = None
middleware = None
root_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_MIDDLEWARE
if 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 = schema
if middleware is not None:
self.middleware = list(instantiate_middleware(middleware))
self.executor = executor
diff --git a/saleor/urls.py b/saleor/urls.py
index 5ff57b4377..8cf6c64e51 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -5,7 +5,7 @@ from django.urls import include, re_path
from django.views.decorators.csrf import csrf_exempt
from .core.views import jwks
-from .graphql.api import schema
+from .graphql.api import backend, schema
from .graphql.views import GraphQLView
from .plugins.views import (
handle_global_plugin_webhook,
@@ -16,7 +16,11 @@ from .product.views import digital_product
from .thumbnail.views import handle_thumbnail
urlpatterns = [
- 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,