Class: GraphQL::Execution::FieldResolveStep

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/execution/field_resolve_step.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent_type:, runner:, key:, selections_step:) ⇒ FieldResolveStep

Returns a new instance of FieldResolveStep.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/graphql/execution/field_resolve_step.rb', line 5

def initialize(parent_type:, runner:, key:, selections_step:)
  @selections_step = selections_step
  @key = key
  @parent_type = parent_type
  @ast_node = @ast_nodes = nil
  @runner = runner
  @field_definition = nil
  @arguments = nil
  @field_results = nil
  @path = nil
  @enqueued_authorization = false
  @all_next_objects = nil
  @all_next_results = nil
  @static_type = nil
  @next_selections = nil
  @results = nil
  @finish_extension_idx = nil
  @was_scoped = nil
  @pending_steps = nil
  @post_processors = @directive_finalizers = nil
end

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments.



30
31
32
# File 'lib/graphql/execution/field_resolve_step.rb', line 30

def arguments
  @arguments
end

#ast_nodeObject (readonly)

Returns the value of attribute ast_node.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def ast_node
  @ast_node
end

#field_definitionObject (readonly)

Returns the value of attribute field_definition.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def field_definition
  @field_definition
end

#field_resultsObject (readonly)

Returns the value of attribute field_results.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def field_results
  @field_results
end

#keyObject (readonly)

Returns the value of attribute key.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def key
  @key
end

#object_is_authorizedObject (readonly)

Returns the value of attribute object_is_authorized.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def object_is_authorized
  @object_is_authorized
end

#parent_typeObject (readonly)

Returns the value of attribute parent_type.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def parent_type
  @parent_type
end

#pending_stepsObject

Returns the value of attribute pending_steps.



30
31
32
# File 'lib/graphql/execution/field_resolve_step.rb', line 30

def pending_steps
  @pending_steps
end

#runnerObject (readonly)

Returns the value of attribute runner.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def runner
  @runner
end

#selections_stepObject (readonly)

Returns the value of attribute selections_step.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def selections_step
  @selections_step
end

#static_typeObject

Returns the value of attribute static_type.



30
31
32
# File 'lib/graphql/execution/field_resolve_step.rb', line 30

def static_type
  @static_type
end

#was_scopedObject (readonly)

Returns the value of attribute was_scoped.



27
28
29
# File 'lib/graphql/execution/field_resolve_step.rb', line 27

def was_scoped
  @was_scoped
end

Instance Method Details

#add_graphql_error(err) ⇒ Object



99
100
101
102
103
104
# File 'lib/graphql/execution/field_resolve_step.rb', line 99

def add_graphql_error(err)
  err.path = path
  err.ast_nodes = ast_nodes
  @selections_step.query.context.add_error(err)
  err
end

#add_non_null_error(is_from_array) ⇒ Object



471
472
473
474
# File 'lib/graphql/execution/field_resolve_step.rb', line 471

def add_non_null_error(is_from_array)
  err = InvalidNullError.new(@parent_type, @field_definition, ast_nodes, is_from_array: is_from_array, path: path)
  @runner.schema.type_error(err, @selections_step.query.context)
end

#any_lazy_results?Boolean

Returns:

  • (Boolean)


277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/graphql/execution/field_resolve_step.rb', line 277

def any_lazy_results?
  lazies = false
  if @runner.resolves_lazies # TODO extract this
    @field_results.each do |field_result|
      if @runner.lazy?(field_result)
        lazies = true
        break
      elsif field_result.is_a?(Array)
        field_result.each do |inner_fr|
          if @runner.lazy?(inner_fr)
            break lazies = true
          end
        end
        if lazies
          break
        end
      end
    end
  end
  lazies
end

#append_selection(ast_node) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/graphql/execution/field_resolve_step.rb', line 40

def append_selection(ast_node)
  if @ast_node.nil?
    @ast_node = ast_node
  elsif @ast_nodes.nil?
    @ast_nodes = [@ast_node, ast_node]
  else
    @ast_nodes << ast_node
  end
  nil
end

#ast_nodesObject



36
37
38
# File 'lib/graphql/execution/field_resolve_step.rb', line 36

def ast_nodes
  @ast_nodes ||= [@ast_node]
end

#authorized_finished(step) ⇒ Object



464
465
466
467
468
469
# File 'lib/graphql/execution/field_resolve_step.rb', line 464

