Skip to content

Commit

Permalink
Fix slot range calculation. (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix authored Aug 22, 2024
1 parent 6a75f89 commit a7d3b3f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
9 changes: 9 additions & 0 deletions cluster/test/async/redis/cluster_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,13 @@

expect(result).to be == value
end

it "can map every slot to a client" do
clients = Async::Redis::ClusterClient::HASH_SLOTS.times.map do |slot|
client = cluster.client_for(slot)
end.uniq

expect(clients.size).to be == 3
expect(clients).not.to have_value(be_nil)
end
end
17 changes: 11 additions & 6 deletions lib/async/redis/cluster_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ class ClusterClient
class ReloadError < StandardError
end

class SlotError < StandardError
end

Node = Struct.new(:id, :endpoint, :role, :health, :client)

class RangeMap
Expand Down Expand Up @@ -84,9 +87,11 @@ def client_for(slot, role = :master)
reload_cluster!
end

nodes = @shards.find(slot)

nodes = nodes.select{|node| node.role == role}
if nodes = @shards.find(slot)
nodes = nodes.select{|node| node.role == role}
else
raise SlotError, "No nodes found for slot #{slot}"
end

if node = nodes.sample
return (node.client ||= Client.new(node.endpoint))
Expand All @@ -106,7 +111,7 @@ def reload_cluster!(endpoints = @endpoints)
shard = shard.each_slice(2).to_h

slots = shard['slots']
range = Range.new(*slots, exclude_end: false)
range = Range.new(*slots)

nodes = shard['nodes'].map do |node|
node = node.each_slice(2).to_h
Expand Down Expand Up @@ -179,10 +184,10 @@ def crc16(bytes)
return sum
end

HASH_SLOTS = 16_384

public

HASH_SLOTS = 16_384

# Return Redis::Client for a given key.
# Modified from https://github.com/antirez/redis-rb-cluster/blob/master/cluster.rb#L104-L117
def slot_for(key)
Expand Down

0 comments on commit a7d3b3f

Please sign in to comment.