Class: GraphQL::Stitching::Supergraph

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/stitching/supergraph.rb,
lib/graphql/stitching/supergraph/source_directive.rb,
lib/graphql/stitching/supergraph/resolver_directive.rb

Defined Under Namespace

Classes: PathNode, ResolverDirective, SourceDirective

Constant Summary collapse

SUPERGRAPH_LOCATION =
"__super"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema:, fields: {}, resolvers: {}, executables: {}) ⇒ Supergraph

Returns a new instance of Supergraph.



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
# File 'lib/graphql/stitching/supergraph.rb', line 84

def initialize(schema:, fields: {}, resolvers: {}, executables: {})
  @schema = schema
  @schema.use(GraphQL::Schema::AlwaysVisible)

  @resolvers = resolvers
  @fields_by_type_and_location = nil
  @locations_by_type = nil
  @memoized_introspection_types = nil
  @memoized_schema_fields = {}
  @memoized_schema_types = nil
  @possible_keys_by_type = {}
  @possible_keys_by_type_and_location = {}
  @static_validator = nil

  # add introspection types into the fields mapping
  @locations_by_type_and_field = memoized_introspection_types.each_with_object(fields) do |(type_name, type), memo|
    next unless type.kind.fields?

    memo[type_name] = type.fields.keys.each_with_object({}) do |field_name, m|
      m[field_name] = [SUPERGRAPH_LOCATION]
    end
  end.freeze

  # validate and normalize executable references
  @executables = executables.each_with_object({ SUPERGRAPH_LOCATION => @schema }) do |(location, executable), memo|
    if self.class.validate_executable!(location, executable)
      memo[location.to_s] = executable
    end
  end.freeze
end

Instance Attribute Details

#executablesHash<String, Executable> (readonly)

Returns a map of executable resources by location.

Returns:

  • (Hash<String, Executable>)

    a map of executable resources by location.



80
81
82
# File 'lib/graphql/stitching/supergraph.rb', line 80

def executables
  @executables
end

#locations_by_type_and_fieldObject (readonly)

Returns the value of attribute locations_by_type_and_field.



82
83
84
# File 'lib/graphql/stitching/supergraph.rb', line 82

def locations_by_type_and_field
  @locations_by_type_and_field
end

#resolversObject (readonly)

Returns the value of attribute resolvers.



82
83
84
# File 'lib/graphql/stitching/supergraph.rb', line 82

def resolvers
  @resolvers
end

#schemaGraphQL::Schema (readonly)

Returns the composed schema for the supergraph.

Returns:

  • (GraphQL::Schema)

    the composed schema for the supergraph.



77
78
79
# File 'lib/graphql/stitching/supergraph.rb', line 77

def schema
  @schema
end

Class Method Details

.from_definition(schema, executables:) ⇒ Object



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
# File 'lib/graphql/stitching/supergraph.rb', line 18

def from_definition(schema, executables:)
  schema = GraphQL::Schema.from_definition(schema) if schema.is_a?(String)
  field_map = {}
  resolver_map = {}
  possible_locations = {}
  introspection_types = schema.introspection_system.types.keys

  schema.types.each do |type_name, type|
    next if introspection_types.include?(type_name)

    type.directives.each do |directive|
      next unless directive.graphql_name == ResolverDirective.graphql_name

      kwargs = directive.arguments.keyword_arguments
      resolver_map[type_name] ||= []
      resolver_map[type_name] << Resolver.new(
        type_name: kwargs.fetch(:type_name, type_name),
        location: kwargs[:location],
        key: kwargs[:key],
        field: kwargs[:field],
        list: kwargs[:list] || false,
        arg: kwargs[:arg],
        arg_type_name: kwargs[:arg_type_name],
        representations: kwargs[:representations] || false,
      )
    end

    next unless type.kind.fields?

    type.fields.each do |field_name, field|
      field.directives.each do |d|
        next unless d.graphql_name == SourceDirective.graphql_name

        location = d.arguments.keyword_arguments[:location]
        field_map[type_name] ||= {}
        field_map[type_name][field_name] ||= []
        field_map[type_name][field_name] << location
        possible_locations[location] = true
      end
    end
  end

  executables = possible_locations.keys.each_with_object({}) do |location, memo|
    executable = executables[location] || executables[location.to_sym]
    if validate_executable!(location, executable)
      memo[location] = executable
    end
  end

  new(
    schema: schema,
    fields: field_map,
    resolvers: resolver_map,
    executables: executables,
  )
