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: {}, boundaries: {}, executables: {}) ⇒ Supergraph

Returns a new instance of Supergraph.



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

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

  @boundaries = boundaries
  @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

#boundariesObject (readonly)

Returns the value of attribute boundaries.



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

def boundaries
  @boundaries
end

#executablesHash<String, Executable> (readonly)

Returns a map of executable resources by location.

Returns:

  • (Hash<String, Executable>)

    a map of executable resources by location.



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

def executables
  @executables
end

#locations_by_type_and_fieldObject (readonly)

Returns the value of attribute locations_by_type_and_field.



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

def locations_by_type_and_field
  @locations_by_type_and_field
end

#schemaGraphQL::Schema (readonly)

Returns the composed schema for the supergraph.

Returns:

  • (GraphQL::Schema)

    the composed schema for the supergraph.



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

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
# 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 = {}
  boundary_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
      boundary_map[type_name] ||= []
      boundary_map[type_name] << Boundary.new(
        type_name: kwargs.fetch(:type_name, type_name),
        location: kwargs[:location],
        key: kwargs[:key],
        field: kwargs[:field],
        arg: kwargs[:arg],
        list: kwargs[:list] || false,
        federation: kwargs[:federation] || 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,
    boundaries: boundary_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



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

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



173
174
175
# File 'lib/graphql/stitching/supergraph.rb', line 173

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", ...]



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

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



177
178
179
# File 'lib/graphql/stitching/supergraph.rb', line 177

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

#locations_by_typeObject

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



239
240
241
242
243
# File 'lib/graphql/stitching/supergraph.rb', line 239

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



181
182
183
# File 'lib/graphql/stitching/supergraph.rb', line 181

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

#memoized_schema_fields(type_name) ⇒ Object



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

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



185
186
187
# File 'lib/graphql/stitching/supergraph.rb', line 185

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

#possible_keys_for_type(type_name) ⇒ Object

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



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

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
      @boundaries[type_name].map(&:key).tap(&:uniq!)
    end
  end
end

#possible_keys_for_type_and_location(type_name, location) ⇒ Object

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



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

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 boundary queries



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

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 boundary keys and just return a location
    goal_locations.each_with_object({}) do |goal_location, memo|
      memo[goal_location] = [Boundary.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 boundaries for the goal locations.
    @boundaries[type_name].each_with_object({}) do |boundary, memo|
      if goal_locations.include?(boundary.location)
        memo[boundary.location] = [boundary]
      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.



169
170
171
# File 'lib/graphql/stitching/supergraph.rb', line 169

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

#to_definitionObject



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

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 boundaries_for_type = @boundaries.dig(type_name)
      boundaries_for_type.each do |boundary|
        existing = type.directives.find do |d|
          kwargs = d.arguments.keyword_arguments
          d.graphql_name == ResolverDirective.graphql_name &&
            kwargs[:location] == boundary.location &&
            kwargs[:key] == boundary.key &&
            kwargs[:field] == boundary.field &&
            kwargs[:arg] == boundary.arg &&
            kwargs.fetch(:list, false) == boundary.list &&
            kwargs.fetch(:federation, false) == boundary.federation
        end

        type.directive(ResolverDirective, **{
          type_name: (boundary.type_name if boundary.type_name != type_name),
          location: boundary.location,
          key: boundary.key,
          field: boundary.field,
          arg: boundary.arg,
          list: boundary.list || nil,
          federation: boundary.federation || 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