Class: GraphQL::Dataloader

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/dataloader.rb,
lib/graphql/dataloader/source.rb,
lib/graphql/dataloader/request.rb,
lib/graphql/dataloader/request_all.rb,
lib/graphql/dataloader/null_dataloader.rb,
lib/graphql/dataloader/async_dataloader.rb,
lib/graphql/dataloader/active_record_source.rb,
lib/graphql/dataloader/active_record_association_source.rb

Overview

This plugin supports Fiber-based concurrency, along with GraphQL::Dataloader::Source.

Examples

Example: Installing Dataloader

class MySchema < GraphQL::Schema
  use GraphQL::Dataloader
end

Example: Waiting for batch-loaded data in a GraphQL field

field :team, Types::Team, null: true

def team
  dataloader.with(Sources::Record, Team).load(object.team_id)
end

Defined Under Namespace

Classes: ActiveRecordAssociationSource, ActiveRecordSource, AsyncDataloader, NullDataloader, Request, RequestAll, Source

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nonblocking: self.class.default_nonblocking, fiber_limit: self.class.default_fiber_limit) ⇒ Dataloader

Returns a new instance of Dataloader.



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/graphql/dataloader.rb', line 67

def initialize(nonblocking: self.class.default_nonblocking, fiber_limit: self.class.default_fiber_limit)
  @source_cache = Hash.new { |h, k| h[k] = {} }.compare_by_identity
  @pending_source_set = Set.new.compare_by_identity
  @pending_sources = []
  @pending_jobs = []
  if !nonblocking.nil?
    @nonblocking = nonblocking
  end
  @fiber_limit = fiber_limit
  @lazies_at_depth = Hash.new { |h, k| h[k] = [] }
end

Class Attribute Details

.default_fiber_limit ⇒ Object

Returns the value of attribute default_fiber_limit.



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

def default_fiber_limit
  @default_fiber_limit
end

.default_nonblocking ⇒ Object

Returns the value of attribute default_nonblocking.



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

def default_nonblocking
  @default_nonblocking
end

Instance Attribute Details

#fiber_limit ⇒ Object (readonly)

Returns

  • Integer, nil


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

def fiber_limit
  @fiber_limit
end

Class Method Details