end

.validate_executable!(location, executable) ⇒ Object

Raises:



12
13
14
15
16
# File 'lib/graphql/stitching/supergraph.rb', line 12

def validate_executable!(location, executable)
  return true if executable.is_a?(Class) && executable <= GraphQL::Schema
  return true if executable && executable.respond_to?(:call)
  raise StitchingError, "Invalid executable provided for location `#{location}`."
end

Instance Method Details

#execute_at_location(location, source, variables, request) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/graphql/stitching/supergraph.rb', line 208

def execute_at_location(location, source, variables, request)
  executable = executables[location]

  if executable.nil?
    raise StitchingError, "No executable assigned for #{location} location."
  elsif executable.is_a?(Class) && executable <= GraphQL::Schema
    executable.execute(
      query: source,
      variables: variables,
      context: request.context.frozen? ? request.context.dup : request.context,
      validate: false,
    )
  elsif executable.respond_to?(:call)
    executable.call(request, source, variables)
  else
    raise StitchingError, "Missing valid executable for #{location} location."
  end
end

#fieldsObject



175
176
177
# File 'lib/graphql/stitching/supergraph.rb', line 175

def fields
  @locations_by_type_and_field.reject { |k, _v| memoized_introspection_types[k] }
end

#fields_by_type_and_locationObject

inverts fields map to provide fields for a type/location "Type" => "location" => ["field1", "field2", ...]



229
230
231
232
233
234
235
236
237
238
# File 'lib/graphql/stitching/supergraph.rb', line 229

def fields_by_type_and_location
  @fields_by_type_and_location ||= @locations_by_type_and_field.each_with_object({}) do |(type_name, fields), memo|
    memo[type_name] = fields.each_with_object({}) do |(field_name, locations), memo|
      locations.each do |location|
        memo[location] ||= []
        memo[location] << field_name
      end
    end
  end
end

#locationsObject



179
180
181
# File 'lib/graphql/stitching/supergraph.rb', line 179

def locations
  @executables.keys.reject { _1 == SUPERGRAPH_LOCATION }
end

#locations_by_typeObject

"Type" => ["location1", "location2", ...]



241
242
243
244
245
# File 'lib/graphql/stitching/supergraph.rb', line 241

def locations_by_type
  @locations_by_type ||= @locations_by_type_and_field.each_with_object({}) do |(type_name, fields), memo|
    memo[type_name] = fields.values.flatten.uniq
  end
end

#memoized_introspection_typesObject



183
184
185
# File 'lib/graphql/stitching/supergraph.rb', line 183

def memoized_introspection_types
  @memoized_introspection_types ||= schema.introspection_system.types
end

#memoized_schema_fields(type_name) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/graphql/stitching/supergraph.rb', line 191

def memoized_schema_fields(type_name)
  @memoized_schema_fields[type_name] ||= begin
    fields = memoized_schema_types[type_name].fields
    @schema.introspection_system.dynamic_fields.each do |field|
      fields[field.name] ||= field # adds __typename
    end

    if type_name == @schema.query.graphql_name
      @schema.introspection_system.entry_points.each do |field|
        fields[field.name] ||= field # adds __schema, __type
      end
    end

    fields
  end
end

#memoized_schema_typesObject



187
188
189
# File 'lib/graphql/stitching/supergraph.rb', line 187

def memoized_schema_types
  @memoized_schema_types ||= @schema.types
end

#possible_keys_for_type(type_name) ⇒ Object

collects all possible resolver keys for a given type ("Type") => ["id", ...]



249
250
251
252
253
254
255
256
257
# File 'lib/graphql/stitching/supergraph.rb', line 249

