-
Notifications
You must be signed in to change notification settings - Fork 2
/
db_buffer.go
237 lines (201 loc) · 5.31 KB
/
db_buffer.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package db_buffer
import (
"fmt"
"github.com/Zondax/zindexer/components/connections/zmetrics"
"github.com/Zondax/zindexer/components/tracker"
cmap "github.com/orcaman/concurrent-map"
"go.uber.org/zap"
"gorm.io/gorm"
"strconv"
"sync"
"time"
)
var (
defaultBucketTime = []float64{1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60}
)
type SyncCB func() SyncResult
type SyncResult struct {
Id string
SyncedHeights *[]uint64 // Synced heights
Error error // Error in db insertion process
}
type BufferMetrics struct {
totalSyncTimeHist zmetrics.Histogram
}
type Buffer struct {
buffer map[string]cmap.ConcurrentMap
dbConn *gorm.DB
syncMutex sync.Mutex
syncTicker *time.Ticker
newDataChan chan string
exitChan chan bool
metrics BufferMetrics
config Config
syncCb SyncCB
enabled bool
SyncComplete chan SyncResult
}
func NewDBBuffer(db *gorm.DB, cfg Config) *Buffer {
b := &Buffer{
buffer: make(map[string]cmap.ConcurrentMap),
dbConn: db,
syncTicker: time.NewTicker(cfg.SyncTimePeriod),
newDataChan: make(chan string),
exitChan: make(chan bool, 1),
config: cfg,
syncCb: func() SyncResult {
return SyncResult{
"",
nil,
fmt.Errorf("no sync function defined. Call SetSyncFunc"),
}
},
SyncComplete: make(chan SyncResult, 1),
}
b.registerMetrics()
b.syncTicker.Stop()
return b
}
// Start starts listening for syncing triggering events
func (b *Buffer) Start() {
go b.checkIsTimeToSync()
b.enabled = true
}
// Stop stops listening for syncing triggering events
func (b *Buffer) Stop() {
b.enabled = false
b.syncTicker.Stop()
// closes the loop in func checkIsTimeToSync
b.exitChan <- true
// wait if a syncing event is in progress,
// syncMutex gets released in func callSync
b.syncMutex.Lock()
defer b.syncMutex.Unlock()
}
// SetSyncFunc sets the syncing callback function
func (b *Buffer) SetSyncFunc(cb SyncCB) {
b.syncCb = cb
}
// InsertData inserts 'data' into the buffer under the key 'key'
// if notify is set to true, the condition 'SyncBlockThreshold' will be tested for that specific key
func (b *Buffer) InsertData(key string, height int64, data interface{}, notify bool) error {
if !b.enabled {
return nil
}
b.syncMutex.Lock()
defer b.syncMutex.Unlock()
if _, ok := b.buffer[key]; !ok {
zap.S().Debugf("[Buffer] created new map for key %s", key)
b.buffer[key] = cmap.New()
}
b.buffer[key].Set(strconv.FormatInt(height, 10), data)
if notify {
// this is done to write to the newDataChan in a non-blocking way
select {
case b.newDataChan <- key:
default:
}
}
b.syncTicker.Reset(b.config.SyncTimePeriod)
return nil
}
func (b *Buffer) ClearBuffer(dataType string) {
if m, ok := b.buffer[dataType]; ok {
m.Clear()
}
}
func (b *Buffer) clearAllBuffers() {
for _, m := range b.buffer {
m.Clear()
}
}
func (b *Buffer) GetBufferSize(dataType string) int {
size := 0
if m, ok := b.buffer[dataType]; ok {
size = m.Count()
}
return size
}
func (b *Buffer) GetData(dataType string) (map[string]interface{}, error) {
if m, ok := b.buffer[dataType]; ok {
return m.Items(), nil
} else {
return nil, fmt.Errorf("[Buffer] buffer doesn't contain dataType %s", dataType)
}
}
func (b *Buffer) callSync() {
zap.S().Debugf("[Buffer] callSync started ...")
defer func() {
zap.S().Debugf("[Buffer] callSync finished!")
}()
b.syncTicker.Stop()
b.syncMutex.Lock()
defer b.syncMutex.Unlock()
defer b.syncTicker.Reset(b.config.SyncTimePeriod)
syncStart := time.Now()
syncResult := b.syncCb()
b.clearAllBuffers()
if syncResult.Error == nil && syncResult.SyncedHeights != nil {
timeTotal := time.Since(syncStart).Seconds()
if timeTotal > 0 {
zap.S().Debugf("[Buffer] Total DB insertion time took %v seconds", timeTotal)
b.metrics.totalSyncTimeHist.Observe(timeTotal)
}
}
b.onDBSyncComplete(&syncResult)
select {
case b.SyncComplete <- syncResult:
default:
}
}
func (b *Buffer) checkIsTimeToSync() {
for {
select {
case <-b.syncTicker.C:
zap.S().Debug("[Buffer] Syncing because of Ticker...")
b.callSync()
case key := <-b.newDataChan:
l := uint(b.GetBufferSize(key))
if l >= b.config.SyncBlockThreshold {
zap.S().Debugf("[Buffer] Syncing because of blocks amount: %d", l)
b.callSync()
}
case <-b.exitChan:
zap.S().Debug("[Buffer] Exiting...")
return
}
}
}
func (b *Buffer) registerMetrics() {
b.metrics.totalSyncTimeHist = zmetrics.NewHistogram(zmetrics.HistogramOpts{
Namespace: "blocks",
Subsystem: "buffer",
Name: "sync_total_time_seconds",
Help: "Total time spent by function 'syncCb'",
Buckets: defaultBucketTime,
})
err := zmetrics.RegisterMetric(b.metrics.totalSyncTimeHist)
if err != nil {
zap.S().Error("Could not register Metric: totalSyncTimeHist")
}
}
func (b *Buffer) onDBSyncComplete(r *SyncResult) {
if r.SyncedHeights == nil {
zap.S().Errorf("onDBSyncComplete received nil SyncedHeights. Check db_sync code!")
return
}
if r.Id == "" {
zap.S().Errorf("onDBSyncComplete received an empty 'Id'. Check db_sync code!")
return
}
if r.Error != nil {
zap.S().Errorf(r.Error.Error())
// Remove WIP heights
_ = tracker.UpdateInProgressHeight(false, r.SyncedHeights, r.Id, b.dbConn)
return
}
err := tracker.UpdateAndRemoveWipHeights(r.SyncedHeights, r.Id, b.dbConn)
if err != nil {
return
}
}