Class: GraphQL::Stitching::Supergraph

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

Overview

Supergraph is the singuar representation of a stitched graph. It provides the combined GraphQL schema and delegation maps used to route selections across subgraph locations.

Defined Under Namespace

Modules: InterfaceType, Visibility Classes: ArgumentType, EnumType, EnumValueType, FieldType, InputObjectType, ObjectType, PathNode, ScalarType, UnionType

Constant Summary collapse

SUPERGRAPH_LOCATION =
"__super"
BASE_TYPES =
{
  enum: EnumType,
  input_object: InputObjectType,
  interface: InterfaceType,
  object: ObjectType,
  scalar: ScalarType,
  union: UnionType,
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Supergraph.



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

def initialize(schema:, fields: {}, resolvers: {}, visibility_profiles: [], executables: {})
  @schema = schema
  @resolvers = resolvers
  @resolvers_by_version = nil
  @fields_by_type_and_location = nil
  @locations_by_type = nil
  @memoized_introspection_types = @schema.introspection_system.types
  @memoized_schema_types = @schema.types
  @memoized_schema_fields = {}
  @possible_keys_by_type = {}
  @possible_keys_by_type_and_location = {}

  # 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

  if visibility_profiles.any?
    profiles = visibility_profiles.each_with_object({ nil => {} }) { |p, m| m[p.to_s] = {} }
    @schema.use(GraphQL::Schema::Visibility, profiles: profiles)
  else
    @schema.use(GraphQL::Schema::AlwaysVisible)
  end
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.



18
19
20
# File 'lib/graphql/stitching/supergraph.rb', line 18

def executables
  @executables
end

#locations_by_type_and_fieldObject (readonly)

Returns the value of attribute locations_by_type_and_field.



23
24
25
# File 'lib/graphql/stitching/supergraph.rb', line 23

def locations_by_type_and_field
  @locations_by_type_and_field
end

#memoized_introspection_typesObject (readonly)

Returns the value of attribute memoized_introspection_types.



22
23
24
# File 'lib/graphql/stitching/supergraph.rb', line 22

def memoized_introspection_types
  @memoized_introspection_types
end

#memoized_schema_typesObject (readonly)

Returns the value of attribute memoized_schema_types.



21
22
23
# File 'lib/graphql/stitching/supergraph.rb', line 21

def memoized_schema_types
  @memoized_schema_types
end

#resolversObject (readonly)

Returns the value of attribute resolvers.



20
21
22
# File 'lib/graphql/stitching/supergraph.rb', line 20

def resolvers
  @resolvers
end

#schemaGraphQL::Schema (readonly)

Returns the composed schema for the supergraph.

Returns:

  • (GraphQL::Schema)

    the composed schema for the supergraph.



15
16
17
# File 'lib/graphql/stitching/supergraph.rb', line 15

def schema
  @schema
end

Class Method Details

.from_definition(schema, executables:) ⇒ Object



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

def from_definition(schema, executables:)
  if schema.is_a?(String)
    schema = if GraphQL::Stitching.supports_visibility?
      GraphQL::Schema.from_definition(schema, base_types: BASE_TYPES)
    else
      GraphQL::Schema.from_definition(schema)
    end
  end

  field_map = {}
  resolver_map = {}
  possible_locations = {}
  visibility_profiles = if (visibility_def = schema.directives[GraphQL::Stitching.visibility_directive])
    visibility_def.get_argument("profiles").default_value
  else
    []
  end

  schema.types.each do |type_name, type|
    next if type.introspection?

    # Collect/build key definitions for each type
    locations_by_key = type.directives.each_with_object({}) do |directive, memo|
      next unless directive.graphql_name == Directives::SupergraphKey.graphql_name

      kwargs = directive.arguments.keyword_arguments
      memo[kwargs[:key]] ||= []
      memo[kwargs[:key]] << kwargs[:location]
    end

    key_definitions = locations_by_key.each_with_object({}) do |(key, locations), memo|
      memo[key] = TypeResolver.parse_key(key, locations)
    end

    # Collect/build resolver definitions for each type
    type.directives.each do |d|
      next unless d.graphql_name == Directives::SupergraphResolver.graphql_name

      kwargs = d.arguments.keyword_arguments
      resolver_map[type_name] ||= []
      resolver_map[type_name] << TypeResolver.new(
        location: kwargs[:location],
        type_name: kwargs.fetch(:type_name, type_name),
        field: kwargs[:field],
        list: kwargs[:list] || false,
        key: key_definitions[kwargs[:key]],
        arguments: TypeResolver.parse_arguments_with_type_defs(kwargs[:arguments], kwargs[:argument_types]),
      )
    end

    next unless type.kind.fields?

    type.fields.each do |field_name, field|
      # Collection locations for each field definition
      field.directives.each do |d|
        next unless d.graphql_name == Directives::SupergraphSource.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,
    visibility_profiles: visibility_profiles,
    executables: executables,
  )
end

.validate_executable!(location, executable) ⇒ Object

Raises:



6
7
8
9
10
# File 'lib/graphql/stitching/supergraph/from_definition.rb', line 6

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



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/graphql/stitching/supergraph.rb', line 98

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.to_h,
      validate: false,
    )
  elsif executable.respond_to?(:call)
    executable.call(request, source, variables)
  else
    raise StitchingError, "Missing valid executable for #{location} location."
  end
end

#fieldsObject



73
74
75
# File 'lib/graphql/stitching/supergraph.rb', line 73

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



119
120
121
122
123
124
125
126
127
128
# File 'lib/graphql/stitching/supergraph.rb', line 119

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



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

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

#locations_by_typeObject

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



131
132
133
134
135
# File 'lib/graphql/stitching/supergraph.rb', line 131

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_schema_fields(type_name) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/graphql/stitching/supergraph.rb', line 81

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

#possible_keys_for_type(type_name) ⇒ Object

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



139
140
141
142
143
144
145
146
147
# File 'lib/graphql/stitching/supergraph.rb', line 139

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).uniq(&:to_definition)
    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") => [Key("id"), ...]



151
152
153
154
155
156
157
158
159
160
# File 'lib/graphql/stitching/supergraph.rb', line 151

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] ||= possible_keys_for_type(type_name).select do |key|
    next true if key.locations.include?(location)

    # Outbound-only locations without resolver queries may dynamically match primitive keys
    location_fields = fields_by_type_and_location[type_name][location] || GraphQL::Stitching::EMPTY_ARRAY
    location_fields.include?(key.primitive_name)
  end
end

#resolvers_by_versionObject



67
68
69
70
71
# File 'lib/graphql/stitching/supergraph.rb', line 67

def resolvers_by_version
  @resolvers_by_version ||= resolvers.values.tap(&:flatten!).each_with_object({}) do |resolver, memo|
    memo[resolver.version] = resolver
  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



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/graphql/stitching/supergraph.rb', line 164

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] = [TypeResolver.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

#to_definition(visibility_profile: nil) ⇒ Object



61
62
63
64
65
# File 'lib/graphql/stitching/supergraph.rb', line 61

def to_definition(visibility_profile: nil)
  @schema.to_definition(context: { 
    visibility_profile: visibility_profile,
  }.tap(&:compact!))
end