Skip to content

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

Remove reference cycle in Asgiref Local (#17594)

Filip Owczarekffd08a22a8d4
diff --git a/saleor/graphql/core/tests/garbage_collection/test_asgiref.py b/saleor/graphql/core/tests/garbage_collection/test_asgiref.py
new file mode 100644
index 0000000000..8e9f3320ba
--- /dev/null
+++ b/saleor/graphql/core/tests/garbage_collection/test_asgiref.py
@@ -0,0 +1,39 @@
+import gc
+
+import pytest
+from asgiref.local import Local
+
+from .utils import (
+ clean_up_after_garbage_collection_test,
+ disable_gc_for_garbage_collection_test,
+)
+
+
+# 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_thread_critical_Local_remove_all_reference_cycles():
+ try:
+ # given
+ # Disable automatic garbage collection and set debugging flag.
+ disable_gc_for_garbage_collection_test()
+
+ # when
+ # Create thread critical Local object in sync context.
+ try:
+ getattr(Local(thread_critical=True), "missing")
+ except AttributeError:
+ pass
+ # 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 == []
+ # 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/patch_local.py b/saleor/patch_local.py
new file mode 100644
index 0000000000..71122acdf3
--- /dev/null
+++ b/saleor/patch_local.py
@@ -0,0 +1,53 @@
+import asyncio
+import contextlib
+
+from asgiref.local import Local, _CVar
+
+
+def _Local_lock_storage(self):
+ # Thread safe access to storage
+ if self._thread_critical:
+ is_async = True
+ try:
+ # this is a test for are we in a async or sync
+ # thread - will raise RuntimeError if there is
+ # no current loop
+ asyncio.get_running_loop()
+ except RuntimeError:
+ is_async = False
+ if not is_async:
+ # We are in a sync thread, the storage is
+ # just the plain thread local (i.e, "global within
+ # this thread" - it doesn't matter where you are
+ # in a call stack you see the same storage)
+ yield self._storage
+ else:
+ # We are in an async thread - storage is still
+ # local to this thread, but additionally should
+ # behave like a context var (is only visible with
+ # the same async call stack)
+
+ # Ensure context exists in the current thread
+ if not hasattr(self._storage, "cvar"):
+ self._storage.cvar = _CVar()
+
+ # self._storage is a thread local, so the members
+ # can't be accessed in another thread (we don't
+ # need any locks)
+ yield self._storage.cvar
+ else:
+ # Lock for thread_critical=False as other threads
+ # can access the exact same storage object
+ with self._thread_lock:
+ yield self._storage
+
+
+def patch_local():
+ """Patch `_lock_storage in `Local` to avoid memory leaks.
+
+ Those changes will remove the circular references inside `Local` class,
+ allowing memory to be freed immediately, without the need of a deep garbage collection cycle.
+ Issue: https://github.com/django/asgiref/issues/487
+ """
+ Local._lock_storage = _Local_lock_storage # type: ignore[method-assign]
diff --git a/saleor/settings.py b/saleor/settings.py
index 96699d7556..0e59dfa055 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -35,6 +35,7 @@ from .core.schedules import initiated_promotion_webhook_schedule
from .graphql.executor import patch_executor
from .graphql.promise import patch_promise
from .patch_gzip import patch_gzip
+from .patch_local import patch_local
django_stubs_ext.monkeypatch()
@@ -1075,3 +1076,7 @@ patch_gzip()
# `BaseDatabaseValidation` and `DatabaseErrorWrapper` 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_db()
+
+# Patch `Local` 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_local()