-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncer.go
461 lines (376 loc) · 10.1 KB
/
syncer.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package isaacstates
import (
"context"
"io"
"sync"
"sync/atomic"
"time"
"github.com/ProtoconNet/mitum2/base"
"github.com/ProtoconNet/mitum2/isaac"
"github.com/ProtoconNet/mitum2/util"
"github.com/ProtoconNet/mitum2/util/logging"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
type (
SyncerBlockMapFunc func(context.Context, base.Height) (base.BlockMap, bool, error)
SyncerBlockMapItemFunc func(
context.Context, base.Height, base.BlockMapItemType) (io.ReadCloser, func() error, bool, error)
NewBlockImporterFunc func(base.BlockMap) (isaac.BlockImporter, error)
SyncerLastBlockMapFunc func(_ context.Context, manifest util.Hash) (
_ base.BlockMap, updated bool, _ error) // NOTE BlockMap.IsValid() should be called
NewImportBlocksFunc func(
_ context.Context,
from, to base.Height,
batchlimit int64,
blockMapFunc func(context.Context, base.Height) (base.BlockMap, bool, error),
) error
)
type SyncerArgs struct {
LastBlockMapFunc SyncerLastBlockMapFunc
BlockMapFunc SyncerBlockMapFunc
TempSyncPool isaac.TempSyncPool
WhenStoppedFunc func() error
RemovePrevBlockFunc func(base.Height) (bool, error)
NewImportBlocksFunc NewImportBlocksFunc
BatchLimit int64
LastBlockMapInterval time.Duration
LastBlockMapTimeout time.Duration
}
func NewSyncerArgs() SyncerArgs {
return SyncerArgs{
LastBlockMapFunc: func(context.Context, util.Hash) (base.BlockMap, bool, error) { return nil, false, nil },
BlockMapFunc: func(context.Context, base.Height) (base.BlockMap, bool, error) { return nil, false, nil },
WhenStoppedFunc: func() error { return nil },
RemovePrevBlockFunc: func(base.Height) (bool, error) { return false, nil },
NewImportBlocksFunc: func(context.Context, base.Height, base.Height, int64,
func(context.Context, base.Height) (base.BlockMap, bool, error),
) error {
return errors.Errorf("nothing happened")
},
BatchLimit: 33, //nolint:gomnd // big enough size
LastBlockMapInterval: time.Second * 2, //nolint:gomnd //...
LastBlockMapTimeout: time.Second * 2, //nolint:gomnd //...
}
}
type Syncer struct {
finishedch chan base.Height
prevvalue *util.Locked[base.BlockMap]
isdonevalue *atomic.Value
checkedprevs *util.GCache[base.Height, string]
startsyncch chan base.Height
donech chan struct{}
doneerr *util.Locked[error]
topvalue *util.Locked[base.Height]
*logging.Logging
*util.ContextDaemon
args SyncerArgs
cancelonece sync.Once
}
func NewSyncer(prev base.BlockMap, args SyncerArgs) *Syncer {
prevheight := base.NilHeight
if prev != nil {
prevheight = prev.Manifest().Height()
}
s := &Syncer{
Logging: logging.NewLogging(func(lctx zerolog.Context) zerolog.Context {
return lctx.Str("module", "syncer")
}),
prevvalue: util.NewLocked(prev),
args: args,
finishedch: make(chan base.Height),
donech: make(chan struct{}, 2),
doneerr: util.EmptyLocked((error)(nil)),
topvalue: util.NewLocked(prevheight),
isdonevalue: &atomic.Value{},
startsyncch: make(chan base.Height),
checkedprevs: util.NewLRUGCache(base.NilHeight, "", 1<<3), //nolint:gomnd //...
}
s.ContextDaemon = util.NewContextDaemon(s.start)
return s
}
func (s *Syncer) Add(height base.Height) bool {
if s.isdonevalue.Load() != nil {
return false
}
var startsync bool
if _, err := s.topvalue.Set(func(top base.Height, _ bool) (base.Height, error) {
synced := s.prevheight()
switch {
case height <= top:
return base.NilHeight, errors.Errorf("old height")
case top == synced:
startsync = true
}
return height, nil
}); err != nil {
return false
}
if startsync {
go func() {
s.startsyncch <- height
}()
}
return true
}
func (s *Syncer) Finished() <-chan base.Height {
return s.finishedch
}
func (s *Syncer) Done() <-chan struct{} {
return s.donech
}
func (s *Syncer) Err() error {
i, _ := s.doneerr.Value()
return i
}
func (s *Syncer) IsFinished() (base.Height, bool) {
top := s.top()
return top, top == s.prevheight()
}
func (s *Syncer) Cancel() error {
var err error
s.cancelonece.Do(func() {
err = s.ContextDaemon.Stop()
if errors.Is(err, util.ErrDaemonAlreadyStopped) {
err = nil
}
defer func() {
_ = s.args.TempSyncPool.Cancel()
}()
_, _ = s.doneerr.Set(func(i error, _ bool) (error, error) {
s.isdonevalue.Store(true)
// close(s.donech)
return i, nil
})
})
return err
}
func (s *Syncer) start(ctx context.Context) error {
defer func() {
_ = s.args.TempSyncPool.Cancel()
}()
uctx, cancel := context.WithCancel(ctx)
defer cancel()
go s.updateLastBlockMap(uctx)
var gerr error
end:
for {
select {
case <-uctx.Done():
gerr = uctx.Err()
break end
case height := <-s.startsyncch:
if err := s.donewitherror(func() error {
return s.sync(uctx, height)
}); err != nil {
gerr = err
break end
}
}
}
switch serr := s.args.WhenStoppedFunc(); {
case gerr == nil,
errors.Is(gerr, context.Canceled),
errors.Is(gerr, context.DeadlineExceeded):
gerr = serr
}
return gerr
}
func (s *Syncer) top() base.Height {
i, _ := s.topvalue.Value()
return i
}
func (s *Syncer) prev() base.BlockMap {
i, _ := s.prevvalue.Value()
return i
}
func (s *Syncer) prevheight() base.Height {
m := s.prev()
if m == nil {
return base.NilHeight
}
return m.Manifest().Height()
}
func (s *Syncer) sync( // revive:disable-line:import-shadowing
ctx context.Context,
to base.Height,
) error {
prev, err := s.prevvalue.Set(func(i base.BlockMap, _ bool) (base.BlockMap, error) {
switch {
case i == nil:
return nil, util.ErrLockedSetIgnore.Call()
case s.checkedprevs.Exists(i.Manifest().Height()):
return nil, util.ErrLockedSetIgnore.Call()
}
newprev, err := s.checkPrevMap(ctx, i)
if err != nil {
return nil, err
}
s.checkedprevs.Set(i.Manifest().Height(), "", 0)
switch {
case newprev != nil:
return newprev, nil
default:
return nil, util.ErrLockedSetIgnore.Call()
}
})
if err != nil {
return err
}
if prev != nil && to <= prev.Manifest().Height() {
return nil
}
newprev, err := s.doSync(ctx, prev, to)
if err != nil {
return err
}
_ = s.prevvalue.SetValue(newprev)
switch top := s.top(); {
case newprev.Manifest().Height() == top:
go func() {
s.finishedch <- top
}()
case newprev.Manifest().Height() < top:
go func() {
s.startsyncch <- top
}()
}
return nil
}
func (s *Syncer) doSync(ctx context.Context, prev base.BlockMap, to base.Height) (base.BlockMap, error) {
e := util.StringErrorFunc("failed to sync")
// NOTE fetch and store all BlockMaps
newprev, err := s.prepareMaps(ctx, prev, to)
if err != nil {
return nil, e(err, "")
}
if err := s.syncBlocks(ctx, prev, to); err != nil {
return nil, e(err, "")
}
return newprev, nil
}
func (s *Syncer) prepareMaps(ctx context.Context, prev base.BlockMap, to base.Height) (base.BlockMap, error) {
var last base.BlockMap
if err := base.BatchValidateMaps(
ctx,
prev,
to,
uint64(s.args.BatchLimit),
s.fetchMap,
func(m base.BlockMap) error {
if h := m.Manifest().Height(); h%100 == 0 || h == to {
s.Log().Debug().Interface("height", h).Msg("blockmap prepared")
}
if err := s.args.TempSyncPool.SetBlockMap(m); err != nil {
return err
}
if m.Manifest().Height() == to {
last = m
}
return nil
},
); err != nil {
return nil, err
}
return last, nil
}
func (s *Syncer) checkPrevMap(ctx context.Context, prev base.BlockMap) (base.BlockMap, error) {
var mp base.BlockMap
switch m, err := s.fetchMap(ctx, prev.Manifest().Height()); {
case err != nil:
return nil, err
case prev.Manifest().Hash().Equal(m.Manifest().Hash()):
return prev, nil
default:
s.Log().Debug().
Interface("previous_block", prev).
Interface("different_previous_block", m).
Msg("different previous block found; will be removed from local")
mp = m
}
// NOTE remove last block from database; if failed, return error
switch removed, err := s.args.RemovePrevBlockFunc(prev.Manifest().Height()); {
case err != nil:
return nil, err
case !removed:
return nil, errors.Errorf("previous manifest does not match with remotes")
default:
return mp, nil
}
}
func (s *Syncer) fetchMap(ctx context.Context, height base.Height) (base.BlockMap, error) {
e := util.StringErrorFunc("failed to fetch BlockMap")
switch m, found, err := s.args.BlockMapFunc(ctx, height); {
case err != nil:
return nil, e(err, "")
case !found:
return nil, e(nil, "not found")
default:
return m, nil
}
}
func (s *Syncer) syncBlocks(ctx context.Context, prev base.BlockMap, to base.Height) error {
e := util.StringErrorFunc("failed to sync blocks")
from := base.GenesisHeight
if prev != nil {
from = prev.Manifest().Height() + 1
}
if err := util.Retry(ctx, func() (bool, error) {
if err := s.args.NewImportBlocksFunc(
ctx,
from, to,
s.args.BatchLimit,
func(_ context.Context, height base.Height) (base.BlockMap, bool, error) {
return s.args.TempSyncPool.BlockMap(height)
},
); err != nil {
return true, err
}
return false, nil
},
-1,
time.Second,
); err != nil {
return e(err, "")
}
return nil
}
func (s *Syncer) updateLastBlockMap(ctx context.Context) {
var last util.Hash
if prev := s.prev(); prev != nil {
last = prev.Manifest().Hash()
}
ticker := time.NewTicker(s.args.LastBlockMapInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
switch m, updated, err := s.lastBlockMap(ctx, last); {
case err != nil:
s.Log().Error().Err(err).Msg("failed to update last BlockMap")
case updated:
_ = s.Add(m.Manifest().Height())
last = m.Manifest().Hash()
}
}
}
}
func (s *Syncer) donewitherror(f func() error) error {
err, _ := s.doneerr.Set(func(i error, _ bool) (error, error) {
if i != nil {
return nil, errors.Errorf("already done by error")
}
return f(), nil
})
if err != nil {
s.donech <- struct{}{}
}
return err
}
func (s *Syncer) lastBlockMap(ctx context.Context, manifest util.Hash) (_ base.BlockMap, updated bool, _ error) {
nctx, cancel := context.WithTimeout(ctx, s.args.LastBlockMapTimeout)
defer cancel()
return s.args.LastBlockMapFunc(nctx, manifest)
}