-
Notifications
You must be signed in to change notification settings - Fork 4
/
engine.go
340 lines (288 loc) · 9.53 KB
/
engine.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
package stream
import (
"fmt"
"strings"
"time"
"github.com/zenchainprotocol/zenchain-node/x/stream/common/kline"
"github.com/zenchainprotocol/zenchain-node/x/stream/kafkaclient"
"github.com/zenchainprotocol/zenchain-node/x/stream/websocket"
"github.com/pkg/errors"
"github.com/go-sql-driver/mysql"
"github.com/tendermint/tendermint/libs/log"
appCfg "github.com/cosmos/cosmos-sdk/server/config"
"github.com/zenchainprotocol/zenchain-node/x/backend"
"github.com/zenchainprotocol/zenchain-node/x/stream/analyservice"
"github.com/zenchainprotocol/zenchain-node/x/stream/common"
"github.com/zenchainprotocol/zenchain-node/x/stream/pulsarclient"
"github.com/zenchainprotocol/zenchain-node/x/stream/pushservice"
pushservicetypes "github.com/zenchainprotocol/zenchain-node/x/stream/pushservice/types"
"github.com/zenchainprotocol/zenchain-node/x/stream/types"
)
type Kind byte
type EngineKind byte
const (
StreamNilKind Kind = 0x00
StreamMysqlKind Kind = 0x01
StreamRedisKind Kind = 0x02
StreamPulsarKind Kind = 0x03
StreamWebSocketKind Kind = 0x04
StreamKafkaKind Kind = 0x05
EngineNilKind EngineKind = 0x00
EngineAnalysisKind EngineKind = 0x01
EngineNotifyKind EngineKind = 0x02
EngineKlineKind EngineKind = 0x03
EngineWebSocketKind EngineKind = 0x04
)
var StreamKind2EngineKindMap = map[Kind]EngineKind{
StreamMysqlKind: EngineAnalysisKind,
StreamRedisKind: EngineNotifyKind,
StreamPulsarKind: EngineKlineKind,
StreamKafkaKind: EngineKlineKind,
StreamWebSocketKind: EngineWebSocketKind,
}
var EngineKind2StreamKindMap = map[EngineKind]Kind{
EngineAnalysisKind: StreamMysqlKind,
EngineNotifyKind: StreamRedisKind,
EngineWebSocketKind: StreamWebSocketKind,
}
type MySQLEngine struct {
url string
logger log.Logger
orm *backend.ORM
}
func NewMySQLEngine(url string, log log.Logger, cfg *appCfg.StreamConfig) (types.IStreamEngine, error) {
ormTmp := analyservice.NewMysqlORM(url)
log.Info("NewAnalysisService succeed")
// connect mysql through streamUrl
return &MySQLEngine{
url: url,
logger: log,
orm: ormTmp,
}, nil
}
func (e *MySQLEngine) URL() string {
return e.url
}
func (e *MySQLEngine) Write(data types.IStreamData, success *bool) {
e.logger.Debug("Entering MySqlEngine write")
enData, ok := data.(*analyservice.DataAnalysis)
if !ok {
panic(fmt.Sprintf("MySqlEngine Convert data %+v to DataAnalysis failed", data))
}
results, err := e.orm.BatchInsertOrUpdate(enData.NewOrders, enData.UpdatedOrders, enData.Deals, enData.MatchResults,
enData.FeeDetails, enData.Trans, enData.SwapInfos, enData.ClaimInfos)
if err != nil {
e.logger.Error(fmt.Sprintf("MySqlEngine write failed: %s, results: %v", err.Error(), results))
*success = false
if mysqlerr, ok := err.(*mysql.MySQLError); ok {
e.logger.Error(fmt.Sprintf("MySQLError: %+v", err.Error()))
// Duplicate entry 'XXX' for key 'PRIMARY'
if mysqlerr.Number == 1062 {
e.logger.Error(fmt.Sprintf("MySqlEngine write failed becoz 1062: %s, considered success, result: %+v", err.Error(), results))
*success = true
}
}
} else {
e.logger.Debug(fmt.Sprintf("MySqlEngine write result: %+v", results))
*success = true
}
}
type PulsarEngine struct {
url string
logger log.Logger
pulsarProducer *pulsarclient.PulsarProducer
}
func NewPulsarEngine(url string, logger log.Logger, cfg *appCfg.StreamConfig) (types.IStreamEngine, error) {
asyncErrs := make(chan error, 16)
producer := pulsarclient.NewPulsarProducer(url, cfg, logger, &asyncErrs)
time.Sleep(time.Second * 3)
if len(asyncErrs) != 0 {
err := <-asyncErrs
logger.Error(fmt.Sprintf("create pulsar producer failed: %s", err.Error()))
return nil, err
}
logger.Info("create pulsar producer succeed")
// connect mysql through streamUrl()
return &PulsarEngine{
url: url,
logger: logger,
pulsarProducer: producer,
}, nil
}
func (e *PulsarEngine) URL() string {
return e.url
}
func (e *PulsarEngine) Write(data types.IStreamData, success *bool) {
e.logger.Debug("Entering PulsarEngine Write")
enData, ok := data.(*kline.KlineData)
if !ok {
panic(fmt.Sprintf("Convert data %+v to KlineData failed", data))
}
err := e.pulsarProducer.RefreshMarketIDMap(enData, e.logger)
if err != nil {
e.logger.Error(fmt.Sprintf("pulsar engine RefreshMarketIdMap failed: %s", err.Error()))
*success = false
return
}
results, err := e.pulsarProducer.SendAllMsg(enData, e.logger)
if err != nil {
e.logger.Error(fmt.Sprintf("pulsar engine write failed: %s, results: %v", err.Error(), results))
*success = false
} else {
e.logger.Debug(fmt.Sprintf("PulsarEngine write result: %+v", results))
*success = true
}
}
type KafkaEngine struct {
url string
logger log.Logger
kafkaProducer *kafkaclient.KafkaProducer
}
func NewKafkaEngine(url string, logger log.Logger, cfg *appCfg.StreamConfig) (types.IStreamEngine, error) {
return &KafkaEngine{
url: url,
logger: logger,
kafkaProducer: kafkaclient.NewKafkaProducer(url, cfg),
}, nil
}
func (ke *KafkaEngine) URL() string {
return ke.url
}
func (ke *KafkaEngine) Write(data types.IStreamData, success *bool) {
ke.logger.Debug("Entering KafkaEngine Write")
enData, ok := data.(*kline.KlineData)
if !ok {
panic(fmt.Sprintf("Convert data %+v to KlineData failed", data))
}
if err := ke.kafkaProducer.RefreshMarketIDMap(enData, ke.logger); err != nil {
ke.logger.Error(fmt.Sprintf("kafka engine RefreshMarketIdMap failed: %s", err.Error()))
*success = false
return
}
results, err := ke.kafkaProducer.SendAllMsg(enData, ke.logger)
if err != nil {
ke.logger.Error(fmt.Sprintf("kafka engine write failed: %s, results: %v", err.Error(), results))
*success = false
} else {
ke.logger.Debug(fmt.Sprintf("kafka engine write result: %+v", results))
*success = true
}
}
type RedisEngine struct {
url string
logger log.Logger
srv *pushservice.PushService
}
func NewRedisEngine(url string, logger log.Logger, cfg *appCfg.StreamConfig) (types.IStreamEngine, error) {
redisURL, redisPassword, err := common.ParseRedisURL(url, cfg.RedisRequirePass)
if err != nil {
return nil, err
}
srv, err := pushservice.NewPushService(redisURL, redisPassword, 0, logger)
if err != nil {
logger.Error("NewPushService failed ", err.Error())
return nil, err
}
logger.Info("NewPushService succeed")
return &RedisEngine{
url: url,
logger: logger,
srv: srv,
}, nil
}
func (e *RedisEngine) URL() string {
return e.url
}
func (e *RedisEngine) Write(data types.IStreamData, success *bool) {
e.logger.Debug("Entering RedisEngine Write")
enData, ok := data.(*pushservicetypes.RedisBlock)
if !ok {
panic(fmt.Sprintf("Convert data %+v to PulsarData failed", data))
}
results, err := e.srv.WriteSync(enData)
if err != nil {
e.logger.Error(fmt.Sprintf("redis engine write failed: %s, results: %+v", err.Error(), results))
*success = false
} else {
e.logger.Debug(fmt.Sprintf("RedisEngine write result: %+v", results))
*success = true
}
}
type EngineCreator func(url string, logger log.Logger, cfg *appCfg.StreamConfig) (types.IStreamEngine, error)
func GetEngineCreator(eKind EngineKind, sKind Kind) (EngineCreator, error) {
m := map[string]EngineCreator{
fmt.Sprintf("%d_%d", EngineAnalysisKind, StreamMysqlKind): NewMySQLEngine,
fmt.Sprintf("%d_%d", EngineNotifyKind, StreamRedisKind): NewRedisEngine,
fmt.Sprintf("%d_%d", EngineKlineKind, StreamPulsarKind): NewPulsarEngine,
fmt.Sprintf("%d_%d", EngineWebSocketKind, StreamWebSocketKind): websocket.NewEngine,
fmt.Sprintf("%d_%d", EngineKlineKind, StreamKafkaKind): NewKafkaEngine,
}
key := fmt.Sprintf("%d_%d", eKind, sKind)
c, ok := m[key]
if ok {
return c, nil
}
return nil, fmt.Errorf("no EngineCreator found for EngineKine %d & StreamKine %d ", eKind, sKind)
}
func ParseStreamEngineConfig(logger log.Logger, cfg *appCfg.StreamConfig) (map[EngineKind]types.IStreamEngine, error) {
if cfg.Engine == "" {
return nil, errors.New("stream engine config is empty")
}
engines := make(map[EngineKind]types.IStreamEngine)
list := strings.Split(cfg.Engine, ",")
for _, item := range list {
enginesConf := strings.Split(item, "|")
// Desktop Stream Engine Mode: mysql | websocket
// HA Stream Engine Mode: mysql | redis | pulsar(kafka)
if len(enginesConf) != 3 {
return nil, fmt.Errorf("expected list in a form of \"engine_type:stream_type:stream_url\" pairs, given pair %s, list %s", item, list)
}
engineType := StringToEngineKind(enginesConf[0])
streamType := StringToStreamKind(enginesConf[1])
streamURL := enginesConf[2]
creatorFunc, err := GetEngineCreator(engineType, streamType)
if err != nil {
return nil, err
}
engine, err := creatorFunc(streamURL, logger, cfg)
if err != nil {
return nil, err
}
engines[engineType] = engine
}
return engines, nil
}
func StringToEngineKind(kind string) EngineKind {
kind = strings.ToLower(kind)
switch kind {
case "analysis":
return EngineAnalysisKind
case "notify":
return EngineNotifyKind
case "kline":
return EngineKlineKind
case "websocket":
return EngineWebSocketKind
default:
return EngineNilKind
}
}
func StringToStreamKind(kind string) Kind {
kind = strings.ToLower(kind)
switch kind {
case "mysql":
return StreamMysqlKind
case "redis":
return StreamRedisKind
case "pulsar":
EngineKind2StreamKindMap[EngineKlineKind] = StreamPulsarKind
return StreamPulsarKind
case "websocket":
return StreamWebSocketKind
case "kafka":
EngineKind2StreamKindMap[EngineKlineKind] = StreamKafkaKind
return StreamKafkaKind
default:
return StreamNilKind
}
}