-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
192 lines (164 loc) · 4.07 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
package binance
import (
"context"
"encoding/json"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/jaztec/go-binance/model"
"github.com/gorilla/websocket"
)
// MessageType describes what kind of message is send, a subscribe
// or unsubscribe
type MessageType string
const (
// BaseStreamURI for the Binance websocket API
BaseStreamURI = "wss://stream.binance.com:9443"
pongPeriod = 2 * time.Minute
// Subscribe to a channel
Subscribe MessageType = "SUBSCRIBE"
// Unsubscribe from a channel
Unsubscribe MessageType = "UNSUBSCRIBE"
)
type subscriberMap map[string][]chan model.StreamData
type channelList []string
func (cl channelList) Len() int { return len(cl) }
func (cl channelList) Swap(i, j int) { cl[i], cl[j] = cl[j], cl[i] }
func (cl channelList) Less(i, j int) bool { return cl[i] < cl[j] }
func (cl channelList) IndexOf(s string) int {
for n, el := range cl {
if el == s {
return n
}
}
return -1
}
// StreamerConfig declares what a new Streamer needs to run
type StreamerConfig struct {
API API
BaseStreamURI string
}
// SubscribeMessage is a representation of the Binance subscribe and unsubscribe
// messages data structure.
type SubscribeMessage struct {
Method MessageType `json:"method"`
Params []string `json:"params"`
ID uint64 `json:"id"`
}
type stream struct {
id string
conn *websocket.Conn
channels channelList
writes chan []byte
lastID uint64
subscribers subscriberMap
logger Logger
closed chan struct{}
}
func (s *stream) unsubscribe(params []string) error {
atomic.AddUint64(&s.lastID, 1)
msg := SubscribeMessage{
Method: Unsubscribe,
Params: params,
ID: s.lastID,
}
b, err := json.Marshal(msg)
if err != nil {
return err
}
s.writes <- b
for _, param := range params {
if list, ok := s.subscribers[param]; ok {
for _, ch := range list {
close(ch)
}
delete(s.subscribers, param)
}
if n := s.channels.IndexOf(param); n > -1 {
// remove channel but keep order intact
s.channels = append(s.channels[:n], s.channels[n+1:]...)
}
}
return nil
}
func (s *stream) subscribe(params []string) (<-chan model.StreamData, error) {
atomic.AddUint64(&s.lastID, 1)
_ = s.logger.Log("subscribe", strings.Join(params, ", "))
newParams := make([]string, 0, len(params))
reads := make(chan model.StreamData, 5)
for _, param := range params {
if _, ok := s.subscribers[param]; !ok {
s.subscribers[param] = make([]chan model.StreamData, 0, 1)
newParams = append(newParams, param)
}
s.subscribers[param] = append(s.subscribers[param], reads)
}
// keep track of channels we connect on
s.channels = append(s.channels, params...)
sort.Sort(s.channels)
if len(newParams) > 0 {
msg := SubscribeMessage{
Method: Subscribe,
Params: newParams,
ID: s.lastID,
}
b, err := json.Marshal(msg)
if err != nil {
return nil, err
}
s.writes <- b
}
return reads, nil
}
func (s *stream) readPump() {
defer func() {
err := s.conn.Close()
if err != nil {
_ = s.logger.Log("close", "readPump", "error", err)
}
}()
for {
_, msg, err := s.conn.ReadMessage()
if err != nil {
_ = s.logger.Log("method", "readPump", "error", err.Error())
close(s.closed)
return
}
var sd model.StreamData
if err = json.Unmarshal(msg, &sd); err != nil {
_ = s.logger.Log("read", "error", "msg", err.Error())
continue
}
list, ok := s.subscribers[sd.Stream]
if !ok {
continue
}
for _, ch := range list {
ch <- sd
}
}
}
func (s *stream) writePump(ctx context.Context) {
t := time.NewTicker(pongPeriod)
defer t.Stop()
for {
select {
case msg := <-s.writes:
if err := s.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
_ = s.logger.Log("write", string(msg), "error", err)
return
}
case <-s.closed:
// when top stream closes we exit too, reset will start new procedures
return
case _ = <-ctx.Done():
_ = s.logger.Log("writePump", "close signal")
return
case <-t.C:
if err := s.conn.WriteMessage(websocket.PongMessage, []byte{}); err != nil {
return
}
}
}
}