Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Batch entites by type in federated queries (#8273)
Rafał Pitońb1cb79cf1547
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7a2b50867..7bd5428dfd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ All notable, unreleased changes to this project will be documented in this file.- Extend `accountRegister` mutation to consume first & last name - #8184 by @piotrgrundas- Introduce sales / vouchers per product variant - #8064 by @kuchichan- Introduce sales webhooks - #8157 @kuchichan+- Batch loads in queries for Apollo Federation - #8273 by @rafalp# 3.0.0 [Unreleased]diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.pyindex 3de9d3462d..a19095f2d4 100644--- a/saleor/graphql/account/resolvers.py+++ b/saleor/graphql/account/resolvers.py@@ -2,6 +2,7 @@ from itertools import chainfrom typing import Optionalfrom django.contrib.auth import models as auth_models+from django.db.models import Qfrom i18naddress import get_validation_rulesfrom ...account import models@@ -68,6 +69,37 @@ def resolve_user(info, id=None, email=None):return PermissionDenied()+@traced_resolver+def resolve_users(info, ids=None, emails=None):+ requester = get_user_or_app_from_context(info.context)+ if not requester:+ return models.User.objects.none()++ if requester.has_perms(+ [AccountPermissions.MANAGE_STAFF, AccountPermissions.MANAGE_USERS]+ ):+ qs = models.User.objects+ elif requester.has_perm(AccountPermissions.MANAGE_STAFF):+ qs = models.User.objects.staff()+ elif requester.has_perm(AccountPermissions.MANAGE_USERS):+ qs = models.User.objects.customers()+ elif requester.id:+ # If user has no access to all users, we can only return themselves, but+ # only if they are authenticated and one of requested users+ qs = models.User.objects.filter(id=requester.id)+ else:+ qs = models.User.objects.none()++ if ids:+ ids = {from_global_id_or_error(id, User, raise_error=True)[1] for id in ids}++ if ids and emails:+ return qs.filter(Q(id__in=ids) | Q(email__in=emails))+ elif ids:+ return qs.filter(id__in=ids)+ return qs.filter(email__in=emails)++@traced_resolverdef resolve_address_validation_rules(info,@@ -165,6 +197,20 @@ def resolve_address(info, id):raise PermissionDenied()+def resolve_addresses(info, ids):+ user = info.context.user+ app = info.context.app+ ids = [+ from_global_id_or_error(address_id, Address, raise_error=True)[1]+ for address_id in ids+ ]+ if app and app.has_perm(AccountPermissions.MANAGE_USERS):+ return models.Address.objects.filter(id__in=ids)+ if user and not user.is_anonymous:+ return user.addresses.filter(id__in=ids)+ return models.Address.objects.none()++def resolve_permissions(root: models.User):permissions = get_user_permissions(root)permissions = permissions.order_by("codename")diff --git a/saleor/graphql/account/tests/benchmark/test_account.py b/saleor/graphql/account/tests/benchmark/test_account.pyindex b9c6964608..34d5b71da9 100644--- a/saleor/graphql/account/tests/benchmark/test_account.py+++ b/saleor/graphql/account/tests/benchmark/test_account.py@@ -358,3 +358,151 @@ def test_customers_query(staff_api_client.user.user_permissions.set([permission_manage_users])content = get_graphql_content(staff_api_client.post_graphql(CUSTOMERS_QUERY))assert content["data"]["customers"] is not None++[email protected]_queries(autouse=False)+def test_users_for_federation_query_count(+ customer_user,+ customer_user2,+ staff_api_client,+ permission_manage_staff,+ permission_manage_users,+ django_assert_num_queries,+ count_queries,+):+ query = """+ query GetUserInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on User {+ id+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "User",+ "id": graphene.Node.to_global_id("User", customer_user.pk),+ },+ {+ "__typename": "User",+ "email": customer_user.email,+ },+ ],+ }++ with django_assert_num_queries(4):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_staff, permission_manage_users],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 2++ variables = {+ "representations": [+ {+ "__typename": "User",+ "id": graphene.Node.to_global_id("User", customer_user.pk),+ },+ {+ "__typename": "User",+ "id": graphene.Node.to_global_id("User", customer_user2.pk),+ },+ {+ "__typename": "User",+ "email": customer_user.email,+ },+ {+ "__typename": "User",+ "email": customer_user2.email,+ },+ ],+ }++ with django_assert_num_queries(4):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_staff, permission_manage_users],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 4++[email protected]_queries(autouse=False)+def test_addresses_for_federation_query_count(+ address,+ customer_user,+ customer_user2,+ staff_api_client,+ permission_manage_users,+ django_assert_num_queries,+ count_queries,+):+ address2 = address.get_copy()+ customer_user.addresses.add(address)+ customer_user2.addresses.add(address2)++ query = """+ query GetAddressInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Address {+ id+ city+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "Address",+ "id": graphene.Node.to_global_id("Address", address.pk),+ },+ ],+ }++ with django_assert_num_queries(3):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_users],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "Address",+ "id": graphene.Node.to_global_id("Address", address.pk),+ },+ {+ "__typename": "Address",+ "id": graphene.Node.to_global_id("Address", address2.pk),+ },+ ],+ }++ with django_assert_num_queries(3):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_users],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 2diff --git a/saleor/graphql/account/tests/benchmark/test_permission_group.py b/saleor/graphql/account/tests/benchmark/test_permission_group.pyindex 2e2768e2ce..f49246bf69 100644--- a/saleor/graphql/account/tests/benchmark/test_permission_group.py+++ b/saleor/graphql/account/tests/benchmark/test_permission_group.py@@ -308,3 +308,62 @@ def test_permission_group_query(content = get_graphql_content(response)data = content["data"]["permissionGroup"]assert data++[email protected]_queries(autouse=False)+def test_groups_for_federation_query_count(+ address,+ customer_user,+ customer_user2,+ api_client,+ django_assert_num_queries,+ count_queries,+):+ groups = Group.objects.bulk_create(+ [+ Group(name="group 1"),+ Group(name="group 2"),+ Group(name="group 3"),+ ]+ )++ query = """+ query GetGroupInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Group {+ id+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": graphene.Node.to_global_id("Group", groups[0].pk),+ },+ ],+ }++ with django_assert_num_queries(2):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": graphene.Node.to_global_id("Group", group.pk),+ }+ for group in groups+ ],+ }++ with django_assert_num_queries(2):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.pyindex ef99aa0a4f..f5bf2b7601 100644--- a/saleor/graphql/account/tests/test_account.py+++ b/saleor/graphql/account/tests/test_account.py@@ -5434,3 +5434,125 @@ def test_unauthenticated_query_address_federation(api_client, address):response = api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)content = get_graphql_content(response)assert content["data"]["_entities"] == [None]+++GROUP_FEDERATION_QUERY = """+ query GetGroupInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Group {+ id+ name+ }+ }+ }+"""+++def test_staff_query_group_federation(staff_api_client, permission_manage_staff):+ group = Group.objects.create(name="empty group")+ group_id = graphene.Node.to_global_id("Group", group.pk)+ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": group_id,+ },+ ],+ }++ response = staff_api_client.post_graphql(+ GROUP_FEDERATION_QUERY,+ variables,+ permissions=[permission_manage_staff],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [+ {+ "__typename": "Group",+ "id": group_id,+ "name": group.name,+ }+ ]+++def test_app_query_group_federation(app_api_client, permission_manage_staff):+ group = Group.objects.create(name="empty group")+ group_id = graphene.Node.to_global_id("Group", group.pk)+ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": group_id,+ },+ ],+ }++ response = app_api_client.post_graphql(+ GROUP_FEDERATION_QUERY,+ variables,+ permissions=[permission_manage_staff],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [+ {+ "__typename": "Group",+ "id": group_id,+ "name": group.name,+ }+ ]+++def test_app_no_permission_query_group_federation(app_api_client):+ group = Group.objects.create(name="empty group")+ group_id = graphene.Node.to_global_id("Group", group.pk)+ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": group_id,+ },+ ],+ }++ response = app_api_client.post_graphql(GROUP_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]+++def test_client_query_group_federation(user_api_client):+ group = Group.objects.create(name="empty group")++ group_id = graphene.Node.to_global_id("Group", group.pk)+ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": group_id,+ },+ ],+ }++ response = user_api_client.post_graphql(GROUP_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]+++def test_unauthenticated_query_group_federation(api_client):+ group = Group.objects.create(name="empty group")++ group_id = graphene.Node.to_global_id("Group", group.pk)+ variables = {+ "representations": [+ {+ "__typename": "Group",+ "id": group_id,+ },+ ],+ }++ response = api_client.post_graphql(GROUP_FEDERATION_QUERY, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.pyindex 2bb8bf5373..9e8b1f8653 100644--- a/saleor/graphql/account/types.py+++ b/saleor/graphql/account/types.py@@ -1,3 +1,5 @@+from typing import List+import graphenefrom django.contrib.auth import get_user_modelfrom django.contrib.auth import models as auth_models@@ -18,6 +20,7 @@ from ..checkout.types import Checkoutfrom ..core.connection import CountableDjangoObjectTypefrom ..core.descriptions import DEPRECATED_IN_3X_FIELDfrom ..core.enums import LanguageCodeEnum+from ..core.federation import resolve_federation_referencesfrom ..core.fields import PrefetchingConnectionFieldfrom ..core.scalars import UUIDfrom ..core.types import CountryDisplay, Image, Permission@@ -121,13 +124,19 @@ class Address(CountableDjangoObjectType):return False@staticmethod- def __resolve_reference(root: "Address", info, **_kwargs):- try:- from .resolvers import resolve_address+ def __resolve_references(roots: List["Address"], info, **_kwargs):+ from .resolvers import resolve_addresses- return resolve_address(info, root.id)- except PermissionDenied:- return None+ root_ids = [root.id for root in roots]+ addresses = {+ address.id: address for address in resolve_addresses(info, root_ids)+ }++ result = []+ for root_id in root_ids:+ _, root_id = from_global_id_or_error(root_id, Address)+ result.append(addresses.get(int(root_id)))+ return resultclass CustomerEvent(CountableDjangoObjectType):@@ -210,8 +219,8 @@ class UserPermission(Permission):return groups-@key("id")-@key("email")+@key(fields="id")+@key(fields="email")class User(CountableDjangoObjectType):addresses = graphene.List(Address, description="List of all user's addresses.")checkout = graphene.Field(@@ -378,32 +387,33 @@ class User(CountableDjangoObjectType):return resolve_wishlist_items_from_user(root)@staticmethod- def __resolve_reference(root: "User", info, **_kwargs):- User = get_user_model()+ def resolve_language_code(root, _info, **_kwargs):+ return LanguageCodeEnum[str_to_enum(root.language_code)]++ @staticmethod+ def __resolve_references(roots: List["User"], info, **_kwargs):+ from .resolvers import resolve_users- try:+ ids = set()+ emails = set()+ for root in roots:if root.id is not None:- user = graphene.Node.get_node_from_global_id(info, root.id)+ ids.add(root.id)else:- user = get_user_model().objects.get(email=root.email)- except User.DoesNotExist:- user = None-- if not user:- return None-- auth_user = info.context.user- manage_staff = auth_user.has_perm(AccountPermissions.MANAGE_STAFF)- manage_users = auth_user.has_perm(AccountPermissions.MANAGE_USERS)+ emails.add(root.email)- if user == auth_user or manage_staff or manage_users:- return user+ users = list(resolve_users(info, ids=ids, emails=emails))+ users_by_id = {user.id: user for user in users}+ users_by_email = {user.email: user for user in users}- return None-- @staticmethod- def resolve_language_code(root, _info, **_kwargs):- return LanguageCodeEnum[str_to_enum(root.language_code)]+ results = []+ for root in roots:+ if root.id is not None:+ _, user_id = from_global_id_or_error(root.id, User)+ results.append(users_by_id.get(int(user_id)))+ else:+ results.append(users_by_email.get(root.email))+ return resultsclass ChoiceValue(graphene.ObjectType):@@ -500,3 +510,15 @@ class Group(CountableDjangoObjectType):def resolve_user_can_manage(root: auth_models.Group, info):user = info.context.userreturn can_user_manage_group(user, root)++ @staticmethod+ def __resolve_references(roots: List["Group"], info, **_kwargs):+ from .resolvers import resolve_permission_groups++ requestor = get_user_or_app_from_context(info.context)+ if not requestor.has_perm(AccountPermissions.MANAGE_STAFF):+ qs = auth_models.Group.objects.none()+ else:+ qs = resolve_permission_groups(info)++ return resolve_federation_references(Group, roots, qs)diff --git a/saleor/graphql/app/tests/benchmarks/test_apps.py b/saleor/graphql/app/tests/benchmarks/test_apps.pynew file mode 100644index 0000000000..78862fa7e5--- /dev/null+++ b/saleor/graphql/app/tests/benchmarks/test_apps.py@@ -0,0 +1,73 @@+import graphene+import pytest++from .....app.models import App+from ....tests.utils import get_graphql_content++[email protected]_queries(autouse=False)+def test_apps_for_federation_query_count(+ staff_api_client,+ permission_manage_apps,+ django_assert_num_queries,+ count_queries,+):+ apps = App.objects.bulk_create(+ [+ App(name="app 1"),+ App(name="app 2"),+ App(name="app 3"),+ ]+ )++ query = """+ query GetAppInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on App {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "App",+ "id": graphene.Node.to_global_id("App", apps[0].pk),+ },+ ],+ }++ with django_assert_num_queries(4):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_apps],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "App",+ "id": graphene.Node.to_global_id("App", app.pk),+ }+ for app in apps+ ],+ }++ with django_assert_num_queries(4):+ response = staff_api_client.post_graphql(+ query,+ variables,+ permissions=[permission_manage_apps],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.pyindex 5f98970a72..b4273078d5 100644--- a/saleor/graphql/app/tests/queries/test_app.py+++ b/saleor/graphql/app/tests/queries/test_app.py@@ -270,36 +270,3 @@ def test_app_with_extensions_query(assigned_permissions = [p.codename for p in app_extension.permissions.all()]assigned_permissions = [{"code": p.upper()} for p in assigned_permissions]assert assigned_permissions in returned_permission_codes---def test_query_app_for_federation(api_client, app):- app_id = graphene.Node.to_global_id("App", app.pk)- variables = {- "representations": [- {- "__typename": "App",- "id": app_id,- },- ],- }- query = """- query GetAppInFederation($representations: [_Any]) {- _entities(representations: $representations) {- __typename- ... on App {- id- name- }- }- }- """-- response = api_client.post_graphql(query, variables)- content = get_graphql_content(response)- assert content["data"]["_entities"] == [- {- "__typename": "App",- "id": app_id,- "name": app.name,- }- ]diff --git a/saleor/graphql/app/tests/queries/test_apps.py b/saleor/graphql/app/tests/queries/test_apps.pyindex 6cd96fefcc..9576218583 100644--- a/saleor/graphql/app/tests/queries/test_apps.py+++ b/saleor/graphql/app/tests/queries/test_apps.py@@ -201,3 +201,59 @@ def test_apps_query_no_permission(permissions=[permission_manage_users, permission_manage_staff],)assert_no_permission(response)+++QUERY_APPS_FOR_FEDERATION = """+ query GetAppInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on App {+ id+ name+ }+ }+ }+"""+++def test_query_app_for_federation(staff_api_client, app, permission_manage_apps):+ app_id = graphene.Node.to_global_id("App", app.pk)+ variables = {+ "representations": [+ {+ "__typename": "App",+ "id": app_id,+ },+ ],+ }++ response = staff_api_client.post_graphql(+ QUERY_APPS_FOR_FEDERATION,+ variables,+ permissions=[permission_manage_apps],+ check_no_permissions=False,+ )+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [+ {+ "__typename": "App",+ "id": app_id,+ "name": app.name,+ }+ ]+++def test_query_app_for_federation_without_permission(api_client, app):+ app_id = graphene.Node.to_global_id("App", app.pk)+ variables = {+ "representations": [+ {+ "__typename": "App",+ "id": app_id,+ },+ ],+ }++ response = api_client.post_graphql(QUERY_APPS_FOR_FEDERATION, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [None]diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex 0e195a082b..eaf22d58a4 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -1,3 +1,5 @@+from typing import List+import graphenefrom graphene_federation import key@@ -6,6 +8,7 @@ from ...core.exceptions import PermissionDeniedfrom ...core.permissions import AppPermissionfrom ..core.connection import CountableDjangoObjectTypefrom ..core.descriptions import ADDED_IN_31+from ..core.federation import resolve_federation_referencesfrom ..core.types import Permissionfrom ..core.types.common import Jobfrom ..meta.types import ObjectWithMetadata@@ -190,10 +193,6 @@ class App(CountableDjangoObjectType):def resolve_tokens(root: models.App, _info, **_kwargs):return root.tokens.all() # type: ignore- @staticmethod- def __resolve_reference(root: "App", _info, **_kwargs):- return graphene.Node.get_node_from_global_id(_info, root.id)-@staticmethoddef resolve_webhooks(root: models.App, _info):return root.webhooks.all()@@ -206,6 +205,18 @@ class App(CountableDjangoObjectType):def resolve_extensions(root: models.App, info):return AppExtensionByAppIdLoader(info.context).load(root.id)+ @staticmethod+ def __resolve_references(roots: List["App"], info, **_kwargs):+ from .resolvers import resolve_apps++ requestor = get_user_or_app_from_context(info.context)+ if not requestor.has_perm(AppPermission.MANAGE_APPS):+ qs = models.App.objects.none()+ else:+ qs = resolve_apps(info)++ return resolve_federation_references(App, roots, qs)+class AppInstallation(CountableDjangoObjectType):class Meta:diff --git a/saleor/graphql/core/federation.py b/saleor/graphql/core/federation.pyindex fded59b998..74127edc50 100644--- a/saleor/graphql/core/federation.py+++ b/saleor/graphql/core/federation.py@@ -1,14 +1,68 @@+from collections import defaultdict++from django.conf import settings+from graphene.utils.str_converters import to_snake_casefrom graphene_federation import build_schema+from graphene_federation.entity import custom_entities+from graphql import GraphQLErrorfrom ..channel import ChannelContext+from .utils import from_global_id_or_errordef build_federated_schema(query=None, mutation=None, **kwargs):schema = build_schema(query, mutation, **kwargs)+ set_entity_resolver(schema)set_entity_type_resolver(schema)return schema+def set_entity_resolver(schema):+ """Set type resolver aware of ChannelContext on _Entity union."""+ entity = schema.get_type("Query")+ entity.fields["_entities"].resolver = resolve_entities+++def resolve_entities(parent, info, representations):+ max_representations = settings.FEDERATED_QUERY_MAX_ENTITIES+ if max_representations and len(representations) > max_representations:+ representations_count = len(representations)+ raise GraphQLError(+ f"Federated query exceeded entity limit: {representations_count} "+ f"items requested over {max_representations}."+ )++ resolvers = {}+ for representation in representations:+ if representation["__typename"] not in resolvers:+ try:+ model = custom_entities[representation["__typename"]]+ resolvers[representation["__typename"]] = getattr(+ model, "_%s__resolve_references" % representation["__typename"]+ )+ except AttributeError:+ pass++ batches = defaultdict(list)+ for representation in representations:+ model = custom_entities[representation["__typename"]]+ model_arguments = representation.copy()+ typename = model_arguments.pop("__typename")+ model_arguments = {to_snake_case(k): v for k, v in model_arguments.items()}+ model_instance = model(**model_arguments)+ batches[typename].append(model_instance)++ entities = []+ for typename, batch in batches.items():+ if typename not in resolvers:+ continue++ resolver = resolvers[typename]+ entities.extend(resolver(batch, info))++ return entities++def set_entity_type_resolver(schema):"""Set type resolver aware of ChannelContext on _Entity union."""entity = schema.get_type("_Entity")@@ -21,3 +75,12 @@ def set_entity_type_resolver(schema):return org_type_resolver(instance, info)entity.resolve_type = resolve_entity_type+++def resolve_federation_references(graphql_type, roots, queryset):+ ids = [+ from_global_id_or_error(root.id, graphql_type, raise_error=True)[1]+ for root in roots+ ]+ objects = {str(obj.id): obj for obj in queryset.filter(id__in=ids)}+ return [objects.get(root_id) for root_id in ids]diff --git a/saleor/graphql/page/tests/benchmark/test_page_type.py b/saleor/graphql/page/tests/benchmark/test_page_type.pyindex ef01879618..e92cb7ccce 100644--- a/saleor/graphql/page/tests/benchmark/test_page_type.py+++ b/saleor/graphql/page/tests/benchmark/test_page_type.py@@ -1,6 +1,7 @@import grapheneimport pytest+from .....page.models import PageTypefrom ....tests.utils import get_graphql_content@@ -143,3 +144,60 @@ def test_query_page_types(content = get_graphql_content(response)data = content["data"]["pageTypes"]assert data++[email protected]_queries(autouse=False)+def test_query_page_types_for_federation(+ api_client,+ django_assert_num_queries,+ count_queries,+):+ page_types = PageType.objects.bulk_create(+ [+ PageType(name="type 1", slug="type-1"),+ PageType(name="type 2", slug="type-2"),+ PageType(name="type 3", slug="type-3"),+ ]+ )++ query = """+ query GetAppInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on PageType {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "PageType",+ "id": graphene.Node.to_global_id("PageType", page_types[0].pk),+ },+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "PageType",+ "id": graphene.Node.to_global_id("PageType", page_type.pk),+ }+ for page_type in page_types+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3diff --git a/saleor/graphql/page/tests/test_page_type_query.py b/saleor/graphql/page/tests/test_page_type_query.pyindex 8cf9f29ceb..146b9e39d2 100644--- a/saleor/graphql/page/tests/test_page_type_query.py+++ b/saleor/graphql/page/tests/test_page_type_query.py@@ -199,3 +199,36 @@ def test_page_type_query_no_pages(available_attributes = page_type_data["availableAttributes"]["edges"]assert len(available_attributes) == 1assert available_attributes[0]["node"]["slug"] == author_page_attribute.slug+++def test_page_types_for_federation_query_count(api_client, page_type):+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)+ variables = {+ "representations": [+ {+ "__typename": "PageType",+ "id": page_type_id,+ },+ ],+ }+ query = """+ query GetPageTypeInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on PageType {+ id+ name+ }+ }+ }+ """++ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert content["data"]["_entities"] == [+ {+ "__typename": "PageType",+ "id": page_type_id,+ "name": page_type.name,+ }+ ]diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.pyindex 57c68fd0cf..28a692a547 100644--- a/saleor/graphql/page/types.py+++ b/saleor/graphql/page/types.py@@ -1,3 +1,5 @@+from typing import List+import graphenefrom graphene_federation import key@@ -8,6 +10,7 @@ from ..attribute.filters import AttributeFilterInputfrom ..attribute.types import Attribute, SelectedAttributefrom ..core.connection import CountableDjangoObjectTypefrom ..core.descriptions import DEPRECATED_IN_3X_FIELD+from ..core.federation import resolve_federation_referencesfrom ..core.fields import FilterInputConnectionFieldfrom ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadata@@ -108,3 +111,7 @@ class PageType(CountableDjangoObjectType):.load(root.pk).then(lambda pages: bool(pages)))++ @staticmethod+ def __resolve_references(roots: List["PageType"], info, **_kwargs):+ return resolve_federation_references(PageType, roots, models.PageType.objects)diff --git a/saleor/graphql/product/tests/benchmark/test_category.py b/saleor/graphql/product/tests/benchmark/test_category.pyindex 1d188a1a22..5198b2ffd5 100644--- a/saleor/graphql/product/tests/benchmark/test_category.py+++ b/saleor/graphql/product/tests/benchmark/test_category.py@@ -1,6 +1,7 @@import grapheneimport pytest+from .....product.models import Categoryfrom ....tests.utils import get_graphql_content@@ -194,3 +195,66 @@ def test_category_delete(content = get_graphql_content(response)errors = content["data"]["categoryDelete"]["errors"]assert not errors++[email protected]_queries(autouse=False)+def test_categories_for_federation_query_count(+ api_client,+ django_assert_num_queries,+ count_queries,+):+ categories = Category.objects.bulk_create(+ [+ Category(+ name="category 1", slug="category-1", lft=0, rght=1, tree_id=0, level=0+ ),+ Category(+ name="category 2", slug="category-2", lft=2, rght=3, tree_id=0, level=0+ ),+ Category(+ name="category 3", slug="category-3", lft=4, rght=5, tree_id=0, level=0+ ),+ ]+ )++ query = """+ query GetCategoryInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Category {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "Category",+ "id": graphene.Node.to_global_id("Category", categories[0].pk),+ },+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "Category",+ "id": graphene.Node.to_global_id("Category", category.pk),+ }+ for category in categories+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3diff --git a/saleor/graphql/product/tests/benchmark/test_collection.py b/saleor/graphql/product/tests/benchmark/test_collection.pyindex 37158493e5..48674bf399 100644--- a/saleor/graphql/product/tests/benchmark/test_collection.py+++ b/saleor/graphql/product/tests/benchmark/test_collection.py@@ -1,6 +1,7 @@import grapheneimport pytest+from .....product.models import Collectionfrom ....tests.utils import get_graphql_content@@ -379,3 +380,69 @@ def test_collection_bulk_delete(content = get_graphql_content(response)assert not content["data"]["collectionBulkDelete"]["errors"]++[email protected]_queries(autouse=False)+def test_collections_for_federation_query_count(+ api_client,+ django_assert_num_queries,+ count_queries,+):+ collections = Collection.objects.bulk_create(+ [+ Collection(+ name="collection 1",+ slug="collection-1",+ ),+ Collection(+ name="collection 2",+ slug="collection-2",+ ),+ Collection(+ name="collection 3",+ slug="collection-3",+ ),+ ]+ )++ query = """+ query GetCollectionInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Collection {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "Collection",+ "id": graphene.Node.to_global_id("Collection", collections[0].pk),+ },+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "Collection",+ "id": graphene.Node.to_global_id("Collection", collection.pk),+ }+ for collection in collections+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.pyindex 90fc480566..708f24fffb 100644--- a/saleor/graphql/product/tests/benchmark/test_product.py+++ b/saleor/graphql/product/tests/benchmark/test_product.py@@ -7,7 +7,7 @@ from graphene import Nodefrom .....attribute.utils import associate_attribute_values_to_instancefrom .....core.taxes import TaxTypefrom .....plugins.manager import PluginsManager-from .....product.models import ProductTranslation+from .....product.models import ProductMedia, ProductTranslationfrom ....tests.utils import get_graphql_content@@ -683,3 +683,179 @@ def test_product_translations(api_client, product_list, channel_USD, count_querivariables = {"channel": channel_USD.slug}get_graphql_content(api_client.post_graphql(query, variables))++[email protected]_queries(autouse=False)+def test_products_for_federation_query_count(+ api_client,+ product,+ shippable_gift_card_product,+ channel_USD,+ django_assert_num_queries,+ count_queries,+):+ query = """+ query GetProductInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on Product {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "Product",+ "id": graphene.Node.to_global_id("Product", product.pk),+ "channel": channel_USD.slug,+ },+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "Product",+ "id": graphene.Node.to_global_id("Product", product.pk),+ "channel": channel_USD.slug,+ },+ {+ "__typename": "Product",+ "id": graphene.Node.to_global_id(+ "Product", shippable_gift_card_product.pk+ ),+ "channel": channel_USD.slug,+ },+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 2++[email protected]_queries(autouse=False)+def test_products_media_for_federation_query_count(+ api_client,+ product,+ image,+ media_root,+ django_assert_num_queries,+ count_queries,+):+ medias = ProductMedia.objects.bulk_create(+ [+ ProductMedia(product=product, image=image),+ ProductMedia(product=product, image=image),+ ProductMedia(product=product, image=image),+ ]+ )++ query = """+ query GetProductMediaInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on ProductMedia {+ id+ url+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "ProductMedia",+ "id": graphene.Node.to_global_id("ProductMedia", medias[0].pk),+ },+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "ProductMedia",+ "id": graphene.Node.to_global_id("ProductMedia", media.pk),+ }+ for media in medias+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 3++[email protected]_queries(autouse=False)+def test_products_types_for_federation_query_count(+ api_client,+ product_type,+ product_type_without_variant,+ django_assert_num_queries,+ count_queries,+):+ query = """+ query GetProductTypeInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on ProductType {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "ProductType",+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),+ },+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "ProductType",+ "id": graphene.Node.to_global_id("ProductType", product_type.pk),+ },+ {+ "__typename": "ProductType",+ "id": graphene.Node.to_global_id(+ "ProductType", product_type_without_variant.pk+ ),+ },+ ],+ }++ with django_assert_num_queries(1):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 2diff --git a/saleor/graphql/product/tests/benchmark/test_variant.py b/saleor/graphql/product/tests/benchmark/test_variant.pyindex cb46885800..213fa6eaf1 100644--- a/saleor/graphql/product/tests/benchmark/test_variant.py+++ b/saleor/graphql/product/tests/benchmark/test_variant.py@@ -349,3 +349,58 @@ def test_update_product_variant())["data"]["productVariantUpdate"]assert not data["errors"]++[email protected]_queries(autouse=False)+def test_products_variants_for_federation_query_count(+ api_client,+ product_variant_list,+ channel_USD,+ django_assert_num_queries,+ count_queries,+):+ query = """+ query GetProductVariantInFederation($representations: [_Any]) {+ _entities(representations: $representations) {+ __typename+ ... on ProductVariant {+ id+ name+ }+ }+ }+ """++ variables = {+ "representations": [+ {+ "__typename": "ProductVariant",+ "id": graphene.Node.to_global_id(+ "ProductVariant", product_variant_list[0].pk+ ),+ "channel": channel_USD.slug,+ },+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 1++ variables = {+ "representations": [+ {+ "__typename": "ProductVariant",+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ }+ for variant in product_variant_list+ ],+ }++ with django_assert_num_queries(3):+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ assert len(content["data"]["_entities"]) == 4diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex bef6757083..d47d270c6d 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1,5 +1,6 @@+from collections import defaultdictfrom dataclasses import asdict-from typing import Optional+from typing import List, Optionalimport graphenefrom django.conf import settings@@ -41,6 +42,7 @@ from ...core.descriptions import (DEPRECATED_IN_3X_INPUT,)from ...core.enums import ReportingPeriod+from ...core.federation import resolve_federation_referencesfrom ...core.fields import (ChannelContextFilterConnectionField,FilterInputConnectionField,@@ -103,11 +105,7 @@ from ..dataloaders import ()from ..enums import ProductTypeKindEnum, VariantAttributeScopefrom ..filters import ProductFilterInput-from ..resolvers import (- resolve_collection_by_id,- resolve_product_by_id,- resolve_variant_by_id,-)+from ..resolvers import resolve_product_variants, resolve_productsfrom ..sorters import ProductOrderfrom .channels import (CollectionChannelListing,@@ -564,24 +562,6 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):def resolve_images(root: ChannelContext[models.ProductVariant], info, *_args):return ImagesByProductVariantIdLoader(info.context).load(root.node.id)- @staticmethod- def __resolve_reference(root: "ProductVariant", info, **_kwargs):- requestor = get_user_or_app_from_context(info.context)- has_required_permissions = has_one_of_permissions(- requestor, ALL_PRODUCTS_PERMISSIONS- )- _, id = from_global_id_or_error(root.id, ProductVariant)- variant = resolve_variant_by_id(- info,- id,- channel_slug=root.channel,- requestor=requestor,- requestor_has_access_to_all=has_required_permissions,- )- return (- ChannelContext(node=variant, channel_slug=root.channel) if variant else None- )-@staticmethoddef resolve_weight(root: ChannelContext[models.ProductVariant], _info, **_kwargs):return convert_weight_to_default_weight_unit(root.node.weight)@@ -612,6 +592,36 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return variant_channel_listings.then(calculate_global_sold_units)+ @staticmethod+ def __resolve_references(roots: List["ProductVariant"], info, **_kwargs):+ requestor = get_user_or_app_from_context(info.context)+ requestor_has_access_to_all = has_one_of_permissions(+ requestor, ALL_PRODUCTS_PERMISSIONS+ )++ channels = defaultdict(set)+ roots_ids = []+ for root in roots:+ roots_ids.append(f"{root.channel}_{root.id}")+ channels[root.channel].add(root.id)++ variants = {}+ for channel, ids in channels.items():+ qs = resolve_product_variants(+ info,+ requestor_has_access_to_all,+ requestor,+ ids=ids,+ channel_slug=channel,+ ).qs+ for variant in qs:+ global_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variants[f"{channel}_{global_id}"] = ChannelContext(+ channel_slug=channel, node=variant+ )++ return [variants.get(root_id) for root_id in roots_ids]+@key(fields="id channel")class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@@ -1018,17 +1028,6 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):.then(return_collections))- @staticmethod- def __resolve_reference(root: "Product", info, **_kwargs):- requestor = get_user_or_app_from_context(info.context)- _, id = from_global_id_or_error(root.id, Product)- product = resolve_product_by_id(- info, id, channel_slug=root.channel, requestor=requestor- )- return (- ChannelContext(node=product, channel_slug=root.channel) if product else None- )-@staticmethoddef resolve_weight(root: ChannelContext[models.Product], _info, **_kwargs):return convert_weight_to_default_weight_unit(root.node.weight)@@ -1073,6 +1072,30 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):def resolve_product_type(root: ChannelContext[models.Product], info):return ProductTypeByIdLoader(info.context).load(root.node.product_type_id)+ @staticmethod+ def __resolve_references(roots: List["Product"], info, **_kwargs):+ requestor = get_user_or_app_from_context(info.context)+ channels = defaultdict(set)+ roots_ids = []+ for root in roots:+ _, root_id = from_global_id_or_error(root.id, Product, raise_error=True)+ if root_id:+ roots_ids.append(f"{root.channel}_{root_id}")+ channels[root.channel].add(root_id)++ products = {}+ for channel, ids in channels.items():+ queryset = resolve_products(+ info, requestor, channel_slug=channel+ ).qs.filter(id__in=ids)++ for product in queryset:+ products[f"{channel}_{product.id}"] = ChannelContext(+ channel_slug=channel, node=product+ )++ return [products.get(root_id) for root_id in roots_ids]+@key(fields="id")class ProductType(CountableDjangoObjectType):@@ -1170,14 +1193,16 @@ class ProductType(CountableDjangoObjectType):)return resolve_attributes(info, qs=qs, **kwargs)- @staticmethod- def __resolve_reference(root: "ProductType", _info, **_kwargs):- return graphene.Node.get_node_from_global_id(_info, root.id)-@staticmethoddef resolve_weight(root: models.ProductType, _info, **_kwargs):return convert_weight_to_default_weight_unit(root.weight)+ @staticmethod+ def __resolve_references(roots: List["ProductType"], _info, **_kwargs):+ return resolve_federation_references(+ ProductType, roots, models.ProductType.objects+ )+@key(fields="id channel")class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):@@ -1259,23 +1284,33 @@ class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):root.node.id)- @staticmethod- def __resolve_reference(root: "Collection", info, **_kwargs):- requestor = get_user_or_app_from_context(info.context)- _type, id = from_global_id_or_error(root.id, Collection)- collection = resolve_collection_by_id(info, id, root.channel, requestor)-- return (- ChannelContext(node=collection, channel_slug=root.channel)- if collection- else None- )-@staticmethoddef resolve_description_json(root: ChannelContext[models.Collection], info):description = root.node.descriptionreturn description if description is not None else {}+ @staticmethod+ def __resolve_references(roots: List["Collection"], info, **_kwargs):+ from ..resolvers import resolve_collections++ channels = defaultdict(set)+ roots_ids = []+ for root in roots:+ _, root_id = from_global_id_or_error(root.id, Collection, raise_error=True)+ roots_ids.append(f"{root.channel}_{root_id}")+ channels[root.channel].add(root_id)++ collections = {}+ for channel, ids in channels.items():+ queryset = resolve_collections(info, channel).qs.filter(id__in=ids)++ for collection in queryset:+ collections[f"{channel}_{collection.id}"] = ChannelContext(+ channel_slug=channel, node=collection+ )++ return [collections.get(root_id) for root_id in roots_ids]+@key(fields="id")class Category(CountableDjangoObjectType):@@ -1375,8 +1410,8 @@ class Category(CountableDjangoObjectType):return ChannelQsContext(qs=qs, channel_slug=channel)@staticmethod- def __resolve_reference(root: "Category", _info, **_kwargs):- return graphene.Node.get_node_from_global_id(_info, root.id)+ def __resolve_references(roots: List["Category"], _info, **_kwargs):+ return resolve_federation_references(Category, roots, models.Category.objects)@key(fields="id")@@ -1405,11 +1440,12 @@ class ProductMedia(CountableDjangoObjectType):return info.context.build_absolute_uri(url)@staticmethod- def __resolve_reference(root: "ProductMedia", _info, **_kwargs):- return graphene.Node.get_node_from_global_id(_info, root.id)+ def __resolve_references(roots: List["ProductMedia"], _info, **_kwargs):+ return resolve_federation_references(+ ProductMedia, roots, models.ProductMedia.objects+ )-@key(fields="id")class ProductImage(graphene.ObjectType):id = graphene.ID(required=True, description="The ID of the image.")alt = graphene.String(description="The alt text of the image.")@@ -1432,7 +1468,7 @@ class ProductImage(graphene.ObjectType):@staticmethoddef resolve_id(root: models.ProductMedia, info):- return graphene.Node.to_global_id("ProductMedia", root.id)+ return graphene.Node.to_global_id("ProductImage", root.id)@staticmethoddef resolve_url(root: models.ProductMedia, info, *, size=None):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex bb1a2d4a5b..99c21b0b00 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -7340,7 +7340,7 @@ enum WeightUnitsEnum {scalar _Any-union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | Collection | Category | ProductMedia | ProductImage | PageType+union _Entity = App | Address | User | Group | ProductVariant | Product | ProductType | Collection | Category | ProductMedia | PageTypetype _Service {sdl: Stringdiff --git a/saleor/settings.py b/saleor/settings.pyindex fa6f41cd43..b611a2715f 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -528,6 +528,12 @@ GRAPHENE = {],}+# Max number entities that can be requested in single query by Apollo Federation+# Federation protocol implements no securities on its own part - malicious actor+# may build a query that requests for potentially few thousands of entities.+# Set FEDERATED_QUERY_MAX_ENTITIES=0 in env to disable (not recommended)+FEDERATED_QUERY_MAX_ENTITIES = int(os.environ.get("FEDERATED_QUERY_MAX_ENTITIES", 100))+BUILTIN_PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin","saleor.plugins.vatlayer.plugin.VatlayerPlugin",