-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathalgorithm.go
More file actions
49 lines (42 loc) · 1.5 KB
/
algorithm.go
File metadata and controls
49 lines (42 loc) · 1.5 KB
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
package algorithm
import (
"database/sql"
"sync"
"github.com/pkg/errors"
)
var (
algorithmsMu sync.RWMutex
algorithms = make(map[string]func() ShardingAlgorithm)
)
// ShardingAlgorithm is a algorithm for assign sharding target.
//
// octillery currently supports modulo and hashmap.
// If use the other new algorithm, implement the following interface as plugin ( new_algorithm.go )
// and call algorithm.Register("algorithm_name", &NewAlgorithmStructure{}).
// Also, new_algorithm.go file should put inside go.knocknote.io/octillery/algorithm directory.
type ShardingAlgorithm interface {
// initialize structure by connection list. if returns true, no more call this.
Init(conns []*sql.DB) bool
// assign sharding target by connection list and shard_key
Shard(conns []*sql.DB, lastInsertID int64) (*sql.DB, error)
}
// Register register sharding algorithm with name
func Register(name string, algorithmFactory func() ShardingAlgorithm) {
algorithmsMu.Lock()
defer algorithmsMu.Unlock()
if algorithmFactory == nil {
panic("register sharding algorithm factory is nil")
}
if _, dup := algorithms[name]; dup {
panic("register called twice for sharding algorithm " + name)
}
algorithms[name] = algorithmFactory
}
// LoadShardingAlgorithm load algorithm by name
func LoadShardingAlgorithm(name string) (ShardingAlgorithm, error) {
algorithmFactory := algorithms[name]
if algorithmFactory == nil {
return nil, errors.Errorf("cannot load sharding algorithm from %s", name)
}
return algorithmFactory(), nil
}