def possible_keys_for_type(type_name)
  @possible_keys_by_type[type_name] ||= begin
    if type_name == @schema.query.graphql_name
      GraphQL::Stitching::EMPTY_ARRAY
    else
      @resolvers[type_name].map(&:key).tap(&:uniq!)
    end
  end
end

#possible_keys_for_type_and_location(type_name, location) ⇒ Object

collects possible resolver keys for a given type and location ("Type", "location") => ["id", ...]



261
262
263
264
265
266
267
# File 'lib/graphql/stitching/supergraph.rb', line 261

def possible_keys_for_type_and_location(type_name, location)
  possible_keys_by_type = @possible_keys_by_type_and_location[type_name] ||= {}
  possible_keys_by_type[location] ||= begin
    location_fields = fields_by_type_and_location[type_name][location] || []
    location_fields & possible_keys_for_type(type_name)
  end
end

#route_type_to_locations(type_name, start_location, goal_locations) ⇒ Object

For a given type, route from one origin location to one or more remote locations used to connect a partial type across locations via resolver queries



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/graphql/stitching/supergraph.rb', line 271

def route_type_to_locations(type_name, start_location, goal_locations)
  key_count = possible_keys_for_type(type_name).length

  if key_count.zero?
    # nested root scopes have no resolver keys and just return a location
    goal_locations.each_with_object({}) do |goal_location, memo|
      memo[goal_location] = [Resolver.new(location: goal_location)]
    end

  elsif key_count > 1
    # multiple keys use an A* search to traverse intermediary locations
    route_type_to_locations_via_search(type_name, start_location, goal_locations)

  else
    # types with a single key attribute must all be within a single hop of each other,
    # so can use a simple match to collect resolvers for the goal locations.
    @resolvers[type_name].each_with_object({}) do |resolver, memo|
      if goal_locations.include?(resolver.location)
        memo[resolver.location] = [resolver]
      end
    end
  end
end

#static_validatorGraphQL::StaticValidation::Validator

Returns static validator for the supergraph schema.

Returns:

  • (GraphQL::StaticValidation::Validator)

    static validator for the supergraph schema.



171
172
173
# File 'lib/graphql/stitching/supergraph.rb', line 171

def static_validator
  @static_validator ||= @schema.static_validator
end

#to_definitionObject



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
# File 'lib/graphql/stitching/supergraph.rb', line 115

def to_definition
  if @schema.directives[ResolverDirective.graphql_name].nil?
    @schema.directive(ResolverDirective)
  end
  if @schema.directives[SourceDirective.graphql_name].nil?
    @schema.directive(SourceDirective)
  end

  @schema.types.each do |type_name, type|
    if resolvers_for_type = @resolvers.dig(type_name)
      resolvers_for_type.each do |resolver|
        existing = type.directives.find do |d|
          kwargs = d.arguments.keyword_arguments
          d.graphql_name == ResolverDirective.graphql_name &&
            kwargs[:location] == resolver.location &&
            kwargs[:key] == resolver.key &&
            kwargs[:field] == resolver.field &&
            kwargs[:arg] == resolver.arg &&
            kwargs.fetch(:list, false) == resolver.list &&
            kwargs.fetch(:representations, false) == resolver.representations
        end

        type.directive(ResolverDirective, **{
          type_name: (resolver.type_name if resolver.type_name != type_name),
          location: resolver.location,
          key: resolver.key,
          field: resolver.field,
          list: resolver.list || nil,
          arg: resolver.arg,
          arg_type_name: resolver.arg_type_name,
          representations: resolver.representations || nil,
        }.tap(&:compact!)) if existing.nil?
      end
    end

    next unless type.kind.fields?

    type.fields.each do |field_name, field|
      locations_for_field = @locations_by_type_and_field.dig(type_name, field_name)
      next if locations_for_field.nil?

      locations_for_field.each do |location|
        existing = field.directives.find do |d|
          d.graphql_name == SourceDirective.graphql_name &&
            d.arguments.keyword_arguments[:location] == location
        end

        field.directive(SourceDirective, location: location) if existing.nil?
      end
    end
  end

  @schema.to_definition
end