Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhance(stitching): improve query batching #1987

Merged
merged 1 commit into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 19 additions & 5 deletions packages/delegate/src/delegateToSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@ import isPromise from 'is-promise';

import { mapAsyncIterator, Transform, ExecutionResult } from '@graphql-tools/utils';

import { IDelegateToSchemaOptions, IDelegateRequestOptions, SubschemaConfig, ExecutionParams } from './types';
import {
IDelegateToSchemaOptions,
IDelegateRequestOptions,
SubschemaConfig,
ExecutionParams,
StitchingInfo,
Endpoint,
} from './types';

import { isSubschemaConfig } from './Subschema';
import { createRequestFromInfo, getDelegatingOperation } from './createRequest';
Expand Down Expand Up @@ -115,6 +122,7 @@ export function delegateRequest({
let targetSchema: GraphQLSchema;
let targetRootValue: Record<string, any>;
let subschemaConfig: SubschemaConfig;
let endpoint: Endpoint;

let allTransforms: Array<Transform>;
if (isSubschemaConfig(subschemaOrSubschemaConfig)) {
Expand All @@ -125,6 +133,12 @@ export function delegateRequest({
subschemaOrSubschemaConfig.transforms != null
? subschemaOrSubschemaConfig.transforms.concat(transforms)
: transforms;
if (subschemaConfig.endpoint != null) {
const stitchingInfo: StitchingInfo = info?.schema.extensions?.stitchingInfo;
endpoint = stitchingInfo.endpoints[subschemaConfig.endpoint];
} else {
endpoint = subschemaConfig;
}
} else {
targetSchema = subschemaOrSubschemaConfig;
targetRootValue = rootValue ?? info?.rootValue;
Expand Down Expand Up @@ -156,10 +170,10 @@ export function delegateRequest({

if (targetOperation === 'query' || targetOperation === 'mutation') {
let executor =
subschemaConfig?.executor || createDefaultExecutor(targetSchema, subschemaConfig?.rootValue || targetRootValue);
endpoint?.executor || createDefaultExecutor(targetSchema, subschemaConfig?.rootValue || targetRootValue);

if (subschemaConfig?.batch) {
executor = getBatchingExecutor(context, subschemaConfig, executor);
if (endpoint?.batch) {
executor = getBatchingExecutor(context, endpoint, executor);
}

const executionResult = executor({
Expand All @@ -175,7 +189,7 @@ export function delegateRequest({
}

const subscriber =
subschemaConfig?.subscriber || createDefaultSubscriber(targetSchema, subschemaConfig?.rootValue || targetRootValue);
endpoint?.subscriber || createDefaultSubscriber(targetSchema, subschemaConfig?.rootValue || targetRootValue);

return subscriber({
...processedRequest,
Expand Down
10 changes: 5 additions & 5 deletions packages/delegate/src/getBatchingExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ import DataLoader from 'dataloader';

import { ExecutionResult } from '@graphql-tools/utils';

import { SubschemaConfig, ExecutionParams } from './types';
import { ExecutionParams, Endpoint } from './types';
import { memoize2of3 } from './memoize';
import { mergeExecutionParams } from './mergeExecutionParams';
import { splitResult } from './splitResult';

export const getBatchingExecutor = memoize2of3(function (
_context: Record<string, any>,
subschemaConfig: SubschemaConfig,
endpoint: Endpoint,
executor: ({ document, context, variables, info }: ExecutionParams) => ExecutionResult | Promise<ExecutionResult>
) {
const loader = new DataLoader(
createLoadFn(
executor ?? subschemaConfig.executor,
subschemaConfig.batchingOptions?.extensionsReducer ?? defaultExtensionsReducer
executor ?? endpoint.executor,
endpoint.batchingOptions?.extensionsReducer ?? defaultExtensionsReducer
),
subschemaConfig.batchingOptions?.dataLoaderOptions
endpoint.batchingOptions?.dataLoaderOptions
);
return (executionParams: ExecutionParams) => loader.load(executionParams);
});
Expand Down
21 changes: 15 additions & 6 deletions packages/delegate/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,9 @@ export interface ICreateProxyingResolverOptions {

export type CreateProxyingResolverFn = (options: ICreateProxyingResolverOptions) => GraphQLFieldResolver<any, any>;

export interface SubschemaConfig<K = any, V = any, C = K> {
schema: GraphQLSchema;
rootValue?: Record<string, any>;
export interface Endpoint<K = any, V = any, C = K> {
executor?: Executor;
subscriber?: Subscriber;
createProxyingResolver?: CreateProxyingResolverFn;
transforms?: Array<Transform>;
merge?: Record<string, MergedTypeConfig>;
batch?: boolean;
batchingOptions?: {
extensionsReducer?: (
Expand All @@ -143,6 +138,19 @@ export interface SubschemaConfig<K = any, V = any, C = K> {
};
}

export interface NamedEndpoint extends Endpoint {
name: string;
}

export interface SubschemaConfig<K = any, V = any, C = K> extends Endpoint<K, V, C> {
schema: GraphQLSchema;
rootValue?: Record<string, any>;
createProxyingResolver?: CreateProxyingResolverFn;
transforms?: Array<Transform>;
merge?: Record<string, MergedTypeConfig>;
endpoint?: string;
}

export interface MergedTypeConfig<K = any, V = any> {
selectionSet?: string;
fields?: Record<string, { selectionSet?: string }>;
Expand All @@ -168,4 +176,5 @@ export interface StitchingInfo {
selectionSetsByField: Record<string, Record<string, SelectionSetNode>>;
dynamicSelectionSetsByField: Record<string, Record<string, Array<(node: FieldNode) => SelectionSetNode>>>;
mergedTypes: Record<string, MergedTypeInfo>;
endpoints: Record<string, Endpoint>;
}
111 changes: 110 additions & 1 deletion packages/delegate/tests/batchExecution.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { graphql, execute, ExecutionResult } from 'graphql';

import { makeExecutableSchema } from '@graphql-tools/schema';
import { delegateToSchema, SubschemaConfig, ExecutionParams, SyncExecutor } from '../src';
import { delegateToSchema, SubschemaConfig, ExecutionParams, SyncExecutor, NamedEndpoint } from '../src';
import { stitchSchemas } from '@graphql-tools/stitch';
import { FilterObjectFields } from '@graphql-tools/wrap';

describe('batch execution', () => {
it('should batch', async () => {
Expand Down Expand Up @@ -58,4 +60,111 @@ describe('batch execution', () => {
expect(result).toEqual(expectedResult);
expect(executions).toEqual(1);
});

it('should share batching dataloader between subschemas when using a common endpoint', async () => {
const innerSchemaA = makeExecutableSchema({
typeDefs: `
type Object {
field1: String
field2: String
}
type Query {
objectA: Object
}
`,
resolvers: {
Query: {
objectA: () => ({}),
},
Object: {
field1: () => 'test1',
field2: () => 'test2',
},
},
});

const innerSchemaB = makeExecutableSchema({
typeDefs: `
type Object {
field3: String
}
type Query {
objectB: Object
}
`,
resolvers: {
Query: {
objectB: () => ({}),
},
Object: {
field3: () => 'test3',
},
},
});

let executions = 0;

const endpoint: NamedEndpoint = {
name: 'commonEndpoint',
batch: true,
executor: ((params: ExecutionParams): ExecutionResult => {
executions++;
return execute(innerSchemaA, params.document, undefined, params.context, params.variables) as ExecutionResult;
}) as SyncExecutor
}

const innerSubschemaConfigA1: SubschemaConfig = {
schema: innerSchemaA,
transforms: [new FilterObjectFields((typeName, fieldName) => typeName !== 'Object' || fieldName !== 'field2')],
merge: {
Object: {
fieldName: 'objectA',
args: () => ({}),
},
},
endpoint: 'commonEndpoint',
}

const innerSubschemaConfigA2: SubschemaConfig = {
schema: innerSchemaA,
transforms: [new FilterObjectFields((typeName, fieldName) => typeName !== 'Object' || fieldName !== 'field1')],
merge: {
Object: {
fieldName: 'objectA',
args: () => ({}),
},
},
endpoint: 'commonEndpoint',
}

const innerSubschemaConfigB: SubschemaConfig = {
schema: innerSchemaB,
merge: {
Object: {
fieldName: 'objectB',
args: () => ({}),
},
},
}

const outerSchema = stitchSchemas({
subschemas: [innerSubschemaConfigA1, innerSubschemaConfigA2, innerSubschemaConfigB],
endpoints: [endpoint],
});

const expectedResult = {
data: {
objectB: {
field1: 'test1',
field2: 'test2',
field3: 'test3',
}
},
};

const result = await graphql(outerSchema, '{ objectB { field1 field2 field3 } }', undefined, {});

expect(result).toEqual(expectedResult);
expect(executions).toEqual(1);
});
});
3 changes: 2 additions & 1 deletion packages/stitch/src/stitchSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { SubschemaConfig, isSubschemaConfig } from '@graphql-tools/delegate';

export function stitchSchemas({
subschemas = [],
endpoints = [],
types = [],
typeDefs,
schemas = [],
Expand Down Expand Up @@ -117,7 +118,7 @@ export function stitchSchemas({
directives.push(directiveMap[directiveName]);
});

let stitchingInfo = createStitchingInfo(transformedSchemas, typeCandidates, mergeTypes);
let stitchingInfo = createStitchingInfo(transformedSchemas, typeCandidates, mergeTypes, endpoints);

const typeMap = buildTypeMap({
typeCandidates,
Expand Down
9 changes: 7 additions & 2 deletions packages/stitch/src/stitchingInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
IFieldResolverOptions,
} from '@graphql-tools/utils';

import { delegateToSchema, isSubschemaConfig, SubschemaConfig } from '@graphql-tools/delegate';
import { delegateToSchema, isSubschemaConfig, SubschemaConfig, NamedEndpoint } from '@graphql-tools/delegate';

import { batchDelegateToSchema } from '@graphql-tools/batch-delegate';

Expand All @@ -32,7 +32,8 @@ import { MergeTypeCandidate, MergedTypeInfo, StitchingInfo, MergeTypeFilter } fr
export function createStitchingInfo(
transformedSchemas: Map<GraphQLSchema | SubschemaConfig, GraphQLSchema>,
typeCandidates: Record<string, Array<MergeTypeCandidate>>,
mergeTypes?: boolean | Array<string> | MergeTypeFilter
mergeTypes?: boolean | Array<string> | MergeTypeFilter,
endpoints?: Array<NamedEndpoint>
): StitchingInfo {
const mergedTypes = createMergedTypes(typeCandidates, mergeTypes);
const selectionSetsByField: Record<string, Record<string, SelectionSetNode>> = Object.create(null);
Expand Down Expand Up @@ -87,6 +88,10 @@ export function createStitchingInfo(
selectionSetsByField,
dynamicSelectionSetsByField: undefined,
mergedTypes,
endpoints: endpoints.reduce((acc, endpoint) => {
acc[endpoint.name] = endpoint;
return acc;
}, Object.create(null)),
};
}

Expand Down
4 changes: 3 additions & 1 deletion packages/stitch/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
GraphQLInputObjectType,
} from 'graphql';
import { ITypeDefinitions, TypeMap } from '@graphql-tools/utils';
import { SubschemaConfig } from '@graphql-tools/delegate';
import { SubschemaConfig, NamedEndpoint, Endpoint } from '@graphql-tools/delegate';
import { IExecutableSchemaDefinition } from '@graphql-tools/schema';

export interface MergeTypeCandidate {
Expand Down Expand Up @@ -55,12 +55,14 @@ export interface StitchingInfo {
selectionSetsByField: Record<string, Record<string, SelectionSetNode>>;
dynamicSelectionSetsByField: Record<string, Record<string, Array<(node: FieldNode) => SelectionSetNode>>>;
mergedTypes: Record<string, MergedTypeInfo>;
endpoints: Record<string, Endpoint>;
}

export type SchemaLikeObject = SubschemaConfig | GraphQLSchema | string | DocumentNode | Array<GraphQLNamedType>;

export interface IStitchSchemasOptions<TContext = any> extends Omit<IExecutableSchemaDefinition<TContext>, 'typeDefs'> {
subschemas?: Array<GraphQLSchema | SubschemaConfig>;
endpoints?: Array<NamedEndpoint>;
typeDefs?: ITypeDefinitions;
types?: Array<GraphQLNamedType>;
schemas?: Array<SchemaLikeObject>;
Expand Down