-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstream.go
353 lines (282 loc) · 8.61 KB
/
stream.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
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
# Callback functions
This library uses callback functions to allow the users to execute the code
needed when certain events are triggered.
the Stream struct accepts the following callback functions
InitHandler func(*eos.ABI)
Called when the first message on the stream arrives.
This message contains the abi with all the information about the functions/types exposed by the websocket api.
BlockHandler func(*ship.GetBlocksResultV0)
Called when the stream reveives a block message from the server.
TraceHandler func([]*ship.TransactionTraceV0)
When the stream reveives a block message from the server and the
Block has any traces attached to it. these traces are then passed to this callback.
StatusHandler func(*ship.GetStatusResultV0)
Called when the stream reveives a status message.
CloseHandler func()
Called when a stream has closed the socket connection (in `(*Stream) Shutdown()` function)
*/
package antelope_ship_client
import (
"context"
"errors"
"sync/atomic"
"time"
"github.com/eosswedenorg-go/antelope-ship-client/websocket"
ws "github.com/gorilla/websocket"
"github.com/shufflingpixels/antelope-go/chain"
"github.com/shufflingpixels/antelope-go/ship"
)
var ErrEndBlockReached = errors.New("ship: end block reached")
const NULL_BLOCK_NUMBER uint32 = 0xffffffff
type (
InitFn func(*chain.Abi)
BlockFn func(*ship.GetBlocksResultV0)
TraceFn func(*ship.TransactionTraceArray)
TableDeltaFn func(*ship.TableDeltaArray)
StatusFn func(*ship.GetStatusResultV0)
CloseFn func()
)
type Stream struct {
// Socket connection
client websocket.Client
// Specifies the duration for the connection to be established before the client bails out.
ConnectTimeout time.Duration
// Specifies the duration for Shutdown() to wait before forcefully disconnecting the socket.
ShutdownTimeout time.Duration
// Block to start receiving notifications on.
StartBlock uint32
// Block to end receiving notifications on.
EndBlock uint32
// if only irreversible blocks should be sent.
IrreversibleOnly bool
// Max messages that can be sent from the server without being acked.
MaxMessagesInFlight uint32
// current number of messages received.
msgRecv uint32
inShutdown atomic.Bool
// Callback functions
InitHandler InitFn
BlockHandler BlockFn
TraceHandler TraceFn
TableDeltaHandler TableDeltaFn
StatusHandler StatusFn
CloseHandler CloseFn
}
type Option func(*Stream)
// Create a new stream
func NewStream(options ...Option) *Stream {
s := &Stream{
ConnectTimeout: time.Second * 30,
ShutdownTimeout: time.Second * 4,
EndBlock: NULL_BLOCK_NUMBER,
MaxMessagesInFlight: 0xffffffff,
}
for _, opt := range options {
opt(s)
}
return s
}
// Option to set Stream.ConnectTimeout
func WithConnectTimeout(value time.Duration) Option {
return func(s *Stream) {
s.ConnectTimeout = value
}
}
// Option to set Stream.ShutdownTimeout
func WithShutdownTimeout(value time.Duration) Option {
return func(s *Stream) {
s.ShutdownTimeout = value
}
}
// Option to set Stream.StartBlock
func WithStartBlock(value uint32) Option {
return func(s *Stream) {
s.StartBlock = value
}
}
// Option to set Stream.EndBlock
func WithEndBlock(value uint32) Option {
return func(s *Stream) {
s.EndBlock = value
}
}
// Option to set Stream.IrreversibleOnly
func WithIrreversibleOnly(value bool) Option {
return func(s *Stream) {
s.IrreversibleOnly = value
}
}
// Option to set Stream.MaxMessagesInFlight
func WithMaxMessagesInFlight(value uint32) Option {
return func(s *Stream) {
s.MaxMessagesInFlight = value
}
}
// Option to set Stream.InitHandler
func WithInitHandler(value InitFn) Option {
return func(s *Stream) {
s.InitHandler = value
}
}
// Option to set Stream.TraceHandler
func WithTraceHandler(value TraceFn) Option {
return func(s *Stream) {
s.TraceHandler = value
}
}
// Option to include traces without using a specific trace handler
func WithTraces() Option {
return func(s *Stream) {
s.TraceHandler = func(*ship.TransactionTraceArray) {}
}
}
// Option to set Stream.BlockHandler
func WithBlockHandler(value BlockFn) Option {
return func(s *Stream) {
s.BlockHandler = value
}
}
// Option to set Stream.TableDeltaHandler
func WithTableDeltaHandler(value TableDeltaFn) Option {
return func(s *Stream) {
s.TableDeltaHandler = value
}
}
// Option to set Stream.StatusHandler
func WithStatusHandler(value StatusFn) Option {
return func(s *Stream) {
s.StatusHandler = value
}
}
// Option to set Stream.CloseHandler
func WithCloseHandler(value CloseFn) Option {
return func(s *Stream) {
s.CloseHandler = value
}
}
// Connect connects to a ship node.
// Url must be of the form schema://host[:port]
// and schema should be "ws" or "wss"
// Connect uses context.Background internally; to specify the context, use ConnectContext.
func (s *Stream) Connect(url string) error {
return s.ConnectContext(context.Background(), url)
}
// ConnectContext connects to a ship node using the provided context
//
// The provided Context must be non-nil.
// If the context expires or is canceled before the connection is complete, an error is returned.
func (s *Stream) ConnectContext(ctx context.Context, url string) error {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.ConnectTimeout)
defer cancel()
if s.InitHandler != nil {
// Tell client that we want the abi.
s.client.FetchABI = true
// defer init handler call
defer func() {
if s.client.ABI != nil {
s.InitHandler(s.client.ABI)
}
}()
}
return s.client.Connect(ctx, url)
}
func (s *Stream) blockRequest() *ship.GetBlocksRequestV0 {
return &ship.GetBlocksRequestV0{
StartBlockNum: s.StartBlock,
EndBlockNum: s.EndBlock,
MaxMessagesInFlight: s.MaxMessagesInFlight,
IrreversibleOnly: s.IrreversibleOnly,
FetchBlock: s.BlockHandler != nil,
FetchTraces: s.TraceHandler != nil,
FetchDeltas: s.TableDeltaHandler != nil,
HavePositions: nil,
}
}
// Send a blocks request to the ship server.
// This tells the server to start sending block message to the client.
func (s *Stream) SendBlocksRequest() error {
return s.client.Write(ship.Request{
BlocksRequest: s.blockRequest(),
})
}
// Send a status request to the ship server.
// This tells the server to start sending status message to the client.
func (s *Stream) SendStatusRequest() error {
return s.client.Write(ship.Request{
StatusRequest: &ship.GetStatusRequestV0{},
})
}
func (s *Stream) routeBlock(block *ship.GetBlocksResultV0) {
if s.BlockHandler != nil {
s.BlockHandler(block)
}
if block.Traces != nil && s.TraceHandler != nil {
s.TraceHandler(block.Traces)
}
if block.Deltas != nil && s.TableDeltaHandler != nil {
s.TableDeltaHandler(block.Deltas)
}
}
// Run starts the stream.
// Messages from the server is read and forwarded to the appropriate callback function.
// This function will block until an error occur or the stream is closed.
// Either way the return value is never nil.
func (s *Stream) Run() error {
var endblockreached bool = false // End of stream
for {
result, err := s.client.Read()
if err != nil {
if ws.IsCloseError(err, ws.CloseNormalClosure) && endblockreached {
err = ErrEndBlockReached
}
if err != websocket.ErrNotConnected && s.inShutdown.Load() == false {
_ = s.Shutdown()
}
return err
}
// Parse message and route to correct callback.
if result.BlocksResult != nil {
block := result.BlocksResult
if block.ThisBlock == nil {
continue
}
s.routeBlock(block)
if block.ThisBlock.BlockNum+1 >= s.EndBlock {
// Send Close message, ignore errors here as we
// should resume reading from the socket.
_ = s.client.WriteClose(ws.CloseNormalClosure, "end block reached")
// Signal that the stream was closed due to end block reached.
endblockreached = true
}
}
if s.StatusHandler != nil && result.StatusResult != nil {
s.StatusHandler(result.StatusResult)
}
s.handleAck()
}
}
func (s *Stream) handleAck() {
s.msgRecv++
if s.msgRecv >= s.MaxMessagesInFlight {
s.client.Write(ship.Request{
BlocksAckRequest: &ship.GetBlocksAckRequestV0{
NumMessages: s.msgRecv,
},
})
s.msgRecv = 0
}
}
// Shutdown closes the stream gracefully by performing a websocket close handshake.
// This function will block until a close message is received from the server, an error occur or timeout is exceeded.
func (s *Stream) Shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), s.ShutdownTimeout)
defer cancel()
if s.CloseHandler != nil {
defer s.CloseHandler()
}
s.inShutdown.Store(true)
defer s.inShutdown.Store(false)
return s.client.Shutdown(ctx)
}