/
subscription.go
299 lines (262 loc) · 7.55 KB
/
subscription.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
package near
import (
"context"
"embed"
"fmt"
"math/rand"
"net/url"
"os"
"os/exec"
"os/signal"
reflect "reflect"
sync "sync"
"time"
"github.com/gorilla/websocket"
"github.com/nakji-network/connector/kafkautils"
"github.com/rs/zerolog/log"
"google.golang.org/protobuf/proto"
)
//go:embed target/x86_64-unknown-linux-musl/release/nakji_near_client
var f embed.FS
var endpointMap = map[string]proto.Message{
"/block": &Block{},
"/tx": &Transaction{},
"/receipt": &Receipt{},
"/outcome": &ExecutionOutcome{},
}
type Subscription struct {
hostname string
port string
backfillPort string
maxRetries int
fromBlock uint64
numBlocks uint64
events []string
fctMsgTypes []proto.Message
bfMsgTypes []proto.Message
done chan struct{}
ctx context.Context
blockChan chan *kafkautils.Message
transactionChan chan *kafkautils.Message
receiptChan chan *kafkautils.Message
executionOutcomeChan chan *kafkautils.Message
errChan chan error
}
func NewSubscription(ctx context.Context, config *Config, events []string) (*Subscription, error) {
// Read binary from embed
bin, err := f.ReadFile("target/x86_64-unknown-linux-musl/release/nakji_near_client")
if err != nil {
log.Fatal().Err(err).Msg("failed read embedded Nakji Near Client binary")
}
// Write binary to file so we can execute it
err = os.WriteFile("/nearclient/nakji_near_client", bin, 0755)
if err != nil {
log.Fatal().Err(err).Msg("failed to write embedded Nakji Near Client binary to local fs")
}
sub := &Subscription{
hostname: config.Hostname,
port: config.Port,
backfillPort: config.BackfillPort,
maxRetries: config.MaxRetries,
events: events,
fctMsgTypes: config.FctMsgTypes,
bfMsgTypes: config.BfMsgTypes,
fromBlock: config.FromBlock,
numBlocks: config.NumBlocks,
done: make(chan struct{}),
ctx: ctx,
blockChan: make(chan *kafkautils.Message, config.ChannelSize),
transactionChan: make(chan *kafkautils.Message, config.ChannelSize),
receiptChan: make(chan *kafkautils.Message, config.ChannelSize),
executionOutcomeChan: make(chan *kafkautils.Message, config.ChannelSize),
errChan: make(chan error, config.ChannelSize),
}
go func() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
select {
case <-interrupt:
sub.Unsubscribe()
case <-ctx.Done():
sub.Unsubscribe()
}
}()
go sub.subscribe()
return sub, nil
}
func (s *Subscription) Unsubscribe() {
log.Info().Str("hostname", s.hostname).Msg("shutting down subscription")
close(s.done)
}
func (s *Subscription) Done() <-chan struct{} {
return s.done
}
func (s *Subscription) Blocks() <-chan *kafkautils.Message {
return s.blockChan
}
func (s *Subscription) Transactions() <-chan *kafkautils.Message {
return s.transactionChan
}
func (s *Subscription) Receipts() <-chan *kafkautils.Message {
return s.receiptChan
}
func (s *Subscription) ExecutionOutcomes() <-chan *kafkautils.Message {
return s.executionOutcomeChan
}
func (s *Subscription) Err() <-chan error {
return s.errChan
}
func (s *Subscription) subscribe() {
// Start Lake Stream from current block
s.startLakeStream(s.port, 0, 0)
go s.initWsStreams(false)
// Backfill if needed
if s.fromBlock > 0 || s.numBlocks > 0 {
go s.backfill()
}
}
func (s *Subscription) backfill() {
log.Info().Msg("starting backfill")
defer log.Info().Msg("finished backfill")
if s.fromBlock > 0 {
s.startLakeStream(s.backfillPort, s.fromBlock, 0)
s.initWsStreams(true)
} else if s.numBlocks > 0 {
s.startLakeStream(s.backfillPort, 0, s.numBlocks)
s.initWsStreams(true)
}
}
func (s *Subscription) startLakeStream(port string, fromBlock uint64, numBlocks uint64) {
// Setup command for Lake stream
cmd := []string{
"/nearclient/nakji_near_client",
}
cmd = append(cmd, fmt.Sprintf("--port=%s", port))
// Arguments for binary are detrmined by backfill config
if fromBlock > 0 {
cmd = append(cmd, "from-block")
cmd = append(cmd, fmt.Sprintf("%d", fromBlock))
} else if numBlocks > 0 {
cmd = append(cmd, "num-blocks")
cmd = append(cmd, fmt.Sprintf("%d", numBlocks))
} else {
cmd = append(cmd, "from-latest")
}
execCmd := exec.Command(cmd[0], cmd[1:]...)
execCmd.Stdout = os.Stdout
execCmd.Stderr = os.Stderr
// Run binary in goroutine
go func() {
if err := execCmd.Run(); err != nil {
log.Fatal().Err(err).Msg(fmt.Sprintf("%s Error running Nakji NEAR Client (Rust binary): ", err))
}
}()
}
func (s *Subscription) initWsStreams(isBackfill bool) {
var wg sync.WaitGroup
var msgTypes []proto.Message
// Connect to ws server to receive data from Lake stream
if isBackfill {
msgTypes = s.bfMsgTypes
} else {
msgTypes = s.fctMsgTypes
}
for endpoint, msgType := range endpointMap {
// Check if msgType is in sub's msgTypes (based on bf or fct msgTypes)
for _, subType := range msgTypes {
if reflect.TypeOf(msgType) == reflect.TypeOf(subType) {
wg.Add(1)
go s.startWsStream(&wg, endpoint, msgType, isBackfill)
}
}
}
wg.Wait()
}
func (s *Subscription) startWsStream(wg *sync.WaitGroup, endpoint string, protoMsgType proto.Message, isBackfill bool) {
defer wg.Done()
// Get port from config
var port string
if isBackfill {
port = s.backfillPort
} else {
port = s.port
}
// Construct ws url
host := fmt.Sprintf("%s%s%s", s.hostname, ":", port)
u := url.URL{Scheme: "ws", Host: host, Path: endpoint}
log.Info().Str("host", host).Str("endpoint", endpoint).Msg("connecting to ws server")
// Output chan determined by protoMsgType
ch := s.getMsgChan(protoMsgType)
if ch == nil {
log.Error().Msg("could not determine output channel")
return
}
// kafkaMsgType determined by backfill
var kafkaMsgType kafkautils.MsgType
if isBackfill {
kafkaMsgType = kafkautils.MsgTypeBf
} else {
kafkaMsgType = kafkautils.MsgTypeFct
}
// Connect to ws server with retry
var conn *websocket.Conn
for retry := 0; ; retry++ {
tryConn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
if retry < s.maxRetries {
// Do exponential backoff with 10% jitter
backoff := float64(int(1) << retry)
backoff += backoff * (0.1 * rand.Float64())
select {
case <-s.done:
return
case <-time.After(time.Second * time.Duration(backoff)):
continue
}
}
log.Fatal().Err(err).Msg(fmt.Sprintf("%s Unable to connect to NEAR WS Server", err))
}
conn = tryConn
break
}
defer conn.Close()
// Read messages from connection
for {
select {
case <-s.done:
return
default:
_, wsMessage, err := conn.ReadMessage()
if err != nil && isBackfill {
log.Debug().Msg(fmt.Sprintf("%s Backfill ws connection closed", err))
return
} else if err != nil {
s.errChan <- err
continue
}
protoMsg := proto.Clone(protoMsgType)
if err := proto.Unmarshal(wsMessage, protoMsg); err != nil {
s.errChan <- err
continue
}
ch <- &kafkautils.Message{
MsgType: kafkaMsgType,
ProtoMsg: protoMsg,
}
}
}
}
func (s *Subscription) getMsgChan(msgType proto.Message) chan *kafkautils.Message {
switch reflect.TypeOf(msgType) {
case reflect.TypeOf(&Block{}):
return s.blockChan
case reflect.TypeOf(&Transaction{}):
return s.transactionChan
case reflect.TypeOf(&Receipt{}):
return s.receiptChan
case reflect.TypeOf(&ExecutionOutcome{}):
return s.executionOutcomeChan
default:
return nil
}
}