This repository has been archived by the owner on Feb 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shard_config.go
88 lines (76 loc) · 1.97 KB
/
shard_config.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package dilithium
import (
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strconv"
)
type ShardConfig struct {
Type string `json:"type"`
Config map[string]interface{} `json:"config"`
Children []ShardConfig `json:"children"`
}
func NewForwardingTableFromJSON(r io.Reader) (*ForwardingTable, error) {
config := make(map[string]ShardConfig)
err := json.NewDecoder(r).Decode(config)
if err != nil {
return nil, err
}
return NewForwardingTable(config)
}
func NewForwardingTable(config map[string]ShardConfig) (*ForwardingTable, error) {
table := &ForwardingTable{}
for m, c := range config {
maxKey, err := strconv.Atoi(m)
if err != nil {
return nil, fmt.Errorf("dilithium: Invalid maxKey from JSON config, expecting integer, got '%s'", maxKey)
}
shard, err := c.NewShard()
if err != nil {
return nil, err
}
table.Insert(&ForwardingTableEntry{maxKey, shard})
}
return table, nil
}
func (config *ShardConfig) NewShard() (shard Shard, err error) {
if config.Type == "" {
return nil, errors.New("dilithium: Missing shard type")
}
shardType := ShardTypeRegistry.Type(config.Type)
if shardType == nil {
return nil, fmt.Errorf("dilithium: Unknown shard type '%s'", config.Type)
}
shard = reflect.New(shardType).Interface().(Shard)
err = shard.Setup(config.Config)
if err != nil {
return nil, err
}
for _, child := range config.Children {
childShard, err := child.NewShard()
if err != nil {
return nil, err
}
childShard.SetParent(shard)
shard.AddChild(childShard)
}
return
}
func NewShardConfig(s Shard) (*ShardConfig, error) {
name := ShardTypeRegistry.Name(s)
if name == "" {
return nil, fmt.Errorf("dilithium: Unregistered shard type %T", s)
}
children := s.Children()
config := &ShardConfig{name, s.Config(), make([]ShardConfig, len(children))}
for i, child := range children {
c, err := NewShardConfig(child)
if err != nil {
return nil, err
}
config.Children[i] = *c
}
return config, nil
}