-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamer.go
180 lines (155 loc) · 4.09 KB
/
streamer.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
package binance
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/dchest/uniuri"
"github.com/gorilla/websocket"
"github.com/jaztec/go-binance/model"
)
// Streamer defines functions that are available in the Binance Websocket API.
type Streamer interface {
Subscribe(ctx context.Context, params []string) (<-chan model.StreamData, error)
Unsubscribe(ctx context.Context, params []string) error
}
// StreamCaller exposes readily implemented calls to the Binance websocket API
type StreamCaller interface {
Streamer
// UserDataStream updates when user account changes have occurred
UserDataStream(ctx context.Context) (<-chan model.UserAccountUpdate, error)
// Kline data for a list of tokens
Kline(ctx context.Context, symbols []string, interval string) (<-chan model.KlineData, error)
// TickerArr changes to prices from the ticker API
TickerArr(ctx context.Context) (chan []model.Ticker, error)
}
type streamer struct {
api *api
logger Logger
streams []*stream
}
func (s *streamer) Subscribe(ctx context.Context, params []string) (<-chan model.StreamData, error) {
st, err := s.stream(ctx)
if err != nil {
return nil, err
}
return st.subscribe(params)
}
func (s *streamer) Unsubscribe(ctx context.Context, params []string) error {
st, err := s.stream(ctx)
if err != nil {
return err
}
return st.unsubscribe(params)
}
func (s *streamer) keepAlive(ctx context.Context, path string, interval time.Duration) {
go func(ctx context.Context, interval time.Duration) {
tC := time.Tick(interval)
for {
select {
case <-tC:
_, _ = s.api.Request(http.MethodPut, path, nil)
case <-ctx.Done():
return
}
}
}(ctx, interval)
}
func (s *streamer) stream(ctx context.Context) (*stream, error) {
_ = s.logger.Log("stream", "request", "current", len(s.streams))
if len(s.streams) > 0 {
_ = s.logger.Log("stream", "request", "returning", "existing")
c := s.streams[0]
return c, nil
}
_ = s.logger.Log("stream", "request", "returning", "new")
conn, err := s.conn()
if err != nil {
return nil, err
}
st := &stream{
id: uniuri.New(),
conn: conn,
channels: make(channelList, 0, 5),
writes: make(chan []byte, 5),
subscribers: make(subscriberMap),
logger: s.logger,
closed: make(chan struct{}),
}
s.streams = append(s.streams, st)
go st.readPump()
go st.writePump(ctx)
go s.monitor(ctx, st)
return st, nil
}
func (s *streamer) conn() (*websocket.Conn, error) {
fullURI := fmt.Sprintf("%s/stream", s.api.cfg.BaseStreamURI)
d := &websocket.Dialer{}
_ = s.logger.Log("msg", "starting stream", "uri", fullURI)
conn, _, err := d.Dial(fullURI, nil)
if err != nil {
return nil, err
}
return conn, err
}
func (s *streamer) resetStream(ctx context.Context, st *stream) error {
// remove stream from list
s.removeStream(st.id)
// get a new stream running
nst, err := s.stream(ctx)
if err != nil {
return err
}
// copy values from last stream to the new one
nst.lastID = st.lastID + 1
for k, v := range st.subscribers {
nst.subscribers[k] = v
}
nst.channels = make([]string, len(st.channels))
copy(nst.channels, st.channels)
_ = s.logger.Log("resetting", strings.Join(nst.channels, ","))
// subscribe to the channels the old stream was subscribed to
// we purposely don't use subscribe method to keep subscriber map intact
if len(nst.channels) > 0 {
msg := SubscribeMessage{
Method: Subscribe,
Params: nst.channels,
ID: nst.lastID,
}
b, err := json.Marshal(msg)
if err != nil {
return err
}
nst.writes <- b
}
return nil
}
func (s *streamer) removeStream(id string) {
for i, st := range s.streams {
if st.id == id {
s.streams = append(s.streams[:i], s.streams[i+1:]...)
}
}
}
func (s *streamer) monitor(ctx context.Context, st *stream) {
for {
select {
case <-st.closed:
err := s.resetStream(ctx, st)
if err != nil {
_ = s.logger.Log("streamer", "monitor", "error resetting", err.Error())
}
return
case <-ctx.Done():
return
}
}
}
func newStreamer(a *api, logger Logger) Streamer {
return &streamer{
api: a,
logger: logger,
}
}