-
Notifications
You must be signed in to change notification settings - Fork 1
/
dds.go
75 lines (64 loc) · 1.48 KB
/
dds.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
package watcher
import (
"bytes"
"log"
"sort"
tmstate "github.com/FiboChain/fbc/libs/tendermint/state"
"github.com/golang/protobuf/proto"
)
func SetWatchDataManager() {
tmstate.SetWasmWatchDataManager(WatchDataManager{})
}
type WatchDataManager struct{}
func (w WatchDataManager) CreateWatchDataGenerator() func() ([]byte, error) {
data := &WatchData{
Messages: make([]*WatchMessage, 0, len(blockStateCache)),
}
for _, v := range blockStateCache {
data.Messages = append(data.Messages, v)
}
sort.Sort(data)
return func() ([]byte, error) {
return proto.Marshal(data)
}
}
func (w WatchDataManager) UnmarshalWatchData(b []byte) (interface{}, error) {
if len(b) == 0 {
return nil, nil
}
var data WatchData
err := proto.Unmarshal(b, &data)
if err != nil {
return nil, err
}
return &data, nil
}
func (w WatchDataManager) ApplyWatchData(v interface{}) {
data, ok := v.(*WatchData)
if !ok {
return
}
task := func() {
batch := db.NewBatch()
for _, msg := range data.Messages {
if msg.IsDelete {
batch.Delete(msg.Key)
} else {
batch.Set(msg.Key, msg.Value)
}
}
if err := batch.Write(); err != nil {
log.Println("ApplyWatchData batch write error:" + err.Error())
}
}
tasks <- task
}
func (d *WatchData) Len() int {
return len(d.Messages)
}
func (d *WatchData) Less(i, j int) bool {
return bytes.Compare(d.Messages[i].Key, d.Messages[j].Key) < 0
}
func (d *WatchData) Swap(i, j int) {
d.Messages[i], d.Messages[j] = d.Messages[j], d.Messages[i]
}