Skip to content

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

Optimize queries to database when initializing PluginsManager (#14340)

Krzysztof Kwaśniak8d55fea1eb11
diff --git a/saleor/graphql/plugins/mutations.py b/saleor/graphql/plugins/mutations.py
index dab1a025bd..d450e2d0d3 100644
--- a/saleor/graphql/plugins/mutations.py
+++ b/saleor/graphql/plugins/mutations.py
@@ -99,7 +99,9 @@ class PluginUpdate(BaseMutation):
plugin_id = cleaned_data["plugin"].PLUGIN_ID
channel_slug = cleaned_data["channel_slug"]
input_data = cleaned_data["data"]
+
manager = get_plugin_manager_promise(info.context).get()
manager.save_plugin_configuration(plugin_id, channel_slug, input_data)
- manager = get_plugins_manager()
+
+ manager = get_plugins_manager(allow_replica=False)
return PluginUpdate(plugin=resolve_plugin(plugin_id, manager))
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 3a944c9589..414275d882 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -101,6 +101,14 @@ class PluginsManager(PaymentInterface):
global_plugins: List["BasePlugin"] = []
all_plugins: List["BasePlugin"] = []
+ @property
+ def database(self):
+ return (
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ if self._allow_replica
+ else settings.DATABASE_CONNECTION_DEFAULT_NAME
+ )
+
def _load_plugin(
self,
PluginClass: Type["BasePlugin"],
@@ -130,12 +138,15 @@ class PluginsManager(PaymentInterface):
def __init__(self, plugins: List[str], requestor_getter=None, allow_replica=True):
with opentracing.global_tracer().start_active_span("PluginsManager.__init__"):
+ self._allow_replica = allow_replica
self.all_plugins = []
self.global_plugins = []
self.plugins_per_channel = defaultdict(list)
- global_db_configs, channel_db_configs = self._get_db_plugin_configs()
- channels = Channel.objects.all()
+ channel_map = self._get_channel_map()
+ global_db_configs, channel_db_configs = self._get_db_plugin_configs(
+ channel_map
+ )
for plugin_path in plugins:
with opentracing.global_tracer().start_active_span(f"{plugin_path}"):
@@ -150,7 +161,7 @@ class PluginsManager(PaymentInterface):
self.global_plugins.append(plugin)
self.all_plugins.append(plugin)
else:
- for channel in channels:
+ for channel in channel_map.values():
channel_configs = channel_db_configs.get(channel, {})
plugin = self._load_plugin(
PluginClass,
@@ -162,26 +173,26 @@ class PluginsManager(PaymentInterface):
self.plugins_per_channel[channel.slug].append(plugin)
self.all_plugins.append(plugin)
- for channel in channels:
+ for channel in channel_map.values():
self.plugins_per_channel[channel.slug].extend(self.global_plugins)
- def _get_db_plugin_configs(self):
+ def _get_db_plugin_configs(self, channel_map):
with opentracing.global_tracer().start_active_span("_get_db_plugin_configs"):
- qs = (
- PluginConfiguration.objects.all()
- .using(settings.DATABASE_CONNECTION_REPLICA_NAME)
- .prefetch_related("channel")
- )
+ plugin_manager_configs = PluginConfiguration.objects.using(
+ self.database
+ ).all()
channel_configs: DefaultDict[Channel, Dict] = defaultdict(dict)
global_configs = {}
- for db_plugin_config in qs:
- channel = db_plugin_config.channel
+ for db_plugin_config in plugin_manager_configs.iterator():
+ channel = channel_map.get(db_plugin_config.channel_id)
if channel is None:
global_configs[db_plugin_config.identifier] = db_plugin_config
else:
+ db_plugin_config.channel = channel
channel_configs[channel][
db_plugin_config.identifier
] = db_plugin_config
+
return global_configs, channel_configs
def __run_method_on_plugins(
@@ -1879,7 +1890,9 @@ class PluginsManager(PaymentInterface):
):
if channel_slug:
plugins = self.get_plugins(channel_slug=channel_slug)
- channel = Channel.objects.filter(slug=channel_slug).first()
+ channel = (
+ Channel.objects.using(self.database).filter(slug=channel_slug).first()
+ )
if not channel:
return None
else:
@@ -1888,7 +1901,9 @@ class PluginsManager(PaymentInterface):
for plugin in plugins:
if plugin.PLUGIN_ID == plugin_id:
- plugin_configuration, _ = PluginConfiguration.objects.get_or_create(
+ plugin_configuration, _ = PluginConfiguration.objects.using(
+ self.database
+ ).get_or_create(
identifier=plugin_id,
channel=channel,
defaults={"configuration": plugin.configuration},
@@ -2091,6 +2106,12 @@ class PluginsManager(PaymentInterface):
only_active_plugins = [plugin for plugin in plugins if plugin.active]
return any([plugin.is_event_active(event) for plugin in only_active_plugins])
+ def _get_channel_map(self):
+ return {
+ channel.pk: channel
+ for channel in Channel.objects.using(self.database).all().iterator()
+ }
+
def get_plugins_manager(
requestor_getter: Optional[Callable[[], "Requestor"]] = None,
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index bff652585d..6fe1eb397b 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -5,6 +5,7 @@ from unittest import mock
import pytest
from django.http import HttpResponseNotFound, JsonResponse
+from django.test import override_settings
from mock import patch
from prices import Money, TaxedMoney
@@ -1516,3 +1517,43 @@ def test_payment_method_process_tokenization(
mocked_payment_method_process_tokenization.assert_called_once_with(
request_data, previous_value=previous_response
)
+
+
+ "allow_replica, expected_connection_name",
+ (
+ (True, "test replica"),
+ (False, "test default"),
+ ),
+)
+def test_plugin_manager_database(allow_replica, expected_connection_name):
+ # given
+ manager = PluginsManager(
+ ["saleor.plugins.tests.sample_plugins.PluginSample"],
+ allow_replica=allow_replica,
+ )
+
+ # when & then
+ with override_settings(
+ DATABASE_CONNECTION_REPLICA_NAME="test replica",
+ DATABASE_CONNECTION_DEFAULT_NAME="test default",
+ ):
+ assert manager.database == expected_connection_name
+
+
+def test_plugin_manager__get_channel_map(
+ channel_USD, channel_PLN, channel_JPY, other_channel_USD
+):
+ # given
+ manager = PluginsManager(["saleor.plugins.tests.sample_plugins.PluginSample"])
+
+ # when
+ channel_map = manager._get_channel_map()
+
+ # then
+ assert channel_map == {
+ channel_USD.pk: channel_USD,
+ channel_PLN.pk: channel_PLN,
+ channel_JPY.pk: channel_JPY,
+ other_channel_USD.pk: other_channel_USD,
+ }