Skip to content

Commit 06643dd

Browse files
authored
fix: race condition for command cache (#145)
1 parent b217e32 commit 06643dd

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

lib/redis_client/cluster/normalized_cmd_name.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,12 @@ def extract_name_from_array(command, index:)
5757
end
5858

5959
def normalize(name)
60-
return @cache[name] if @cache.key?(name)
60+
return @cache[name] || name.to_s.downcase if @cache.key?(name)
6161
return name.to_s.downcase if @mutex.locked?
6262

63-
@mutex.synchronize { @cache[name] = name.to_s.downcase }
64-
@cache[name]
63+
str = name.to_s.downcase
64+
@mutex.synchronize { @cache[name] = str }
65+
str
6566
end
6667
end
6768
end

test/redis_client/cluster/test_normalized_cmd_name.rb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,20 @@ def test_get_by_name
6363
end
6464

6565
def test_thread_safety
66-
attempts = Array.new(100, true)
66+
attempts = Array.new(100, 'dummy')
67+
6768
threads = attempts.each_with_index.map do |_, i|
6869
Thread.new do
6970
Thread.pass
7071
Thread.current.thread_variable_set(:index, i)
7172
got = if i.even?
72-
@subject.get_by_command(%w[SET foo bar]) == 'set'
73+
@subject.get_by_command(%w[SET foo bar])
7374
else
74-
@subject.clear
75+
@subject.clear ? 'set' : 'clear failed'
7576
end
7677
Thread.current.thread_variable_set(:got, got)
77-
rescue StandardError
78-
Thread.current.thread_variable_set(:got, false)
78+
rescue StandardError => e
79+
Thread.current.thread_variable_set(:got, "#{e.class.name}: #{e.message}")
7980
end
8081
end
8182

@@ -84,8 +85,7 @@ def test_thread_safety
8485
attempts[t.thread_variable_get(:index)] = t.thread_variable_get(:got)
8586
end
8687

87-
refute_includes(attempts, false)
88-
refute_includes(attempts, nil)
88+
attempts.each { |got| assert_equal('set', got) }
8989
end
9090
end
9191
end

0 commit comments

Comments
 (0)