-
Notifications
You must be signed in to change notification settings - Fork 39
/
stchain_connection.go
238 lines (198 loc) · 5.82 KB
/
stchain_connection.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
package client
import (
"context"
"fmt"
"sync"
"time"
"github.com/cometbft/cometbft/rpc/client/http"
coretypes "github.com/cometbft/cometbft/rpc/core/types"
comettypes "github.com/cometbft/cometbft/types"
"github.com/pkg/errors"
"github.com/stratosnet/sds/framework/utils"
"github.com/stratosnet/sds/relayer/cmd/relayd/setting"
"github.com/stratosnet/sds/relayer/stratoschain"
"github.com/stratosnet/sds/relayer/stratoschain/handlers"
)
// stchainConnection is used to subscribe to stratos-chain events and receive messages via websocket
type stchainConnection struct {
client *MultiClient
stratosEventsChannels *sync.Map
cancel context.CancelFunc
ctx context.Context
once *sync.Once
wg *sync.WaitGroup
mux sync.Mutex
}
type websocketSubscription struct {
channel <-chan coretypes.ResultEvent
client *http.HTTP
query string
}
func newStchainConnection(client *MultiClient) *stchainConnection {
return &stchainConnection{
client: client,
stratosEventsChannels: &sync.Map{},
}
}
func (s *stchainConnection) stop() {
if s.once == nil {
return
}
s.once.Do(func() {
s.cancel()
s.stratosEventsChannels.Range(func(k, v interface{}) bool {
subscription, ok := v.(websocketSubscription)
if !ok {
return false
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
if subscription.client == nil {
return
}
err := subscription.client.Unsubscribe(context.Background(), "", subscription.query)
if err != nil {
utils.ErrorLog("couldn't unsubscribe from "+subscription.query, err)
} else {
utils.DetailLog("unsubscribed from " + subscription.query)
}
_ = subscription.client.Stop()
}()
return false
})
s.wg.Wait()
utils.Log("stchain connection has been stopped")
})
}
func (s *stchainConnection) refresh() {
if !s.mux.TryLock() {
return // Refresh procedure already started
}
defer s.mux.Unlock()
s.stop() // Stop the connection if it was started before
s.ctx, s.cancel = context.WithCancel(s.client.Ctx)
s.once = &sync.Once{}
s.wg = &sync.WaitGroup{}
s.wg.Add(1)
defer s.wg.Done()
// Schedule next connection refresh
if setting.Config.StratosChain.ConnectionRetries.RefreshInterval > 0 {
s.wg.Add(1)
go func() {
defer s.wg.Done()
select {
case <-time.After(time.Duration(setting.Config.StratosChain.ConnectionRetries.RefreshInterval) * time.Second):
utils.Logf("stchain connection has been alive for a long time and will be refreshed")
go s.refresh()
case <-s.ctx.Done():
return
}
}()
}
// Connect to stratos-chain in a loop
i := 0
for ; i < setting.Config.StratosChain.ConnectionRetries.Max; i++ {
if s.ctx.Err() != nil {
return
}
if i != 0 {
time.Sleep(time.Millisecond * time.Duration(setting.Config.StratosChain.ConnectionRetries.SleepDuration))
}
err := s.subscribeToStratosChainEvents()
if err != nil {
utils.ErrorLog(err)
continue
}
utils.Log("Successfully subscribed to events from stratos-chain")
return
}
// This is reached when we couldn't establish the connection to the stratos-chain
if i == setting.Config.StratosChain.ConnectionRetries.Max {
utils.ErrorLog("Couldn't connect to stratos-chain after many tries. Relayd will shutdown")
} else {
utils.ErrorLog("Couldn't subscribe to stratos-chain events through websockets. Relayd will shutdown")
}
s.client.cancel() // Cancel global context
}
func (s *stchainConnection) stratosSubscriptionReaderLoop(subscription websocketSubscription, handler func(coretypes.ResultEvent)) {
s.wg.Add(1)
defer func() {
if r := recover(); r != nil {
utils.ErrorLog("Recovering from panic in stratos-chain subscription reader loop", r)
}
s.wg.Done()
go s.refresh()
}()
for {
select {
case <-s.ctx.Done():
return
case message, ok := <-subscription.channel:
if !ok {
utils.Log("The stratos-chain events websocket channel has been closed")
return
}
utils.Logf("Received a new message of type [%v] from stratos-chain!", subscription.query)
cleanEventStrings(message)
handler(message)
}
}
}
func (s *stchainConnection) subscribeToStratosChain(msgType string) error {
handler, ok := handlers.Handlers[msgType]
if !ok {
return errors.Errorf("Cannot subscribe to message [%v] in stratos-chain: missing handler function", msgType)
}
query := fmt.Sprintf("message.action='%v'", msgType)
if _, ok := s.stratosEventsChannels.Load(query); ok {
return nil
}
client, err := stratoschain.DialWebsocket(setting.Config.StratosChain.WebsocketServer)
if err != nil {
return err
}
out, err := client.Subscribe(context.Background(), "", query, 20)
if err != nil {
return errors.New("failed to subscribe to query in stratos-chain: " + err.Error())
}
subscription := websocketSubscription{
channel: out,
client: client,
query: query,
}
s.stratosEventsChannels.Store(query, subscription)
go s.stratosSubscriptionReaderLoop(subscription, handler)
return nil
}
func (s *stchainConnection) subscribeToStratosChainEvents() error {
for msgType := range handlers.Handlers {
err := s.subscribeToStratosChain(msgType)
if err != nil {
return err
}
}
return nil
}
func cleanEventStrings(resultEvent coretypes.ResultEvent) {
for name, values := range resultEvent.Events {
for i, value := range values {
if len(value) >= 2 && value[0:1] == "\"" && value[len(value)-1:] == "\"" {
values[i] = value[1 : len(value)-1]
}
}
resultEvent.Events[name] = values
}
eventDataTx, ok := resultEvent.Data.(comettypes.EventDataTx)
if !ok {
return
}
for i, event := range eventDataTx.Result.Events {
for j, attribute := range event.Attributes {
if len(attribute.Value) >= 2 && attribute.Value[0:1] == "\"" && attribute.Value[len(attribute.Value)-1:] == "\"" {
event.Attributes[j].Value = attribute.Value[1 : len(attribute.Value)-1]
}
}
eventDataTx.Result.Events[i] = event
}
}