aboutsummaryrefslogtreecommitdiff
path: root/shards.go
blob: ae6e069b63cc6ef73f08c95aa44f541861505785 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main

import (
	"hash/fnv"
	"sort"
	"sync"
)
type Shard struct{
	mu sync.Mutex
	id int
	data map[string]Item
}

func (db *RedisDB) getShard(key string)*Shard{
	hash := fnv.New64a()
	hash.Write([]byte(key))
	val := hash.Sum64()

	return db.shards[val%NumShards]
}

func (db *RedisDB) Execute(key string, fn func(*Shard) interface{}) interface{} {
    shard := db.getShard(key)
    shard.mu.Lock()
    defer shard.mu.Unlock()
    return fn(shard)
}

func ( db *RedisDB) ExecuteMulti(keys []string, fn func([]*Shard) interface{})interface{}{
	shardMap := make(map[int]*Shard)
	for _, k := range keys {
        shard := db.getShard(k)
        shardMap[shard.id] = shard
    }
	var sortedIDs []int
    for id := range shardMap {
        sortedIDs = append(sortedIDs, id)
    }
	sort.Ints(sortedIDs)
	for _, id := range sortedIDs{
		shardMap[id].mu.Lock()
	}
	defer func(){
		for i := len(sortedIDs)-1; i >= 0; i --{
			shardMap[sortedIDs[i]].mu.Unlock()
		}
	}()
	
	shards := make([]*Shard, 0, len(shardMap))
    for _, id := range sortedIDs {
        shards = append(shards, shardMap[id])
    }
    return fn(shards)
}