Skip to content

Commit 2e4ec15

Browse files
authored
Merge pull request rmosolgo#4994 from igorbelo/fix/4993-fiber-local-variables-are-not-copied-when-using-async-dataloader
Copy Fiber-local variables over to sources when using AsyncDataloader
2 parents 7caaa24 + 0b422af commit 2e4ec15

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/graphql/dataloader/async_dataloader.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ def run
2121
manager = spawn_fiber do
2222
while first_pass || job_fibers.any?
2323
first_pass = false
24+
fiber_vars = get_fiber_variables
2425

2526
while (f = (job_fibers.shift || spawn_job_fiber))
2627
if f.alive?
@@ -34,6 +35,7 @@ def run
3435
next_job_fibers.clear
3536

3637
Sync do |root_task|
38+
set_fiber_variables(fiber_vars)
3739
while source_tasks.any? || @source_cache.each_value.any? { |group_sources| group_sources.each_value.any?(&:pending?) }
3840
while (task = source_tasks.shift || spawn_source_task(root_task, sources_condition))
3941
if task.alive?

spec/graphql/dataloader/async_dataloader_spec.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ def fetch(keys)
5252
end
5353
end
5454

55+
class FiberLocalContextSource < GraphQL::Dataloader::Source
56+
def fetch(keys)
57+
keys.map { |key| Thread.current[key] }
58+
end
59+
end
60+
5561
class Sleeper < GraphQL::Schema::Object
5662
field :sleeper, Sleeper, null: false, resolver_method: :sleep do
5763
argument :duration, Float
@@ -126,6 +132,13 @@ def list_waiters(wait:, tags:)
126132
Kernel.sleep(0.1)
127133
tags.map { |t| { tag: t, wait: wait }}
128134
end
135+
136+
field :fiber_local_context, String do
137+
argument :key, String
138+
end
139+
def fiber_local_context(key:)
140+
dataloader.with(FiberLocalContextSource).load(key)
141+
end
129142
end
130143

131144
query(Query)
@@ -273,6 +286,20 @@ def self.included(child_class)
273286
assert_in_delta 0.3, t2 - t1, 0.06, "Wait was parallel"
274287
assert_equal [["a", "b", "c"]], AsyncSchema::KeyWaitForSource.fetches, "All keys were fetched at once"
275288
end
289+
290+
it 'copies fiber-local variables over to sources' do
291+
key = 'arbitrary_context'
292+
value = 'test'
293+
Thread.current[key] = value
294+
query_str = <<-GRAPHQL
295+
{
296+
fiberLocalContext(key: "#{key}")
297+
}
298+
GRAPHQL
299+
300+
result = AsyncSchema.execute(query_str)
301+
assert_equal value, result['data']['fiberLocalContext']
302+
end
276303
end
277304
end
278305
end

0 commit comments

Comments
 (0)