Skip to content

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

Remove reference cycles in Promise (#17564)

Filip Owczarekc38cfceaab35
diff --git a/saleor/graphql/core/tests/garbage_collection/test_promise.py b/saleor/graphql/core/tests/garbage_collection/test_promise.py
new file mode 100644
index 0000000000..ca1a194b7b
--- /dev/null
+++ b/saleor/graphql/core/tests/garbage_collection/test_promise.py
@@ -0,0 +1,67 @@
+import gc
+import json
+
+import pytest
+from django.core.serializers.json import DjangoJSONEncoder
+
+from ....api import backend, schema
+from ....tests.utils import get_graphql_content
+from ....views import GraphQLView
+from .utils import (
+ clean_up_after_garbage_collection_test,
+ disable_gc_for_garbage_collection_test,
+)
+
+PRODUCTS_QUERY = """
+query FetchProducts($first: Int, $channel: String!){
+ products(first: $first, channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ defaultVariant {
+ name
+ }
+ }
+ }
+ }
+}
+"""
+
+
+# Group all tests that require garbage collection so that they do not run concurrently.
+# This is necessary to ensure that tests don't interfere with each other.
+# Without grouping we could receive false positive results.
[email protected]_group(name="garbage_collection")
+def test_query_remove_all_memory_cycles_in_promise(rf, product, channel_USD):
+ try:
+ # given
+ # Disable automatic garbage collection and set debugging flag.
+ disable_gc_for_garbage_collection_test()
+ # Prepare request body with GraphQL query and variables.
+ variables = {"channel": channel_USD.slug, "first": 1}
+ data = {"query": PRODUCTS_QUERY, "variables": variables}
+ data = json.dumps(data, cls=DjangoJSONEncoder)
+
+ # when
+ # Execute the query.
+ content = get_graphql_content(
+ GraphQLView(backend=backend, schema=schema).handle_query(
+ rf.post(path="/graphql/", data=data, content_type="application/json")
+ ),
+ ignore_errors=True,
+ )
+ # Enforce garbage collection to populate the garbage list for inspection.
+ gc.collect()
+
+ # then
+ # Ensure that the garbage list is empty. The garbage list is only valid
+ # until the next collection cycle so we can only make assertions about it
+ # before re-enabling automatic collection.
+ assert gc.garbage == []
+ # Ensure that the query returned the expected data.
+ assert content["data"]["products"]["edges"][0]["node"]["name"] == product.name
+ # Restore garbage collection settings to their original state. This should always be run to avoid interfering
+ # with other tests to ensure that code should be executed in the `finally' block.
+ finally:
+ clean_up_after_garbage_collection_test()
diff --git a/saleor/graphql/promise.py b/saleor/graphql/promise.py
new file mode 100644
index 0000000000..95838cd213
--- /dev/null
+++ b/saleor/graphql/promise.py
@@ -0,0 +1,22 @@
+from promise import Promise
+
+
+def __del_promise__(self: Promise) -> None:
+ # Clean up references to break up any reference cycles
+ self._handlers = None # type: ignore[assignment]
+ self._fulfillment_handler0 = None
+ self._rejection_handler0 = None
+ self._promise0 = None
+ self._future = None # type: ignore[assignment]
+ self._event_instance = None # type: ignore[attr-defined]
+ self._traceback = None
+
+
+def patch_promise():
+ """Patch Promise.__del__ to avoid memory leaks.
+
+ Promise.__del__ will remove all references that could result in reference cycles,
+ allowing memory to be freed immediately, without the need of a deep garbage collection cycle.
+ Issue: https://github.com/syrusakbary/promise/issues/106
+ """
+ Promise.__del__ = __del_promise__ # type: ignore[attr-defined]
diff --git a/saleor/settings.py b/saleor/settings.py
index 3205ecc425..9d44b0c09c 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -32,6 +32,7 @@ from .account.i18n_rules_override import i18n_rules_override
from .core.languages import LANGUAGES as CORE_LANGUAGES
from .core.schedules import initiated_promotion_webhook_schedule
from .graphql.executor import patch_executor
+from .graphql.promise import patch_promise
django_stubs_ext.monkeypatch()
@@ -1058,3 +1059,8 @@ BREAKER_BOARD_DRY_RUN_SYNC_EVENTS = get_list(
# Library `google-i18n-address` use `AddressValidationMetadata` form Google to provide address validation rules.
# Patch `i18n` module to allows to override the default address rules.
i18n_rules_override()
+
+
+# Patch Promise to remove all references that could result in reference cycles, allowing memory to be freed
+# immediately, without the need of a deep garbage collection cycle.
+patch_promise()