forked from mtfelian/golang-socketio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannel.go
344 lines (283 loc) · 8.18 KB
/
channel.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
package gosocketio
import (
"encoding/json"
"errors"
"net/http"
"sync"
"time"
"github.com/mtfelian/golang-socketio/logging"
"github.com/mtfelian/golang-socketio/protocol"
"github.com/mtfelian/golang-socketio/transport"
)
const (
queueBufferSize = 500
headerForward = "X-Forwarded-For"
)
var (
ErrorSendTimeout = errors.New("timeout")
ErrorSocketOverflood = errors.New("socket overflood")
)
// connectionHeader represents engine.io connection header
type connectionHeader struct {
Sid string `json:"sid"`
Upgrades []string `json:"upgrades"`
PingInterval int `json:"pingInterval"`
PingTimeout int `json:"pingTimeout"`
}
// Channel represents socket.io connection
type Channel struct {
conn transport.Connection
outC chan string
stubC chan string
upgradedC chan string
connHeader connectionHeader
alive bool
aliveMu sync.Mutex
ack *acks
server *Server
address string
header http.Header
}
// init the Channel
func (c *Channel) init() {
c.outC, c.stubC, c.upgradedC = make(chan string, queueBufferSize), make(chan string), make(chan string)
c.ack = &acks{}
c.ack.ackC = make(map[int]chan string)
c.alive = true
}
// Id returns an ID of the current socket connection
func (c *Channel) Id() string { return c.connHeader.Sid }
// IsAlive checks that Channel is still alive
func (c *Channel) IsAlive() bool {
c.aliveMu.Lock()
defer c.aliveMu.Unlock()
return c.alive
}
// Close the client (Channel) connection
func (c *Channel) Close() error { return c.close(c.server.event) }
// stub closes the polling client (Channel) connection at socket.io upgrade
func (c *Channel) stub() error { return c.close(nil) }
// close channel
func (c *Channel) close(e *event) error {
switch c.conn.(type) {
case *transport.PollingConnection:
logging.Log().Debug("Channel.close() type: PollingConnection")
case *transport.WebsocketConnection:
logging.Log().Debug("Channel.close() type: WebsocketConnection")
}
c.aliveMu.Lock()
defer c.aliveMu.Unlock()
if !c.alive { // already closed
return nil
}
c.conn.Close()
c.alive = false
// clean outloop
for len(c.outC) > 0 {
<-c.outC
}
if e != nil { // close
c.outC <- protocol.MessageClose
e.callHandler(c, OnDisconnection)
} else { // stub at transport upgrade
c.outC <- protocol.MessageStub
}
overfloodedMu.Lock()
delete(overflooded, c)
overfloodedMu.Unlock()
return nil
}
// inLoop is an incoming events loop
func (c *Channel) inLoop(e *event) error {
for {
message, err := c.conn.GetMessage()
if err != nil {
logging.Log().Debugf("Channel.inLoop(), c.conn.GetMessage() err: %v, message: %s", err, message)
return c.close(e)
}
if message == transport.StopMessage {
logging.Log().Debug("Channel.inLoop(): StopMessage")
return nil
}
decodedMessage, err := protocol.Decode(message)
if err != nil {
logging.Log().Debugf("Channel.inLoop() decoding err: %v, message: %s", err, message)
c.close(e)
return err
}
switch decodedMessage.Type {
case protocol.MessageTypeOpen:
logging.Log().Debugf("Channel.inLoop(), protocol.MessageTypeOpen, decodedMessage: %+v", decodedMessage)
if err := json.Unmarshal([]byte(decodedMessage.Source[1:]), &c.connHeader); err != nil {
c.close(e)
}
e.callHandler(c, OnConnection)
case protocol.MessageTypePing:
logging.Log().Debugf("Channel.inLoop(), protocol.MessageTypePing, decodedMessage: %+v", decodedMessage)
if decodedMessage.Source == protocol.MessagePingProbe {
logging.Log().Debugf("Channel.inLoop(), decodedMessage.Source: %s", decodedMessage.Source)
c.outC <- protocol.MessagePongProbe
c.upgradedC <- transport.UpgradedMessage
} else {
c.outC <- protocol.MessagePong
}
case protocol.MessageTypeUpgrade:
case protocol.MessageTypeBlank:
case protocol.MessageTypePong:
default:
go e.processIncoming(c, decodedMessage)
}
}
return nil
}
// outLoop is an outgoing events loop, sends messages from channel to socket
func (c *Channel) outLoop(e *event) error {
for {
outBufferLen := len(c.outC)
logging.Log().Debug("Channel.outLoop(), outBufferLen:", outBufferLen)
switch {
case outBufferLen >= queueBufferSize-1:
logging.Log().Debug("Channel.outLoop(), outBufferLen >= queueBufferSize-1")
return c.close(e)
case outBufferLen > int(queueBufferSize/2):
overfloodedMu.Lock()
overflooded[c] = struct{}{}
overfloodedMu.Unlock()
default:
overfloodedMu.Lock()
delete(overflooded, c)
overfloodedMu.Unlock()
}
m := <-c.outC
if m == protocol.MessageClose || m == protocol.MessageStub {
return nil
}
if err := c.conn.WriteMessage(m); err != nil {
logging.Log().Debug("Channel.outLoop(), failed to c.conn.WriteMessage() with err:", err)
return c.close(e)
}
}
return nil
}
// pingLoop sends ping messages for keeping connection alive
func (c *Channel) pingLoop() {
for {
interval, _ := c.conn.PingParams()
time.Sleep(interval)
if !c.IsAlive() {
return
}
c.outC <- protocol.MessagePing
}
}
// send message packet to the given channel c with payload
func (c *Channel) send(m *protocol.Message, payload interface{}) error {
// preventing encoding/json "index out of range" panic
defer func() {
if r := recover(); r != nil {
logging.Log().Warn("Channel.send(): recovered from panic:", r)
}
}()
if payload != nil {
b, err := json.Marshal(&payload)
if err != nil {
return err
}
m.Args = string(b)
}
command, err := protocol.Encode(m)
if err != nil {
return err
}
if len(c.outC) == queueBufferSize {
return ErrorSocketOverflood
}
c.outC <- command
return nil
}
// Emit an asynchronous event with the given name and payload
func (c *Channel) Emit(name string, payload interface{}) error {
message := &protocol.Message{Type: protocol.MessageTypeEmit, EventName: name}
return c.send(message, payload)
}
// Ack a synchronous event with the given name and payload and wait for/receive the response
func (c *Channel) Ack(name string, payload interface{}, timeout time.Duration) (string, error) {
m := &protocol.Message{Type: protocol.MessageTypeAckRequest, AckID: c.ack.nextId(), EventName: name}
ackC := make(chan string)
c.ack.register(m.AckID, ackC)
if err := c.send(m, payload); err != nil {
c.ack.unregister(m.AckID)
}
select {
case result := <-ackC:
return result, nil
case <-time.After(timeout):
c.ack.unregister(m.AckID)
return "", ErrorSendTimeout
}
}
// IP returns an IP of the socket client
func (c *Channel) IP() string {
forward := c.RequestHeader().Get(headerForward)
if forward != "" {
return forward
}
return c.address
}
// RequestHeader returns a connection request connectionHeader
func (c *Channel) RequestHeader() http.Header { return c.header }
// Join this channel to the given room
func (c *Channel) Join(room string) error {
if c.server == nil {
return ErrorServerNotSet
}
c.server.channelsMu.Lock()
defer c.server.channelsMu.Unlock()
if _, ok := c.server.channels[room]; !ok {
c.server.channels[room] = make(map[*Channel]struct{})
}
if _, ok := c.server.rooms[c]; !ok {
c.server.rooms[c] = make(map[string]struct{})
}
c.server.channels[room][c], c.server.rooms[c][room] = struct{}{}, struct{}{}
return nil
}
// Leave the given room (remove channel from it)
func (c *Channel) Leave(room string) error {
if c.server == nil {
return ErrorServerNotSet
}
c.server.channelsMu.Lock()
defer c.server.channelsMu.Unlock()
if _, ok := c.server.channels[room]; ok {
delete(c.server.channels[room], c)
if len(c.server.channels[room]) == 0 {
delete(c.server.channels, room)
}
}
if _, ok := c.server.rooms[c]; ok {
delete(c.server.rooms[c], room)
}
return nil
}
// Amount returns an amount of channels joined to the given room, using channel
func (c *Channel) Amount(room string) int {
if c.server == nil {
return 0
}
return c.server.Amount(room)
}
// List returns a list of channels joined to the given room, using channel
func (c *Channel) List(room string) []*Channel {
if c.server == nil {
return []*Channel{}
}
return c.server.List(room)
}
// BroadcastTo the the given room an event with given name and payload, using channel
func (c *Channel) BroadcastTo(room, name string, payload interface{}) {
if c.server == nil {
return
}
c.server.BroadcastTo(room, name, payload)
}