.use(schema, nonblocking: nil, fiber_limit: nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/graphql/dataloader.rb', line 39

def self.use(schema, nonblocking: nil, fiber_limit: nil)
  dataloader_class = if nonblocking
    warn("`nonblocking: true` is deprecated from `GraphQL::Dataloader`, please use `GraphQL::Dataloader::AsyncDataloader` instead. Docs: https://graphql-ruby.org/dataloader/async_dataloader.")
    Class.new(self) { self.default_nonblocking = true }
  else
    self
  end

  if fiber_limit
    dataloader_class = Class.new(dataloader_class)
    dataloader_class.default_fiber_limit = fiber_limit
  end

  schema.dataloader_class = dataloader_class
end

.with_dataloading(&block) ⇒ Object

Call the block with a Dataloader instance, then run all enqueued jobs and return the result of the block.



57
58
59
60
61
62
63
64
65
# File 'lib/graphql/dataloader.rb', line 57

def self.with_dataloading(&block)
  dataloader = self.new
  result = nil #: untyped
  dataloader.append_job {
    result = block.call(dataloader)
  }
  dataloader.run
  result
end

Instance Method Details

#append_job(callable = nil, &job) ⇒ Object

:nodoc:



177
178
179
180
181
182
# File 'lib/graphql/dataloader.rb', line 177

def append_job(callable = nil, &job) # :nodoc:
  # Given a block, queue it up to be worked through when `#run` is called.
  # (If the dataloader is already running, then a Fiber will pick this up later.)
  @pending_jobs.push(callable || job)
  nil
end

#cleanup_fiber ⇒ Object

This method is called when Dataloader is finished using a fiber. Use it to perform any cleanup, such as releasing database connections (if required manually)



126
127
# File 'lib/graphql/dataloader.rb', line 126

def cleanup_fiber
end

#clear_cache ⇒ Object

Clear any already-loaded objects from Source caches

Returns

  • void

:call-seq:

clear_cache() -> void


199
200
201
202
203
204
# File 'lib/graphql/dataloader.rb', line 199

def clear_cache
  @source_cache.each do |_source_class, batched_sources|
    batched_sources.each_value(&:clear_cache)
  end
  nil
end

#get_fiber_variables ⇒ Object

This is called before the fiber is spawned, from the parent context (i.e. from the thread or fiber that it is scheduled from).

Returns

  • Hash<Symbol, Object> — Current fiber-local variables

:call-seq:

get_fiber_variables() -> Hash[Symbol, Object]


97
98
99
100
101
102
103
# File 'lib/graphql/dataloader.rb', line 97

def get_fiber_variables
  fiber_vars = {}
  Thread.current.keys.each do |fiber_var_key|
    fiber_vars[fiber_var_key] = Thread.current[fiber_var_key]
  end
  fiber_vars
end

#lazy_at_depth(depth, lazy) ⇒ Object

:nodoc:



300
301
302
# File 'lib/graphql/dataloader.rb', line 300

def lazy_at_depth(depth, lazy) # :nodoc:
  @lazies_at_depth[depth] << lazy
end

#merge_records(records, index_by: :id) ⇒ Object

Pre-warm the Dataloader cache with ActiveRecord objects which were loaded elsewhere. These will be used by Dataloader::ActiveRecordSource, Dataloader::ActiveRecordAssociationSource and their helper methods, dataload_record and dataload_association.

Parameters

  • records (Array<ActiveRecord::Base>) — Already-loaded records to warm the cache with
  • index_by (Symbol) — The attribute to use as the cache key. (Should match find_by: when using ActiveRecordSource)

Returns

  • void

:call-seq:

merge_records(Array[ActiveRecord::Base] records, Symbol index_by:) -> void


331
332
333
334
335
336
337
338
339
# File 'lib/graphql/dataloader.rb', line 331

def merge_records(records, index_by: :id)
  records_by_class = Hash.new { |h, k| h[k] = {} }
  records.each do |r|
    records_by_class[r.class][r.public_send(index_by)] = r
  end
  records_by_class.each do |r_class, records|
    with(ActiveRecordSource, r_class).merge(records)
  end
end

#nonblocking? ⇒ Boolean

Returns:

  • (Boolean)


84
85
86
# File 'lib/graphql/dataloader.rb', line 84

def nonblocking?
  @nonblocking
end

#queue_pending_source(source) ⇒ Object

:nodoc:



184
185
186
187
188
189
# File 'lib/graphql/dataloader.rb', line 184

def queue_pending_source(source) # :nodoc:
  if @pending_source_set.add?(source)
    @pending_sources << source
  end
  nil
end

#run(trace_query_lazy: nil) ⇒ Object

Parameters

  • trace_query_lazy (nil, Execution::Multiplex)

:call-seq:

run(nil | Execution::Multiplex trace_query_lazy:)


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
# File 'lib/graphql/dataloader.rb', line 251

def run(trace_query_lazy: nil)
  trace = Fiber[:__graphql_current_multiplex]&.current_trace
  jobs_fiber_limit, total_fiber_limit = calculate_fiber_limit
  job_fibers = []
  next_job_fibers = []
  source_fibers = []
  next_source_fibers = []
  first_pass = true #: bool
  manager = spawn_fiber do
    trace&.begin_dataloader(self)
    while first_pass || !job_fibers.empty?
      first_pass = false

      run_pending_steps(trace, job_fibers, next_job_fibers, jobs_fiber_limit, source_fibers, next_source_fibers, total_fiber_limit)

      if !@lazies_at_depth.empty?
        with_trace_query_lazy(trace_query_lazy) do
          if enqueue_next_pending_lazies(@lazies_at_depth)
            job_fibers.unshift(spawn_job_fiber(trace))
            run_pending_steps(trace, job_fibers, next_job_fibers, jobs_fiber_limit, source_fibers, next_source_fibers, total_fiber_limit)
          end
        end
      end
    end

    trace&.end_dataloader(self)
  end

  run_fiber(manager)

  if manager.alive?
    raise "Invariant: Manager fiber didn't terminate properly."
  end

  if !job_fibers.empty?
    raise "Invariant: job fibers should have exited but #{job_fibers.size} remained"
  end
  if !source_fibers.empty?
    raise "Invariant: source fibers should have exited but #{source_fibers.size} remained"
  end

rescue UncaughtThrowError => e
  throw e.tag, e.value
end

#run_fiber(f) ⇒ Object



296
297
298
# File 'lib/graphql/dataloader.rb', line 296

def run_fiber(f)
  f.resume
end

#run_isolated ⇒ Object

Use a self-contained queue for the work in the block.



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
# File 'lib/graphql/dataloader.rb', line 207

def run_isolated
  prev_queue = @pending_jobs
  prev_pending_keys = {}
  prev_lazies_at_depth = @lazies_at_depth
  @lazies_at_depth = @lazies_at_depth.dup.clear
  # Clear pending loads but keep already-cached records
  # in case they are useful to the given block.
  @source_cache.each do |source_class, batched_sources|
    batched_sources.each do |batch_args, batched_source_instance|
      if batched_source_instance.pending?
        prev_pending_keys[batched_source_instance] = batched_source_instance.pending.dup
        batched_source_instance.pending.clear
      end
    end
  end

  @pending_jobs = []
  res = nil #: untyped
  # Make sure the block is inside a Fiber, so it can `Fiber.yield`
  append_job {
    res = yield
  }
  run
  res
ensure
  @pending_jobs = prev_queue
  @lazies_at_depth = prev_lazies_at_depth
  prev_pending_keys #: as !nil
    .each do |source_instance, pending|
    pending.each do |key, value|
      next if source_instance.results.key?(key)

      queue_pending_source(source_instance) if source_instance.pending.empty?
      source_instance.pending[key] = value
    end
  end
end

#set_fiber_variables(vars) ⇒ Object

Set up the fiber variables in a new fiber.

This is called within the fiber, right after it is spawned.

Parameters

Returns

  • void

:call-seq:

set_fiber_variables(Hash[Symbol, Object] vars) -> void


119
120
121
122
# File 'lib/graphql/dataloader.rb', line 119

def set_fiber_variables(vars)
  vars.each { |k, v| Thread.current[k] = v }
  nil
end

#spawn_fiber ⇒ Object



304
305
306
307
308
309
310
311
312
313
314
# File 'lib/graphql/dataloader.rb', line 304

def spawn_fiber
  fiber_vars = get_fiber_variables
  Fiber.new(blocking: !@nonblocking) do
    # Fibers inherit the spawning fiber's storage; give each one its own execution state.
    Fiber[:__graphql_runtime_info] = nil
    set_fiber_variables(fiber_vars)
    yield
  ensure
    cleanup_fiber
  end
end

#with(source_class, *batch_args, **batch_kwargs) ⇒ Object



150
151
152
153
154
155
156
157
# File 'lib/graphql/dataloader.rb', line 150

def with(source_class, *batch_args, **batch_kwargs)
  batch_key = source_class.batch_key_for(*batch_args, **batch_kwargs)
  @source_cache[source_class][batch_key] ||= begin
    source = source_class.new(*batch_args, **batch_kwargs)
    source.setup(self)
    source
  end
end

#yield(source = ) ⇒ Object

Tell the dataloader that this fiber is waiting for data.

Dataloader will resume the fiber after the requested data has been loaded (by another Fiber).

Returns

  • void

:call-seq:

yield(source:) -> void


169
170
171
172
173
174
175
# File 'lib/graphql/dataloader.rb', line 169

def yield(source = Fiber[:__graphql_current_dataloader_source])
  trace = Fiber[:__graphql_current_multiplex]&.current_trace
  trace&.dataloader_fiber_yield(source)
  Fiber.yield
  trace&.dataloader_fiber_resume(source)
  nil
end