def authorized_finished(step)
  @pending_steps.delete(step)
  if @enqueued_authorization && @pending_steps.size == 0
    @runner.add_step(self)
  end
end

#build_argumentsObject



106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/graphql/execution/field_resolve_step.rb', line 106

def build_arguments
  query = @selections_step.query
  field_name = @ast_node.name
  @field_definition = query.types.field(@parent_type, field_name) || raise("Invariant: no field found for #{@parent_type.to_type_signature}.#{ast_node.name}")
  arguments = @runner.input_values[query].argument_values(@field_definition, @ast_node.arguments, self) # rubocop:disable Development/ContextIsPassedCop
  @arguments ||= arguments # may have already been set to an error

  if (@pending_steps.nil? || @pending_steps.size == 0) &&
      @field_results.nil? # Make sure the arguments flow didn't already call through
    execute_field
  end
end

#build_resultsObject



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
# File 'lib/graphql/execution/field_resolve_step.rb', line 340

def build_results
  return_type = @field_definition.type
  return_result_type = return_type.unwrap

  @post_processors&.each do |post_processor|
    @field_results = post_processor.after_resolve(@field_results)
  end

  if return_result_type.kind.composite?
    @static_type = return_result_type
    if @ast_nodes
      @next_selections = []
      @ast_nodes.each do |ast_node|
        @next_selections.concat(ast_node.selections)
      end
    else
      @next_selections = @ast_node.selections
    end

    @all_next_objects = []
    @all_next_results = []

    is_list = return_type.list?
    is_non_null = return_type.non_null?
    i = 0
    s = @results.size
    while i < s do
      result_h = @results[i]
      result = @field_results[i]
      i += 1
      build_graphql_result(result_h, @key, result, return_type, is_non_null, is_list, false)
    end
    @enqueued_authorization = true

    if @pending_steps.nil? || @pending_steps.size == 0
      enqueue_next_steps
    else
      # Do nothing -- it will enqueue itself later
    end
  else
    ctx = @selections_step.query.context
    i = 0
    s = @results.size
    while i < s do
      result_h = @results[i]
      field_result = @field_results[i]
      i += 1
      finish_leaf_result(result_h, @key, field_result, return_type, ctx)
    end
  end
end

#callObject



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/graphql/execution/field_resolve_step.rb', line 78

def call
  if @enqueued_authorization
    enqueue_next_steps
  elsif @finish_extension_idx
    finish_extensions
  elsif @field_results
    build_results
  elsif @arguments
    execute_field
  else
    build_arguments
  end
rescue StandardError => err
  if @field_definition && !err.message.start_with?("Resolving ")
    # TODO remove this check ^^^^^^ when NullDataloader isn't recursive
    raise err, "Resolving #{@field_definition.path}: #{err.message}", err.backtrace
  else
    raise
  end
end

#enqueue_next_stepsObject



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
# File 'lib/graphql/execution/field_resolve_step.rb', line 415

def enqueue_next_steps
  if !@all_next_results.empty?
    @all_next_objects.compact!

    query = @selections_step.query
    ctx = query.context
    if @static_type.kind.abstract?
      next_objects_by_type = Hash.new { |h, obj_t| h[obj_t] = [] }.compare_by_identity
      next_results_by_type = Hash.new { |h, obj_t| h[obj_t] = [] }.compare_by_identity

      @all_next_objects.each_with_index do |next_object, i|
        result = @all_next_results[i]
        if (object_type = @runner.runtime_type_at[result])
          # OK
        else
          object_type = @runner.resolve_type(@static_type, next_object, query)
          @runner.runtime_type_at[result] = object_type
        end
        next_objects_by_type[object_type] << next_object
        next_results_by_type[object_type] << result
      end

      next_objects_by_type.each do |obj_type, next_objects|
        query.current_trace.objects(obj_type, next_objects, ctx)
        @runner.add_step(SelectionsStep.new(
          path: path,
          parent_type: obj_type,
          selections: @next_selections,
          objects: next_objects,
          results: next_results_by_type[obj_type],
          runner: @runner,
          query: query,
        ))
      end
    else
      query.current_trace.objects(@static_type, @all_next_objects, ctx)
      @runner.add_step(SelectionsStep.new(
        path: path,
        parent_type: @static_type,
        selections: @next_selections,
        objects: @all_next_objects,
        results: @all_next_results,
        runner: @runner,
        query: query,
      ))
    end
  end
