Skip to content

Commit

Permalink
Merge pull request #35 from tariq1890/master
Browse files Browse the repository at this point in the history
Removed duplicated code and added a few unit tests.
  • Loading branch information
shawnfeldman authored Oct 30, 2017
2 parents 82f783c + 07acf53 commit 10158d3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 34 deletions.
25 changes: 8 additions & 17 deletions hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,18 @@ import (
)

func Hash(key CompositeKey) int32 {
mask := 32 - 16 - key.Bits
if key.DocID != "" {
hashes := []int32{
int32(murmur3.Sum32([]byte(key.ShardKey))),
int32(murmur3.Sum32([]byte(key.DocID))),
}
masks := []int32{
-1 << mask, // -10000000000000000
65535, // 1111111111111111
}
return (hashes[0] & masks[0]) | (hashes[1] & masks[1])
}
hashes := []int32{
int32(murmur3.Sum32([]byte(key.ShardKey))),
int32(0),
}

mask := 16 - key.Bits
masks := []int32{
-1 << mask, // -10000000000000000
65535, // 1111111111111111
}
hashes := make([]int32, 2)
hashes[0] = int32(murmur3.Sum32([]byte(key.ShardKey)))
if key.DocID != "" {
hashes[1] = int32(murmur3.Sum32([]byte(key.DocID)))
} else {
hashes[1] = int32(0)
}
return (hashes[0] & masks[0]) | (hashes[1] & masks[1])
}

Expand Down
32 changes: 32 additions & 0 deletions hash_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package solr

import (
"testing"
)

func TestHash(t *testing.T) {
t.Run("Test Hash with Doc ID", func(t *testing.T) {
expected := int32(-1530595841)
c := CompositeKey{
ShardKey: "foobar",
DocID: "123",
Bits: 16,
}
hash := Hash(c)
if hash != expected {
t.Errorf("Error in TestHash. Expected %d but got %d", expected, hash)
}
})

t.Run("Test Hash without Doc ID", func(t *testing.T) {
expected := int32(-1530604355)
c := CompositeKey{
ShardKey: "foobar",
Bits: 16,
}
hash := Hash(c)
if hash != expected {
t.Errorf("Error in TestHash. Expected %d but got %d", expected, hash)
}
})
}
22 changes: 5 additions & 17 deletions solr_leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,14 @@ func findShard(key string, cs *Collection) (*Shard, error) {
}

func findReplicas(key string, cs *Collection) (map[string]Replica, error) {
composite, err := NewCompositeKey(key)
replicas := make(map[string]Replica)
shard, err := findShard(key, cs)
if err != nil {
return nil, err
}
shardKeyHash := Hash(composite)
replicas := make(map[string]Replica)
for _, shard := range cs.Shards {
if isShardActive(&shard) {
hashRange, err := ConvertToHashRange(shard.Range)
if err != nil {
return nil, err
}
if shardKeyHash >= hashRange.Low && shardKeyHash <= hashRange.High {
for k, v := range shard.Replicas {
if isReplicaActive(&v) {
replicas[k] = v
}
}
break
}
for k, v := range shard.Replicas {
if isReplicaActive(&v) {
replicas[k] = v
}
}
return replicas, nil
Expand Down

0 comments on commit 10158d3

Please sign in to comment.