-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
federation.go
378 lines (339 loc) · 11 KB
/
federation.go
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
package federation
import (
"fmt"
"sort"
"strings"
"github.com/vektah/gqlparser/v2/ast"
"github.com/99designs/gqlgen/codegen"
"github.com/99designs/gqlgen/codegen/config"
"github.com/99designs/gqlgen/codegen/templates"
"github.com/99designs/gqlgen/plugin"
"github.com/99designs/gqlgen/plugin/federation/fieldset"
)
type federation struct {
Entities []*Entity
}
// New returns a federation plugin that injects
// federated directives and types into the schema
func New() plugin.Plugin {
return &federation{}
}
// Name returns the plugin name
func (f *federation) Name() string {
return "federation"
}
// MutateConfig mutates the configuration
func (f *federation) MutateConfig(cfg *config.Config) error {
builtins := config.TypeMap{
"_Service": {
Model: config.StringList{
"github.com/99designs/gqlgen/plugin/federation/fedruntime.Service",
},
},
"_Entity": {
Model: config.StringList{
"github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity",
},
},
"Entity": {
Model: config.StringList{
"github.com/99designs/gqlgen/plugin/federation/fedruntime.Entity",
},
},
"_Any": {
Model: config.StringList{"github.com/99designs/gqlgen/graphql.Map"},
},
}
for typeName, entry := range builtins {
if cfg.Models.Exists(typeName) {
return fmt.Errorf("%v already exists which must be reserved when Federation is enabled", typeName)
}
cfg.Models[typeName] = entry
}
cfg.Directives["external"] = config.DirectiveConfig{SkipRuntime: true}
cfg.Directives["requires"] = config.DirectiveConfig{SkipRuntime: true}
cfg.Directives["provides"] = config.DirectiveConfig{SkipRuntime: true}
cfg.Directives["key"] = config.DirectiveConfig{SkipRuntime: true}
cfg.Directives["extends"] = config.DirectiveConfig{SkipRuntime: true}
return nil
}
func (f *federation) InjectSourceEarly() *ast.Source {
return &ast.Source{
Name: "federation/directives.graphql",
Input: `
scalar _Any
scalar _FieldSet
directive @external on FIELD_DEFINITION
directive @requires(fields: _FieldSet!) on FIELD_DEFINITION
directive @provides(fields: _FieldSet!) on FIELD_DEFINITION
directive @key(fields: _FieldSet!) repeatable on OBJECT | INTERFACE
directive @extends on OBJECT | INTERFACE
`,
BuiltIn: true,
}
}
// InjectSources creates a GraphQL Entity type with all
// the fields that had the @key directive
func (f *federation) InjectSourceLate(schema *ast.Schema) *ast.Source {
f.setEntities(schema)
var entities, resolvers, entityResolverInputDefinitions string
for i, e := range f.Entities {
if i != 0 {
entities += " | "
}
entities += e.Name
for _, r := range e.Resolvers {
if e.Multi {
if entityResolverInputDefinitions != "" {
entityResolverInputDefinitions += "\n\n"
}
entityResolverInputDefinitions += "input " + r.InputType + " {\n"
for _, keyField := range r.KeyFields {
entityResolverInputDefinitions += fmt.Sprintf("\t%s: %s\n", keyField.Field.ToGo(), keyField.Definition.Type.String())
}
entityResolverInputDefinitions += "}"
resolvers += fmt.Sprintf("\t%s(reps: [%s!]!): [%s]\n", r.ResolverName, r.InputType, e.Name)
} else {
resolverArgs := ""
for _, keyField := range r.KeyFields {
resolverArgs += fmt.Sprintf("%s: %s,", keyField.Field.ToGoPrivate(), keyField.Definition.Type.String())
}
resolvers += fmt.Sprintf("\t%s(%s): %s!\n", r.ResolverName, resolverArgs, e.Name)
}
}
}
var blocks []string
if entities != "" {
entities = `# a union of all types that use the @key directive
union _Entity = ` + entities
blocks = append(blocks, entities)
}
// resolvers can be empty if a service defines only "empty
// extend" types. This should be rare.
if resolvers != "" {
if entityResolverInputDefinitions != "" {
blocks = append(blocks, entityResolverInputDefinitions)
}
resolvers = `# fake type to build resolver interfaces for users to implement
type Entity {
` + resolvers + `
}`
blocks = append(blocks, resolvers)
}
_serviceTypeDef := `type _Service {
sdl: String
}`
blocks = append(blocks, _serviceTypeDef)
var additionalQueryFields string
// Quote from the Apollo Federation subgraph specification:
// If no types are annotated with the key directive, then the
// _Entity union and _entities field should be removed from the schema
if len(f.Entities) > 0 {
additionalQueryFields += ` _entities(representations: [_Any!]!): [_Entity]!
`
}
// _service field is required in any case
additionalQueryFields += ` _service: _Service!`
extendTypeQueryDef := `extend type ` + schema.Query.Name + ` {
` + additionalQueryFields + `
}`
blocks = append(blocks, extendTypeQueryDef)
return &ast.Source{
Name: "federation/entity.graphql",
BuiltIn: true,
Input: "\n" + strings.Join(blocks, "\n\n") + "\n",
}
}
// Entity represents a federated type
// that was declared in the GQL schema.
type Entity struct {
Name string // The same name as the type declaration
Def *ast.Definition
Resolvers []*EntityResolver
Requires []*Requires
Multi bool
}
type EntityResolver struct {
ResolverName string // The resolver name, such as FindUserByID
KeyFields []*KeyField // The fields declared in @key.
InputType string // The Go generated input type for multi entity resolvers
}
type KeyField struct {
Definition *ast.FieldDefinition
Field fieldset.Field // len > 1 for nested fields
Type *config.TypeReference // The Go representation of that field type
}
// Requires represents an @requires clause
type Requires struct {
Name string // the name of the field
Field fieldset.Field // source Field, len > 1 for nested fields
Type *config.TypeReference // The Go representation of that field type
}
func (e *Entity) allFieldsAreExternal() bool {
for _, field := range e.Def.Fields {
if field.Directives.ForName("external") == nil {
return false
}
}
return true
}
func (f *federation) GenerateCode(data *codegen.Data) error {
if len(f.Entities) > 0 {
if data.Objects.ByName("Entity") != nil {
data.Objects.ByName("Entity").Root = true
}
for _, e := range f.Entities {
obj := data.Objects.ByName(e.Def.Name)
for _, r := range e.Resolvers {
// fill in types for key fields
//
for _, keyField := range r.KeyFields {
if len(keyField.Field) == 0 {
fmt.Println(
"skipping @key field " + keyField.Definition.Name + " in " + r.ResolverName + " in " + e.Def.Name,
)
continue
}
cgField := keyField.Field.TypeReference(obj, data.Objects)
keyField.Type = cgField.TypeReference
}
}
// fill in types for requires fields
//
for _, reqField := range e.Requires {
if len(reqField.Field) == 0 {
fmt.Println("skipping @requires field " + reqField.Name + " in " + e.Def.Name)
continue
}
cgField := reqField.Field.TypeReference(obj, data.Objects)
reqField.Type = cgField.TypeReference
}
}
}
return templates.Render(templates.Options{
PackageName: data.Config.Federation.Package,
Filename: data.Config.Federation.Filename,
Data: f,
GeneratedHeader: true,
Packages: data.Config.Packages,
})
}
func (f *federation) setEntities(schema *ast.Schema) {
for _, schemaType := range schema.Types {
keys, ok := isFederatedEntity(schemaType)
if !ok {
continue
}
e := &Entity{
Name: schemaType.Name,
Def: schemaType,
Resolvers: nil,
Requires: nil,
}
// Let's process custom entity resolver settings.
dir := schemaType.Directives.ForName("entityResolver")
if dir != nil {
if dirArg := dir.Arguments.ForName("multi"); dirArg != nil {
if dirVal, err := dirArg.Value.Value(nil); err == nil {
e.Multi = dirVal.(bool)
}
}
}
// If our schema has a field with a type defined in
// another service, then we need to define an "empty
// extend" of that type in this service, so this service
// knows what the type is like. But the graphql-server
// will never ask us to actually resolve this "empty
// extend", so we don't require a resolver function for
// it. (Well, it will never ask in practice; it's
// unclear whether the spec guarantees this. See
// https://github.com/apollographql/apollo-server/issues/3852
// ). Example:
// type MyType {
// myvar: TypeDefinedInOtherService
// }
// // Federation needs this type, but
// // it doesn't need a resolver for it!
// extend TypeDefinedInOtherService @key(fields: "id") {
// id: ID @external
// }
if !e.allFieldsAreExternal() {
for _, dir := range keys {
if len(dir.Arguments) != 1 || dir.Arguments[0].Name != "fields" {
panic("Exactly one `fields` argument needed for @key declaration.")
}
arg := dir.Arguments[0]
keyFieldSet := fieldset.New(arg.Value.Raw, nil)
keyFields := make([]*KeyField, len(keyFieldSet))
resolverFields := []string{}
for i, field := range keyFieldSet {
def := field.FieldDefinition(schemaType, schema)
if def == nil {
panic(fmt.Sprintf("no field for %v", field))
}
keyFields[i] = &KeyField{Definition: def, Field: field}
resolverFields = append(resolverFields, keyFields[i].Field.ToGo())
}
resolverFieldsToGo := schemaType.Name + "By" + strings.Join(resolverFields, "And")
var resolverName string
if e.Multi {
resolverFieldsToGo += "s" // Pluralize for better API readability
resolverName = fmt.Sprintf("findMany%s", resolverFieldsToGo)
} else {
resolverName = fmt.Sprintf("find%s", resolverFieldsToGo)
}
e.Resolvers = append(e.Resolvers, &EntityResolver{
ResolverName: resolverName,
KeyFields: keyFields,
InputType: resolverFieldsToGo + "Input",
})
}
e.Requires = []*Requires{}
for _, f := range schemaType.Fields {
dir := f.Directives.ForName("requires")
if dir == nil {
continue
}
if len(dir.Arguments) != 1 || dir.Arguments[0].Name != "fields" {
panic("Exactly one `fields` argument needed for @requires declaration.")
}
requiresFieldSet := fieldset.New(dir.Arguments[0].Value.Raw, nil)
for _, field := range requiresFieldSet {
e.Requires = append(e.Requires, &Requires{
Name: field.ToGoPrivate(),
Field: field,
})
}
}
}
f.Entities = append(f.Entities, e)
}
// make sure order remains stable across multiple builds
sort.Slice(f.Entities, func(i, j int) bool {
return f.Entities[i].Name < f.Entities[j].Name
})
}
func isFederatedEntity(schemaType *ast.Definition) ([]*ast.Directive, bool) {
switch schemaType.Kind {
case ast.Object:
keys := schemaType.Directives.ForNames("key")
if len(keys) > 0 {
return keys, true
}
case ast.Interface:
// TODO: support @key and @extends for interfaces
if dir := schemaType.Directives.ForName("key"); dir != nil {
fmt.Printf("@key directive found on \"interface %s\". Will be ignored.\n", schemaType.Name)
}
if dir := schemaType.Directives.ForName("extends"); dir != nil {
panic(
fmt.Sprintf(
"@extends directive is not currently supported for interfaces, use \"extend interface %s\" instead.",
schemaType.Name,
))
}
default:
// ignore
}
return nil, false
}