end

#execute_fieldObject



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
# File 'lib/graphql/execution/field_resolve_step.rb', line 119

def execute_field
  objects = @selections_step.objects
  @results = @selections_step.results
  # TODO not as good because only one error?
  if @arguments.is_a?(GraphQL::RuntimeError)
    @field_results = Array.new(objects.size, @arguments)
    build_results
    return
  end

  query = @selections_step.query
  ctx = query.context
  if (v = @field_definition.validators).any?  # rubocop:disable Development/NoneWithoutBlockCop
    begin
      Schema::Validator.validate!(v, nil, ctx, @arguments)
    rescue GraphQL::RuntimeError => err
      @field_results = Array.new(objects.size, err)
      build_results
      return
    end
  end

  @field_definition.extras.each do |extra|
    case extra
    when :lookahead
      if @arguments.frozen?
        @arguments = @arguments.dup
      end
      @arguments[:lookahead] = Execution::Lookahead.new(
        query: query,
        ast_nodes: ast_nodes,
        field: @field_definition,
      )
    when :ast_node
      if @arguments.frozen?
        @arguments = @arguments.dup
      end
      @arguments[:ast_node] = ast_node
    else
      raise ArgumentError, "This `extra` isn't supported yet: #{extra.inspect}. Open an issue on GraphQL-Ruby to add compatibility for it."
    end
  end

  if @field_definition.dynamic_introspection
    # TODO break this backwards compat somehow?
    objects = @selections_step.graphql_objects
  end

  if @runner.authorization && @runner.authorizes?(@field_definition, ctx)
    authorized_objects = []
    authorized_results = []
    l = objects.size
    i = 0
    while i < l
      o = objects[i]
      if @field_definition.authorized?(o, @arguments, ctx)
        authorized_results << @results[i]
        authorized_objects << o
      else
        begin
          err = GraphQL::UnauthorizedFieldError.new(object: o, type: @parent_type, context: ctx, field: @field_definition)
          authorized_objects << query.schema.unauthorized_object(err)
          authorized_results << @results[i]
        rescue GraphQL::ExecutionError => exec_err
          add_graphql_error(exec_err)
        end
      end
      i += 1
    end

    if authorized_objects.size == 0
      return
    end
    @results = authorized_results
  else
    authorized_objects = objects
  end

  if @parent_type.default_relay? && authorized_objects.all? { |o| o.respond_to?(:was_authorized_by_scope_items?) && o.was_authorized_by_scope_items? }
    @was_scoped = true
  end

  query.current_trace.begin_execute_field(@field_definition, @arguments, authorized_objects, query)

  if @runner.uses_runtime_directives
    if @ast_nodes.nil? || @ast_nodes.size == 1
      directives = if !@ast_node.directives.empty?
        @ast_node.directives
      else
        nil
      end
    else
      directives = nil
      @ast_nodes.each do |n|
        if (d = n.directives).any? # rubocop:disable Development/NoneWithoutBlockCop
          directives ||= []
          directives.concat(d)
        end
      end
    end

    if directives
      directives.each do |dir_node|
        if (dir_defn = @runner.runtime_directives[dir_node.name])
          # TODO: `coerce_arguments` modifies self, assuming it's field arguments. Extract to pure function for use
          # here and with fragments.
          dir_args = @runner.input_values[query].argument_values(dir_defn, dir_node.arguments, nil)  # rubocop:disable Development/ContextIsPassedCop
          result = dir_defn.resolve_field(ast_nodes, @parent_type, field_definition, authorized_objects, dir_args, ctx)
          if !result.nil?
            if result.is_a?(Finalizer)
              result.path = path
              @directive_finalizers ||= []
              @directive_finalizers << result
            end

            if result.is_a?(PostProcessor)
              @post_processors ||= []
              @post_processors << result
            end

            if result.is_a?(HaltExecution)
              @directive_finalizers&.each { |f|
                @selections_step.results.each { |r|  @runner.add_finalizer(query, r, key, f) }
              }
              return
            end
          end
        end
      end
    end
  end

  has_extensions = @field_definition.extensions.size > 0
  if has_extensions
    @extended = GraphQL::Schema::Field::ExtendedState.new(@arguments, authorized_objects)
    @field_results = @field_definition.run_next_extensions_before_resolve(authorized_objects, @arguments, ctx, @extended) do |objs, args|
      if (added_extras = @extended.added_extras)
        args = args.dup
        added_extras.each { |e| args.delete(e) }
      end
      resolve_batch(objs, ctx, args)
    end
    @finish_extension_idx = 0
  else
    @field_results = resolve_batch(authorized_objects, ctx, @arguments)
  end

  query.current_trace.end_execute_field(@field_definition, @arguments, authorized_objects, query, @field_results)

  if any_lazy_results?
    @runner.dataloader.lazy_at_depth(path.size, self)
  elsif has_extensions
    finish_extensions
  elsif @pending_steps.nil? || @pending_steps.empty?
    build_results
  end
