-
Notifications
You must be signed in to change notification settings - Fork 36
/
block_dispatcher.go
93 lines (79 loc) · 2.09 KB
/
block_dispatcher.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
package sources
import (
"context"
"encoding/json"
"sync"
"go.uber.org/zap"
)
// BlockDispatcher tracks all subscribers and works as a fan-out queue:
// on receiving a new block, BlockDispatcher sends a notification about it to all subscribers.
type BlockDispatcher struct {
logger *zap.Logger
// mu protects "subscribes" and "currentID" fields.
mu sync.RWMutex
currentID subscriberID
subscribes map[subscriberID]blockDeliveryFn
}
type blockDeliveryFn func(eventData []byte, workchain int)
func NewBlockDispatcher(logger *zap.Logger) *BlockDispatcher {
return &BlockDispatcher{
logger: logger,
currentID: 1,
subscribes: map[subscriberID]blockDeliveryFn{},
}
}
func (disp *BlockDispatcher) Run(ctx context.Context) chan BlockEvent {
ch := make(chan BlockEvent, 100)
go func() {
for {
select {
case <-ctx.Done():
return
case event := <-ch:
disp.logger.Debug("handling block",
zap.String("block", event.String()))
disp.dispatch(&event)
}
}
}()
return ch
}
func (disp *BlockDispatcher) dispatch(event *BlockEvent) {
eventData, err := json.Marshal(event)
if err != nil {
disp.logger.Error("json.Marshal() failed: %v", zap.Error(err))
return
}
disp.mu.RLock()
defer disp.mu.RUnlock()
for _, deliveryFn := range disp.subscribes {
deliveryFn(eventData, int(event.Workchain))
}
}
func (disp *BlockDispatcher) RegisterSubscriber(fn DeliveryFn, opts SubscribeToBlockHeadersOptions) CancelFn {
disp.mu.Lock()
defer disp.mu.Unlock()
id := disp.currentID
disp.currentID += 1
disp.subscribes[id] = createBlockDeliveryFnBasedOnOptions(fn, opts)
return func() {
disp.unsubscribe(id)
}
}
func createBlockDeliveryFnBasedOnOptions(fn DeliveryFn, options SubscribeToBlockHeadersOptions) blockDeliveryFn {
if options.Workchain == nil {
return func(eventData []byte, workchain int) {
fn(eventData)
}
}
return func(eventData []byte, workchain int) {
if workchain == *options.Workchain {
fn(eventData)
}
}
}
func (disp *BlockDispatcher) unsubscribe(id subscriberID) {
disp.mu.Lock()
defer disp.mu.Unlock()
delete(disp.subscribes, id)
}