-
Notifications
You must be signed in to change notification settings - Fork 247
/
subscriptions.go
319 lines (292 loc) · 8.01 KB
/
subscriptions.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
// Copyright (c) 2018 The VeChainThor developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>
package subscriptions
import (
"net/http"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/inconshreveable/log15"
"github.com/pkg/errors"
"github.com/vechain/thor/api/utils"
"github.com/vechain/thor/block"
"github.com/vechain/thor/chain"
"github.com/vechain/thor/thor"
)
type Subscriptions struct {
backtraceLimit uint32
repo *chain.Repository
upgrader *websocket.Upgrader
done chan struct{}
wg sync.WaitGroup
}
type msgReader interface {
Read() (msgs []interface{}, hasMore bool, err error)
}
var (
log = log15.New("pkg", "subscriptions")
)
const (
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 7) / 10
)
func New(repo *chain.Repository, allowedOrigins []string, backtraceLimit uint32) *Subscriptions {
return &Subscriptions{
backtraceLimit: backtraceLimit,
repo: repo,
upgrader: &websocket.Upgrader{
EnableCompression: true,
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
for _, allowedOrigin := range allowedOrigins {
if allowedOrigin == origin || allowedOrigin == "*" {
return true
}
}
return false
},
},
done: make(chan struct{}),
}
}
func (s *Subscriptions) handleBlockReader(w http.ResponseWriter, req *http.Request) (*blockReader, error) {
position, err := s.parsePosition(req.URL.Query().Get("pos"))
if err != nil {
return nil, err
}
return newBlockReader(s.repo, position), nil
}
func (s *Subscriptions) handleEventReader(w http.ResponseWriter, req *http.Request) (*eventReader, error) {
position, err := s.parsePosition(req.URL.Query().Get("pos"))
if err != nil {
return nil, err
}
address, err := parseAddress(req.URL.Query().Get("addr"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "addr"))
}
t0, err := parseTopic(req.URL.Query().Get("t0"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "t0"))
}
t1, err := parseTopic(req.URL.Query().Get("t1"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "t1"))
}
t2, err := parseTopic(req.URL.Query().Get("t2"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "t2"))
}
t3, err := parseTopic(req.URL.Query().Get("t3"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "t3"))
}
t4, err := parseTopic(req.URL.Query().Get("t4"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "t4"))
}
eventFilter := &EventFilter{
Address: address,
Topic0: t0,
Topic1: t1,
Topic2: t2,
Topic3: t3,
Topic4: t4,
}
return newEventReader(s.repo, position, eventFilter), nil
}
func (s *Subscriptions) handleTransferReader(w http.ResponseWriter, req *http.Request) (*transferReader, error) {
position, err := s.parsePosition(req.URL.Query().Get("pos"))
if err != nil {
return nil, err
}
txOrigin, err := parseAddress(req.URL.Query().Get("txOrigin"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "txOrigin"))
}
sender, err := parseAddress(req.URL.Query().Get("sender"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "sender"))
}
recipient, err := parseAddress(req.URL.Query().Get("recipient"))
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "recipient"))
}
transferFilter := &TransferFilter{
TxOrigin: txOrigin,
Sender: sender,
Recipient: recipient,
}
return newTransferReader(s.repo, position, transferFilter), nil
}
func (s *Subscriptions) handleBeatReader(w http.ResponseWriter, req *http.Request) (*beatReader, error) {
position, err := s.parsePosition(req.URL.Query().Get("pos"))
if err != nil {
return nil, err
}
return newBeatReader(s.repo, position), nil
}
func (s *Subscriptions) handleBeat2Reader(w http.ResponseWriter, req *http.Request) (*beat2Reader, error) {
position, err := s.parsePosition(req.URL.Query().Get("pos"))
if err != nil {
return nil, err
}
return newBeat2Reader(s.repo, position), nil
}
func (s *Subscriptions) handleSubject(w http.ResponseWriter, req *http.Request) error {
s.wg.Add(1)
defer s.wg.Done()
var (
reader msgReader
err error
)
switch mux.Vars(req)["subject"] {
case "block":
if reader, err = s.handleBlockReader(w, req); err != nil {
return err
}
case "event":
if reader, err = s.handleEventReader(w, req); err != nil {
return err
}
case "transfer":
if reader, err = s.handleTransferReader(w, req); err != nil {
return err
}
case "beat":
if reader, err = s.handleBeatReader(w, req); err != nil {
return err
}
case "beat2":
if reader, err = s.handleBeat2Reader(w, req); err != nil {
return err
}
default:
return utils.HTTPError(errors.New("not found"), http.StatusNotFound)
}
conn, err := s.upgrader.Upgrade(w, req, nil)
// since the conn is hijacked here, no error should be returned in lines below
if err != nil {
log.Debug("upgrade to websocket", "err", err)
return nil
}
defer func() {
if err := conn.Close(); err != nil {
log.Debug("close websocket", "err", err)
}
}()
var closeMsg []byte
if err := s.pipe(conn, reader); err != nil {
closeMsg = websocket.FormatCloseMessage(websocket.CloseInternalServerErr, err.Error())
} else {
closeMsg = websocket.FormatCloseMessage(websocket.CloseGoingAway, "")
}
if err := conn.WriteMessage(websocket.CloseMessage, closeMsg); err != nil {
log.Debug("write close message", "err", err)
}
return nil
}
func (s *Subscriptions) pipe(conn *websocket.Conn, reader msgReader) error {
closed := make(chan struct{})
// start read loop to handle close event
s.wg.Add(1)
go func() {
defer s.wg.Done()
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
if _, _, err := conn.ReadMessage(); err != nil {
log.Debug("websocket read err", "err", err)
close(closed)
break
}
}
}()
ticker := s.repo.NewTicker()
pingTicker := time.NewTicker(pingPeriod)
defer pingTicker.Stop()
for {
msgs, hasMore, err := reader.Read()
if err != nil {
return err
}
for _, msg := range msgs {
if err := conn.WriteJSON(msg); err != nil {
return err
}
}
if hasMore {
select {
case <-s.done:
return nil
case <-closed:
return nil
case <-pingTicker.C:
conn.WriteMessage(websocket.PingMessage, nil)
default:
}
} else {
select {
case <-s.done:
return nil
case <-closed:
return nil
case <-ticker.C():
case <-pingTicker.C:
conn.WriteMessage(websocket.PingMessage, nil)
}
}
}
}
func (s *Subscriptions) parsePosition(posStr string) (thor.Bytes32, error) {
bestID := s.repo.BestBlockSummary().Header.ID()
if posStr == "" {
return bestID, nil
}
pos, err := thor.ParseBytes32(posStr)
if err != nil {
return thor.Bytes32{}, utils.BadRequest(errors.WithMessage(err, "pos"))
}
if block.Number(bestID)-block.Number(pos) > s.backtraceLimit {
return thor.Bytes32{}, utils.Forbidden(errors.New("pos: backtrace limit exceeded"))
}
return pos, nil
}
func parseTopic(t string) (*thor.Bytes32, error) {
if t == "" {
return nil, nil
}
topic, err := thor.ParseBytes32(t)
if err != nil {
return nil, err
}
return &topic, nil
}
func parseAddress(addr string) (*thor.Address, error) {
if addr == "" {
return nil, nil
}
address, err := thor.ParseAddress(addr)
if err != nil {
return nil, err
}
return &address, nil
}
func (s *Subscriptions) Close() {
close(s.done)
s.wg.Wait()
}
func (s *Subscriptions) Mount(root *mux.Router, pathPrefix string) {
sub := root.PathPrefix(pathPrefix).Subrouter()
sub.Path("/{subject}").Methods("Get").HandlerFunc(utils.WrapHandlerFunc(s.handleSubject))
}