end

#finish_extensionsObject



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
# File 'lib/graphql/execution/field_resolve_step.rb', line 299

def finish_extensions
  ctx = @selections_step.query.context
  memos = @extended.memos || EmptyObjects::EMPTY_HASH
  while ext = @field_definition.extensions[@finish_extension_idx]
    # These two are hardcoded here because of how they need to interact with runtime metadata.
    # It would probably be better
    case ext
    when Schema::Field::ConnectionExtension
      conns = ctx.schema.connections
      @field_results.map!.each_with_index do |value, idx|
        object = @extended.object[idx]
        conn = conns.populate_connection(@field_definition, object, value, @arguments, ctx)
        if conn
          conn.was_authorized_by_scope_items = @was_scoped
        end
        conn
      end
    when Schema::Field::ScopeExtension
      if @was_scoped.nil?
        if (rt = @field_definition.type.unwrap).respond_to?(:scope_items)
          @was_scoped = true
          @field_results.map! { |v| v.nil? ? v : rt.scope_items(v, ctx) }
        else
          @was_scoped = false
        end
      end
    else
      memo = memos[@finish_extension_idx]
      @field_results = ext.after_resolve(objects: @extended.object, arguments: @extended.arguments, context: ctx, values: @field_results, memo: memo) # rubocop:disable Development/ContextIsPassedCop
    end
    @finish_extension_idx += 1
    if any_lazy_results?
      @runner.dataloader.lazy_at_depth(path.size, self)
      return
    end
  end

  @finish_extension_idx = nil
  build_results
end

#finish_leaf_result(result_h, key, field_result, return_type, ctx) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/graphql/execution/field_resolve_step.rb', line 392

def finish_leaf_result(result_h, key, field_result, return_type, ctx)
  final_field_result = if field_result.nil?
    if return_type.non_null?
      add_non_null_error(false)
    else
      nil
    end
  elsif field_result.is_a?(Finalizer)
    if field_result.is_a?(GraphQL::RuntimeError)
      add_graphql_error(field_result)
    else
      field_result.path = path
      @runner.add_finalizer(ctx.query, result_h, key, field_result)
    end
  else
    # TODO `nil`s in [T!] types aren't handled
    return_type.coerce_result(field_result, ctx)
  end

  @directive_finalizers&.each { |f| @runner.add_finalizer(ctx.query, result_h, key, f) }
  result_h[@key] = final_field_result
end

#pathObject



32
33
34
# File 'lib/graphql/execution/field_resolve_step.rb', line 32

def path
  @path ||= [*@selections_step.path, @key].freeze
end

#sync(lazy) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/graphql/execution/field_resolve_step.rb', line 60

def sync(lazy)
  if lazy.is_a?(Array)
    lazy.map! { |l| sync(l)}
  else
    @runner.schema.sync_lazy(lazy)
  end
rescue GraphQL::UnauthorizedError => auth_err
  @runner.schema.unauthorized_object(auth_err)
rescue GraphQL::ExecutionError => err
  err
rescue StandardError => stderr
  begin
    @selections_step.query.handle_or_reraise(stderr)
  rescue GraphQL::ExecutionError => ex_err
    ex_err
  end
end

#valueObject



51
52
53
54
55
56
57
58
# File 'lib/graphql/execution/field_resolve_step.rb', line 51

def value
  query = @selections_step.query
  query.current_trace.begin_execute_field(@field_definition, @arguments, @field_results, query)
  sync(@field_results)
  query.current_trace.end_execute_field(@field_definition, @arguments, @field_results, query, @field_results)
  @runner.add_step(self)
  true
end