-
Notifications
You must be signed in to change notification settings - Fork 39
/
nodeownercache.go
81 lines (68 loc) · 1.92 KB
/
nodeownercache.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
package icstate
import (
"github.com/icon-project/goloop/common/containerdb"
"github.com/icon-project/goloop/common/errors"
"github.com/icon-project/goloop/icon/iiss/icobject"
"github.com/icon-project/goloop/icon/iiss/icutils"
"github.com/icon-project/goloop/module"
"github.com/icon-project/goloop/service/scoredb"
)
var nodeOwnerDictPrefix = containerdb.ToKey(
containerdb.HashBuilder,
scoredb.DictDBPrefix,
"node_owner",
)
// TODO: Remove old nodes which is not used anymore
type NodeOwnerCache struct {
dict *containerdb.DictDB
nodeToOwner map[string]module.Address
ownerToNode map[string]module.Address
}
func (c *NodeOwnerCache) Add(node, owner module.Address) error {
// TODO: node must not be an owner of other PRep
oldOwner := c.Get(node)
if oldOwner != nil {
return errors.Errorf("Node already exists: %s", node)
}
c.nodeToOwner[icutils.ToKey(node)] = owner
c.ownerToNode[icutils.ToKey(owner)] = node
return nil
}
func (c *NodeOwnerCache) Get(node module.Address) module.Address {
key := icutils.ToKey(node)
owner := c.nodeToOwner[key]
if owner != nil {
return owner
}
o := c.dict.Get(node)
if o == nil {
return nil
}
owner = o.Address()
if owner != nil {
c.nodeToOwner[key] = owner
}
return owner
}
func (c *NodeOwnerCache) Clear() {
c.nodeToOwner = make(map[string]module.Address)
c.ownerToNode = make(map[string]module.Address)
}
func (c *NodeOwnerCache) Reset() {
c.Clear()
}
func (c *NodeOwnerCache) Flush() {
for node, owner := range c.nodeToOwner {
o := icobject.NewBytesObject(owner.Bytes())
if err := c.dict.Set(node, o); err != nil {
panic(errors.Errorf("DictDB.Set(%s, %s) is failed", node, owner))
}
}
}
func newNodeOwnerCache(store containerdb.ObjectStoreState) *NodeOwnerCache {
return &NodeOwnerCache{
dict: containerdb.NewDictDB(store, 1, nodeOwnerDictPrefix),
nodeToOwner: make(map[string]module.Address),
ownerToNode: make(map[string]module.Address),
}
}