/
client.go
645 lines (578 loc) · 17.8 KB
/
client.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package stream
import (
"context"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"sync"
"time"
)
type StreamClient interface {
// Connect establishes a connection and **reestablishes it when errors occur**
// as long as the configured number of retries has not been exceeded.
//
// It blocks until the connection has been established for the first time (or it failed to do so).
//
// **Should only be called once!**
Connect(ctx context.Context) error
// Terminated returns a channel that the client sends an error to when it has terminated.
// The channel is also closed upon termination.
Terminated() <-chan error
}
// StocksClient is a client that connects to an Alpaca Data V2 stream server
// and handles communication both ways.
//
// After constructing, Connect() must be called before any subscription changes
// are called. Connect keeps the connection alive and reestablishes it until
// a configured number of retries has not been exceeded.
//
// Terminated() returns a channel that the client sends an error to when it has terminated.
// A client can not be reused once it has terminated!
//
// SubscribeTo... and UnsubscribeFrom... can be used to modify subscriptions and
// the handler used to process incoming trades/quotes/bars/etc. These block until an
// irrecoverable error occurs or if they succeed.
//
// Note that subscription changes can not be called concurrently.
type StocksClient interface {
StreamClient
SubscribeToTrades(handler func(trade Trade), symbols ...string) error
UnsubscribeFromTrades(symbols ...string) error
SubscribeToQuotes(handler func(quote Quote), symbols ...string) error
UnsubscribeFromQuotes(symbols ...string) error
SubscribeToBars(handler func(bar Bar), symbols ...string) error
UnsubscribeFromBars(symbols ...string) error
SubscribeToUpdatedBars(handler func(bar Bar), symbols ...string) error
UnsubscribeFromUpdatedBars(symbols ...string) error
SubscribeToDailyBars(handler func(bar Bar), symbols ...string) error
UnsubscribeFromDailyBars(symbols ...string) error
SubscribeToStatuses(handler func(ts TradingStatus), symbols ...string) error
UnsubscribeFromStatuses(symbols ...string) error
SubscribeToLULDs(handler func(luld LULD), symbols ...string) error
UnsubscribeFromLULDs(symbols ...string) error
RegisterCancelErrors(handler func(tce TradeCancelError))
UnregisterCancelErrors()
RegisterCorrections(handler func(tc TradeCorrection))
UnregisterCorrections()
}
// CryptoClient is a client that connects to an Alpaca Data V2 stream server
// and handles communication both ways.
//
// After constructing, Connect() must be called before any subscription changes
// are called. Connect keeps the connection alive and reestablishes it until
// a configured number of retries has not been exceeded.
//
// Terminated() returns a channel that the client sends an error to when it has terminated.
// A client can not be reused once it has terminated!
//
// SubscribeTo... and UnsubscribeFrom... can be used to modify subscriptions and
// the handler used to process incoming trades/quotes/bars. These block until an
// irrecoverable error occurs or if they succeed.
//
// Note that subscription changes can not be called concurrently.
type CryptoClient interface {
StreamClient
SubscribeToTrades(handler func(trade CryptoTrade), symbols ...string) error
UnsubscribeFromTrades(symbols ...string) error
SubscribeToQuotes(handler func(quote CryptoQuote), symbols ...string) error
UnsubscribeFromQuotes(symbols ...string) error
SubscribeToBars(handler func(bar CryptoBar), symbols ...string) error
UnsubscribeFromBars(symbols ...string) error
SubscribeToUpdatedBars(handler func(bar CryptoBar), symbols ...string) error
UnsubscribeFromUpdatedBars(symbols ...string) error
SubscribeToDailyBars(handler func(bar CryptoBar), symbols ...string) error
UnsubscribeFromDailyBars(symbols ...string) error
SubscribeToOrderbooks(handler func(ob CryptoOrderbook), symbols ...string) error
UnsubscribeFromOrderbooks(symbols ...string) error
}
type NewsClient interface {
StreamClient
SubscribeToNews(handler func(news News), symbols ...string) error
UnsubscribeFromNews(symbols ...string) error
}
type client struct {
logger Logger
baseURL string
key string
secret string
reconnectLimit int
reconnectDelay time.Duration
connectCallback func()
disconnectCallback func()
processorCount int
bufferSize int
connectOnce sync.Once
connectCalled bool
hasTerminated bool
terminatedChan chan error
conn conn
in chan []byte
subChanges chan []byte
sub subscriptions
handler msgHandler
pendingSubChangeMutex sync.Mutex
pendingSubChange *subChangeRequest
connCreator func(ctx context.Context, u url.URL) (conn, error)
}
func newClient() *client {
return &client{
terminatedChan: make(chan error, 1),
subChanges: make(chan []byte, 1),
}
}
func (c *client) configure(o options) {
c.logger = o.logger
c.baseURL = o.baseURL
c.key = o.key
c.secret = o.secret
c.reconnectLimit = o.reconnectLimit
c.reconnectDelay = o.reconnectDelay
c.connectCallback = o.connectCallback
c.disconnectCallback = o.disconnectCallback
c.processorCount = o.processorCount
c.bufferSize = o.bufferSize
c.sub = o.sub
c.connCreator = o.connCreator
}
type stocksClient struct {
*client
feed string
handler *stocksMsgHandler
}
var _ StocksClient = (*stocksClient)(nil)
// NewStocksClient returns a new StocksClient that will connect to feed data feed
// and whose default configurations are modified by opts.
func NewStocksClient(feed string, opts ...StockOption) StocksClient {
sc := stocksClient{
client: newClient(),
feed: feed,
handler: &stocksMsgHandler{},
}
sc.client.handler = sc.handler
o := defaultStockOptions()
o.applyStock(opts...)
sc.configure(*o)
return &sc
}
func (sc *stocksClient) configure(o stockOptions) {
sc.client.configure(o.options)
sc.handler.tradeHandler = o.tradeHandler
sc.handler.quoteHandler = o.quoteHandler
sc.handler.barHandler = o.barHandler
sc.handler.updatedBarHandler = o.updatedBarHandler
sc.handler.dailyBarHandler = o.dailyBarHandler
sc.handler.tradingStatusHandler = o.tradingStatusHandler
sc.handler.luldHandler = o.luldHandler
sc.handler.cancelErrorHandler = o.cancelErrorHandler
sc.handler.correctionHandler = o.correctionHandler
}
func (sc *stocksClient) Connect(ctx context.Context) error {
u, err := sc.constructURL()
if err != nil {
return err
}
return sc.connect(ctx, u)
}
func (sc *stocksClient) constructURL() (url.URL, error) {
scheme := "wss"
ub, err := url.Parse(sc.baseURL)
if err != nil {
return url.URL{}, err
}
switch ub.Scheme {
case "http", "ws":
scheme = "ws"
}
return url.URL{Scheme: scheme, Host: ub.Host, Path: ub.Path + "/" + sc.feed}, nil
}
type cryptoClient struct {
*client
exchanges []string
handler *cryptoMsgHandler
}
var _ CryptoClient = (*cryptoClient)(nil)
// NewCryptoClient returns a new CryptoClient that will connect to the crypto feed
// and whose default configurations are modified by opts.
func NewCryptoClient(opts ...CryptoOption) CryptoClient {
cc := cryptoClient{
client: newClient(),
handler: &cryptoMsgHandler{},
}
cc.client.handler = cc.handler
o := defaultCryptoOptions()
o.applyCrypto(opts...)
cc.configure(*o)
return &cc
}
func (cc *cryptoClient) configure(o cryptoOptions) {
cc.client.configure(o.options)
cc.handler.tradeHandler = o.tradeHandler
cc.handler.quoteHandler = o.quoteHandler
cc.handler.barHandler = o.barHandler
cc.handler.updatedBarHandler = o.updatedBarHandler
cc.handler.dailyBarHandler = o.dailyBarHandler
cc.handler.orderbookHandler = o.orderbookHandler
cc.exchanges = o.exchanges
}
func (cc *cryptoClient) Connect(ctx context.Context) error {
u, err := cc.constructURL()
if err != nil {
return err
}
return cc.connect(ctx, u)
}
func (cc *cryptoClient) constructURL() (url.URL, error) {
scheme := "wss"
ub, err := url.Parse(cc.baseURL)
if err != nil {
return url.URL{}, err
}
switch ub.Scheme {
case "http", "ws":
scheme = "ws"
}
var rawQuery string
if len(cc.exchanges) > 0 {
rawQuery = "exchanges=" + strings.Join(cc.exchanges, ",")
}
return url.URL{Scheme: scheme, Host: ub.Host, Path: ub.Path, RawQuery: rawQuery}, nil
}
type newsClient struct {
*client
handler *newsMsgHandler
}
var _ NewsClient = (*newsClient)(nil)
// NewNewsClient returns a new NewsClient that will connect the news stream.
func NewNewsClient(opts ...NewsOption) NewsClient {
nc := newsClient{
client: newClient(),
handler: &newsMsgHandler{},
}
nc.client.handler = nc.handler
o := defaultNewsOptions()
o.applyNews(opts...)
nc.configure(*o)
return &nc
}
func (nc *newsClient) configure(o newsOptions) {
nc.client.configure(o.options)
nc.handler.newsHandler = o.newsHandler
}
func (nc *newsClient) Connect(ctx context.Context) error {
u, err := nc.constructURL()
if err != nil {
return err
}
return nc.connect(ctx, u)
}
func (nc *newsClient) constructURL() (url.URL, error) {
scheme := "wss"
ub, err := url.Parse(nc.baseURL)
if err != nil {
return url.URL{}, err
}
switch ub.Scheme {
case "http", "ws":
scheme = "ws"
}
return url.URL{Scheme: scheme, Host: ub.Host, Path: ub.Path}, nil
}
func (c *client) connect(ctx context.Context, u url.URL) error {
err := ErrConnectCalledMultipleTimes
c.connectOnce.Do(func() {
err = c.connectAndMaintainConnection(ctx, u)
if err != nil {
c.terminatedChan <- err
close(c.terminatedChan)
}
c.connectCalled = true
})
return err
}
func (c *client) connectAndMaintainConnection(ctx context.Context, u url.URL) error {
initialResultCh := make(chan error)
go c.maintainConnection(ctx, u, initialResultCh)
return <-initialResultCh
}
func (c *client) Terminated() <-chan error {
return c.terminatedChan
}
// maintainConnection initializes a connection to u, starts the necessary goroutines
// and recreates them if there was an error as long as reconnectLimit consecutive
// connection initialization errors don't occur. It sends the first connection
// initialization's result to initialResultCh.
func (c *client) maintainConnection(ctx context.Context, u url.URL, initialResultCh chan<- error) {
var connError error
failedAttemptsInARow := 0
connectedAtLeastOnce := false
callbackWaitGroup := sync.WaitGroup{}
defer func() {
// If there is a pending sub change we should terminate that
c.pendingSubChangeMutex.Lock()
defer c.pendingSubChangeMutex.Unlock()
if c.pendingSubChange != nil {
c.pendingSubChange.result <- ErrSubscriptionChangeInterrupted
}
c.pendingSubChange = nil
c.hasTerminated = true
// if we haven't connected at least once then Connected should close the channel
if connectedAtLeastOnce {
close(c.terminatedChan)
}
// If a disconnect/connect callback is running then wait until it finishes or times out.
timeout := time.Second
if waitTimeout(&callbackWaitGroup, timeout) {
c.logger.Warnf("datav2stream: timed out after waiting %s for connect/disconnect callbacks to return", timeout)
}
}()
sendError := func(err error) {
if !connectedAtLeastOnce {
initialResultCh <- err
} else {
c.terminatedChan <- err
}
}
for {
select {
case <-ctx.Done():
if !connectedAtLeastOnce {
c.logger.Warnf("datav2stream: cancelled before connection could be established, last error: %v", connError)
err := fmt.Errorf("cancelled before connection could be established, last error: %w", connError)
initialResultCh <- err
} else {
c.terminatedChan <- nil
}
return
default:
if c.reconnectLimit != 0 && failedAttemptsInARow >= c.reconnectLimit {
c.logger.Errorf("datav2stream: max reconnect limit has been reached, last error: %v", connError)
e := fmt.Errorf("max reconnect limit has been reached, last error: %w", connError)
sendError(e)
return
}
time.Sleep(time.Duration(failedAttemptsInARow) * c.reconnectDelay)
failedAttemptsInARow++
c.logger.Infof("datav2stream: connecting to %s, attempt %d/%d ...", u.String(), failedAttemptsInARow, c.reconnectLimit)
conn, err := c.connCreator(ctx, u)
if err != nil {
connError = err
if isHttp4xx(err) {
c.logger.Errorf("datav2stream: %v", wrapIrrecoverable(err))
sendError(wrapIrrecoverable(err))
return
}
c.logger.Warnf("datav2stream: failed to connect, error: %v", err)
continue
}
c.conn = conn
c.logger.Infof("datav2stream: established connection")
if err := c.initialize(ctx); err != nil {
connError = err
c.conn.close()
if isErrorIrrecoverableAtInit(err) {
c.logger.Errorf("datav2stream: %v", wrapIrrecoverable(err))
sendError(wrapIrrecoverable(err))
return
}
c.logger.Warnf("datav2stream: connection setup failed, error: %v", err)
continue
}
c.logger.Infof("datav2stream: finished connection setup")
if c.connectCallback != nil {
callbackWaitGroup.Add(1)
go func() {
defer callbackWaitGroup.Done()
c.connectCallback()
}()
}
connError = nil
if !connectedAtLeastOnce {
initialResultCh <- nil
connectedAtLeastOnce = true
}
failedAttemptsInARow = 0
c.in = make(chan []byte, c.bufferSize)
wg := sync.WaitGroup{}
wg.Add(c.processorCount + 3)
closeCh := make(chan struct{})
for i := 0; i < c.processorCount; i++ {
go c.messageProcessor(ctx, &wg)
}
go c.connPinger(ctx, &wg, closeCh)
go c.connReader(ctx, &wg, closeCh)
go c.connWriter(ctx, &wg, closeCh)
wg.Wait()
if ctx.Err() != nil {
c.logger.Infof("datav2stream: disconnected")
} else {
c.logger.Warnf("datav2stream: connection lost")
}
if c.disconnectCallback != nil {
callbackWaitGroup.Add(1)
go func() {
defer callbackWaitGroup.Done()
c.disconnectCallback()
}()
}
}
}
}
// waitTimeout waits for the WaitGroup for the specified max timeout.
// Returns true if waiting timed out.
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
c := make(chan struct{})
go func() {
defer close(c)
wg.Wait()
}()
select {
case <-c:
return false // completed normally
case <-time.After(timeout):
return true // timed out
}
}
// irrecoverableErrorsAtInit contains errors that are considered irrecoverable when initializing
// the connection.
//
// ErrSubscriptionChangeInvalidForFeed means that the subscribe command failed and normally
// that "only" results in less messages from the server. However at startup this fails the whole
// flow, and can not be helped by a retry. So irrecoverableErrorsAtInit should only be used at init,
// once the connection was successfully made, ErrSubscriptionChangeInvalidForFeed should not be
// considered fatal.
var irrecoverableErrorsAtInit = []error{
ErrInvalidCredentials,
ErrInsufficientSubscription,
ErrInsufficientScope,
ErrSubscriptionChangeInvalidForFeed,
}
// isErrorIrrecoverableAtInit returns whether the error is irrecoverable and further retries should
// not take place at initialisation.
func isErrorIrrecoverableAtInit(err error) bool {
for _, irrErr := range irrecoverableErrorsAtInit {
if errors.Is(err, irrErr) {
return true
}
}
return false
}
func isHttp4xx(err error) bool {
// Unfortunately the nhoory error is a simple formatted string, created by fmt.Errorf,
// so the only check we can do is string matching
pattern := `expected handshake response status code 101 but got 4\d\d`
ok, _ := regexp.MatchString(pattern, err.Error())
return ok
}
func wrapIrrecoverable(err error) error {
return fmt.Errorf("irrecoverable error: %w", err)
}
var newPingTicker = func() ticker {
return &timeTicker{ticker: time.NewTicker(pingPeriod)}
}
// connPinger periodically calls c.conn.Ping to ensure the connection is still alive
func (c *client) connPinger(ctx context.Context, wg *sync.WaitGroup, closeCh <-chan struct{}) {
pingTicker := newPingTicker()
defer func() {
pingTicker.Stop()
c.conn.close()
wg.Done()
}()
for {
select {
case <-closeCh:
return
case <-ctx.Done():
return
case <-pingTicker.C():
if err := c.conn.ping(ctx); err != nil {
if ctx.Err() == nil {
c.logger.Warnf("datav2stream: ping failed, error: %v", err)
}
return
}
}
}
}
// connReader reads from c.conn and sends those messages to c.in.
// It is also responsible for closing closeCh that terminates the other worker
// goroutines and also for closing c.in which terminates messageProcessors.
func (c *client) connReader(
ctx context.Context,
wg *sync.WaitGroup,
closeCh chan<- struct{},
) {
defer func() {
close(closeCh)
c.conn.close()
close(c.in)
wg.Done()
}()
for {
msg, err := c.conn.readMessage(ctx)
if err != nil {
if ctx.Err() == nil {
c.logger.Warnf("datav2stream: reading from conn failed, error: %v", err)
}
return
}
c.in <- msg
}
}
// connWriter handles writing messages from c.subChanges to c.conn
func (c *client) connWriter(ctx context.Context, wg *sync.WaitGroup, closeCh <-chan struct{}) {
defer func() {
c.conn.close()
wg.Done()
}()
// We need to make sure that the pending sub change is handled
// Goal: make sure the message is in c.subChanges
c.pendingSubChangeMutex.Lock()
if c.pendingSubChange != nil {
select {
case <-c.subChanges:
default:
}
c.subChanges <- c.pendingSubChange.msg
}
c.pendingSubChangeMutex.Unlock()
for {
select {
case <-closeCh:
return
case <-ctx.Done():
return
case msg := <-c.subChanges:
if err := c.conn.writeMessage(ctx, msg); err != nil {
if ctx.Err() == nil {
c.logger.Warnf("datav2stream: writing to conn failed, error: %v", err)
}
return
}
}
}
}
// messageProcessor reads from c.in (while it's open) and processes the messages
func (c *client) messageProcessor(
ctx context.Context,
wg *sync.WaitGroup,
) {
defer func() {
wg.Done()
}()
for {
select {
case <-ctx.Done():
return
case msg, ok := <-c.in:
if !ok {
return
}
err := c.handleMessage(msg)
if err != nil {
c.logger.Errorf("datav2stream: could not handle message, error: %v", err)
}
}
}
}