-
Notifications
You must be signed in to change notification settings - Fork 211
/
blocks.go
58 lines (52 loc) · 1.26 KB
/
blocks.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
package blockssync
import (
"context"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"github.com/spacemeshos/go-spacemesh/common/types"
)
//go:generate mockgen -typed -package=blockssync -destination=./mocks.go -source=./blocks.go
type blockFetcher interface {
GetBlocks(context.Context, []types.BlockID) error
}
// Sync requests last specified blocks in background.
func Sync(ctx context.Context, logger *zap.Logger, requests <-chan []types.BlockID, fetcher blockFetcher) error {
var (
eg errgroup.Group
lastch = make(chan map[types.BlockID]struct{})
)
eg.Go(func() error {
var (
send chan map[types.BlockID]struct{}
last map[types.BlockID]struct{}
)
for {
select {
case <-ctx.Done():
close(lastch)
return ctx.Err()
case req := <-requests:
if last == nil {
last = map[types.BlockID]struct{}{}
send = lastch
}
for _, id := range req {
last[id] = struct{}{}
}
case send <- last:
last = nil
send = nil
}
}
})
for batch := range lastch {
blocks := make([]types.BlockID, 0, len(batch))
for id := range batch {
blocks = append(blocks, id)
}
if err := fetcher.GetBlocks(ctx, blocks); err != nil {
logger.Warn("failed to fetch blocks", zap.Error(err))
}
}
return eg.Wait()
}