-
Notifications
You must be signed in to change notification settings - Fork 179
/
server.go
313 lines (274 loc) · 7.74 KB
/
server.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
package websockets
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"strings"
"sync"
"github.com/ethereum/go-ethereum/rpc"
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/prometheus"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/okex/exchain/libs/cosmos-sdk/client/context"
"github.com/okex/exchain/libs/cosmos-sdk/server"
"github.com/okex/exchain/libs/tendermint/libs/log"
"github.com/okex/exchain/x/common/monitor"
stdprometheus "github.com/prometheus/client_golang/prometheus"
"github.com/spf13/viper"
)
// Server defines a server that handles Ethereum websockets.
type Server struct {
rpcAddr string // listen address of rest-server
wsAddr string // listen address of ws server
api *PubSubAPI
logger log.Logger
connPool chan struct{}
connPoolLock *sync.Mutex
currentConnNum metrics.Gauge
maxConnNum metrics.Gauge
}
// NewServer creates a new websocket server instance.
func NewServer(clientCtx context.CLIContext, log log.Logger, wsAddr string) *Server {
restServerAddr := viper.GetString(server.FlagListenAddr)
parts := strings.SplitN(restServerAddr, "://", 2)
if len(parts) != 2 {
panic(fmt.Errorf("invalid listening address %s (use fully formed addresses, including the tcp:// or unix:// prefix)", restServerAddr))
}
url := parts[1]
urlParts := strings.SplitN(url, ":", 2)
if len(urlParts) != 2 {
panic(fmt.Errorf("invalid listening address %s (use ip:port as an url)", url))
}
port := urlParts[1]
return &Server{
rpcAddr: "http://localhost:" + port,
wsAddr: wsAddr,
api: NewAPI(clientCtx, log),
logger: log.With("module", "websocket-server"),
connPool: make(chan struct{}, viper.GetInt(server.FlagWsMaxConnections)),
connPoolLock: new(sync.Mutex),
currentConnNum: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{
Namespace: monitor.XNameSpace,
Subsystem: "websocket",
Name: "connection_number",
Help: "the number of current websocket client connections",
}, nil),
maxConnNum: prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{
Namespace: monitor.XNameSpace,
Subsystem: "websocket",
Name: "connection_capacity",
Help: "the capacity number of websocket client connections",
}, nil),
}
}
// Start runs the websocket server
func (s *Server) Start() {
ws := mux.NewRouter()
ws.Handle("/", s)
s.maxConnNum.Set(float64(viper.GetInt(server.FlagWsMaxConnections)))
s.currentConnNum.Set(0)
go func() {
err := http.ListenAndServe(fmt.Sprintf(":%s", s.wsAddr), ws)
if err != nil {
s.logger.Error("http error:", err)
}
}()
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.connPoolLock.Lock()
defer s.connPoolLock.Unlock()
if len(s.connPool) >= cap(s.connPool) {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
s.logger.Error("websocket upgrade failed", " error", err)
return
}
s.connPool <- struct{}{}
s.currentConnNum.Set(float64(len(s.connPool)))
go s.readLoop(&wsConn{
mux: new(sync.Mutex),
conn: conn,
})
}
func (s *Server) sendErrResponse(conn *wsConn, msg string) {
res := &ErrorResponseJSON{
Jsonrpc: "2.0",
Error: &ErrorMessageJSON{
Code: big.NewInt(-32600),
Message: msg,
},
ID: big.NewInt(1),
}
err := conn.WriteJSON(res)
if err != nil {
s.logger.Error("websocket failed write message", "error", err)
}
}
type wsConn struct {
conn *websocket.Conn
mux *sync.Mutex
}
func (w *wsConn) WriteJSON(v interface{}) error {
w.mux.Lock()
defer w.mux.Unlock()
return w.conn.WriteJSON(v)
}
func (w *wsConn) Close() error {
w.mux.Lock()
defer w.mux.Unlock()
return w.conn.Close()
}
func (w *wsConn) ReadMessage() (messageType int, p []byte, err error) {
// not protected by write mutex
return w.conn.ReadMessage()
}
func (s *Server) readLoop(wsConn *wsConn) {
subIds := make(map[rpc.ID]struct{})
for {
_, mb, err := wsConn.ReadMessage()
if err != nil {
_ = wsConn.Close()
s.logger.Error("failed to read message, close the websocket connection.", "error", err)
s.closeWsConnection(subIds)
return
}
var msg map[string]interface{}
if err = json.Unmarshal(mb, &msg); err != nil {
if err = s.batchCall(mb, wsConn); err != nil {
s.sendErrResponse(wsConn, "invalid request")
}
continue
}
// check if method == eth_subscribe or eth_unsubscribe
method := msg["method"]
if method.(string) == "eth_subscribe" {
params := msg["params"].([]interface{})
if len(params) == 0 {
s.sendErrResponse(wsConn, "invalid parameters")
continue
}
reqId, ok := msg["id"].(float64)
if !ok {
s.sendErrResponse(wsConn, "invaild id in request message")
continue
}
id, err := s.api.subscribe(wsConn, params)
if err != nil {
s.sendErrResponse(wsConn, err.Error())
continue
}
res := &SubscriptionResponseJSON{
Jsonrpc: "2.0",
ID: reqId,
Result: id,
}
err = wsConn.WriteJSON(res)
if err != nil {
s.logger.Error("failed to write json response", "ID", id, "error", err)
continue
}
s.logger.Debug("successfully subscribe", "ID", id)
subIds[id] = struct{}{}
continue
} else if method.(string) == "eth_unsubscribe" {
ids, ok := msg["params"].([]interface{})
if len(ids) == 0 {
s.sendErrResponse(wsConn, "invalid parameters")
continue
}
id, idok := ids[0].(string)
if !ok || !idok {
s.sendErrResponse(wsConn, "invalid parameters")
continue
}
reqId, ok := msg["id"].(float64)
if !ok {
s.sendErrResponse(wsConn, "invaild id in request message")
continue
}
ok = s.api.unsubscribe(rpc.ID(id))
res := &SubscriptionResponseJSON{
Jsonrpc: "2.0",
ID: reqId,
Result: ok,
}
err = wsConn.WriteJSON(res)
if err != nil {
s.logger.Error("failed to write json response", "ID", id, "error", err)
continue
}
s.logger.Debug("successfully unsubscribe", "ID", id)
delete(subIds, rpc.ID(id))
continue
}
// otherwise, call the usual rpc server to respond
err = s.tcpGetAndSendResponse(wsConn, mb)
if err != nil {
s.sendErrResponse(wsConn, err.Error())
}
}
}
// tcpGetAndSendResponse connects to the rest-server over tcp, posts a JSON-RPC request, and sends the response
// to the client over websockets
func (s *Server) tcpGetAndSendResponse(conn *wsConn, mb []byte) error {
req, err := http.NewRequest(http.MethodPost, s.rpcAddr, bytes.NewReader(mb))
if err != nil {
return fmt.Errorf("failed to request; %s", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to write to rest-server; %s", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("could not read body from response; %s", err)
}
var wsSend interface{}
err = json.Unmarshal(body, &wsSend)
if err != nil {
return fmt.Errorf("failed to unmarshal rest-server response; %s", err)
}
return conn.WriteJSON(wsSend)
}
func (s *Server) closeWsConnection(subIds map[rpc.ID]struct{}) {
for id := range subIds {
s.api.unsubscribe(id)
delete(subIds, id)
}
s.connPoolLock.Lock()
defer s.connPoolLock.Unlock()
<-s.connPool
s.currentConnNum.Set(float64(len(s.connPool)))
}
func (s *Server) batchCall(mb []byte, wsConn *wsConn) error {
var msgs []interface{}
if err := json.Unmarshal(mb, &msgs); err != nil {
return err
}
for i := 0; i < len(msgs); i++ {
b, err := json.Marshal(msgs[i])
if err != nil {
s.sendErrResponse(wsConn, err.Error())
continue
}
err = s.tcpGetAndSendResponse(wsConn, b)
if err != nil {
s.sendErrResponse(wsConn, err.Error())
}
}
return nil
}