/
compose.ts
580 lines (524 loc) 路 18.9 KB
/
compose.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import 'apollo-server-env';
import {
GraphQLSchema,
extendSchema,
Kind,
isTypeDefinitionNode,
isTypeExtensionNode,
GraphQLError,
GraphQLNamedType,
isObjectType,
FieldDefinitionNode,
InputValueDefinitionNode,
DocumentNode,
GraphQLObjectType,
specifiedDirectives,
TypeDefinitionNode,
DirectiveDefinitionNode,
TypeExtensionNode,
} from 'graphql';
import { transformSchema } from 'apollo-graphql';
import federationDirectives from '../directives';
import {
findDirectivesOnTypeOrField,
isStringValueNode,
parseSelections,
mapFieldNamesToServiceName,
stripExternalFieldsFromTypeDefs,
typeNodesAreEquivalent,
mapValues,
isFederationDirective,
executableDirectiveLocations,
stripTypeSystemDirectivesFromTypeDefs,
} from './utils';
import {
ServiceDefinition,
ExternalFieldDefinition,
ServiceNameToKeyDirectivesMap,
} from './types';
import { validateSDL } from 'graphql/validation/validate';
import { compositionRules } from './rules';
const EmptyQueryDefinition = {
kind: Kind.OBJECT_TYPE_DEFINITION,
name: { kind: Kind.NAME, value: 'Query' },
fields: [],
serviceName: null,
};
const EmptyMutationDefinition = {
kind: Kind.OBJECT_TYPE_DEFINITION,
name: { kind: Kind.NAME, value: 'Mutation' },
fields: [],
serviceName: null,
};
// Map of all type definitions to eventually be passed to extendSchema
interface TypeDefinitionsMap {
[name: string]: TypeDefinitionNode[];
}
// Map of all type extensions to eventually be passed to extendSchema
interface TypeExtensionsMap {
[name: string]: TypeExtensionNode[];
}
// Map of all directive definitions to eventually be passed to extendSchema
interface DirectiveDefinitionsMap {
[name: string]: { [serviceName: string]: DirectiveDefinitionNode };
}
/**
* A map of base types to their owning service. Used by query planner to direct traffic.
* This contains the base type's "owner". Any fields that extend this type in another service
* are listed under "extensionFieldsToOwningServiceMap". extensionFieldsToOwningServiceMap are in the format { myField: my-service-name }
*
* Example resulting typeToServiceMap shape:
*
* const typeToServiceMap = {
* Product: {
* serviceName: "ProductService",
* extensionFieldsToOwningServiceMap: {
* reviews: "ReviewService", // Product.reviews comes from the ReviewService
* dimensions: "ShippingService",
* weight: "ShippingService"
* }
* }
* }
*/
interface TypeToServiceMap {
[typeName: string]: {
owningService?: string;
extensionFieldsToOwningServiceMap: { [fieldName: string]: string };
};
}
/*
* Map of types to their key directives (maintains association to their services)
*
* Example resulting KeyDirectivesMap shape:
*
* const keyDirectives = {
* Product: {
* serviceA: ["sku", "upc"]
* serviceB: ["color {id value}"] // Selection node simplified for readability
* }
* }
*/
export interface KeyDirectivesMap {
[typeName: string]: ServiceNameToKeyDirectivesMap;
}
/**
* A set of type names that have been determined to be a value type, a type
* shared across at least 2 services.
*/
type ValueTypes = Set<string>;
/**
* Loop over each service and process its typeDefs (`definitions`)
* - build up typeToServiceMap
* - push individual definitions onto either typeDefinitionsMap or typeExtensionsMap
*/
export function buildMapsFromServiceList(serviceList: ServiceDefinition[]) {
const typeDefinitionsMap: TypeDefinitionsMap = Object.create(null);
const typeExtensionsMap: TypeExtensionsMap = Object.create(null);
const directiveDefinitionsMap: DirectiveDefinitionsMap = Object.create(null);
const typeToServiceMap: TypeToServiceMap = Object.create(null);
const externalFields: ExternalFieldDefinition[] = [];
const keyDirectivesMap: KeyDirectivesMap = Object.create(null);
const valueTypes: ValueTypes = new Set();
for (const { typeDefs, name: serviceName } of serviceList) {
// Build a new SDL with @external fields removed, as well as information about
// the fields that were removed.
const {
typeDefsWithoutExternalFields,
strippedFields,
} = stripExternalFieldsFromTypeDefs(typeDefs, serviceName);
externalFields.push(...strippedFields);
// Type system directives from downstream services are not a concern of the
// gateway, but rather the services on which the fields live which serve
// those types. In other words, its up to an implementing service to
// act on such directives, not the gateway.
const typeDefsWithoutTypeSystemDirectives =
stripTypeSystemDirectivesFromTypeDefs(typeDefsWithoutExternalFields);
for (const definition of typeDefsWithoutTypeSystemDirectives.definitions) {
if (
definition.kind === Kind.OBJECT_TYPE_DEFINITION ||
definition.kind === Kind.OBJECT_TYPE_EXTENSION
) {
const typeName = definition.name.value;
for (const keyDirective of findDirectivesOnTypeOrField(
definition,
'key',
)) {
if (
keyDirective.arguments &&
isStringValueNode(keyDirective.arguments[0].value)
) {
// Initialize the entry for this type if necessary
keyDirectivesMap[typeName] = keyDirectivesMap[typeName] || {};
// Initialize the entry for this service if necessary
keyDirectivesMap[typeName][serviceName] =
keyDirectivesMap[typeName][serviceName] || [];
// Add @key metadata to the array
keyDirectivesMap[typeName][serviceName].push(
parseSelections(keyDirective.arguments[0].value.value),
);
}
}
}
if (isTypeDefinitionNode(definition)) {
const typeName = definition.name.value;
/**
* This type is a base definition (not an extension). If this type is already in the typeToServiceMap, then
* 1. It was declared by a previous service, but this newer one takes precedence, or...
* 2. It was extended by a service before declared
*/
if (!typeToServiceMap[typeName]) {
typeToServiceMap[typeName] = {
extensionFieldsToOwningServiceMap: Object.create(null),
};
}
typeToServiceMap[typeName].owningService = serviceName;
/**
* If this type already exists in the definitions map, push this definition to the array (newer defs
* take precedence). If the types are determined to be identical, add the type name
* to the valueTypes Set.
*
* If not, create the definitions array and add it to the typeDefinitionsMap.
*/
if (typeDefinitionsMap[typeName]) {
const isValueType = typeNodesAreEquivalent(
typeDefinitionsMap[typeName][
typeDefinitionsMap[typeName].length - 1
],
definition,
);
if (isValueType) {
valueTypes.add(typeName);
}
typeDefinitionsMap[typeName].push({ ...definition, serviceName });
} else {
typeDefinitionsMap[typeName] = [{ ...definition, serviceName }];
}
} else if (isTypeExtensionNode(definition)) {
const typeName = definition.name.value;
/**
* This definition is an extension of an OBJECT type defined in another service.
* TODO: handle extensions of non-object types?
*/
if (
definition.kind === Kind.OBJECT_TYPE_EXTENSION ||
definition.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION
) {
if (!definition.fields) break;
const fields = mapFieldNamesToServiceName<
FieldDefinitionNode | InputValueDefinitionNode
>(definition.fields, serviceName);
/**
* If the type already exists in the typeToServiceMap, add the extended fields. If not, create the object
* and add the extensionFieldsToOwningServiceMap, but don't add a serviceName. That will be added once that service
* definition is processed.
*/
if (typeToServiceMap[typeName]) {
typeToServiceMap[typeName].extensionFieldsToOwningServiceMap = {
...typeToServiceMap[typeName].extensionFieldsToOwningServiceMap,
...fields,
};
} else {
typeToServiceMap[typeName] = {
extensionFieldsToOwningServiceMap: fields,
};
}
}
if (definition.kind === Kind.ENUM_TYPE_EXTENSION) {
if (!definition.values) break;
const values = mapFieldNamesToServiceName(
definition.values,
serviceName,
);
if (typeToServiceMap[typeName]) {
typeToServiceMap[typeName].extensionFieldsToOwningServiceMap = {
...typeToServiceMap[typeName].extensionFieldsToOwningServiceMap,
...values,
};
} else {
typeToServiceMap[typeName] = {
extensionFieldsToOwningServiceMap: values,
};
}
}
/**
* If an extension for this type already exists in the extensions map, push this extension to the
* array (since a type can be extended by multiple services). If not, create the extensions array
* and add it to the typeExtensionsMap.
*/
if (typeExtensionsMap[typeName]) {
typeExtensionsMap[typeName].push({ ...definition, serviceName });
} else {
typeExtensionsMap[typeName] = [{ ...definition, serviceName }];
}
} else if (definition.kind === Kind.DIRECTIVE_DEFINITION) {
const directiveName = definition.name.value;
// The composed schema should only contain directives and their
// ExecutableDirectiveLocations. This filters out any TypeSystemDirectiveLocations.
// A new DirectiveDefinitionNode with this filtered list will be what is
// added to the schema.
const executableLocations = definition.locations.filter(location =>
executableDirectiveLocations.includes(location.value),
);
// If none of the directive's locations are executable, we don't need to
// include it in the composed schema at all.
if (executableLocations.length === 0) continue;
const definitionWithExecutableLocations: DirectiveDefinitionNode = {
...definition,
locations: executableLocations,
};
if (directiveDefinitionsMap[directiveName]) {
directiveDefinitionsMap[directiveName][
serviceName
] = definitionWithExecutableLocations;
} else {
directiveDefinitionsMap[directiveName] = {
[serviceName]: definitionWithExecutableLocations,
};
}
}
}
}
// Since all Query/Mutation definitions in service schemas are treated as
// extensions, we don't have a Query or Mutation DEFINITION in the definitions
// list. Without a Query/Mutation definition, we can't _extend_ the type.
// extendSchema will complain about this. We can't add an empty
// GraphQLObjectType to the schema constructor, so we add an empty definition
// here. We only add mutation if there is a mutation extension though.
if (!typeDefinitionsMap.Query)
typeDefinitionsMap.Query = [EmptyQueryDefinition];
if (typeExtensionsMap.Mutation && !typeDefinitionsMap.Mutation)
typeDefinitionsMap.Mutation = [EmptyMutationDefinition];
return {
typeToServiceMap,
typeDefinitionsMap,
typeExtensionsMap,
directiveDefinitionsMap,
externalFields,
keyDirectivesMap,
valueTypes,
};
}
export function buildSchemaFromDefinitionsAndExtensions({
typeDefinitionsMap,
typeExtensionsMap,
directiveDefinitionsMap,
}: {
typeDefinitionsMap: TypeDefinitionsMap;
typeExtensionsMap: TypeExtensionsMap;
directiveDefinitionsMap: DirectiveDefinitionsMap;
}) {
let errors: GraphQLError[] | undefined = undefined;
let schema = new GraphQLSchema({
query: undefined,
directives: [...specifiedDirectives, ...federationDirectives],
});
// Extend the blank schema with the base type definitions (as an AST node)
const definitionsDocument: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: [
...Object.values(typeDefinitionsMap).flat(),
...Object.values(directiveDefinitionsMap).map(
definitions => Object.values(definitions)[0],
),
],
};
errors = validateSDL(definitionsDocument, schema, compositionRules);
schema = extendSchema(schema, definitionsDocument, { assumeValidSDL: true });
// Extend the schema with the extension definitions (as an AST node)
const extensionsDocument: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: Object.values(typeExtensionsMap).flat(),
};
errors.push(...validateSDL(extensionsDocument, schema, compositionRules));
schema = extendSchema(schema, extensionsDocument, { assumeValidSDL: true });
// Remove federation directives from the final schema
schema = new GraphQLSchema({
...schema.toConfig(),
directives: [
...schema.getDirectives().filter(x => !isFederationDirective(x)),
],
});
return { schema, errors };
}
/**
* Using the various information we've collected about the schema, augment the
* `schema` itself with `federation` metadata to the types and fields
*/
export function addFederationMetadataToSchemaNodes({
schema,
typeToServiceMap,
externalFields,
keyDirectivesMap,
valueTypes,
directiveDefinitionsMap,
}: {
schema: GraphQLSchema;
typeToServiceMap: TypeToServiceMap;
externalFields: ExternalFieldDefinition[];
keyDirectivesMap: KeyDirectivesMap;
valueTypes: ValueTypes;
directiveDefinitionsMap: DirectiveDefinitionsMap;
}) {
for (const [
typeName,
{ owningService, extensionFieldsToOwningServiceMap },
] of Object.entries(typeToServiceMap)) {
const namedType = schema.getType(typeName) as GraphQLNamedType;
if (!namedType) continue;
// Extend each type in the GraphQLSchema with the serviceName that owns it
// and the key directives that belong to it
const isValueType = valueTypes.has(typeName);
const serviceName = isValueType ? null : owningService;
namedType.federation = {
...namedType.federation,
serviceName,
isValueType,
...(keyDirectivesMap[typeName] && {
keys: keyDirectivesMap[typeName],
}),
};
// For object types, add metadata for all the @provides directives from its fields
if (isObjectType(namedType)) {
for (const field of Object.values(namedType.getFields())) {
const [providesDirective] = findDirectivesOnTypeOrField(
field.astNode,
'provides',
);
if (
providesDirective &&
providesDirective.arguments &&
isStringValueNode(providesDirective.arguments[0].value)
) {
field.federation = {
...field.federation,
serviceName,
provides: parseSelections(
providesDirective.arguments[0].value.value,
),
belongsToValueType: isValueType,
};
}
}
}
/**
* For extension fields, do 2 things:
* 1. Add serviceName metadata to all fields that belong to a type extension
* 2. add metadata from the @requires directive for each field extension
*/
for (const [fieldName, extendingServiceName] of Object.entries(
extensionFieldsToOwningServiceMap,
)) {
// TODO: Why don't we need to check for non-object types here
if (isObjectType(namedType)) {
const field = namedType.getFields()[fieldName];
field.federation = {
...field.federation,
serviceName: extendingServiceName,
};
const [requiresDirective] = findDirectivesOnTypeOrField(
field.astNode,
'requires',
);
if (
requiresDirective &&
requiresDirective.arguments &&
isStringValueNode(requiresDirective.arguments[0].value)
) {
field.federation = {
...field.federation,
requires: parseSelections(
requiresDirective.arguments[0].value.value,
),
};
}
}
}
}
// add externals metadata
for (const field of externalFields) {
const namedType = schema.getType(field.parentTypeName);
if (!namedType) continue;
namedType.federation = {
...namedType.federation,
externals: {
...(namedType.federation && namedType.federation.externals),
[field.serviceName]: [
...(namedType.federation &&
namedType.federation.externals &&
namedType.federation.externals[field.serviceName]
? namedType.federation.externals[field.serviceName]
: []),
field,
],
},
};
}
// add all definitions of a specific directive for validation later
for (const directiveName of Object.keys(directiveDefinitionsMap)) {
const directive = schema.getDirective(directiveName);
if (!directive) continue;
directive.federation = {
...directive.federation,
directiveDefinitions: directiveDefinitionsMap[directiveName],
};
}
}
export function composeServices(services: ServiceDefinition[]) {
const {
typeToServiceMap,
typeDefinitionsMap,
typeExtensionsMap,
directiveDefinitionsMap,
externalFields,
keyDirectivesMap,
valueTypes,
} = buildMapsFromServiceList(services);
let { schema, errors } = buildSchemaFromDefinitionsAndExtensions({
typeDefinitionsMap,
typeExtensionsMap,
directiveDefinitionsMap,
});
// TODO: We should fix this to take non-default operation root types in
// implementing services into account.
const operationTypeMap = {
query: 'Query',
mutation: 'Mutation',
subscription: 'Subscription',
};
schema = new GraphQLSchema({
...schema.toConfig(),
...mapValues(operationTypeMap, typeName =>
typeName
? (schema.getType(typeName) as GraphQLObjectType<any, any>)
: undefined,
),
});
// If multiple type definitions and extensions for the same type implement the
// same interface, it will get added to the constructed object multiple times,
// resulting in a schema validation error. We therefore need to remove
// duplicate interfaces from object types manually.
schema = transformSchema(schema, type => {
if (isObjectType(type)) {
const config = type.toConfig();
return new GraphQLObjectType({
...config,
interfaces: Array.from(new Set(config.interfaces)),
});
}
return undefined;
});
addFederationMetadataToSchemaNodes({
schema,
typeToServiceMap,
externalFields,
keyDirectivesMap,
valueTypes,
directiveDefinitionsMap,
});
/**
* At the end, we're left with a full GraphQLSchema that _also_ has `serviceName` fields for every type,
* and every field that was extended. Fields that were _not_ extended (added on the base type by the owner),
* there is no `serviceName`, and we should refer to the type's `serviceName`
*/
return { schema, errors };
}