forked from streamingfast/bstream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.go
256 lines (216 loc) · 6.84 KB
/
tracker.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package bstream
/**
Usage:
a.tracker.AddGetter(bstream.StreamHeadTarget, dexer.Hub)
a.tracker.AddGetter(bstream.StreamHeadTarget, timeline.ParallelGetter(relayerClient.GetterFactory(a.config.RelayerAddr), blockmeta.TrackerGetterFactory(a.config.BlockmetaAddr)))
a.tracker.AddGetter(bstream.StreamHeadTarget, codec.GetterFactory(eosAPI))
//a.tracker.AddGetter(dmesh.ArchiveHeadTarget, dmesh.TrackerGetterFactory(dmeshServer))
// dmesh/interface.go
// const ArchiveTailTarget = dtrack.Target("archive-tail")
blockRef, err := a.tracker.Latest(dmesh.ArchiveTailTarget)
REVIEW THE ABOVE.. find a nice pattern ^^
*/
import (
"context"
"errors"
"fmt"
"strings"
"time"
"go.uber.org/zap"
)
//
// Types to support the Tracker
//
// BlockRefGetter is a function to retrieve a block ref from any system.
type BlockRefGetter func(context.Context) (BlockRef, error)
var ErrTrackerBlockNotFound = errors.New("tracker block not found")
var ErrGetterUndefined = errors.New("no getter defined")
type Target string
const (
FileSourceHeadTarget = Target("filesource-head")
LiveSourceHeadTarget = Target("livesource-head")
LiveSourceTailTarget = Target("livesource-tail")
NetworkHeadTarget = Target("network-head")
NetworkLIBTarget = Target("network-lib")
BlockStreamHeadTarget = Target("bstream-head")
BlockStreamLIBTarget = Target("bstream-lib")
HubHeadTarget = Target("hub-head")
HubLIBTarget = Target("hub-lib")
// DatabaseHeadTarget = Target("db-head")
// DmeshTailTarget = Target("dmesh-tail")
// DmeshHeadTarget = Target("dmesh-head")
)
// Tracker tracks the chain progress and block history. Allows many
// processes to take decisions on the state of different pieces being
// sync'd (live) or in catch-up mode.
type Tracker struct {
getters map[Target][]BlockRefGetter
// Number of blocks between two targets before we consider the
// first as "near" the second. Like a relayer stream being near
// the tip of the network.
nearBlocksCount int64
}
func NewTracker(nearBlocksCount uint64) *Tracker {
return &Tracker{
getters: make(map[Target][]BlockRefGetter),
nearBlocksCount: int64(nearBlocksCount),
}
}
func (t *Tracker) AddGetter(target Target, f BlockRefGetter) {
t.getters[target] = append(t.getters[target], f)
}
func (t *Tracker) SetNearBlocksCount(count int64) {
t.nearBlocksCount = count
}
func (t *Tracker) Clone() *Tracker {
dstGettersMap := map[Target][]BlockRefGetter{}
for k, srcGetters := range t.getters {
var dstGetters []BlockRefGetter
for _, getter := range srcGetters {
dstGetters = append(dstGetters, getter)
}
dstGettersMap[k] = dstGetters
}
return &Tracker{
nearBlocksCount: t.nearBlocksCount,
getters: dstGettersMap,
}
}
// IsNearManualCheck allows you to manually check two "already resolved values" for nearness.
func (t *Tracker) IsNearManualCheck(from, to uint64) bool {
return to < uint64(t.nearBlocksCount) || int64(to)-int64(from) <= t.nearBlocksCount
}
// IsNearWithResults returns BlockRefs for the two targets. It can short-circuit the lookup for `from` if `to` is near the beginning of the chain, within the `nearBlocksCount`, in which case `fromBlockRef` will be nil.
func (t *Tracker) IsNearWithResults(ctx context.Context, from Target, to Target) (fromBlockRef BlockRef, toBlockRef BlockRef, isNear bool, err error) {
toBlockRef, err = t.Get(ctx, to)
if err != nil {
return
}
if toBlockRef.Num() < uint64(t.nearBlocksCount) {
// Near the beginning of the chain!
isNear = true
return
}
fromBlockRef, err = t.Get(ctx, from)
if err != nil {
return
}
if int64(toBlockRef.Num())-int64(fromBlockRef.Num()) <= t.nearBlocksCount {
isNear = true
}
return
}
func (t *Tracker) IsNear(ctx context.Context, from Target, to Target) (bool, error) {
_, _, result, err := t.IsNearWithResults(ctx, from, to)
return result, err
}
func (t *Tracker) Get(ctx context.Context, target Target) (BlockRef, error) {
getters := t.getters[target]
if len(getters) == 0 {
return nil, fmt.Errorf("tracker getter for target %q: %w", target, ErrGetterUndefined)
}
var errs []string
for _, f := range getters {
ref, err := f(ctx)
if err != nil {
errs = append(errs, err.Error())
continue
}
return ref, nil
}
return nil, errors.New("tracking fetch errors in order: " + strings.Join(errs, ", "))
// Get from EOS API
// Get from HeadInfo from any service ()
// Get from SubscriptionHub (use `tracker.AddGetter(bstream.StreamHeadTarget, hub.HeadTracker)`)
// Get from blockmeta
// Get from blkdb/trxdb's last written block
// Get from fluxdb's latest written block
// Get from command-line checkpoint?
}
func (t *Tracker) GetRelativeBlock(ctx context.Context, potentiallyNegativeBlockNum int64, target Target) (uint64, error) {
if potentiallyNegativeBlockNum < 0 {
blk, err := t.Get(ctx, target)
if err != nil {
return 0, err
}
if blk.Num() < uint64(-potentiallyNegativeBlockNum) {
return GetProtocolFirstStreamableBlock, nil
}
return uint64(int64(blk.Num()) + potentiallyNegativeBlockNum), nil
}
if uint64(potentiallyNegativeBlockNum) < GetProtocolFirstStreamableBlock {
return GetProtocolFirstStreamableBlock, nil
}
return uint64(potentiallyNegativeBlockNum), nil
}
func HighestBlockRefGetter(getters ...BlockRefGetter) BlockRefGetter {
type resp struct {
ref BlockRef
err error
}
return func(ctx context.Context) (BlockRef, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
outChan := make(chan *resp)
for _, getter := range getters {
g := getter
go func() {
ref, err := g(ctx)
resp := &resp{
ref: ref,
err: err,
}
select {
case outChan <- resp:
case <-ctx.Done():
}
}()
}
var errs []string
var highest BlockRef
for cnt := 0; cnt < len(getters); cnt++ {
select {
case <-ctx.Done():
return nil, ctx.Err()
case resp := <-outChan:
if resp.err != nil {
errs = append(errs, resp.err.Error())
} else {
if highest == nil {
highest = resp.ref
} else {
if resp.ref.Num() > highest.Num() {
highest = resp.ref
}
}
}
}
}
if len(errs) == len(getters) {
return nil, errors.New("all parallel getters failed: " + strings.Join(errs, ", "))
}
return highest, nil
}
}
func RetryableBlockRefGetter(attempts int, wait time.Duration, next BlockRefGetter) BlockRefGetter {
return func(ctx context.Context) (ref BlockRef, err error) {
var errs []string
for attempt := 0; attempts == -1 || attempt <= attempts; attempt++ {
if err = ctx.Err(); err != nil {
errs = append(errs, err.Error())
break
}
ref, err = next(ctx)
if err != nil {
zlog.Debug("got an error from a block ref getter", zap.Error(err))
errs = append(errs, err.Error())
attempt++
time.Sleep(wait)
continue
}
return
}
err = fmt.Errorf("retryable block ref getter failed: %s", strings.Join(errs, ", "))
return
}
}