-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathssclient.go
226 lines (181 loc) · 4.55 KB
/
ssclient.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
package scclient
import (
"bytes"
"encoding/json"
"errors"
"sync"
"time"
"github.com/gorilla/websocket"
)
var Ping = []byte("#1")
var Pong = []byte("#2")
type LogLevel int
const (
LogLevelDebug = iota
LogLevelError = iota
)
type Client struct {
EventHandler func(event string, data []byte)
ConnectCallback func() error
Logger func(level LogLevel, levelmsg string)
url string
conn *connection
connMu *sync.RWMutex
dialer *websocket.Dialer
missingPingTimeoutCount int
subscriptions map[string]chan []byte
subscriptionsMu *sync.RWMutex
callbacks map[uint64]func([]byte, *parsedResponseError)
callbackMu *sync.Mutex
}
func New(url string) *Client {
out := &Client{
url: url,
connMu: &sync.RWMutex{},
callbacks: make(map[uint64]func([]byte, *parsedResponseError), 0),
callbackMu: &sync.Mutex{},
subscriptions: make(map[string]chan []byte),
subscriptionsMu: &sync.RWMutex{},
missingPingTimeoutCount: 3,
}
return out
}
func (c *Client) Connect() error {
return c.ConnectWithDialer(&websocket.Dialer{})
}
func (c *Client) ConnectWithDialer(dialer *websocket.Dialer) error {
c.dialer = dialer
return c.connect()
}
type parsedResponse struct {
Rid uint64 `json:"rid"`
Data json.RawMessage `json:"data"`
Event string `json:"event"`
Error *parsedResponseError `json:"error"`
}
type parsedResponseError struct {
Message string `json:"message"`
Name string `json:"name"`
}
func (c *Client) handleIncoming() {
for {
msgType, p, err := c.receive()
if err != nil {
// Will attempt to reconnect automatically and respawn this receive loop
return
}
if msgType == -1 {
panic("Something's gone wrong!")
}
if msgType == websocket.TextMessage && bytes.Equal(p, Ping) {
c.handlePing()
continue
}
parsedResponse := &parsedResponse{}
if err := json.Unmarshal(p, parsedResponse); err != nil {
panic(err)
}
if parsedResponse.Rid == 0 {
go c.handleIncomingEvent(parsedResponse)
continue
}
c.callbackMu.Lock()
callback := c.callbacks[parsedResponse.Rid]
if callback != nil {
delete(c.callbacks, parsedResponse.Rid)
go callback(parsedResponse.Data, parsedResponse.Error)
}
c.callbackMu.Unlock()
}
}
func (c *Client) handleIncomingEvent(event *parsedResponse) {
if event.Event == "#publish" {
c.handlePublishEvent(event)
return
}
if c.EventHandler == nil {
return
}
c.EventHandler(event.Event, []byte(event.Data))
}
func (c *Client) Emit(msgType string, data interface{}) (out []byte, outErr error) {
m := c.newMsg(msgType, data)
done := make(chan struct{}, 0)
var once sync.Once
callback := func(ret []byte, err *parsedResponseError) {
once.Do(func() {
out = ret
if err != nil {
outErr = errors.New(err.Name + ": " + err.Message)
}
close(done)
})
}
c.callbackMu.Lock()
c.callbacks[m.MsgId] = callback
c.callbackMu.Unlock()
go func() {
time.Sleep(5 * time.Second) // Hardcoded timeout, for now
once.Do(func() {
outErr = errors.New("no response received before the deadline expired")
c.callbackMu.Lock()
delete(c.callbacks, m.MsgId)
c.callbackMu.Unlock()
close(done)
})
}()
c.send(m.Serialize())
<-done
return out, outErr
}
func (c *Client) EmitWithoutResponse(msgType string, data interface{}) error {
m := c.newMsg(msgType, data)
return c.send(m.Serialize())
}
func (c *Client) handshake() (interface{}, error) {
return c.Emit("#handshake", map[string]*string{"authToken": nil})
}
func (c *Client) Subscribe(chName string) (<-chan []byte, error) {
ch := make(chan []byte, 0)
c.subscriptionsMu.Lock()
c.subscriptions[chName] = ch
c.subscriptionsMu.Unlock()
err := c.subscribe(chName)
return ch, err
}
func (c *Client) resubscribe() {
c.subscriptionsMu.Lock()
for chName := range c.subscriptions {
c.subscribe(chName)
}
c.subscriptionsMu.Unlock()
}
func (c *Client) subscribe(chName string) error {
_, err := c.Emit("#subscribe", struct {
Channel string `json:"channel"`
}{chName})
return err
}
type publishEvent struct {
Channel string `json:"channel"`
Data json.RawMessage `json:"data"`
}
func (c *Client) handlePublishEvent(event *parsedResponse) {
publishEvent := &publishEvent{}
if err := json.Unmarshal(event.Data, publishEvent); err != nil {
panic(err)
}
c.subscriptionsMu.RLock()
channel, ok := c.subscriptions[publishEvent.Channel]
c.subscriptionsMu.RUnlock()
if !ok {
return
}
channel <- []byte(publishEvent.Data)
}
func (c *Client) log(level LogLevel, msg string) {
if c.Logger == nil {
return
}
c.Logger(level, msg)
}